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

Upload GUI.py

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