nevreal commited on
Commit
4fe5d1c
·
verified ·
1 Parent(s): ba49d8e

Delete tools/rvc_for_realtime.py

Browse files
Files changed (1) hide show
  1. tools/rvc_for_realtime.py +0 -445
tools/rvc_for_realtime.py DELETED
@@ -1,445 +0,0 @@
1
- from io import BytesIO
2
- import os
3
- import pickle
4
- import sys
5
- import traceback
6
- from infer.lib import jit
7
- from infer.lib.jit.get_synthesizer import get_synthesizer
8
- from time import time as ttime
9
- import fairseq
10
- import faiss
11
- import numpy as np
12
- import parselmouth
13
- import pyworld
14
- import scipy.signal as signal
15
- import torch
16
- import torch.nn as nn
17
- import torch.nn.functional as F
18
- import torchcrepe
19
-
20
- from infer.lib.infer_pack.models import (
21
- SynthesizerTrnMs256NSFsid,
22
- SynthesizerTrnMs256NSFsid_nono,
23
- SynthesizerTrnMs768NSFsid,
24
- SynthesizerTrnMs768NSFsid_nono,
25
- )
26
-
27
- now_dir = os.getcwd()
28
- sys.path.append(now_dir)
29
- from multiprocessing import Manager as M
30
-
31
- from configs.config import Config
32
-
33
- # config = Config()
34
-
35
- mm = M()
36
-
37
-
38
- def printt(strr, *args):
39
- if len(args) == 0:
40
- print(strr)
41
- else:
42
- print(strr % args)
43
-
44
-
45
- # config.device=torch.device("cpu")########强制cpu测试
46
- # config.is_half=False########强制cpu测试
47
- class RVC:
48
- def __init__(
49
- self,
50
- key,
51
- pth_path,
52
- index_path,
53
- index_rate,
54
- n_cpu,
55
- inp_q,
56
- opt_q,
57
- config: Config,
58
- last_rvc=None,
59
- ) -> None:
60
- """
61
- 初始化
62
- """
63
- try:
64
- if config.dml == True:
65
-
66
- def forward_dml(ctx, x, scale):
67
- ctx.scale = scale
68
- res = x.clone().detach()
69
- return res
70
-
71
- fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
72
- # global config
73
- self.config = config
74
- self.inp_q = inp_q
75
- self.opt_q = opt_q
76
- # device="cpu"########强制cpu测试
77
- self.device = config.device
78
- self.f0_up_key = key
79
- self.f0_min = 50
80
- self.f0_max = 1100
81
- self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
82
- self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
83
- self.n_cpu = n_cpu
84
- self.use_jit = self.config.use_jit
85
- self.is_half = config.is_half
86
-
87
- if index_rate != 0:
88
- self.index = faiss.read_index(index_path)
89
- self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
90
- printt("Index search enabled")
91
- self.pth_path: str = pth_path
92
- self.index_path = index_path
93
- self.index_rate = index_rate
94
- self.cache_pitch: torch.Tensor = torch.zeros(
95
- 1024, device=self.device, dtype=torch.long
96
- )
97
- self.cache_pitchf = torch.zeros(
98
- 1024, device=self.device, dtype=torch.float32
99
- )
100
-
101
- if last_rvc is None:
102
- models, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
103
- ["assets/hubert/hubert_base.pt"],
104
- suffix="",
105
- )
106
- hubert_model = models[0]
107
- hubert_model = hubert_model.to(self.device)
108
- if self.is_half:
109
- hubert_model = hubert_model.half()
110
- else:
111
- hubert_model = hubert_model.float()
112
- hubert_model.eval()
113
- self.model = hubert_model
114
- else:
115
- self.model = last_rvc.model
116
-
117
- self.net_g: nn.Module = None
118
-
119
- def set_default_model():
120
- self.net_g, cpt = get_synthesizer(self.pth_path, self.device)
121
- self.tgt_sr = cpt["config"][-1]
122
- cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
123
- self.if_f0 = cpt.get("f0", 1)
124
- self.version = cpt.get("version", "v1")
125
- if self.is_half:
126
- self.net_g = self.net_g.half()
127
- else:
128
- self.net_g = self.net_g.float()
129
-
130
- def set_jit_model():
131
- jit_pth_path = self.pth_path.rstrip(".pth")
132
- jit_pth_path += ".half.jit" if self.is_half else ".jit"
133
- reload = False
134
- if str(self.device) == "cuda":
135
- self.device = torch.device("cuda:0")
136
- if os.path.exists(jit_pth_path):
137
- cpt = jit.load(jit_pth_path)
138
- model_device = cpt["device"]
139
- if model_device != str(self.device):
140
- reload = True
141
- else:
142
- reload = True
143
-
144
- if reload:
145
- cpt = jit.synthesizer_jit_export(
146
- self.pth_path,
147
- "script",
148
- None,
149
- device=self.device,
150
- is_half=self.is_half,
151
- )
152
-
153
- self.tgt_sr = cpt["config"][-1]
154
- self.if_f0 = cpt.get("f0", 1)
155
- self.version = cpt.get("version", "v1")
156
- self.net_g = torch.jit.load(
157
- BytesIO(cpt["model"]), map_location=self.device
158
- )
159
- self.net_g.infer = self.net_g.forward
160
- self.net_g.eval().to(self.device)
161
-
162
- def set_synthesizer():
163
- if self.use_jit and not config.dml:
164
- if self.is_half and "cpu" in str(self.device):
165
- printt(
166
- "Use default Synthesizer model. \
167
- Jit is not supported on the CPU for half floating point"
168
- )
169
- set_default_model()
170
- else:
171
- set_jit_model()
172
- else:
173
- set_default_model()
174
-
175
- if last_rvc is None or last_rvc.pth_path != self.pth_path:
176
- set_synthesizer()
177
- else:
178
- self.tgt_sr = last_rvc.tgt_sr
179
- self.if_f0 = last_rvc.if_f0
180
- self.version = last_rvc.version
181
- self.is_half = last_rvc.is_half
182
- if last_rvc.use_jit != self.use_jit:
183
- set_synthesizer()
184
- else:
185
- self.net_g = last_rvc.net_g
186
-
187
- if last_rvc is not None and hasattr(last_rvc, "model_rmvpe"):
188
- self.model_rmvpe = last_rvc.model_rmvpe
189
- if last_rvc is not None and hasattr(last_rvc, "model_fcpe"):
190
- self.device_fcpe = last_rvc.device_fcpe
191
- self.model_fcpe = last_rvc.model_fcpe
192
- except:
193
- printt(traceback.format_exc())
194
-
195
- def change_key(self, new_key):
196
- self.f0_up_key = new_key
197
-
198
- def change_index_rate(self, new_index_rate):
199
- if new_index_rate != 0 and self.index_rate == 0:
200
- self.index = faiss.read_index(self.index_path)
201
- self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
202
- printt("Index search enabled")
203
- self.index_rate = new_index_rate
204
-
205
- def get_f0_post(self, f0):
206
- if not torch.is_tensor(f0):
207
- f0 = torch.from_numpy(f0)
208
- f0 = f0.float().to(self.device).squeeze()
209
- f0_mel = 1127 * torch.log(1 + f0 / 700)
210
- f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * 254 / (
211
- self.f0_mel_max - self.f0_mel_min
212
- ) + 1
213
- f0_mel[f0_mel <= 1] = 1
214
- f0_mel[f0_mel > 255] = 255
215
- f0_coarse = torch.round(f0_mel).long()
216
- return f0_coarse, f0
217
-
218
- def get_f0(self, x, f0_up_key, n_cpu, method="harvest"):
219
- n_cpu = int(n_cpu)
220
- if method == "crepe":
221
- return self.get_f0_crepe(x, f0_up_key)
222
- if method == "rmvpe":
223
- return self.get_f0_rmvpe(x, f0_up_key)
224
- if method == "fcpe":
225
- return self.get_f0_fcpe(x, f0_up_key)
226
- x = x.cpu().numpy()
227
- if method == "pm":
228
- p_len = x.shape[0] // 160 + 1
229
- f0_min = 65
230
- l_pad = int(np.ceil(1.5 / f0_min * 16000))
231
- r_pad = l_pad + 1
232
- s = parselmouth.Sound(np.pad(x, (l_pad, r_pad)), 16000).to_pitch_ac(
233
- time_step=0.01,
234
- voicing_threshold=0.6,
235
- pitch_floor=f0_min,
236
- pitch_ceiling=1100,
237
- )
238
- assert np.abs(s.t1 - 1.5 / f0_min) < 0.001
239
- f0 = s.selected_array["frequency"]
240
- if len(f0) < p_len:
241
- f0 = np.pad(f0, (0, p_len - len(f0)))
242
- f0 = f0[:p_len]
243
- f0 *= pow(2, f0_up_key / 12)
244
- return self.get_f0_post(f0)
245
- if n_cpu == 1:
246
- f0, t = pyworld.harvest(
247
- x.astype(np.double),
248
- fs=16000,
249
- f0_ceil=1100,
250
- f0_floor=50,
251
- frame_period=10,
252
- )
253
- f0 = signal.medfilt(f0, 3)
254
- f0 *= pow(2, f0_up_key / 12)
255
- return self.get_f0_post(f0)
256
- f0bak = np.zeros(x.shape[0] // 160 + 1, dtype=np.float64)
257
- length = len(x)
258
- part_length = 160 * ((length // 160 - 1) // n_cpu + 1)
259
- n_cpu = (length // 160 - 1) // (part_length // 160) + 1
260
- ts = ttime()
261
- res_f0 = mm.dict()
262
- for idx in range(n_cpu):
263
- tail = part_length * (idx + 1) + 320
264
- if idx == 0:
265
- self.inp_q.put((idx, x[:tail], res_f0, n_cpu, ts))
266
- else:
267
- self.inp_q.put(
268
- (idx, x[part_length * idx - 320 : tail], res_f0, n_cpu, ts)
269
- )
270
- while 1:
271
- res_ts = self.opt_q.get()
272
- if res_ts == ts:
273
- break
274
- f0s = [i[1] for i in sorted(res_f0.items(), key=lambda x: x[0])]
275
- for idx, f0 in enumerate(f0s):
276
- if idx == 0:
277
- f0 = f0[:-3]
278
- elif idx != n_cpu - 1:
279
- f0 = f0[2:-3]
280
- else:
281
- f0 = f0[2:]
282
- f0bak[part_length * idx // 160 : part_length * idx // 160 + f0.shape[0]] = (
283
- f0
284
- )
285
- f0bak = signal.medfilt(f0bak, 3)
286
- f0bak *= pow(2, f0_up_key / 12)
287
- return self.get_f0_post(f0bak)
288
-
289
- def get_f0_crepe(self, x, f0_up_key):
290
- if "privateuseone" in str(
291
- self.device
292
- ): ###不支持dml,cpu又太慢用不成,拿fcpe顶替
293
- return self.get_f0(x, f0_up_key, 1, "fcpe")
294
- # printt("using crepe,device:%s"%self.device)
295
- f0, pd = torchcrepe.predict(
296
- x.unsqueeze(0).float(),
297
- 16000,
298
- 160,
299
- self.f0_min,
300
- self.f0_max,
301
- "full",
302
- batch_size=512,
303
- # device=self.device if self.device.type!="privateuseone" else "cpu",###crepe不用半精度全部是全精度所以不愁###cpu延迟高到没法用
304
- device=self.device,
305
- return_periodicity=True,
306
- )
307
- pd = torchcrepe.filter.median(pd, 3)
308
- f0 = torchcrepe.filter.mean(f0, 3)
309
- f0[pd < 0.1] = 0
310
- f0 *= pow(2, f0_up_key / 12)
311
- return self.get_f0_post(f0)
312
-
313
- def get_f0_rmvpe(self, x, f0_up_key):
314
- if hasattr(self, "model_rmvpe") == False:
315
- from infer.lib.rmvpe import RMVPE
316
-
317
- printt("Loading rmvpe model")
318
- self.model_rmvpe = RMVPE(
319
- "assets/rmvpe/rmvpe.pt",
320
- is_half=self.is_half,
321
- device=self.device,
322
- use_jit=self.config.use_jit,
323
- )
324
- f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
325
- f0 *= pow(2, f0_up_key / 12)
326
- return self.get_f0_post(f0)
327
-
328
- def get_f0_fcpe(self, x, f0_up_key):
329
- if hasattr(self, "model_fcpe") == False:
330
- from torchfcpe import spawn_bundled_infer_model
331
-
332
- printt("Loading fcpe model")
333
- if "privateuseone" in str(self.device):
334
- self.device_fcpe = "cpu"
335
- else:
336
- self.device_fcpe = self.device
337
- self.model_fcpe = spawn_bundled_infer_model(self.device_fcpe)
338
- f0 = self.model_fcpe.infer(
339
- x.to(self.device_fcpe).unsqueeze(0).float(),
340
- sr=16000,
341
- decoder_mode="local_argmax",
342
- threshold=0.006,
343
- )
344
- f0 *= pow(2, f0_up_key / 12)
345
- return self.get_f0_post(f0)
346
-
347
- def infer(
348
- self,
349
- input_wav: torch.Tensor,
350
- block_frame_16k,
351
- skip_head,
352
- return_length,
353
- f0method,
354
- ) -> np.ndarray:
355
- t1 = ttime()
356
- with torch.no_grad():
357
- if self.config.is_half:
358
- feats = input_wav.half().view(1, -1)
359
- else:
360
- feats = input_wav.float().view(1, -1)
361
- padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
362
- inputs = {
363
- "source": feats,
364
- "padding_mask": padding_mask,
365
- "output_layer": 9 if self.version == "v1" else 12,
366
- }
367
- logits = self.model.extract_features(**inputs)
368
- feats = (
369
- self.model.final_proj(logits[0]) if self.version == "v1" else logits[0]
370
- )
371
- feats = torch.cat((feats, feats[:, -1:, :]), 1)
372
- t2 = ttime()
373
- try:
374
- if hasattr(self, "index") and self.index_rate != 0:
375
- npy = feats[0][skip_head // 2 :].cpu().numpy().astype("float32")
376
- score, ix = self.index.search(npy, k=8)
377
- if (ix >= 0).all():
378
- weight = np.square(1 / score)
379
- weight /= weight.sum(axis=1, keepdims=True)
380
- npy = np.sum(
381
- self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1
382
- )
383
- if self.config.is_half:
384
- npy = npy.astype("float16")
385
- feats[0][skip_head // 2 :] = (
386
- torch.from_numpy(npy).unsqueeze(0).to(self.device)
387
- * self.index_rate
388
- + (1 - self.index_rate) * feats[0][skip_head // 2 :]
389
- )
390
- else:
391
- printt(
392
- "Invalid index. You MUST use added_xxxx.index but not trained_xxxx.index!"
393
- )
394
- else:
395
- printt("Index search FAILED or disabled")
396
- except:
397
- traceback.print_exc()
398
- printt("Index search FAILED")
399
- t3 = ttime()
400
- p_len = input_wav.shape[0] // 160
401
- if self.if_f0 == 1:
402
- f0_extractor_frame = block_frame_16k + 800
403
- if f0method == "rmvpe":
404
- f0_extractor_frame = 5120 * ((f0_extractor_frame - 1) // 5120 + 1) - 160
405
- pitch, pitchf = self.get_f0(
406
- input_wav[-f0_extractor_frame:], self.f0_up_key, self.n_cpu, f0method
407
- )
408
- shift = block_frame_16k // 160
409
- self.cache_pitch[:-shift] = self.cache_pitch[shift:].clone()
410
- self.cache_pitchf[:-shift] = self.cache_pitchf[shift:].clone()
411
- self.cache_pitch[4 - pitch.shape[0] :] = pitch[3:-1]
412
- self.cache_pitchf[4 - pitch.shape[0] :] = pitchf[3:-1]
413
- cache_pitch = self.cache_pitch[None, -p_len:]
414
- cache_pitchf = self.cache_pitchf[None, -p_len:]
415
- t4 = ttime()
416
- feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
417
- feats = feats[:, :p_len, :]
418
- p_len = torch.LongTensor([p_len]).to(self.device)
419
- sid = torch.LongTensor([0]).to(self.device)
420
- skip_head = torch.LongTensor([skip_head])
421
- return_length = torch.LongTensor([return_length])
422
- with torch.no_grad():
423
- if self.if_f0 == 1:
424
- infered_audio, _, _ = self.net_g.infer(
425
- feats,
426
- p_len,
427
- cache_pitch,
428
- cache_pitchf,
429
- sid,
430
- skip_head,
431
- return_length,
432
- )
433
- else:
434
- infered_audio, _, _ = self.net_g.infer(
435
- feats, p_len, sid, skip_head, return_length
436
- )
437
- t5 = ttime()
438
- printt(
439
- "Spent time: fea = %.3fs, index = %.3fs, f0 = %.3fs, model = %.3fs",
440
- t2 - t1,
441
- t3 - t2,
442
- t4 - t3,
443
- t5 - t4,
444
- )
445
- return infered_audio.squeeze().float()