Delete rvc_for_realtime.py
Browse files- rvc_for_realtime.py +0 -297
rvc_for_realtime.py
DELETED
@@ -1,297 +0,0 @@
|
|
1 |
-
import faiss, torch, traceback, parselmouth, numpy as np, torchcrepe, torch.nn as nn, pyworld
|
2 |
-
from fairseq import checkpoint_utils
|
3 |
-
from lib.infer_pack.models import (
|
4 |
-
SynthesizerTrnMs256NSFsid,
|
5 |
-
SynthesizerTrnMs256NSFsid_nono,
|
6 |
-
SynthesizerTrnMs768NSFsid,
|
7 |
-
SynthesizerTrnMs768NSFsid_nono,
|
8 |
-
)
|
9 |
-
import os, sys
|
10 |
-
from time import time as ttime
|
11 |
-
import torch.nn.functional as F
|
12 |
-
import scipy.signal as signal
|
13 |
-
|
14 |
-
now_dir = os.getcwd()
|
15 |
-
sys.path.append(now_dir)
|
16 |
-
from config import Config
|
17 |
-
from multiprocessing import Manager as M
|
18 |
-
|
19 |
-
mm = M()
|
20 |
-
config = Config()
|
21 |
-
|
22 |
-
|
23 |
-
class RVC:
|
24 |
-
def __init__(
|
25 |
-
self, key, pth_path, index_path, index_rate, n_cpu, inp_q, opt_q, device
|
26 |
-
) -> None:
|
27 |
-
"""
|
28 |
-
初始化
|
29 |
-
"""
|
30 |
-
try:
|
31 |
-
global config
|
32 |
-
self.inp_q = inp_q
|
33 |
-
self.opt_q = opt_q
|
34 |
-
self.device = device
|
35 |
-
self.f0_up_key = key
|
36 |
-
self.time_step = 160 / 16000 * 1000
|
37 |
-
self.f0_min = 50
|
38 |
-
self.f0_max = 1100
|
39 |
-
self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
|
40 |
-
self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
|
41 |
-
self.sr = 16000
|
42 |
-
self.window = 160
|
43 |
-
self.n_cpu = n_cpu
|
44 |
-
if index_rate != 0:
|
45 |
-
self.index = faiss.read_index(index_path)
|
46 |
-
self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
|
47 |
-
print("index search enabled")
|
48 |
-
self.index_rate = index_rate
|
49 |
-
models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
|
50 |
-
["hubert_base.pt"],
|
51 |
-
suffix="",
|
52 |
-
)
|
53 |
-
hubert_model = models[0]
|
54 |
-
hubert_model = hubert_model.to(config.device)
|
55 |
-
if config.is_half:
|
56 |
-
hubert_model = hubert_model.half()
|
57 |
-
else:
|
58 |
-
hubert_model = hubert_model.float()
|
59 |
-
hubert_model.eval()
|
60 |
-
self.model = hubert_model
|
61 |
-
cpt = torch.load(pth_path, map_location="cpu")
|
62 |
-
self.tgt_sr = cpt["config"][-1]
|
63 |
-
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
|
64 |
-
self.if_f0 = cpt.get("f0", 1)
|
65 |
-
self.version = cpt.get("version", "v1")
|
66 |
-
if self.version == "v1":
|
67 |
-
if self.if_f0 == 1:
|
68 |
-
self.net_g = SynthesizerTrnMs256NSFsid(
|
69 |
-
*cpt["config"], is_half=config.is_half
|
70 |
-
)
|
71 |
-
else:
|
72 |
-
self.net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
73 |
-
elif self.version == "v2":
|
74 |
-
if self.if_f0 == 1:
|
75 |
-
self.net_g = SynthesizerTrnMs768NSFsid(
|
76 |
-
*cpt["config"], is_half=config.is_half
|
77 |
-
)
|
78 |
-
else:
|
79 |
-
self.net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
80 |
-
del self.net_g.enc_q
|
81 |
-
print(self.net_g.load_state_dict(cpt["weight"], strict=False))
|
82 |
-
self.net_g.eval().to(device)
|
83 |
-
if config.is_half:
|
84 |
-
self.net_g = self.net_g.half()
|
85 |
-
else:
|
86 |
-
self.net_g = self.net_g.float()
|
87 |
-
self.is_half = config.is_half
|
88 |
-
except:
|
89 |
-
print(traceback.format_exc())
|
90 |
-
|
91 |
-
def get_f0_post(self, f0):
|
92 |
-
f0_min = self.f0_min
|
93 |
-
f0_max = self.f0_max
|
94 |
-
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
95 |
-
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
96 |
-
f0bak = f0.copy()
|
97 |
-
f0_mel = 1127 * np.log(1 + f0 / 700)
|
98 |
-
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
99 |
-
f0_mel_max - f0_mel_min
|
100 |
-
) + 1
|
101 |
-
f0_mel[f0_mel <= 1] = 1
|
102 |
-
f0_mel[f0_mel > 255] = 255
|
103 |
-
f0_coarse = np.rint(f0_mel).astype(np.int)
|
104 |
-
return f0_coarse, f0bak
|
105 |
-
|
106 |
-
def get_f0(self, x, f0_up_key, n_cpu, method="harvest"):
|
107 |
-
n_cpu = int(n_cpu)
|
108 |
-
if method == "crepe":
|
109 |
-
return self.get_f0_crepe(x, f0_up_key)
|
110 |
-
if method == "rmvpe":
|
111 |
-
return self.get_f0_rmvpe(x, f0_up_key)
|
112 |
-
if method == "pm":
|
113 |
-
p_len = x.shape[0] // 160
|
114 |
-
f0 = (
|
115 |
-
parselmouth.Sound(x, 16000)
|
116 |
-
.to_pitch_ac(
|
117 |
-
time_step=0.01,
|
118 |
-
voicing_threshold=0.6,
|
119 |
-
pitch_floor=50,
|
120 |
-
pitch_ceiling=1100,
|
121 |
-
)
|
122 |
-
.selected_array["frequency"]
|
123 |
-
)
|
124 |
-
|
125 |
-
pad_size = (p_len - len(f0) + 1) // 2
|
126 |
-
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
127 |
-
print(pad_size, p_len - len(f0) - pad_size)
|
128 |
-
f0 = np.pad(
|
129 |
-
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
130 |
-
)
|
131 |
-
|
132 |
-
f0 *= pow(2, f0_up_key / 12)
|
133 |
-
return self.get_f0_post(f0)
|
134 |
-
if n_cpu == 1:
|
135 |
-
f0, t = pyworld.harvest(
|
136 |
-
x.astype(np.double),
|
137 |
-
fs=16000,
|
138 |
-
f0_ceil=1100,
|
139 |
-
f0_floor=50,
|
140 |
-
frame_period=10,
|
141 |
-
)
|
142 |
-
f0 = signal.medfilt(f0, 3)
|
143 |
-
f0 *= pow(2, f0_up_key / 12)
|
144 |
-
return self.get_f0_post(f0)
|
145 |
-
f0bak = np.zeros(x.shape[0] // 160, dtype=np.float64)
|
146 |
-
length = len(x)
|
147 |
-
part_length = int(length / n_cpu / 160) * 160
|
148 |
-
ts = ttime()
|
149 |
-
res_f0 = mm.dict()
|
150 |
-
for idx in range(n_cpu):
|
151 |
-
tail = part_length * (idx + 1) + 320
|
152 |
-
if idx == 0:
|
153 |
-
self.inp_q.put((idx, x[:tail], res_f0, n_cpu, ts))
|
154 |
-
else:
|
155 |
-
self.inp_q.put(
|
156 |
-
(idx, x[part_length * idx - 320 : tail], res_f0, n_cpu, ts)
|
157 |
-
)
|
158 |
-
while 1:
|
159 |
-
res_ts = self.opt_q.get()
|
160 |
-
if res_ts == ts:
|
161 |
-
break
|
162 |
-
f0s = [i[1] for i in sorted(res_f0.items(), key=lambda x: x[0])]
|
163 |
-
for idx, f0 in enumerate(f0s):
|
164 |
-
if idx == 0:
|
165 |
-
f0 = f0[:-3]
|
166 |
-
elif idx != n_cpu - 1:
|
167 |
-
f0 = f0[2:-3]
|
168 |
-
else:
|
169 |
-
f0 = f0[2:-1]
|
170 |
-
f0bak[
|
171 |
-
part_length * idx // 160 : part_length * idx // 160 + f0.shape[0]
|
172 |
-
] = f0
|
173 |
-
f0bak = signal.medfilt(f0bak, 3)
|
174 |
-
f0bak *= pow(2, f0_up_key / 12)
|
175 |
-
return self.get_f0_post(f0bak)
|
176 |
-
|
177 |
-
def get_f0_crepe(self, x, f0_up_key):
|
178 |
-
audio = torch.tensor(np.copy(x))[None].float()
|
179 |
-
f0, pd = torchcrepe.predict(
|
180 |
-
audio,
|
181 |
-
self.sr,
|
182 |
-
160,
|
183 |
-
self.f0_min,
|
184 |
-
self.f0_max,
|
185 |
-
"full",
|
186 |
-
batch_size=512,
|
187 |
-
device=self.device,
|
188 |
-
return_periodicity=True,
|
189 |
-
)
|
190 |
-
pd = torchcrepe.filter.median(pd, 3)
|
191 |
-
f0 = torchcrepe.filter.mean(f0, 3)
|
192 |
-
f0[pd < 0.1] = 0
|
193 |
-
f0 = f0[0].cpu().numpy()
|
194 |
-
f0 *= pow(2, f0_up_key / 12)
|
195 |
-
return self.get_f0_post(f0)
|
196 |
-
|
197 |
-
def get_f0_rmvpe(self, x, f0_up_key):
|
198 |
-
if hasattr(self, "model_rmvpe") == False:
|
199 |
-
from lib.rmvpe import RMVPE
|
200 |
-
|
201 |
-
print("loading rmvpe model")
|
202 |
-
self.model_rmvpe = RMVPE(
|
203 |
-
"rmvpe.pt", is_half=self.is_half, device=self.device
|
204 |
-
)
|
205 |
-
# self.model_rmvpe = RMVPE("aug2_58000_half.pt", is_half=self.is_half, device=self.device)
|
206 |
-
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
207 |
-
f0 *= pow(2, f0_up_key / 12)
|
208 |
-
return self.get_f0_post(f0)
|
209 |
-
|
210 |
-
def infer(
|
211 |
-
self,
|
212 |
-
feats: torch.Tensor,
|
213 |
-
indata: np.ndarray,
|
214 |
-
rate1,
|
215 |
-
rate2,
|
216 |
-
cache_pitch,
|
217 |
-
cache_pitchf,
|
218 |
-
f0method,
|
219 |
-
) -> np.ndarray:
|
220 |
-
feats = feats.view(1, -1)
|
221 |
-
if config.is_half:
|
222 |
-
feats = feats.half()
|
223 |
-
else:
|
224 |
-
feats = feats.float()
|
225 |
-
feats = feats.to(self.device)
|
226 |
-
t1 = ttime()
|
227 |
-
with torch.no_grad():
|
228 |
-
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
|
229 |
-
inputs = {
|
230 |
-
"source": feats,
|
231 |
-
"padding_mask": padding_mask,
|
232 |
-
"output_layer": 9 if self.version == "v1" else 12,
|
233 |
-
}
|
234 |
-
logits = self.model.extract_features(**inputs)
|
235 |
-
feats = (
|
236 |
-
self.model.final_proj(logits[0]) if self.version == "v1" else logits[0]
|
237 |
-
)
|
238 |
-
t2 = ttime()
|
239 |
-
try:
|
240 |
-
if hasattr(self, "index") and self.index_rate != 0:
|
241 |
-
leng_replace_head = int(rate1 * feats[0].shape[0])
|
242 |
-
npy = feats[0][-leng_replace_head:].cpu().numpy().astype("float32")
|
243 |
-
score, ix = self.index.search(npy, k=8)
|
244 |
-
weight = np.square(1 / score)
|
245 |
-
weight /= weight.sum(axis=1, keepdims=True)
|
246 |
-
npy = np.sum(self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
247 |
-
if config.is_half:
|
248 |
-
npy = npy.astype("float16")
|
249 |
-
feats[0][-leng_replace_head:] = (
|
250 |
-
torch.from_numpy(npy).unsqueeze(0).to(self.device) * self.index_rate
|
251 |
-
+ (1 - self.index_rate) * feats[0][-leng_replace_head:]
|
252 |
-
)
|
253 |
-
else:
|
254 |
-
print("index search FAIL or disabled")
|
255 |
-
except:
|
256 |
-
traceback.print_exc()
|
257 |
-
print("index search FAIL")
|
258 |
-
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
|
259 |
-
t3 = ttime()
|
260 |
-
if self.if_f0 == 1:
|
261 |
-
pitch, pitchf = self.get_f0(indata, self.f0_up_key, self.n_cpu, f0method)
|
262 |
-
cache_pitch[:] = np.append(cache_pitch[pitch[:-1].shape[0] :], pitch[:-1])
|
263 |
-
cache_pitchf[:] = np.append(
|
264 |
-
cache_pitchf[pitchf[:-1].shape[0] :], pitchf[:-1]
|
265 |
-
)
|
266 |
-
p_len = min(feats.shape[1], 13000, cache_pitch.shape[0])
|
267 |
-
else:
|
268 |
-
cache_pitch, cache_pitchf = None, None
|
269 |
-
p_len = min(feats.shape[1], 13000)
|
270 |
-
t4 = ttime()
|
271 |
-
feats = feats[:, :p_len, :]
|
272 |
-
if self.if_f0 == 1:
|
273 |
-
cache_pitch = cache_pitch[:p_len]
|
274 |
-
cache_pitchf = cache_pitchf[:p_len]
|
275 |
-
cache_pitch = torch.LongTensor(cache_pitch).unsqueeze(0).to(self.device)
|
276 |
-
cache_pitchf = torch.FloatTensor(cache_pitchf).unsqueeze(0).to(self.device)
|
277 |
-
p_len = torch.LongTensor([p_len]).to(self.device)
|
278 |
-
ii = 0 # sid
|
279 |
-
sid = torch.LongTensor([ii]).to(self.device)
|
280 |
-
with torch.no_grad():
|
281 |
-
if self.if_f0 == 1:
|
282 |
-
infered_audio = (
|
283 |
-
self.net_g.infer(
|
284 |
-
feats, p_len, cache_pitch, cache_pitchf, sid, rate2
|
285 |
-
)[0][0, 0]
|
286 |
-
.data.cpu()
|
287 |
-
.float()
|
288 |
-
)
|
289 |
-
else:
|
290 |
-
infered_audio = (
|
291 |
-
self.net_g.infer(feats, p_len, sid, rate2)[0][0, 0]
|
292 |
-
.data.cpu()
|
293 |
-
.float()
|
294 |
-
)
|
295 |
-
t5 = ttime()
|
296 |
-
print("time->fea-index-f0-model:", t2 - t1, t3 - t2, t4 - t3, t5 - t4)
|
297 |
-
return infered_audio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|