Ba1yya commited on
Commit
e2614e3
·
1 Parent(s): 1e5feda

Upload EasierGUI.py

Browse files
Files changed (1) hide show
  1. EasierGUI.py +2346 -0
EasierGUI.py ADDED
@@ -0,0 +1,2346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zipfile, glob, subprocess, torch, os, traceback, sys, warnings, shutil, numpy as np
2
+ from mega import Mega
3
+ os.environ["no_proxy"] = "localhost, 127.0.0.1, ::1"
4
+ import threading
5
+ from time import sleep
6
+ from subprocess import Popen
7
+ import faiss
8
+ from random import shuffle
9
+ import json, datetime, requests
10
+ from gtts import gTTS
11
+ now_dir = os.getcwd()
12
+ sys.path.append(now_dir)
13
+ tmp = os.path.join(now_dir, "TEMP")
14
+ shutil.rmtree(tmp, ignore_errors=True)
15
+ shutil.rmtree("%s/runtime/Lib/site-packages/infer_pack" % (now_dir), ignore_errors=True)
16
+ shutil.rmtree("%s/runtime/Lib/site-packages/uvr5_pack" % (now_dir), ignore_errors=True)
17
+ os.makedirs(tmp, exist_ok=True)
18
+ os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
19
+ os.makedirs(os.path.join(now_dir, "weights"), exist_ok=True)
20
+ os.environ["TEMP"] = tmp
21
+ warnings.filterwarnings("ignore")
22
+ torch.manual_seed(114514)
23
+ from i18n import I18nAuto
24
+ import ffmpeg
25
+ #from MDXNet import MDXNetDereverb
26
+
27
+ i18n = I18nAuto()
28
+ #i18n.print()
29
+ # 判断是否有能用来训练和加速推理的N卡
30
+ ngpu = torch.cuda.device_count()
31
+ gpu_infos = []
32
+ mem = []
33
+ if (not torch.cuda.is_available()) or ngpu == 0:
34
+ if_gpu_ok = False
35
+ else:
36
+ if_gpu_ok = False
37
+ for i in range(ngpu):
38
+ gpu_name = torch.cuda.get_device_name(i)
39
+ if (
40
+ "10" in gpu_name
41
+ or "16" in gpu_name
42
+ or "20" in gpu_name
43
+ or "30" in gpu_name
44
+ or "40" in gpu_name
45
+ or "A2" in gpu_name.upper()
46
+ or "A3" in gpu_name.upper()
47
+ or "A4" in gpu_name.upper()
48
+ or "P4" in gpu_name.upper()
49
+ or "A50" in gpu_name.upper()
50
+ or "A60" in gpu_name.upper()
51
+ or "70" in gpu_name
52
+ or "80" in gpu_name
53
+ or "90" in gpu_name
54
+ or "M4" in gpu_name.upper()
55
+ or "T4" in gpu_name.upper()
56
+ or "TITAN" in gpu_name.upper()
57
+ ): # A10#A100#V100#A40#P40#M40#K80#A4500
58
+ if_gpu_ok = True # 至少有一张能用的N卡
59
+ gpu_infos.append("%s\t%s" % (i, gpu_name))
60
+ mem.append(
61
+ int(
62
+ torch.cuda.get_device_properties(i).total_memory
63
+ / 1024
64
+ / 1024
65
+ / 1024
66
+ + 0.4
67
+ )
68
+ )
69
+ if if_gpu_ok == True and len(gpu_infos) > 0:
70
+ gpu_info = "\n".join(gpu_infos)
71
+ default_batch_size = min(mem) // 2
72
+ else:
73
+ gpu_info = i18n("很遗憾您这没有能用的显卡来支持您训练")
74
+ default_batch_size = 1
75
+ gpus = "-".join([i[0] for i in gpu_infos])
76
+ from lib.infer_pack.models import (
77
+ SynthesizerTrnMs256NSFsid,
78
+ SynthesizerTrnMs256NSFsid_nono,
79
+ SynthesizerTrnMs768NSFsid,
80
+ SynthesizerTrnMs768NSFsid_nono,
81
+ )
82
+ import soundfile as sf
83
+ from fairseq import checkpoint_utils
84
+ import gradio as gr
85
+ import logging
86
+ from vc_infer_pipeline import VC
87
+ from config import Config
88
+ from infer_uvr5 import _audio_pre_, _audio_pre_new
89
+ from my_utils import load_audio
90
+ from train.process_ckpt import show_info, change_info, merge, extract_small_model
91
+
92
+ config = Config()
93
+ # from trainset_preprocess_pipeline import PreProcess
94
+ logging.getLogger("numba").setLevel(logging.WARNING)
95
+
96
+ hubert_model = None
97
+
98
+ def load_hubert():
99
+ global hubert_model
100
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
101
+ ["hubert_base.pt"],
102
+ suffix="",
103
+ )
104
+ hubert_model = models[0]
105
+ hubert_model = hubert_model.to(config.device)
106
+ if config.is_half:
107
+ hubert_model = hubert_model.half()
108
+ else:
109
+ hubert_model = hubert_model.float()
110
+ hubert_model.eval()
111
+
112
+
113
+ weight_root = "weights"
114
+ weight_uvr5_root = "uvr5_weights"
115
+ index_root = "logs"
116
+ names = []
117
+ for name in os.listdir(weight_root):
118
+ if name.endswith(".pth"):
119
+ names.append(name)
120
+ index_paths = []
121
+ for root, dirs, files in os.walk(index_root, topdown=False):
122
+ for name in files:
123
+ if name.endswith(".index") and "trained" not in name:
124
+ index_paths.append("%s/%s" % (root, name))
125
+ uvr5_names = []
126
+ for name in os.listdir(weight_uvr5_root):
127
+ if name.endswith(".pth") or "onnx" in name:
128
+ uvr5_names.append(name.replace(".pth", ""))
129
+
130
+
131
+ def vc_single(
132
+ sid,
133
+ input_audio_path,
134
+ f0_up_key,
135
+ f0_file,
136
+ f0_method,
137
+ file_index,
138
+ #file_index2,
139
+ # file_big_npy,
140
+ index_rate,
141
+ filter_radius,
142
+ resample_sr,
143
+ rms_mix_rate,
144
+ protect,
145
+ crepe_hop_length,
146
+ ): # spk_item, input_audio0, vc_transform0,f0_file,f0method0
147
+ global tgt_sr, net_g, vc, hubert_model, version
148
+ if input_audio_path is None:
149
+ return "You need to upload an audio", None
150
+ f0_up_key = int(f0_up_key)
151
+ try:
152
+ audio = load_audio(input_audio_path, 16000)
153
+ audio_max = np.abs(audio).max() / 0.95
154
+ if audio_max > 1:
155
+ audio /= audio_max
156
+ times = [0, 0, 0]
157
+ if hubert_model == None:
158
+ load_hubert()
159
+ if_f0 = cpt.get("f0", 1)
160
+ file_index = (
161
+ (
162
+ file_index.strip(" ")
163
+ .strip('"')
164
+ .strip("\n")
165
+ .strip('"')
166
+ .strip(" ")
167
+ .replace("trained", "added")
168
+ )
169
+ ) # 防止小白写错,自动帮他替换掉
170
+ # file_big_npy = (
171
+ # file_big_npy.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
172
+ # )
173
+ audio_opt = vc.pipeline(
174
+ hubert_model,
175
+ net_g,
176
+ sid,
177
+ audio,
178
+ input_audio_path,
179
+ times,
180
+ f0_up_key,
181
+ f0_method,
182
+ file_index,
183
+ # file_big_npy,
184
+ index_rate,
185
+ if_f0,
186
+ filter_radius,
187
+ tgt_sr,
188
+ resample_sr,
189
+ rms_mix_rate,
190
+ version,
191
+ protect,
192
+ crepe_hop_length,
193
+ f0_file=f0_file,
194
+ )
195
+ if resample_sr >= 16000 and tgt_sr != resample_sr:
196
+ tgt_sr = resample_sr
197
+ index_info = (
198
+ "Using index:%s." % file_index
199
+ if os.path.exists(file_index)
200
+ else "Index not used."
201
+ )
202
+ return "Success.\n %s\nTime:\n npy:%ss, f0:%ss, infer:%ss" % (
203
+ index_info,
204
+ times[0],
205
+ times[1],
206
+ times[2],
207
+ ), (tgt_sr, audio_opt)
208
+ except:
209
+ info = traceback.format_exc()
210
+ print(info)
211
+ return info, (None, None)
212
+
213
+
214
+ def vc_multi(
215
+ sid,
216
+ dir_path,
217
+ opt_root,
218
+ paths,
219
+ f0_up_key,
220
+ f0_method,
221
+ file_index,
222
+ file_index2,
223
+ # file_big_npy,
224
+ index_rate,
225
+ filter_radius,
226
+ resample_sr,
227
+ rms_mix_rate,
228
+ protect,
229
+ format1,
230
+ crepe_hop_length,
231
+ ):
232
+ try:
233
+ dir_path = (
234
+ dir_path.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
235
+ ) # 防止小白拷路径头尾带了空格和"和回车
236
+ opt_root = opt_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
237
+ os.makedirs(opt_root, exist_ok=True)
238
+ try:
239
+ if dir_path != "":
240
+ paths = [os.path.join(dir_path, name) for name in os.listdir(dir_path)]
241
+ else:
242
+ paths = [path.name for path in paths]
243
+ except:
244
+ traceback.print_exc()
245
+ paths = [path.name for path in paths]
246
+ infos = []
247
+ for path in paths:
248
+ info, opt = vc_single(
249
+ sid,
250
+ path,
251
+ f0_up_key,
252
+ None,
253
+ f0_method,
254
+ file_index,
255
+ file_index2,
256
+ # file_big_npy,
257
+ index_rate,
258
+ filter_radius,
259
+ resample_sr,
260
+ rms_mix_rate,
261
+ protect,
262
+ crepe_hop_length
263
+ )
264
+ if "Success" in info:
265
+ try:
266
+ tgt_sr, audio_opt = opt
267
+ if format1 in ["wav", "flac"]:
268
+ sf.write(
269
+ "%s/%s.%s" % (opt_root, os.path.basename(path), format1),
270
+ audio_opt,
271
+ tgt_sr,
272
+ )
273
+ else:
274
+ path = "%s/%s.wav" % (opt_root, os.path.basename(path))
275
+ sf.write(
276
+ path,
277
+ audio_opt,
278
+ tgt_sr,
279
+ )
280
+ if os.path.exists(path):
281
+ os.system(
282
+ "ffmpeg -i %s -vn %s -q:a 2 -y"
283
+ % (path, path[:-4] + ".%s" % format1)
284
+ )
285
+ except:
286
+ info += traceback.format_exc()
287
+ infos.append("%s->%s" % (os.path.basename(path), info))
288
+ yield "\n".join(infos)
289
+ yield "\n".join(infos)
290
+ except:
291
+ yield traceback.format_exc()
292
+
293
+
294
+ def uvr(model_name, inp_root, save_root_vocal, paths, save_root_ins, agg, format0):
295
+ infos = []
296
+ try:
297
+ inp_root = inp_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
298
+ save_root_vocal = (
299
+ save_root_vocal.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
300
+ )
301
+ save_root_ins = (
302
+ save_root_ins.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
303
+ )
304
+ if model_name == "onnx_dereverb_By_FoxJoy":
305
+ pre_fun = MDXNetDereverb(15)
306
+ else:
307
+ func = _audio_pre_ if "DeEcho" not in model_name else _audio_pre_new
308
+ pre_fun = func(
309
+ agg=int(agg),
310
+ model_path=os.path.join(weight_uvr5_root, model_name + ".pth"),
311
+ device=config.device,
312
+ is_half=config.is_half,
313
+ )
314
+ if inp_root != "":
315
+ paths = [os.path.join(inp_root, name) for name in os.listdir(inp_root)]
316
+ else:
317
+ paths = [path.name for path in paths]
318
+ for path in paths:
319
+ inp_path = os.path.join(inp_root, path)
320
+ need_reformat = 1
321
+ done = 0
322
+ try:
323
+ info = ffmpeg.probe(inp_path, cmd="ffprobe")
324
+ if (
325
+ info["streams"][0]["channels"] == 2
326
+ and info["streams"][0]["sample_rate"] == "44100"
327
+ ):
328
+ need_reformat = 0
329
+ pre_fun._path_audio_(
330
+ inp_path, save_root_ins, save_root_vocal, format0
331
+ )
332
+ done = 1
333
+ except:
334
+ need_reformat = 1
335
+ traceback.print_exc()
336
+ if need_reformat == 1:
337
+ tmp_path = "%s/%s.reformatted.wav" % (tmp, os.path.basename(inp_path))
338
+ os.system(
339
+ "ffmpeg -i %s -vn -acodec pcm_s16le -ac 2 -ar 44100 %s -y"
340
+ % (inp_path, tmp_path)
341
+ )
342
+ inp_path = tmp_path
343
+ try:
344
+ if done == 0:
345
+ pre_fun._path_audio_(
346
+ inp_path, save_root_ins, save_root_vocal, format0
347
+ )
348
+ infos.append("%s->Success" % (os.path.basename(inp_path)))
349
+ yield "\n".join(infos)
350
+ except:
351
+ infos.append(
352
+ "%s->%s" % (os.path.basename(inp_path), traceback.format_exc())
353
+ )
354
+ yield "\n".join(infos)
355
+ except:
356
+ infos.append(traceback.format_exc())
357
+ yield "\n".join(infos)
358
+ finally:
359
+ try:
360
+ if model_name == "onnx_dereverb_By_FoxJoy":
361
+ del pre_fun.pred.model
362
+ del pre_fun.pred.model_
363
+ else:
364
+ del pre_fun.model
365
+ del pre_fun
366
+ except:
367
+ traceback.print_exc()
368
+ print("clean_empty_cache")
369
+ if torch.cuda.is_available():
370
+ torch.cuda.empty_cache()
371
+ yield "\n".join(infos)
372
+
373
+
374
+ # 一个选项卡全局只能有一个音色
375
+ def get_vc(sid):
376
+ global n_spk, tgt_sr, net_g, vc, cpt, version
377
+ if sid == "" or sid == []:
378
+ global hubert_model
379
+ if hubert_model != None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的
380
+ print("clean_empty_cache")
381
+ del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt
382
+ hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None
383
+ if torch.cuda.is_available():
384
+ torch.cuda.empty_cache()
385
+ ###楼下不这么折腾清理不干净
386
+ if_f0 = cpt.get("f0", 1)
387
+ version = cpt.get("version", "v1")
388
+ if version == "v1":
389
+ if if_f0 == 1:
390
+ net_g = SynthesizerTrnMs256NSFsid(
391
+ *cpt["config"], is_half=config.is_half
392
+ )
393
+ else:
394
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
395
+ elif version == "v2":
396
+ if if_f0 == 1:
397
+ net_g = SynthesizerTrnMs768NSFsid(
398
+ *cpt["config"], is_half=config.is_half
399
+ )
400
+ else:
401
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
402
+ del net_g, cpt
403
+ if torch.cuda.is_available():
404
+ torch.cuda.empty_cache()
405
+ cpt = None
406
+ return {"visible": False, "__type__": "update"}
407
+ person = "%s/%s" % (weight_root, sid)
408
+ print("loading %s" % person)
409
+ cpt = torch.load(person, map_location="cpu")
410
+ tgt_sr = cpt["config"][-1]
411
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
412
+ if_f0 = cpt.get("f0", 1)
413
+ version = cpt.get("version", "v1")
414
+ if version == "v1":
415
+ if if_f0 == 1:
416
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
417
+ else:
418
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
419
+ elif version == "v2":
420
+ if if_f0 == 1:
421
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
422
+ else:
423
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
424
+ del net_g.enc_q
425
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
426
+ net_g.eval().to(config.device)
427
+ if config.is_half:
428
+ net_g = net_g.half()
429
+ else:
430
+ net_g = net_g.float()
431
+ vc = VC(tgt_sr, config)
432
+ n_spk = cpt["config"][-3]
433
+ return {"visible": False, "maximum": n_spk, "__type__": "update"}
434
+
435
+
436
+ def change_choices():
437
+ names = []
438
+ for name in os.listdir(weight_root):
439
+ if name.endswith(".pth"):
440
+ names.append(name)
441
+ index_paths = []
442
+ for root, dirs, files in os.walk(index_root, topdown=False):
443
+ for name in files:
444
+ if name.endswith(".index") and "trained" not in name:
445
+ index_paths.append("%s/%s" % (root, name))
446
+ return {"choices": sorted(names), "__type__": "update"}, {
447
+ "choices": sorted(index_paths),
448
+ "__type__": "update",
449
+ }
450
+
451
+
452
+ def clean():
453
+ return {"value": "", "__type__": "update"}
454
+
455
+
456
+ sr_dict = {
457
+ "32k": 32000,
458
+ "40k": 40000,
459
+ "48k": 48000,
460
+ }
461
+
462
+
463
+ def if_done(done, p):
464
+ while 1:
465
+ if p.poll() == None:
466
+ sleep(0.5)
467
+ else:
468
+ break
469
+ done[0] = True
470
+
471
+
472
+ def if_done_multi(done, ps):
473
+ while 1:
474
+ # poll==None代表进程未结束
475
+ # 只要有一个进程未结束都不停
476
+ flag = 1
477
+ for p in ps:
478
+ if p.poll() == None:
479
+ flag = 0
480
+ sleep(0.5)
481
+ break
482
+ if flag == 1:
483
+ break
484
+ done[0] = True
485
+
486
+
487
+ def preprocess_dataset(trainset_dir, exp_dir, sr, n_p):
488
+ sr = sr_dict[sr]
489
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
490
+ f = open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "w")
491
+ f.close()
492
+ cmd = (
493
+ config.python_cmd
494
+ + " trainset_preprocess_pipeline_print.py %s %s %s %s/logs/%s "
495
+ % (trainset_dir, sr, n_p, now_dir, exp_dir)
496
+ + str(config.noparallel)
497
+ )
498
+ print(cmd)
499
+ p = Popen(cmd, shell=True) # , stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir
500
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
501
+ done = [False]
502
+ threading.Thread(
503
+ target=if_done,
504
+ args=(
505
+ done,
506
+ p,
507
+ ),
508
+ ).start()
509
+ while 1:
510
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
511
+ yield (f.read())
512
+ sleep(1)
513
+ if done[0] == True:
514
+ break
515
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
516
+ log = f.read()
517
+ print(log)
518
+ yield log
519
+
520
+
521
+ # but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])
522
+ def extract_f0_feature(gpus, n_p, f0method, if_f0, exp_dir, version19, echl):
523
+ gpus = gpus.split("-")
524
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
525
+ f = open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "w")
526
+ f.close()
527
+ if if_f0:
528
+ cmd = config.python_cmd + " extract_f0_print.py %s/logs/%s %s %s %s" % (
529
+ now_dir,
530
+ exp_dir,
531
+ n_p,
532
+ f0method,
533
+ echl,
534
+ )
535
+ print(cmd)
536
+ p = Popen(cmd, shell=True, cwd=now_dir) # , stdin=PIPE, stdout=PIPE,stderr=PIPE
537
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
538
+ done = [False]
539
+ threading.Thread(
540
+ target=if_done,
541
+ args=(
542
+ done,
543
+ p,
544
+ ),
545
+ ).start()
546
+ while 1:
547
+ with open(
548
+ "%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r"
549
+ ) as f:
550
+ yield (f.read())
551
+ sleep(1)
552
+ if done[0] == True:
553
+ break
554
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
555
+ log = f.read()
556
+ print(log)
557
+ yield log
558
+ ####对不同part分别开多进程
559
+ """
560
+ n_part=int(sys.argv[1])
561
+ i_part=int(sys.argv[2])
562
+ i_gpu=sys.argv[3]
563
+ exp_dir=sys.argv[4]
564
+ os.environ["CUDA_VISIBLE_DEVICES"]=str(i_gpu)
565
+ """
566
+ leng = len(gpus)
567
+ ps = []
568
+ for idx, n_g in enumerate(gpus):
569
+ cmd = (
570
+ config.python_cmd
571
+ + " extract_feature_print.py %s %s %s %s %s/logs/%s %s"
572
+ % (
573
+ config.device,
574
+ leng,
575
+ idx,
576
+ n_g,
577
+ now_dir,
578
+ exp_dir,
579
+ version19,
580
+ )
581
+ )
582
+ print(cmd)
583
+ p = Popen(
584
+ cmd, shell=True, cwd=now_dir
585
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
586
+ ps.append(p)
587
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
588
+ done = [False]
589
+ threading.Thread(
590
+ target=if_done_multi,
591
+ args=(
592
+ done,
593
+ ps,
594
+ ),
595
+ ).start()
596
+ while 1:
597
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
598
+ yield (f.read())
599
+ sleep(1)
600
+ if done[0] == True:
601
+ break
602
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
603
+ log = f.read()
604
+ print(log)
605
+ yield log
606
+
607
+
608
+ def change_sr2(sr2, if_f0_3, version19):
609
+ path_str = "" if version19 == "v1" else "_v2"
610
+ f0_str = "f0" if if_f0_3 else ""
611
+ if_pretrained_generator_exist = os.access("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK)
612
+ if_pretrained_discriminator_exist = os.access("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK)
613
+ if (if_pretrained_generator_exist == False):
614
+ print("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), "not exist, will not use pretrained model")
615
+ if (if_pretrained_discriminator_exist == False):
616
+ print("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), "not exist, will not use pretrained model")
617
+ return (
618
+ ("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)) if if_pretrained_generator_exist else "",
619
+ ("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)) if if_pretrained_discriminator_exist else "",
620
+ {"visible": True, "__type__": "update"}
621
+ )
622
+
623
+ def change_version19(sr2, if_f0_3, version19):
624
+ path_str = "" if version19 == "v1" else "_v2"
625
+ f0_str = "f0" if if_f0_3 else ""
626
+ if_pretrained_generator_exist = os.access("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK)
627
+ if_pretrained_discriminator_exist = os.access("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK)
628
+ if (if_pretrained_generator_exist == False):
629
+ print("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), "not exist, will not use pretrained model")
630
+ if (if_pretrained_discriminator_exist == False):
631
+ print("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), "not exist, will not use pretrained model")
632
+ return (
633
+ ("pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)) if if_pretrained_generator_exist else "",
634
+ ("pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)) if if_pretrained_discriminator_exist else "",
635
+ )
636
+
637
+
638
+ def change_f0(if_f0_3, sr2, version19): # f0method8,pretrained_G14,pretrained_D15
639
+ path_str = "" if version19 == "v1" else "_v2"
640
+ if_pretrained_generator_exist = os.access("pretrained%s/f0G%s.pth" % (path_str, sr2), os.F_OK)
641
+ if_pretrained_discriminator_exist = os.access("pretrained%s/f0D%s.pth" % (path_str, sr2), os.F_OK)
642
+ if (if_pretrained_generator_exist == False):
643
+ print("pretrained%s/f0G%s.pth" % (path_str, sr2), "not exist, will not use pretrained model")
644
+ if (if_pretrained_discriminator_exist == False):
645
+ print("pretrained%s/f0D%s.pth" % (path_str, sr2), "not exist, will not use pretrained model")
646
+ if if_f0_3:
647
+ return (
648
+ {"visible": True, "__type__": "update"},
649
+ "pretrained%s/f0G%s.pth" % (path_str, sr2) if if_pretrained_generator_exist else "",
650
+ "pretrained%s/f0D%s.pth" % (path_str, sr2) if if_pretrained_discriminator_exist else "",
651
+ )
652
+ return (
653
+ {"visible": False, "__type__": "update"},
654
+ ("pretrained%s/G%s.pth" % (path_str, sr2)) if if_pretrained_generator_exist else "",
655
+ ("pretrained%s/D%s.pth" % (path_str, sr2)) if if_pretrained_discriminator_exist else "",
656
+ )
657
+
658
+
659
+ # but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])
660
+ def click_train(
661
+ exp_dir1,
662
+ sr2,
663
+ if_f0_3,
664
+ spk_id5,
665
+ save_epoch10,
666
+ total_epoch11,
667
+ batch_size12,
668
+ if_save_latest13,
669
+ pretrained_G14,
670
+ pretrained_D15,
671
+ gpus16,
672
+ if_cache_gpu17,
673
+ if_save_every_weights18,
674
+ version19,
675
+ ):
676
+ # 生成filelist
677
+ exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
678
+ os.makedirs(exp_dir, exist_ok=True)
679
+ gt_wavs_dir = "%s/0_gt_wavs" % (exp_dir)
680
+ feature_dir = (
681
+ "%s/3_feature256" % (exp_dir)
682
+ if version19 == "v1"
683
+ else "%s/3_feature768" % (exp_dir)
684
+ )
685
+ if if_f0_3:
686
+ f0_dir = "%s/2a_f0" % (exp_dir)
687
+ f0nsf_dir = "%s/2b-f0nsf" % (exp_dir)
688
+ names = (
689
+ set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
690
+ & set([name.split(".")[0] for name in os.listdir(feature_dir)])
691
+ & set([name.split(".")[0] for name in os.listdir(f0_dir)])
692
+ & set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
693
+ )
694
+ else:
695
+ names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
696
+ [name.split(".")[0] for name in os.listdir(feature_dir)]
697
+ )
698
+ opt = []
699
+ for name in names:
700
+ if if_f0_3:
701
+ opt.append(
702
+ "%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
703
+ % (
704
+ gt_wavs_dir.replace("\\", "\\\\"),
705
+ name,
706
+ feature_dir.replace("\\", "\\\\"),
707
+ name,
708
+ f0_dir.replace("\\", "\\\\"),
709
+ name,
710
+ f0nsf_dir.replace("\\", "\\\\"),
711
+ name,
712
+ spk_id5,
713
+ )
714
+ )
715
+ else:
716
+ opt.append(
717
+ "%s/%s.wav|%s/%s.npy|%s"
718
+ % (
719
+ gt_wavs_dir.replace("\\", "\\\\"),
720
+ name,
721
+ feature_dir.replace("\\", "\\\\"),
722
+ name,
723
+ spk_id5,
724
+ )
725
+ )
726
+ fea_dim = 256 if version19 == "v1" else 768
727
+ if if_f0_3:
728
+ for _ in range(2):
729
+ opt.append(
730
+ "%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"
731
+ % (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
732
+ )
733
+ else:
734
+ for _ in range(2):
735
+ opt.append(
736
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
737
+ % (now_dir, sr2, now_dir, fea_dim, spk_id5)
738
+ )
739
+ shuffle(opt)
740
+ with open("%s/filelist.txt" % exp_dir, "w") as f:
741
+ f.write("\n".join(opt))
742
+ print("write filelist done")
743
+ # 生成config#无需生成config
744
+ # 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"
745
+ print("use gpus:", gpus16)
746
+ if pretrained_G14 == "":
747
+ print("no pretrained Generator")
748
+ if pretrained_D15 == "":
749
+ print("no pretrained Discriminator")
750
+ if gpus16:
751
+ cmd = (
752
+ config.python_cmd
753
+ + " train_nsf_sim_cache_sid_load_pretrain.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"
754
+ % (
755
+ exp_dir1,
756
+ sr2,
757
+ 1 if if_f0_3 else 0,
758
+ batch_size12,
759
+ gpus16,
760
+ total_epoch11,
761
+ save_epoch10,
762
+ ("-pg %s" % pretrained_G14) if pretrained_G14 != "" else "",
763
+ ("-pd %s" % pretrained_D15) if pretrained_D15 != "" else "",
764
+ 1 if if_save_latest13 == i18n("是") else 0,
765
+ 1 if if_cache_gpu17 == i18n("是") else 0,
766
+ 1 if if_save_every_weights18 == i18n("是") else 0,
767
+ version19,
768
+ )
769
+ )
770
+ else:
771
+ cmd = (
772
+ config.python_cmd
773
+ + " train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s"
774
+ % (
775
+ exp_dir1,
776
+ sr2,
777
+ 1 if if_f0_3 else 0,
778
+ batch_size12,
779
+ total_epoch11,
780
+ save_epoch10,
781
+ ("-pg %s" % pretrained_G14) if pretrained_G14 != "" else "\b",
782
+ ("-pd %s" % pretrained_D15) if pretrained_D15 != "" else "\b",
783
+ 1 if if_save_latest13 == i18n("是") else 0,
784
+ 1 if if_cache_gpu17 == i18n("是") else 0,
785
+ 1 if if_save_every_weights18 == i18n("是") else 0,
786
+ version19,
787
+ )
788
+ )
789
+ print(cmd)
790
+ p = Popen(cmd, shell=True, cwd=now_dir)
791
+ p.wait()
792
+ return "训练结束, 您可查看控制台训练日志或实验文件夹下的train.log"
793
+
794
+
795
+ # but4.click(train_index, [exp_dir1], info3)
796
+ def train_index(exp_dir1, version19):
797
+ exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
798
+ os.makedirs(exp_dir, exist_ok=True)
799
+ feature_dir = (
800
+ "%s/3_feature256" % (exp_dir)
801
+ if version19 == "v1"
802
+ else "%s/3_feature768" % (exp_dir)
803
+ )
804
+ if os.path.exists(feature_dir) == False:
805
+ return "请先进行特征提取!"
806
+ listdir_res = list(os.listdir(feature_dir))
807
+ if len(listdir_res) == 0:
808
+ return "请先进行特征提取!"
809
+ npys = []
810
+ for name in sorted(listdir_res):
811
+ phone = np.load("%s/%s" % (feature_dir, name))
812
+ npys.append(phone)
813
+ big_npy = np.concatenate(npys, 0)
814
+ big_npy_idx = np.arange(big_npy.shape[0])
815
+ np.random.shuffle(big_npy_idx)
816
+ big_npy = big_npy[big_npy_idx]
817
+ np.save("%s/total_fea.npy" % exp_dir, big_npy)
818
+ # n_ivf = big_npy.shape[0] // 39
819
+ n_ivf = min(int(16 * np.sqrt(big_npy.shape[0])), big_npy.shape[0] // 39)
820
+ infos = []
821
+ infos.append("%s,%s" % (big_npy.shape, n_ivf))
822
+ yield "\n".join(infos)
823
+ index = faiss.index_factory(256 if version19 == "v1" else 768, "IVF%s,Flat" % n_ivf)
824
+ # index = faiss.index_factory(256if version19=="v1"else 768, "IVF%s,PQ128x4fs,RFlat"%n_ivf)
825
+ infos.append("training")
826
+ yield "\n".join(infos)
827
+ index_ivf = faiss.extract_index_ivf(index) #
828
+ index_ivf.nprobe = 1
829
+ index.train(big_npy)
830
+ faiss.write_index(
831
+ index,
832
+ "%s/trained_IVF%s_Flat_nprobe_%s_%s_%s.index"
833
+ % (exp_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
834
+ )
835
+ # faiss.write_index(index, '%s/trained_IVF%s_Flat_FastScan_%s.index'%(exp_dir,n_ivf,version19))
836
+ infos.append("adding")
837
+ yield "\n".join(infos)
838
+ batch_size_add = 8192
839
+ for i in range(0, big_npy.shape[0], batch_size_add):
840
+ index.add(big_npy[i : i + batch_size_add])
841
+ faiss.write_index(
842
+ index,
843
+ "%s/added_IVF%s_Flat_nprobe_%s_%s_%s.index"
844
+ % (exp_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
845
+ )
846
+ infos.append(
847
+ "成功构建索引,added_IVF%s_Flat_nprobe_%s_%s_%s.index"
848
+ % (n_ivf, index_ivf.nprobe, exp_dir1, version19)
849
+ )
850
+ # faiss.write_index(index, '%s/added_IVF%s_Flat_FastScan_%s.index'%(exp_dir,n_ivf,version19))
851
+ # infos.append("成功构建索引,added_IVF%s_Flat_FastScan_%s.index"%(n_ivf,version19))
852
+ yield "\n".join(infos)
853
+
854
+
855
+ # 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)
856
+ def train1key(
857
+ exp_dir1,
858
+ sr2,
859
+ if_f0_3,
860
+ trainset_dir4,
861
+ spk_id5,
862
+ np7,
863
+ f0method8,
864
+ save_epoch10,
865
+ total_epoch11,
866
+ batch_size12,
867
+ if_save_latest13,
868
+ pretrained_G14,
869
+ pretrained_D15,
870
+ gpus16,
871
+ if_cache_gpu17,
872
+ if_save_every_weights18,
873
+ version19,
874
+ echl
875
+ ):
876
+ infos = []
877
+
878
+ def get_info_str(strr):
879
+ infos.append(strr)
880
+ return "\n".join(infos)
881
+
882
+ model_log_dir = "%s/logs/%s" % (now_dir, exp_dir1)
883
+ preprocess_log_path = "%s/preprocess.log" % model_log_dir
884
+ extract_f0_feature_log_path = "%s/extract_f0_feature.log" % model_log_dir
885
+ gt_wavs_dir = "%s/0_gt_wavs" % model_log_dir
886
+ feature_dir = (
887
+ "%s/3_feature256" % model_log_dir
888
+ if version19 == "v1"
889
+ else "%s/3_feature768" % model_log_dir
890
+ )
891
+
892
+ os.makedirs(model_log_dir, exist_ok=True)
893
+ #########step1:处理数据
894
+ open(preprocess_log_path, "w").close()
895
+ cmd = (
896
+ config.python_cmd
897
+ + " trainset_preprocess_pipeline_print.py %s %s %s %s "
898
+ % (trainset_dir4, sr_dict[sr2], np7, model_log_dir)
899
+ + str(config.noparallel)
900
+ )
901
+ yield get_info_str(i18n("step1:正在处理数据"))
902
+ yield get_info_str(cmd)
903
+ p = Popen(cmd, shell=True)
904
+ p.wait()
905
+ with open(preprocess_log_path, "r") as f:
906
+ print(f.read())
907
+ #########step2a:提取音高
908
+ open(extract_f0_feature_log_path, "w")
909
+ if if_f0_3:
910
+ yield get_info_str("step2a:正在提取音高")
911
+ cmd = config.python_cmd + " extract_f0_print.py %s %s %s %s" % (
912
+ model_log_dir,
913
+ np7,
914
+ f0method8,
915
+ echl
916
+ )
917
+ yield get_info_str(cmd)
918
+ p = Popen(cmd, shell=True, cwd=now_dir)
919
+ p.wait()
920
+ with open(extract_f0_feature_log_path, "r") as f:
921
+ print(f.read())
922
+ else:
923
+ yield get_info_str(i18n("step2a:无需提取音高"))
924
+ #######step2b:提取特征
925
+ yield get_info_str(i18n("step2b:正在提取特征"))
926
+ gpus = gpus16.split("-")
927
+ leng = len(gpus)
928
+ ps = []
929
+ for idx, n_g in enumerate(gpus):
930
+ cmd = config.python_cmd + " extract_feature_print.py %s %s %s %s %s %s" % (
931
+ config.device,
932
+ leng,
933
+ idx,
934
+ n_g,
935
+ model_log_dir,
936
+ version19,
937
+ )
938
+ yield get_info_str(cmd)
939
+ p = Popen(
940
+ cmd, shell=True, cwd=now_dir
941
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
942
+ ps.append(p)
943
+ for p in ps:
944
+ p.wait()
945
+ with open(extract_f0_feature_log_path, "r") as f:
946
+ print(f.read())
947
+ #######step3a:训练模型
948
+ yield get_info_str(i18n("step3a:正在训练模型"))
949
+ # 生成filelist
950
+ if if_f0_3:
951
+ f0_dir = "%s/2a_f0" % model_log_dir
952
+ f0nsf_dir = "%s/2b-f0nsf" % model_log_dir
953
+ names = (
954
+ set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
955
+ & set([name.split(".")[0] for name in os.listdir(feature_dir)])
956
+ & set([name.split(".")[0] for name in os.listdir(f0_dir)])
957
+ & set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
958
+ )
959
+ else:
960
+ names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
961
+ [name.split(".")[0] for name in os.listdir(feature_dir)]
962
+ )
963
+ opt = []
964
+ for name in names:
965
+ if if_f0_3:
966
+ opt.append(
967
+ "%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
968
+ % (
969
+ gt_wavs_dir.replace("\\", "\\\\"),
970
+ name,
971
+ feature_dir.replace("\\", "\\\\"),
972
+ name,
973
+ f0_dir.replace("\\", "\\\\"),
974
+ name,
975
+ f0nsf_dir.replace("\\", "\\\\"),
976
+ name,
977
+ spk_id5,
978
+ )
979
+ )
980
+ else:
981
+ opt.append(
982
+ "%s/%s.wav|%s/%s.npy|%s"
983
+ % (
984
+ gt_wavs_dir.replace("\\", "\\\\"),
985
+ name,
986
+ feature_dir.replace("\\", "\\\\"),
987
+ name,
988
+ spk_id5,
989
+ )
990
+ )
991
+ fea_dim = 256 if version19 == "v1" else 768
992
+ if if_f0_3:
993
+ for _ in range(2):
994
+ opt.append(
995
+ "%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"
996
+ % (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
997
+ )
998
+ else:
999
+ for _ in range(2):
1000
+ opt.append(
1001
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
1002
+ % (now_dir, sr2, now_dir, fea_dim, spk_id5)
1003
+ )
1004
+ shuffle(opt)
1005
+ with open("%s/filelist.txt" % model_log_dir, "w") as f:
1006
+ f.write("\n".join(opt))
1007
+ yield get_info_str("write filelist done")
1008
+ if gpus16:
1009
+ cmd = (
1010
+ config.python_cmd
1011
+ +" train_nsf_sim_cache_sid_load_pretrain.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"
1012
+ % (
1013
+ exp_dir1,
1014
+ sr2,
1015
+ 1 if if_f0_3 else 0,
1016
+ batch_size12,
1017
+ gpus16,
1018
+ total_epoch11,
1019
+ save_epoch10,
1020
+ ("-pg %s" % pretrained_G14) if pretrained_G14 != "" else "",
1021
+ ("-pd %s" % pretrained_D15) if pretrained_D15 != "" else "",
1022
+ 1 if if_save_latest13 == i18n("是") else 0,
1023
+ 1 if if_cache_gpu17 == i18n("是") else 0,
1024
+ 1 if if_save_every_weights18 == i18n("是") else 0,
1025
+ version19,
1026
+ )
1027
+ )
1028
+ else:
1029
+ cmd = (
1030
+ config.python_cmd
1031
+ + " train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s"
1032
+ % (
1033
+ exp_dir1,
1034
+ sr2,
1035
+ 1 if if_f0_3 else 0,
1036
+ batch_size12,
1037
+ total_epoch11,
1038
+ save_epoch10,
1039
+ ("-pg %s" % pretrained_G14) if pretrained_G14 != "" else "",
1040
+ ("-pd %s" % pretrained_D15) if pretrained_D15 != "" else "",
1041
+ 1 if if_save_latest13 == i18n("是") else 0,
1042
+ 1 if if_cache_gpu17 == i18n("是") else 0,
1043
+ 1 if if_save_every_weights18 == i18n("是") else 0,
1044
+ version19,
1045
+ )
1046
+ )
1047
+ yield get_info_str(cmd)
1048
+ p = Popen(cmd, shell=True, cwd=now_dir)
1049
+ p.wait()
1050
+ yield get_info_str(i18n("训练结束, 您可查看控制台训练日志或实验文件夹下的train.log"))
1051
+ #######step3b:训练索引
1052
+ npys = []
1053
+ listdir_res = list(os.listdir(feature_dir))
1054
+ for name in sorted(listdir_res):
1055
+ phone = np.load("%s/%s" % (feature_dir, name))
1056
+ npys.append(phone)
1057
+ big_npy = np.concatenate(npys, 0)
1058
+
1059
+ big_npy_idx = np.arange(big_npy.shape[0])
1060
+ np.random.shuffle(big_npy_idx)
1061
+ big_npy = big_npy[big_npy_idx]
1062
+ np.save("%s/total_fea.npy" % model_log_dir, big_npy)
1063
+
1064
+ # n_ivf = big_npy.shape[0] // 39
1065
+ n_ivf = min(int(16 * np.sqrt(big_npy.shape[0])), big_npy.shape[0] // 39)
1066
+ yield get_info_str("%s,%s" % (big_npy.shape, n_ivf))
1067
+ index = faiss.index_factory(256 if version19 == "v1" else 768, "IVF%s,Flat" % n_ivf)
1068
+ yield get_info_str("training index")
1069
+ index_ivf = faiss.extract_index_ivf(index) #
1070
+ index_ivf.nprobe = 1
1071
+ index.train(big_npy)
1072
+ faiss.write_index(
1073
+ index,
1074
+ "%s/trained_IVF%s_Flat_nprobe_%s_%s_%s.index"
1075
+ % (model_log_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
1076
+ )
1077
+ yield get_info_str("adding index")
1078
+ batch_size_add = 8192
1079
+ for i in range(0, big_npy.shape[0], batch_size_add):
1080
+ index.add(big_npy[i : i + batch_size_add])
1081
+ faiss.write_index(
1082
+ index,
1083
+ "%s/added_IVF%s_Flat_nprobe_%s_%s_%s.index"
1084
+ % (model_log_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
1085
+ )
1086
+ yield get_info_str(
1087
+ "成功构建索引, added_IVF%s_Flat_nprobe_%s_%s_%s.index"
1088
+ % (n_ivf, index_ivf.nprobe, exp_dir1, version19)
1089
+ )
1090
+ yield get_info_str(i18n("全流程结束!"))
1091
+
1092
+
1093
+ # ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])
1094
+ def change_info_(ckpt_path):
1095
+ if (
1096
+ os.path.exists(ckpt_path.replace(os.path.basename(ckpt_path), "train.log"))
1097
+ == False
1098
+ ):
1099
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
1100
+ try:
1101
+ with open(
1102
+ ckpt_path.replace(os.path.basename(ckpt_path), "train.log"), "r"
1103
+ ) as f:
1104
+ info = eval(f.read().strip("\n").split("\n")[0].split("\t")[-1])
1105
+ sr, f0 = info["sample_rate"], info["if_f0"]
1106
+ version = "v2" if ("version" in info and info["version"] == "v2") else "v1"
1107
+ return sr, str(f0), version
1108
+ except:
1109
+ traceback.print_exc()
1110
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
1111
+
1112
+
1113
+ from lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM
1114
+
1115
+
1116
+ def export_onnx(ModelPath, ExportedPath, MoeVS=True):
1117
+ cpt = torch.load(ModelPath, map_location="cpu")
1118
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
1119
+ hidden_channels = 256 if cpt.get("version","v1")=="v1"else 768#cpt["config"][-2] # hidden_channels,为768Vec做准备
1120
+
1121
+ test_phone = torch.rand(1, 200, hidden_channels) # hidden unit
1122
+ test_phone_lengths = torch.tensor([200]).long() # hidden unit 长度(貌似没啥用)
1123
+ test_pitch = torch.randint(size=(1, 200), low=5, high=255) # 基频(单位赫兹)
1124
+ test_pitchf = torch.rand(1, 200) # nsf基频
1125
+ test_ds = torch.LongTensor([0]) # 说话人ID
1126
+ test_rnd = torch.rand(1, 192, 200) # 噪声(加入随机因子)
1127
+
1128
+ device = "cpu" # 导出时设备(不影响使用模型)
1129
+
1130
+
1131
+ net_g = SynthesizerTrnMsNSFsidM(
1132
+ *cpt["config"], is_half=False,version=cpt.get("version","v1")
1133
+ ) # fp32导出(C++要支持fp16必须手动将内存重新排列所以暂时不用fp16)
1134
+ net_g.load_state_dict(cpt["weight"], strict=False)
1135
+ input_names = ["phone", "phone_lengths", "pitch", "pitchf", "ds", "rnd"]
1136
+ output_names = [
1137
+ "audio",
1138
+ ]
1139
+ # net_g.construct_spkmixmap(n_speaker) 多角色混合轨道导出
1140
+ torch.onnx.export(
1141
+ net_g,
1142
+ (
1143
+ test_phone.to(device),
1144
+ test_phone_lengths.to(device),
1145
+ test_pitch.to(device),
1146
+ test_pitchf.to(device),
1147
+ test_ds.to(device),
1148
+ test_rnd.to(device),
1149
+ ),
1150
+ ExportedPath,
1151
+ dynamic_axes={
1152
+ "phone": [1],
1153
+ "pitch": [1],
1154
+ "pitchf": [1],
1155
+ "rnd": [2],
1156
+ },
1157
+ do_constant_folding=False,
1158
+ opset_version=16,
1159
+ verbose=False,
1160
+ input_names=input_names,
1161
+ output_names=output_names,
1162
+ )
1163
+ return "Finished"
1164
+
1165
+
1166
+ #region Mangio-RVC-Fork CLI App
1167
+ import re as regex
1168
+ import scipy.io.wavfile as wavfile
1169
+
1170
+ cli_current_page = "HOME"
1171
+
1172
+ def cli_split_command(com):
1173
+ exp = r'(?:(?<=\s)|^)"(.*?)"(?=\s|$)|(\S+)'
1174
+ split_array = regex.findall(exp, com)
1175
+ split_array = [group[0] if group[0] else group[1] for group in split_array]
1176
+ return split_array
1177
+
1178
+ def execute_generator_function(genObject):
1179
+ for _ in genObject: pass
1180
+
1181
+ def cli_infer(com):
1182
+ # get VC first
1183
+ com = cli_split_command(com)
1184
+ model_name = com[0]
1185
+ source_audio_path = com[1]
1186
+ output_file_name = com[2]
1187
+ feature_index_path = com[3]
1188
+ f0_file = None # Not Implemented Yet
1189
+
1190
+ # Get parameters for inference
1191
+ speaker_id = int(com[4])
1192
+ transposition = float(com[5])
1193
+ f0_method = com[6]
1194
+ crepe_hop_length = int(com[7])
1195
+ harvest_median_filter = int(com[8])
1196
+ resample = int(com[9])
1197
+ mix = float(com[10])
1198
+ feature_ratio = float(com[11])
1199
+ protection_amnt = float(com[12])
1200
+
1201
+ print("Mangio-RVC-Fork Infer-CLI: Starting the inference...")
1202
+ vc_data = get_vc(model_name)
1203
+ print(vc_data)
1204
+ print("Mangio-RVC-Fork Infer-CLI: Performing inference...")
1205
+ conversion_data = vc_single(
1206
+ speaker_id,
1207
+ source_audio_path,
1208
+ transposition,
1209
+ f0_file,
1210
+ f0_method,
1211
+ feature_index_path,
1212
+ #feature_index_path,
1213
+ feature_ratio,
1214
+ harvest_median_filter,
1215
+ resample,
1216
+ mix,
1217
+ protection_amnt,
1218
+ crepe_hop_length,
1219
+ )
1220
+ if "Success." in conversion_data[0]:
1221
+ print("Mangio-RVC-Fork Infer-CLI: Inference succeeded. Writing to %s/%s..." % ('audio-outputs', output_file_name))
1222
+ wavfile.write('%s/%s' % ('audio-outputs', output_file_name), conversion_data[1][0], conversion_data[1][1])
1223
+ print("Mangio-RVC-Fork Infer-CLI: Finished! Saved output to %s/%s" % ('audio-outputs', output_file_name))
1224
+ else:
1225
+ print("Mangio-RVC-Fork Infer-CLI: Inference failed. Here's the traceback: ")
1226
+ print(conversion_data[0])
1227
+
1228
+ def cli_pre_process(com):
1229
+ com = cli_split_command(com)
1230
+ model_name = com[0]
1231
+ trainset_directory = com[1]
1232
+ sample_rate = com[2]
1233
+ num_processes = int(com[3])
1234
+
1235
+ print("Mangio-RVC-Fork Pre-process: Starting...")
1236
+ generator = preprocess_dataset(
1237
+ trainset_directory,
1238
+ model_name,
1239
+ sample_rate,
1240
+ num_processes
1241
+ )
1242
+ execute_generator_function(generator)
1243
+ print("Mangio-RVC-Fork Pre-process: Finished")
1244
+
1245
+ def cli_extract_feature(com):
1246
+ com = cli_split_command(com)
1247
+ model_name = com[0]
1248
+ gpus = com[1]
1249
+ num_processes = int(com[2])
1250
+ has_pitch_guidance = True if (int(com[3]) == 1) else False
1251
+ f0_method = com[4]
1252
+ crepe_hop_length = int(com[5])
1253
+ version = com[6] # v1 or v2
1254
+
1255
+ print("Mangio-RVC-CLI: Extract Feature Has Pitch: " + str(has_pitch_guidance))
1256
+ print("Mangio-RVC-CLI: Extract Feature Version: " + str(version))
1257
+ print("Mangio-RVC-Fork Feature Extraction: Starting...")
1258
+ generator = extract_f0_feature(
1259
+ gpus,
1260
+ num_processes,
1261
+ f0_method,
1262
+ has_pitch_guidance,
1263
+ model_name,
1264
+ version,
1265
+ crepe_hop_length
1266
+ )
1267
+ execute_generator_function(generator)
1268
+ print("Mangio-RVC-Fork Feature Extraction: Finished")
1269
+
1270
+ def cli_train(com):
1271
+ com = cli_split_command(com)
1272
+ model_name = com[0]
1273
+ sample_rate = com[1]
1274
+ has_pitch_guidance = True if (int(com[2]) == 1) else False
1275
+ speaker_id = int(com[3])
1276
+ save_epoch_iteration = int(com[4])
1277
+ total_epoch = int(com[5]) # 10000
1278
+ batch_size = int(com[6])
1279
+ gpu_card_slot_numbers = com[7]
1280
+ if_save_latest = i18n("是") if (int(com[8]) == 1) else i18n("否")
1281
+ if_cache_gpu = i18n("是") if (int(com[9]) == 1) else i18n("否")
1282
+ if_save_every_weight = i18n("是") if (int(com[10]) == 1) else i18n("否")
1283
+ version = com[11]
1284
+
1285
+ pretrained_base = "pretrained/" if version == "v1" else "pretrained_v2/"
1286
+
1287
+ g_pretrained_path = "%sf0G%s.pth" % (pretrained_base, sample_rate)
1288
+ d_pretrained_path = "%sf0D%s.pth" % (pretrained_base, sample_rate)
1289
+
1290
+ print("Mangio-RVC-Fork Train-CLI: Training...")
1291
+ click_train(
1292
+ model_name,
1293
+ sample_rate,
1294
+ has_pitch_guidance,
1295
+ speaker_id,
1296
+ save_epoch_iteration,
1297
+ total_epoch,
1298
+ batch_size,
1299
+ if_save_latest,
1300
+ g_pretrained_path,
1301
+ d_pretrained_path,
1302
+ gpu_card_slot_numbers,
1303
+ if_cache_gpu,
1304
+ if_save_every_weight,
1305
+ version
1306
+ )
1307
+
1308
+ def cli_train_feature(com):
1309
+ com = cli_split_command(com)
1310
+ model_name = com[0]
1311
+ version = com[1]
1312
+ print("Mangio-RVC-Fork Train Feature Index-CLI: Training... Please wait")
1313
+ generator = train_index(
1314
+ model_name,
1315
+ version
1316
+ )
1317
+ execute_generator_function(generator)
1318
+ print("Mangio-RVC-Fork Train Feature Index-CLI: Done!")
1319
+
1320
+ def cli_extract_model(com):
1321
+ com = cli_split_command(com)
1322
+ model_path = com[0]
1323
+ save_name = com[1]
1324
+ sample_rate = com[2]
1325
+ has_pitch_guidance = com[3]
1326
+ info = com[4]
1327
+ version = com[5]
1328
+ extract_small_model_process = extract_small_model(
1329
+ model_path,
1330
+ save_name,
1331
+ sample_rate,
1332
+ has_pitch_guidance,
1333
+ info,
1334
+ version
1335
+ )
1336
+ if extract_small_model_process == "Success.":
1337
+ print("Mangio-RVC-Fork Extract Small Model: Success!")
1338
+ else:
1339
+ print(str(extract_small_model_process))
1340
+ print("Mangio-RVC-Fork Extract Small Model: Failed!")
1341
+
1342
+ def print_page_details():
1343
+ if cli_current_page == "HOME":
1344
+ print(" go home : Takes you back to home with a navigation list.")
1345
+ print(" go infer : Takes you to inference command execution.\n")
1346
+ print(" go pre-process : Takes you to training step.1) pre-process command execution.")
1347
+ print(" go extract-feature : Takes you to training step.2) extract-feature command execution.")
1348
+ print(" go train : Takes you to training step.3) being or continue training command execution.")
1349
+ print(" go train-feature : Takes you to the train feature index command execution.\n")
1350
+ print(" go extract-model : Takes you to the extract small model command execution.")
1351
+ elif cli_current_page == "INFER":
1352
+ print(" arg 1) model name with .pth in ./weights: mi-test.pth")
1353
+ print(" arg 2) source audio path: myFolder\\MySource.wav")
1354
+ print(" arg 3) output file name to be placed in './audio-outputs': MyTest.wav")
1355
+ print(" arg 4) feature index file path: logs/mi-test/added_IVF3042_Flat_nprobe_1.index")
1356
+ print(" arg 5) speaker id: 0")
1357
+ print(" arg 6) transposition: 0")
1358
+ print(" arg 7) f0 method: harvest (pm, harvest, crepe, crepe-tiny, hybrid[x,x,x,x], mangio-crepe, mangio-crepe-tiny)")
1359
+ print(" arg 8) crepe hop length: 160")
1360
+ print(" arg 9) harvest median filter radius: 3 (0-7)")
1361
+ print(" arg 10) post resample rate: 0")
1362
+ print(" arg 11) mix volume envelope: 1")
1363
+ print(" arg 12) feature index ratio: 0.78 (0-1)")
1364
+ print(" arg 13) Voiceless Consonant Protection (Less Artifact): 0.33 (Smaller number = more protection. 0.50 means Dont Use.) \n")
1365
+ print("Example: mi-test.pth saudio/Sidney.wav myTest.wav logs/mi-test/added_index.index 0 -2 harvest 160 3 0 1 0.95 0.33")
1366
+ elif cli_current_page == "PRE-PROCESS":
1367
+ print(" arg 1) Model folder name in ./logs: mi-test")
1368
+ print(" arg 2) Trainset directory: mydataset (or) E:\\my-data-set")
1369
+ print(" arg 3) Sample rate: 40k (32k, 40k, 48k)")
1370
+ print(" arg 4) Number of CPU threads to use: 8 \n")
1371
+ print("Example: mi-test mydataset 40k 24")
1372
+ elif cli_current_page == "EXTRACT-FEATURE":
1373
+ print(" arg 1) Model folder name in ./logs: mi-test")
1374
+ print(" arg 2) Gpu card slot: 0 (0-1-2 if using 3 GPUs)")
1375
+ print(" arg 3) Number of CPU threads to use: 8")
1376
+ print(" arg 4) Has Pitch Guidance?: 1 (0 for no, 1 for yes)")
1377
+ print(" arg 5) f0 Method: harvest (pm, harvest, dio, crepe)")
1378
+ print(" arg 6) Crepe hop length: 128")
1379
+ print(" arg 7) Version for pre-trained models: v2 (use either v1 or v2)\n")
1380
+ print("Example: mi-test 0 24 1 harvest 128 v2")
1381
+ elif cli_current_page == "TRAIN":
1382
+ print(" arg 1) Model folder name in ./logs: mi-test")
1383
+ print(" arg 2) Sample rate: 40k (32k, 40k, 48k)")
1384
+ print(" arg 3) Has Pitch Guidance?: 1 (0 for no, 1 for yes)")
1385
+ print(" arg 4) speaker id: 0")
1386
+ print(" arg 5) Save epoch iteration: 50")
1387
+ print(" arg 6) Total epochs: 10000")
1388
+ print(" arg 7) Batch size: 8")
1389
+ print(" arg 8) Gpu card slot: 0 (0-1-2 if using 3 GPUs)")
1390
+ print(" arg 9) Save only the latest checkpoint: 0 (0 for no, 1 for yes)")
1391
+ print(" arg 10) Whether to cache training set to vram: 0 (0 for no, 1 for yes)")
1392
+ print(" arg 11) Save extracted small model every generation?: 0 (0 for no, 1 for yes)")
1393
+ print(" arg 12) Model architecture version: v2 (use either v1 or v2)\n")
1394
+ print("Example: mi-test 40k 1 0 50 10000 8 0 0 0 0 v2")
1395
+ elif cli_current_page == "TRAIN-FEATURE":
1396
+ print(" arg 1) Model folder name in ./logs: mi-test")
1397
+ print(" arg 2) Model architecture version: v2 (use either v1 or v2)\n")
1398
+ print("Example: mi-test v2")
1399
+ elif cli_current_page == "EXTRACT-MODEL":
1400
+ print(" arg 1) Model Path: logs/mi-test/G_168000.pth")
1401
+ print(" arg 2) Model save name: MyModel")
1402
+ print(" arg 3) Sample rate: 40k (32k, 40k, 48k)")
1403
+ print(" arg 4) Has Pitch Guidance?: 1 (0 for no, 1 for yes)")
1404
+ print(' arg 5) Model information: "My Model"')
1405
+ print(" arg 6) Model architecture version: v2 (use either v1 or v2)\n")
1406
+ print('Example: logs/mi-test/G_168000.pth MyModel 40k 1 "Created by Cole Mangio" v2')
1407
+ print("")
1408
+
1409
+ def change_page(page):
1410
+ global cli_current_page
1411
+ cli_current_page = page
1412
+ return 0
1413
+
1414
+ def execute_command(com):
1415
+ if com == "go home":
1416
+ return change_page("HOME")
1417
+ elif com == "go infer":
1418
+ return change_page("INFER")
1419
+ elif com == "go pre-process":
1420
+ return change_page("PRE-PROCESS")
1421
+ elif com == "go extract-feature":
1422
+ return change_page("EXTRACT-FEATURE")
1423
+ elif com == "go train":
1424
+ return change_page("TRAIN")
1425
+ elif com == "go train-feature":
1426
+ return change_page("TRAIN-FEATURE")
1427
+ elif com == "go extract-model":
1428
+ return change_page("EXTRACT-MODEL")
1429
+ else:
1430
+ if com[:3] == "go ":
1431
+ print("page '%s' does not exist!" % com[3:])
1432
+ return 0
1433
+
1434
+ if cli_current_page == "INFER":
1435
+ cli_infer(com)
1436
+ elif cli_current_page == "PRE-PROCESS":
1437
+ cli_pre_process(com)
1438
+ elif cli_current_page == "EXTRACT-FEATURE":
1439
+ cli_extract_feature(com)
1440
+ elif cli_current_page == "TRAIN":
1441
+ cli_train(com)
1442
+ elif cli_current_page == "TRAIN-FEATURE":
1443
+ cli_train_feature(com)
1444
+ elif cli_current_page == "EXTRACT-MODEL":
1445
+ cli_extract_model(com)
1446
+
1447
+ def cli_navigation_loop():
1448
+ while True:
1449
+ print("You are currently in '%s':" % cli_current_page)
1450
+ print_page_details()
1451
+ command = input("%s: " % cli_current_page)
1452
+ try:
1453
+ execute_command(command)
1454
+ except:
1455
+ print(traceback.format_exc())
1456
+
1457
+ if(config.is_cli):
1458
+ print("\n\nMangio-RVC-Fork v2 CLI App!\n")
1459
+ print("Welcome to the CLI version of RVC. Please read the documentation on https://github.com/Mangio621/Mangio-RVC-Fork (README.MD) to understand how to use this app.\n")
1460
+ cli_navigation_loop()
1461
+
1462
+ #endregion
1463
+
1464
+ #region RVC WebUI App
1465
+
1466
+ def get_presets():
1467
+ data = None
1468
+ with open('../inference-presets.json', 'r') as file:
1469
+ data = json.load(file)
1470
+ preset_names = []
1471
+ for preset in data['presets']:
1472
+ preset_names.append(preset['name'])
1473
+
1474
+ return preset_names
1475
+
1476
+ def change_choices2():
1477
+ audio_files=[]
1478
+ for filename in os.listdir("./audios"):
1479
+ if filename.endswith(('.wav','.mp3')):
1480
+ audio_files.append(os.path.join('./audios',filename))
1481
+ return {"choices": sorted(audio_files), "__type__": "update"}, {"__type__": "update"}
1482
+
1483
+ audio_files=[]
1484
+ for filename in os.listdir("./audios"):
1485
+ if filename.endswith(('.wav','.mp3')):
1486
+ audio_files.append(os.path.join('./audios',filename))
1487
+
1488
+ def get_index():
1489
+ if check_for_name() != '':
1490
+ chosen_model=sorted(names)[0].split(".")[0]
1491
+ logs_path="./logs/"+chosen_model
1492
+ if os.path.exists(logs_path):
1493
+ for file in os.listdir(logs_path):
1494
+ if file.endswith(".index"):
1495
+ return os.path.join(logs_path, file)
1496
+ return ''
1497
+ else:
1498
+ return ''
1499
+
1500
+ def get_indexes():
1501
+ indexes_list=[]
1502
+ for dirpath, dirnames, filenames in os.walk("./logs/"):
1503
+ for filename in filenames:
1504
+ if filename.endswith(".index"):
1505
+ indexes_list.append(os.path.join(dirpath,filename))
1506
+ if len(indexes_list) > 0:
1507
+ return indexes_list
1508
+ else:
1509
+ return ''
1510
+
1511
+ def get_name():
1512
+ if len(audio_files) > 0:
1513
+ return sorted(audio_files)[0]
1514
+ else:
1515
+ return ''
1516
+
1517
+ def save_to_wav(record_button):
1518
+ if record_button is None:
1519
+ pass
1520
+ else:
1521
+ path_to_file=record_button
1522
+ new_name = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+'.wav'
1523
+ new_path='./audios/'+new_name
1524
+ shutil.move(path_to_file,new_path)
1525
+ return new_path
1526
+
1527
+ def save_to_wav2(dropbox):
1528
+ file_path=dropbox.name
1529
+ shutil.move(file_path,'./audios')
1530
+ return os.path.join('./audios',os.path.basename(file_path))
1531
+
1532
+ def match_index(sid0):
1533
+ folder=sid0.split(".")[0]
1534
+ parent_dir="./logs/"+folder
1535
+ if os.path.exists(parent_dir):
1536
+ for filename in os.listdir(parent_dir):
1537
+ if filename.endswith(".index"):
1538
+ index_path=os.path.join(parent_dir,filename)
1539
+ return index_path
1540
+ else:
1541
+ return ''
1542
+
1543
+ def check_for_name():
1544
+ if len(names) > 0:
1545
+ return sorted(names)[0]
1546
+ else:
1547
+ return ''
1548
+
1549
+ def download_from_url(url, model):
1550
+ if url == '':
1551
+ return "URL cannot be left empty."
1552
+ if model =='':
1553
+ return "You need to name your model. For example: My-Model"
1554
+ url = url.strip()
1555
+ zip_dirs = ["zips", "unzips"]
1556
+ for directory in zip_dirs:
1557
+ if os.path.exists(directory):
1558
+ shutil.rmtree(directory)
1559
+ os.makedirs("zips", exist_ok=True)
1560
+ os.makedirs("unzips", exist_ok=True)
1561
+ zipfile = model + '.zip'
1562
+ zipfile_path = './zips/' + zipfile
1563
+ try:
1564
+ if "drive.google.com" in url:
1565
+ subprocess.run(["gdown", url, "--fuzzy", "-O", zipfile_path])
1566
+ elif "mega.nz" in url:
1567
+ m = Mega()
1568
+ m.download_url(url, './zips')
1569
+ else:
1570
+ subprocess.run(["wget", url, "-O", zipfile_path])
1571
+ for filename in os.listdir("./zips"):
1572
+ if filename.endswith(".zip"):
1573
+ zipfile_path = os.path.join("./zips/",filename)
1574
+ shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
1575
+ else:
1576
+ return "No zipfile found."
1577
+ for root, dirs, files in os.walk('./unzips'):
1578
+ for file in files:
1579
+ file_path = os.path.join(root, file)
1580
+ if file.endswith(".index"):
1581
+ os.mkdir(f'./logs/{model}')
1582
+ shutil.copy2(file_path,f'./logs/{model}')
1583
+ elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
1584
+ shutil.copy(file_path,f'./weights/{model}.pth')
1585
+ shutil.rmtree("zips")
1586
+ shutil.rmtree("unzips")
1587
+ return "Success."
1588
+ except:
1589
+ return "There's been an error."
1590
+ def success_message(face):
1591
+ return f'{face.name} has been uploaded.', 'None'
1592
+ def mouth(size, face, voice, faces):
1593
+ if size == 'Half':
1594
+ size = 2
1595
+ else:
1596
+ size = 1
1597
+ if faces == 'None':
1598
+ character = face.name
1599
+ else:
1600
+ if faces == 'Ben Shapiro':
1601
+ character = '/content/wav2lip-HD/inputs/ben-shapiro-10.mp4'
1602
+ elif faces == 'Andrew Tate':
1603
+ character = '/content/wav2lip-HD/inputs/tate-7.mp4'
1604
+ command = "python inference.py " \
1605
+ "--checkpoint_path checkpoints/wav2lip.pth " \
1606
+ f"--face {character} " \
1607
+ f"--audio {voice} " \
1608
+ "--pads 0 20 0 0 " \
1609
+ "--outfile /content/wav2lip-HD/outputs/result.mp4 " \
1610
+ "--fps 24 " \
1611
+ f"--resize_factor {size}"
1612
+ process = subprocess.Popen(command, shell=True, cwd='/content/wav2lip-HD/Wav2Lip-master')
1613
+ stdout, stderr = process.communicate()
1614
+ return '/content/wav2lip-HD/outputs/result.mp4', 'Animation completed.'
1615
+ eleven_voices = ['Adam','Antoni','Josh','Arnold','Sam','Bella','Rachel','Domi','Elli']
1616
+ eleven_voices_ids=['pNInz6obpgDQGcFmaJgB','ErXwobaYiN019PkySvjV','TxGEqnHWrfWFTfGW9XjX','VR6AewLTigWG4xSOukaG','yoZ06aMxZJJ28mfd3POQ','EXAVITQu4vr4xnSDxMaL','21m00Tcm4TlvDq8ikWAM','AZnzlk1XvdvUeBnXmlld','MF3mGyEYCl7XYWbV9V6O']
1617
+ chosen_voice = dict(zip(eleven_voices, eleven_voices_ids))
1618
+ def elevenTTS(xiapi, text, id, lang):
1619
+ if xiapi!= '' and id !='':
1620
+ choice = chosen_voice[id]
1621
+ CHUNK_SIZE = 1024
1622
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{choice}"
1623
+ headers = {
1624
+ "Accept": "audio/mpeg",
1625
+ "Content-Type": "application/json",
1626
+ "xi-api-key": xiapi
1627
+ }
1628
+ if lang == 'en':
1629
+ data = {
1630
+ "text": text,
1631
+ "model_id": "eleven_monolingual_v1",
1632
+ "voice_settings": {
1633
+ "stability": 0.5,
1634
+ "similarity_boost": 0.5
1635
+ }
1636
+ }
1637
+ else:
1638
+ data = {
1639
+ "text": text,
1640
+ "model_id": "eleven_multilingual_v1",
1641
+ "voice_settings": {
1642
+ "stability": 0.5,
1643
+ "similarity_boost": 0.5
1644
+ }
1645
+ }
1646
+
1647
+ response = requests.post(url, json=data, headers=headers)
1648
+ with open('./temp_eleven.mp3', 'wb') as f:
1649
+ for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
1650
+ if chunk:
1651
+ f.write(chunk)
1652
+ aud_path = save_to_wav('./temp_eleven.mp3')
1653
+ return aud_path, aud_path
1654
+ else:
1655
+ tts = gTTS(text, lang=lang)
1656
+ tts.save('./temp_gTTS.mp3')
1657
+ aud_path = save_to_wav('./temp_gTTS.mp3')
1658
+ return aud_path, aud_path
1659
+
1660
+ def upload_to_dataset(files, dir):
1661
+ if dir == '':
1662
+ dir = './dataset'
1663
+ if not os.path.exists(dir):
1664
+ os.makedirs(dir)
1665
+ count = 0
1666
+ for file in files:
1667
+ path=file.name
1668
+ shutil.copy2(path,dir)
1669
+ count += 1
1670
+ return f' {count} files uploaded to {dir}.'
1671
+
1672
+ def zip_downloader(model):
1673
+ if not os.path.exists(f'./weights/{model}.pth'):
1674
+ return {"__type__": "update"}, f'Make sure the Voice Name is correct. I could not find {model}.pth'
1675
+ index_found = False
1676
+ for file in os.listdir(f'./logs/{model}'):
1677
+ if file.endswith('.index') and 'added' in file:
1678
+ log_file = file
1679
+ index_found = True
1680
+ if index_found:
1681
+ return [f'./weights/{model}.pth', f'./logs/{model}/{log_file}'], "Done"
1682
+ else:
1683
+ return f'./weights/{model}.pth', "Could not find Index file."
1684
+
1685
+ with gr.Blocks(theme=gr.themes.Base()) as app:
1686
+ with gr.Tabs():
1687
+ with gr.TabItem("Inference"):
1688
+ gr.HTML("<h1> RVC V2 by https://www.youtube.com/@ba1yya 💻 </h1>")
1689
+ # Inference Preset Row
1690
+ # with gr.Row():
1691
+ # mangio_preset = gr.Dropdown(label="Inference Preset", choices=sorted(get_presets()))
1692
+ # mangio_preset_name_save = gr.Textbox(
1693
+ # label="Your preset name"
1694
+ # )
1695
+ # mangio_preset_save_btn = gr.Button('Save Preset', variant="primary")
1696
+
1697
+ # Other RVC stuff
1698
+ with gr.Row():
1699
+ sid0 = gr.Dropdown(label="1.Выберете модель.", choices=sorted(names), value=check_for_name())
1700
+ refresh_button = gr.Button("Обновить", variant="primary")
1701
+ if check_for_name() != '':
1702
+ get_vc(sorted(names)[0])
1703
+ vc_transform0 = gr.Number(label="Необязательно: здесь вы можете изменить высоту тона или оставить значение 0.", value=0)
1704
+ #clean_button = gr.Button(i18n("卸载音色省显存"), variant="primary")
1705
+ spk_item = gr.Slider(
1706
+ minimum=0,
1707
+ maximum=2333,
1708
+ step=1,
1709
+ label=i18n("请选择说话人id"),
1710
+ value=0,
1711
+ visible=False,
1712
+ interactive=True,
1713
+ )
1714
+ #clean_button.click(fn=clean, inputs=[], outputs=[sid0])
1715
+ sid0.change(
1716
+ fn=get_vc,
1717
+ inputs=[sid0],
1718
+ outputs=[spk_item],
1719
+ )
1720
+ but0 = gr.Button("Convert", variant="primary")
1721
+ with gr.Row():
1722
+ with gr.Column():
1723
+ with gr.Row():
1724
+ dropbox = gr.File(label="Перетащите сюда свой аудиофайл и нажмите кнопку «Обновить».")
1725
+ with gr.Row():
1726
+ record_button=gr.Audio(source="microphone", label="ИЛИ Запись звука.", type="filepath")
1727
+ with gr.Row():
1728
+ input_audio0 = gr.Dropdown(
1729
+ label="2.Выберите аудио.",
1730
+ value="./audios/someguy.mp3",
1731
+ choices=audio_files
1732
+ )
1733
+ dropbox.upload(fn=save_to_wav2, inputs=[dropbox], outputs=[input_audio0])
1734
+ dropbox.upload(fn=change_choices2, inputs=[], outputs=[input_audio0])
1735
+ refresh_button2 = gr.Button("Обновить", variant="primary", size='sm')
1736
+ record_button.change(fn=save_to_wav, inputs=[record_button], outputs=[input_audio0])
1737
+ record_button.change(fn=change_choices2, inputs=[], outputs=[input_audio0])
1738
+ with gr.Row():
1739
+ with gr.Accordion('Текст в речь', open=False):
1740
+ with gr.Column():
1741
+ lang = gr.Radio(label='Китайский и японский языки в настоящее время не работают с ElevenLabs..',choices=['en','es','fr','pt','zh-CN','de','hi','ja'], value='en')
1742
+ api_box = gr.Textbox(label="Введите свой ключ API для ElevenLabs или оставьте пустым, чтобы использовать GoogleTTS.", value='')
1743
+ elevenid=gr.Dropdown(label="Голос:", choices=eleven_voices)
1744
+ with gr.Column():
1745
+ tfs = gr.Textbox(label="Введите свой текст", interactive=True, value="This is a test.")
1746
+ tts_button = gr.Button(value="Говорить")
1747
+ tts_button.click(fn=elevenTTS, inputs=[api_box,tfs, elevenid, lang], outputs=[record_button, input_audio0])
1748
+ with gr.Row():
1749
+ with gr.Accordion('Wav2Lip', open=False):
1750
+ with gr.Row():
1751
+ size = gr.Radio(label='Разрешение:',choices=['Half','Full'])
1752
+ face = gr.UploadButton("Загрузите персонажа",type='file')
1753
+ faces = gr.Dropdown(label="ИЛИ Выберите один:", choices=['None','Ben Shapiro','Andrew Tate'])
1754
+ with gr.Row():
1755
+ preview = gr.Textbox(label="Статус:",interactive=False)
1756
+ face.upload(fn=success_message,inputs=[face], outputs=[preview, faces])
1757
+ with gr.Row():
1758
+ animation = gr.Video(type='filepath')
1759
+ refresh_button2.click(fn=change_choices2, inputs=[], outputs=[input_audio0, animation])
1760
+ with gr.Row():
1761
+ animate_button = gr.Button('Animate')
1762
+
1763
+ with gr.Column():
1764
+ with gr.Accordion("Настройки индекса", open=False):
1765
+ file_index1 = gr.Dropdown(
1766
+ label="3. Путь к файлу add.index (если он не был найден автоматически)",
1767
+ choices=get_indexes(),
1768
+ value=get_index(),
1769
+ interactive=True,
1770
+ )
1771
+ sid0.change(fn=match_index, inputs=[sid0],outputs=[file_index1])
1772
+ refresh_button.click(
1773
+ fn=change_choices, inputs=[], outputs=[sid0, file_index1]
1774
+ )
1775
+ # file_big_npy1 = gr.Textbox(
1776
+ # label=i18n("特征文件路径"),
1777
+ # value="E:\\codes\py39\\vits_vc_gpu_train\\logs\\mi-test-1key\\total_fea.npy",
1778
+ # interactive=True,
1779
+ # )
1780
+ index_rate1 = gr.Slider(
1781
+ minimum=0,
1782
+ maximum=1,
1783
+ label=i18n("检索特征占比"),
1784
+ value=0.66,
1785
+ interactive=True,
1786
+ )
1787
+ vc_output2 = gr.Audio(label="Вывод аудио (нажмите три точки в правом углу, чтобы загрузить)",type='filepath')
1788
+ animate_button.click(fn=mouth, inputs=[size, face, vc_output2, faces], outputs=[animation, preview])
1789
+ with gr.Accordion("Расширенные настройки", open=False):
1790
+ f0method0 = gr.Radio(
1791
+ label="Необязательно: измените алгоритм извлечения высоты звука..",
1792
+ choices=["pm", "dio", "mangio-crepe-tiny", "crepe-tiny", "crepe", "mangio-crepe", "harvest","rmvpe"], # Fork Feature. Add Crepe-Tiny
1793
+ value="mangio-crepe",
1794
+ interactive=True,
1795
+ )
1796
+ crepe_hop_length = gr.Slider(
1797
+ minimum=1,
1798
+ maximum=512,
1799
+ step=1,
1800
+ label="Mangio-Crepe Hop Length. Более высокие числа уменьшат вероятность резких изменений шага, но меньшие числа повысят точность..",
1801
+ value=120,
1802
+ interactive=True
1803
+ )
1804
+ filter_radius0 = gr.Slider(
1805
+ minimum=0,
1806
+ maximum=7,
1807
+ label=i18n(">=3则使用对harvest音高识别的结果使用中值滤波,数值为滤波半径,使用可以削弱哑音"),
1808
+ value=3,
1809
+ step=1,
1810
+ interactive=True,
1811
+ )
1812
+ resample_sr0 = gr.Slider(
1813
+ minimum=0,
1814
+ maximum=48000,
1815
+ label=i18n("后处理重采样至最终采样率,0为不进行重采样"),
1816
+ value=0,
1817
+ step=1,
1818
+ interactive=True,
1819
+ visible=False
1820
+ )
1821
+ rms_mix_rate0 = gr.Slider(
1822
+ minimum=0,
1823
+ maximum=1,
1824
+ label=i18n("输入源音量包络替换输出音量包络融合比例,越靠近1越使用输出包络"),
1825
+ value=0.21,
1826
+ interactive=True,
1827
+ )
1828
+ protect0 = gr.Slider(
1829
+ minimum=0,
1830
+ maximum=0.5,
1831
+ label=i18n("保护清辅音和呼吸声,防止电音撕裂等artifact,拉满0.5不开启,调低加大保护力度但可能降低索引效果"),
1832
+ value=0.33,
1833
+ step=0.01,
1834
+ interactive=True,
1835
+ )
1836
+ with gr.Row():
1837
+ vc_output1 = gr.Textbox("")
1838
+ f0_file = gr.File(label=i18n("F0曲线文件, 可选, 一行一个音高, 代替默认F0及升降调"), visible=False)
1839
+
1840
+ but0.click(
1841
+ vc_single,
1842
+ [
1843
+ spk_item,
1844
+ input_audio0,
1845
+ vc_transform0,
1846
+ f0_file,
1847
+ f0method0,
1848
+ file_index1,
1849
+ # file_index2,
1850
+ # file_big_npy1,
1851
+ index_rate1,
1852
+ filter_radius0,
1853
+ resample_sr0,
1854
+ rms_mix_rate0,
1855
+ protect0,
1856
+ crepe_hop_length
1857
+ ],
1858
+ [vc_output1, vc_output2],
1859
+ )
1860
+
1861
+ with gr.Accordion("Batch Conversion",open=False):
1862
+ with gr.Row():
1863
+ with gr.Column():
1864
+ vc_transform1 = gr.Number(
1865
+ label=i18n("变调(整数, 半音数量, 升八度12降八度-12)"), value=0
1866
+ )
1867
+ opt_input = gr.Textbox(label=i18n("指定输出文件夹"), value="opt")
1868
+ f0method1 = gr.Radio(
1869
+ label=i18n(
1870
+ "选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比,crepe效果好但吃GPU"
1871
+ ),
1872
+ choices=["pm", "harvest", "crepe"],
1873
+ value="pm",
1874
+ interactive=True,
1875
+ )
1876
+ filter_radius1 = gr.Slider(
1877
+ minimum=0,
1878
+ maximum=7,
1879
+ label=i18n(">=3则使用对harvest音高识别的结果使用中值滤波,数值为滤波半径,使用可以削弱哑音"),
1880
+ value=3,
1881
+ step=1,
1882
+ interactive=True,
1883
+ )
1884
+ with gr.Column():
1885
+ file_index3 = gr.Textbox(
1886
+ label=i18n("特征检索库文件路径,为空则使用下拉的选择结果"),
1887
+ value="",
1888
+ interactive=True,
1889
+ )
1890
+ file_index4 = gr.Dropdown(
1891
+ label=i18n("自动检测index路径,下拉式选择(dropdown)"),
1892
+ choices=sorted(index_paths),
1893
+ interactive=True,
1894
+ )
1895
+ refresh_button.click(
1896
+ fn=lambda: change_choices()[1],
1897
+ inputs=[],
1898
+ outputs=file_index4,
1899
+ )
1900
+ # file_big_npy2 = gr.Textbox(
1901
+ # label=i18n("特征文件路径"),
1902
+ # value="E:\\codes\\py39\\vits_vc_gpu_train\\logs\\mi-test-1key\\total_fea.npy",
1903
+ # interactive=True,
1904
+ # )
1905
+ index_rate2 = gr.Slider(
1906
+ minimum=0,
1907
+ maximum=1,
1908
+ label=i18n("检索特征占比"),
1909
+ value=1,
1910
+ interactive=True,
1911
+ )
1912
+ with gr.Column():
1913
+ resample_sr1 = gr.Slider(
1914
+ minimum=0,
1915
+ maximum=48000,
1916
+ label=i18n("后处理重采样至最终采样率,0为不进行重采样"),
1917
+ value=0,
1918
+ step=1,
1919
+ interactive=True,
1920
+ )
1921
+ rms_mix_rate1 = gr.Slider(
1922
+ minimum=0,
1923
+ maximum=1,
1924
+ label=i18n("输入源音量包络替换输出音量包络融合比例,越靠近1越使用输出包络"),
1925
+ value=1,
1926
+ interactive=True,
1927
+ )
1928
+ protect1 = gr.Slider(
1929
+ minimum=0,
1930
+ maximum=0.5,
1931
+ label=i18n(
1932
+ "保护清辅音和呼吸声,防止电音撕裂等artifact,拉满0.5不开启,调低加大保护力度但可能降低索引效果"
1933
+ ),
1934
+ value=0.33,
1935
+ step=0.01,
1936
+ interactive=True,
1937
+ )
1938
+ with gr.Column():
1939
+ dir_input = gr.Textbox(
1940
+ label=i18n("输入待处理音频文件夹路径(去文件管理器地址栏拷就行了)"),
1941
+ value="E:\codes\py39\\test-20230416b\\todo-songs",
1942
+ )
1943
+ inputs = gr.File(
1944
+ file_count="multiple", label=i18n("也可批量输入音频文件, 二选一, 优先读文件夹")
1945
+ )
1946
+ with gr.Row():
1947
+ format1 = gr.Radio(
1948
+ label=i18n("导出文件格式"),
1949
+ choices=["wav", "flac", "mp3", "m4a"],
1950
+ value="flac",
1951
+ interactive=True,
1952
+ )
1953
+ but1 = gr.Button(i18n("转换"), variant="primary")
1954
+ vc_output3 = gr.Textbox(label=i18n("输出信息"))
1955
+ but1.click(
1956
+ vc_multi,
1957
+ [
1958
+ spk_item,
1959
+ dir_input,
1960
+ opt_input,
1961
+ inputs,
1962
+ vc_transform1,
1963
+ f0method1,
1964
+ file_index3,
1965
+ file_index4,
1966
+ # file_big_npy2,
1967
+ index_rate2,
1968
+ filter_radius1,
1969
+ resample_sr1,
1970
+ rms_mix_rate1,
1971
+ protect1,
1972
+ format1,
1973
+ crepe_hop_length,
1974
+ ],
1975
+ [vc_output3],
1976
+ )
1977
+ but1.click(fn=lambda: easy_uploader.clear())
1978
+ with gr.TabItem("Загрузка готовой модели"):
1979
+ with gr.Row():
1980
+ url=gr.Textbox(label="Введите URL-адрес модели:")
1981
+ with gr.Row():
1982
+ model = gr.Textbox(label="Назовите свою модель:")
1983
+ download_button=gr.Button("Скачать")
1984
+ with gr.Row():
1985
+ status_bar=gr.Textbox(label="")
1986
+ download_button.click(fn=download_from_url, inputs=[url, model], outputs=[status_bar])
1987
+ with gr.Row():
1988
+ gr.Markdown(
1989
+ """
1990
+ Original RVC:https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI
1991
+ ❤️ Если вам нравится моя версия RVC, помогите мне сохранить ее.❤️
1992
+ https://boosty.to/ba1yya
1993
+ """
1994
+ )
1995
+
1996
+ with gr.TabItem("Train", visible=False):
1997
+ with gr.Row():
1998
+ with gr.Column():
1999
+ exp_dir1 = gr.Textbox(label="Голосовое имя:", value="My-Voice")
2000
+ sr2 = gr.Radio(
2001
+ label=i18n("目标采样率"),
2002
+ choices=["40k", "48k"],
2003
+ value="40k",
2004
+ interactive=True,
2005
+ visible=False
2006
+ )
2007
+ if_f0_3 = gr.Radio(
2008
+ label=i18n("模型是否带音高指导(唱歌一定要, 语音可以不要)"),
2009
+ choices=[True, False],
2010
+ value=True,
2011
+ interactive=True,
2012
+ visible=False
2013
+ )
2014
+ version19 = gr.Radio(
2015
+ label="RVC version",
2016
+ choices=["v1", "v2"],
2017
+ value="v2",
2018
+ interactive=True,
2019
+ visible=False,
2020
+ )
2021
+ np7 = gr.Slider(
2022
+ minimum=0,
2023
+ maximum=config.n_cpu,
2024
+ step=1,
2025
+ label="# of CPUs for data processing (Leave as it is)",
2026
+ value=config.n_cpu,
2027
+ interactive=True,
2028
+ visible=True
2029
+ )
2030
+ trainset_dir4 = gr.Textbox(label="Путь к вашему набору данных (аудиофайлы, а не zip):", value="./dataset")
2031
+ easy_uploader = gr.Files(label='ИЛИ Перетащите сюда свои аудиозаписи. Они будут загружены по указанному выше пути к набору данных..',file_types=['audio'])
2032
+ but1 = gr.Button("1.Обработать набор данных", variant="primary")
2033
+ info1 = gr.Textbox(label="Статус:", value="")
2034
+ easy_uploader.upload(fn=upload_to_dataset, inputs=[easy_uploader, trainset_dir4], outputs=[info1])
2035
+ but1.click(
2036
+ preprocess_dataset, [trainset_dir4, exp_dir1, sr2, np7], [info1]
2037
+ )
2038
+ with gr.Column():
2039
+ spk_id5 = gr.Slider(
2040
+ minimum=0,
2041
+ maximum=4,
2042
+ step=1,
2043
+ label=i18n("请指定说话人id"),
2044
+ value=0,
2045
+ interactive=True,
2046
+ visible=False
2047
+ )
2048
+ with gr.Accordion('GPU Settings', open=False, visible=False):
2049
+ gpus6 = gr.Textbox(
2050
+ label=i18n("以-分隔输入使用的卡号, 例如 0-1-2 使用卡0和卡1和卡2"),
2051
+ value=gpus,
2052
+ interactive=True,
2053
+ visible=False
2054
+ )
2055
+ gpu_info9 = gr.Textbox(label=i18n("显卡信息"), value=gpu_info)
2056
+ f0method8 = gr.Radio(
2057
+ label=i18n(
2058
+ "选择音高提取算法:输入歌声可用pm提速,高质量语音但CPU差可用dio提速,harvest质量更好但慢"
2059
+ ),
2060
+ choices=["harvest","crepe", "mangio-crepe"], # Fork feature: Crepe on f0 extraction for training.
2061
+ value="mangio-crepe",
2062
+ interactive=True,
2063
+ )
2064
+ extraction_crepe_hop_length = gr.Slider(
2065
+ minimum=1,
2066
+ maximum=512,
2067
+ step=1,
2068
+ label=i18n("crepe_hop_length"),
2069
+ value=128,
2070
+ interactive=True
2071
+ )
2072
+ but2 = gr.Button("2.Извлечение высоты тона", variant="primary")
2073
+ info2 = gr.Textbox(label="Статус:", value="", max_lines=8)
2074
+ but2.click(
2075
+ extract_f0_feature,
2076
+ [gpus6, np7, f0method8, if_f0_3, exp_dir1, version19, extraction_crepe_hop_length],
2077
+ [info2],
2078
+ )
2079
+ with gr.Row():
2080
+ with gr.Column():
2081
+ total_epoch11 = gr.Slider(
2082
+ minimum=0,
2083
+ maximum=10000,
2084
+ step=10,
2085
+ label="Общее количество эпох обучения (много не вводите, возможна перетренировка):",
2086
+ value=250,
2087
+ interactive=True,
2088
+ )
2089
+ but3 = gr.Button("3.Тренировать модель", variant="primary")
2090
+ but4 = gr.Button("4.Тренировать индекс", variant="primary")
2091
+ info3 = gr.Textbox(label="Статус:", value="", max_lines=10)
2092
+ with gr.Accordion("Настройки обучения (вы можете оставить их как есть)", open=False):
2093
+ #gr.Markdown(value=i18n("step3: 填写训练设置, 开始训练模型和索引"))
2094
+ with gr.Column():
2095
+ save_epoch10 = gr.Slider(
2096
+ minimum=0,
2097
+ maximum=100,
2098
+ step=5,
2099
+ label="Резервное копирование каждые # эпох:",
2100
+ value=25,
2101
+ interactive=True,
2102
+ )
2103
+ batch_size12 = gr.Slider(
2104
+ minimum=1,
2105
+ maximum=40,
2106
+ step=1,
2107
+ label="Размер пакета (Оставьте его, если вы не знаете, что это!):",
2108
+ value=default_batch_size,
2109
+ interactive=True,
2110
+ )
2111
+ if_save_latest13 = gr.Radio(
2112
+ label=i18n("是否仅保存最新的ckpt文件以节省硬盘空间"),
2113
+ choices=[i18n("是"), i18n("否")],
2114
+ value=i18n("是"),
2115
+ interactive=True,
2116
+ )
2117
+ if_cache_gpu17 = gr.Radio(
2118
+ label=i18n(
2119
+ "是否缓存所有训练集至显存. 10min以下小数据可缓存以加速训练, 大数据缓存会炸显存也加不了多少速"
2120
+ ),
2121
+ choices=[i18n("是"), i18n("否")],
2122
+ value=i18n("否"),
2123
+ interactive=True,
2124
+ )
2125
+ if_save_every_weights18 = gr.Radio(
2126
+ label=i18n("是否在每次保存时间点将最终小模型保存至weights文件夹"),
2127
+ choices=[i18n("是"), i18n("否")],
2128
+ value=i18n("是"),
2129
+ interactive=True,
2130
+ )
2131
+ zip_model = gr.Button('5.Скачать модель')
2132
+ zipped_model = gr.Files(label='Файл вашей модели и индекса можно скачать здесь:')
2133
+ zip_model.click(fn=zip_downloader, inputs=[exp_dir1], outputs=[zipped_model, info3])
2134
+ with gr.Group():
2135
+ with gr.Accordion("Расположение базовой модели:", open=False, visible=False):
2136
+ pretrained_G14 = gr.Textbox(
2137
+ label=i18n("加载预训练底模G路径"),
2138
+ value="pretrained_v2/f0G40k.pth",
2139
+ interactive=True,
2140
+ )
2141
+ pretrained_D15 = gr.Textbox(
2142
+ label=i18n("加载预训练底模D路径"),
2143
+ value="pretrained_v2/f0D40k.pth",
2144
+ interactive=True,
2145
+ )
2146
+ gpus16 = gr.Textbox(
2147
+ label=i18n("以-分隔输入使用的卡号, 例如 0-1-2 使用卡0和卡1和卡2"),
2148
+ value=gpus,
2149
+ interactive=True,
2150
+ )
2151
+ sr2.change(
2152
+ change_sr2,
2153
+ [sr2, if_f0_3, version19],
2154
+ [pretrained_G14, pretrained_D15, version19],
2155
+ )
2156
+ version19.change(
2157
+ change_version19,
2158
+ [sr2, if_f0_3, version19],
2159
+ [pretrained_G14, pretrained_D15],
2160
+ )
2161
+ if_f0_3.change(
2162
+ change_f0,
2163
+ [if_f0_3, sr2, version19],
2164
+ [f0method8, pretrained_G14, pretrained_D15],
2165
+ )
2166
+ but5 = gr.Button(i18n("一键训练"), variant="primary", visible=False)
2167
+ but3.click(
2168
+ click_train,
2169
+ [
2170
+ exp_dir1,
2171
+ sr2,
2172
+ if_f0_3,
2173
+ spk_id5,
2174
+ save_epoch10,
2175
+ total_epoch11,
2176
+ batch_size12,
2177
+ if_save_latest13,
2178
+ pretrained_G14,
2179
+ pretrained_D15,
2180
+ gpus16,
2181
+ if_cache_gpu17,
2182
+ if_save_every_weights18,
2183
+ version19,
2184
+ ],
2185
+ info3,
2186
+ )
2187
+ but4.click(train_index, [exp_dir1, version19], info3)
2188
+ but5.click(
2189
+ train1key,
2190
+ [
2191
+ exp_dir1,
2192
+ sr2,
2193
+ if_f0_3,
2194
+ trainset_dir4,
2195
+ spk_id5,
2196
+ np7,
2197
+ f0method8,
2198
+ save_epoch10,
2199
+ total_epoch11,
2200
+ batch_size12,
2201
+ if_save_latest13,
2202
+ pretrained_G14,
2203
+ pretrained_D15,
2204
+ gpus16,
2205
+ if_cache_gpu17,
2206
+ if_save_every_weights18,
2207
+ version19,
2208
+ extraction_crepe_hop_length
2209
+ ],
2210
+ info3,
2211
+ )
2212
+
2213
+
2214
+ try:
2215
+ if tab_faq == "常见问题解答":
2216
+ with open("docs/faq.md", "r", encoding="utf8") as f:
2217
+ info = f.read()
2218
+ else:
2219
+ with open("docs/faq_en.md", "r", encoding="utf8") as f:
2220
+ info = f.read()
2221
+ gr.Markdown(value=info)
2222
+ except:
2223
+ gr.Markdown("")
2224
+
2225
+
2226
+ #region Mangio Preset Handler Region
2227
+ def save_preset(preset_name,sid0,vc_transform,input_audio,f0method,crepe_hop_length,filter_radius,file_index1,file_index2,index_rate,resample_sr,rms_mix_rate,protect,f0_file):
2228
+ data = None
2229
+ with open('../inference-presets.json', 'r') as file:
2230
+ data = json.load(file)
2231
+ preset_json = {
2232
+ 'name': preset_name,
2233
+ 'model': sid0,
2234
+ 'transpose': vc_transform,
2235
+ 'audio_file': input_audio,
2236
+ 'f0_method': f0method,
2237
+ 'crepe_hop_length': crepe_hop_length,
2238
+ 'median_filtering': filter_radius,
2239
+ 'feature_path': file_index1,
2240
+ 'auto_feature_path': file_index2,
2241
+ 'search_feature_ratio': index_rate,
2242
+ 'resample': resample_sr,
2243
+ 'volume_envelope': rms_mix_rate,
2244
+ 'protect_voiceless': protect,
2245
+ 'f0_file_path': f0_file
2246
+ }
2247
+ data['presets'].append(preset_json)
2248
+ with open('../inference-presets.json', 'w') as file:
2249
+ json.dump(data, file)
2250
+ file.flush()
2251
+ print("Saved Preset %s into inference-presets.json!" % preset_name)
2252
+
2253
+
2254
+ def on_preset_changed(preset_name):
2255
+ print("Changed Preset to %s!" % preset_name)
2256
+ data = None
2257
+ with open('../inference-presets.json', 'r') as file:
2258
+ data = json.load(file)
2259
+
2260
+ print("Searching for " + preset_name)
2261
+ returning_preset = None
2262
+ for preset in data['presets']:
2263
+ if(preset['name'] == preset_name):
2264
+ print("Found a preset")
2265
+ returning_preset = preset
2266
+ # return all new input values
2267
+ return (
2268
+ # returning_preset['model'],
2269
+ # returning_preset['transpose'],
2270
+ # returning_preset['audio_file'],
2271
+ # returning_preset['f0_method'],
2272
+ # returning_preset['crepe_hop_length'],
2273
+ # returning_preset['median_filtering'],
2274
+ # returning_preset['feature_path'],
2275
+ # returning_preset['auto_feature_path'],
2276
+ # returning_preset['search_feature_ratio'],
2277
+ # returning_preset['resample'],
2278
+ # returning_preset['volume_envelope'],
2279
+ # returning_preset['protect_voiceless'],
2280
+ # returning_preset['f0_file_path']
2281
+ )
2282
+
2283
+ # Preset State Changes
2284
+
2285
+ # This click calls save_preset that saves the preset into inference-presets.json with the preset name
2286
+ # mangio_preset_save_btn.click(
2287
+ # fn=save_preset,
2288
+ # inputs=[
2289
+ # mangio_preset_name_save,
2290
+ # sid0,
2291
+ # vc_transform0,
2292
+ # input_audio0,
2293
+ # f0method0,
2294
+ # crepe_hop_length,
2295
+ # filter_radius0,
2296
+ # file_index1,
2297
+ # file_index2,
2298
+ # index_rate1,
2299
+ # resample_sr0,
2300
+ # rms_mix_rate0,
2301
+ # protect0,
2302
+ # f0_file
2303
+ # ],
2304
+ # outputs=[]
2305
+ # )
2306
+
2307
+ # mangio_preset.change(
2308
+ # on_preset_changed,
2309
+ # inputs=[
2310
+ # # Pass inputs here
2311
+ # mangio_preset
2312
+ # ],
2313
+ # outputs=[
2314
+ # # Pass Outputs here. These refer to the gradio elements that we want to directly change
2315
+ # # sid0,
2316
+ # # vc_transform0,
2317
+ # # input_audio0,
2318
+ # # f0method0,
2319
+ # # crepe_hop_length,
2320
+ # # filter_radius0,
2321
+ # # file_index1,
2322
+ # # file_index2,
2323
+ # # index_rate1,
2324
+ # # resample_sr0,
2325
+ # # rms_mix_rate0,
2326
+ # # protect0,
2327
+ # # f0_file
2328
+ # ]
2329
+ # )
2330
+
2331
+
2332
+ # with gr.TabItem(i18n("招募音高曲线前端编辑器")):
2333
+ # gr.Markdown(value=i18n("加开发群联系我xxxxx"))
2334
+ # with gr.TabItem(i18n("点击查看交流、问题反馈群号")):
2335
+ # gr.Markdown(value=i18n("xxxxx"))
2336
+
2337
+
2338
+ if config.iscolab or config.paperspace: # Share gradio link for colab and paperspace (FORK FEATURE)
2339
+ app.queue(concurrency_count=511, max_size=1022).launch(share=True, quiet=True)
2340
+ else:
2341
+ app.queue(concurrency_count=511, max_size=1022).launch(
2342
+ server_name="0.0.0.0",
2343
+ inbrowser=not config.noautoopen,
2344
+ server_port=config.listen_port,
2345
+ quiet=True,
2346
+ )