Bless2776 commited on
Commit
ab8383e
1 Parent(s): ea587d6

Upload vc_infer_pipeline.py

Browse files
Files changed (1) hide show
  1. vc_infer_pipeline.py +306 -0
vc_infer_pipeline.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np, parselmouth, torch, pdb
2
+ from time import time as ttime
3
+ import torch.nn.functional as F
4
+ from config import x_pad, x_query, x_center, x_max
5
+ import scipy.signal as signal
6
+ import pyworld, os, traceback, faiss
7
+ from scipy import signal
8
+
9
+ bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
10
+
11
+
12
+ class VC(object):
13
+ def __init__(self, tgt_sr, device, is_half):
14
+ self.sr = 16000 # hubert输入采样率
15
+ self.window = 160 # 每帧点数
16
+ self.t_pad = self.sr * x_pad # 每条前后pad时间
17
+ self.t_pad_tgt = tgt_sr * x_pad
18
+ self.t_pad2 = self.t_pad * 2
19
+ self.t_query = self.sr * x_query # 查询切点前后查询时间
20
+ self.t_center = self.sr * x_center # 查询切点位置
21
+ self.t_max = self.sr * x_max # 免查询时长阈值
22
+ self.device = device
23
+ self.is_half = is_half
24
+
25
+ def get_f0(self, x, p_len, f0_up_key, f0_method, inp_f0=None):
26
+ time_step = self.window / self.sr * 1000
27
+ f0_min = 50
28
+ f0_max = 1100
29
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
30
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
31
+ if f0_method == "pm":
32
+ f0 = (
33
+ parselmouth.Sound(x, self.sr)
34
+ .to_pitch_ac(
35
+ time_step=time_step / 1000,
36
+ voicing_threshold=0.6,
37
+ pitch_floor=f0_min,
38
+ pitch_ceiling=f0_max,
39
+ )
40
+ .selected_array["frequency"]
41
+ )
42
+ pad_size = (p_len - len(f0) + 1) // 2
43
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
44
+ f0 = np.pad(
45
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
46
+ )
47
+ elif f0_method == "harvest":
48
+ f0, t = pyworld.harvest(
49
+ x.astype(np.double),
50
+ fs=self.sr,
51
+ f0_ceil=f0_max,
52
+ f0_floor=f0_min,
53
+ frame_period=10,
54
+ )
55
+ f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
56
+ f0 = signal.medfilt(f0, 3)
57
+ f0 *= pow(2, f0_up_key / 12)
58
+ # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
59
+ tf0 = self.sr // self.window # 每秒f0点数
60
+ if inp_f0 is not None:
61
+ delta_t = np.round(
62
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
63
+ ).astype("int16")
64
+ replace_f0 = np.interp(
65
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
66
+ )
67
+ shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0]
68
+ f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape]
69
+ # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
70
+ f0bak = f0.copy()
71
+ f0_mel = 1127 * np.log(1 + f0 / 700)
72
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
73
+ f0_mel_max - f0_mel_min
74
+ ) + 1
75
+ f0_mel[f0_mel <= 1] = 1
76
+ f0_mel[f0_mel > 255] = 255
77
+ f0_coarse = np.rint(f0_mel).astype(np.int)
78
+ return f0_coarse, f0bak # 1-0
79
+
80
+ def vc(
81
+ self,
82
+ model,
83
+ net_g,
84
+ sid,
85
+ audio0,
86
+ pitch,
87
+ pitchf,
88
+ times,
89
+ index,
90
+ big_npy,
91
+ index_rate,
92
+ ): # ,file_index,file_big_npy
93
+ feats = torch.from_numpy(audio0)
94
+ if self.is_half:
95
+ feats = feats.half()
96
+ else:
97
+ feats = feats.float()
98
+ if feats.dim() == 2: # double channels
99
+ feats = feats.mean(-1)
100
+ assert feats.dim() == 1, feats.dim()
101
+ feats = feats.view(1, -1)
102
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
103
+
104
+ inputs = {
105
+ "source": feats.to(self.device),
106
+ "padding_mask": padding_mask,
107
+ "output_layer": 9, # layer 9
108
+ }
109
+ t0 = ttime()
110
+ with torch.no_grad():
111
+ logits = model.extract_features(**inputs)
112
+ feats = model.final_proj(logits[0])
113
+
114
+ if (
115
+ isinstance(index, type(None)) == False
116
+ and isinstance(big_npy, type(None)) == False
117
+ and index_rate != 0
118
+ ):
119
+ npy = feats[0].cpu().numpy()
120
+ if self.is_half:
121
+ npy = npy.astype("float32")
122
+ _, I = index.search(npy, 1)
123
+ npy = big_npy[I.squeeze()]
124
+ if self.is_half:
125
+ npy = npy.astype("float16")
126
+ feats = (
127
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
128
+ + (1 - index_rate) * feats
129
+ )
130
+
131
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
132
+ t1 = ttime()
133
+ p_len = audio0.shape[0] // self.window
134
+ if feats.shape[1] < p_len:
135
+ p_len = feats.shape[1]
136
+ if pitch != None and pitchf != None:
137
+ pitch = pitch[:, :p_len]
138
+ pitchf = pitchf[:, :p_len]
139
+ p_len = torch.tensor([p_len], device=self.device).long()
140
+ with torch.no_grad():
141
+ if pitch != None and pitchf != None:
142
+ audio1 = (
143
+ (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0] * 32768)
144
+ .data.cpu()
145
+ .float()
146
+ .numpy()
147
+ .astype(np.int16)
148
+ )
149
+ else:
150
+ audio1 = (
151
+ (net_g.infer(feats, p_len, sid)[0][0, 0] * 32768)
152
+ .data.cpu()
153
+ .float()
154
+ .numpy()
155
+ .astype(np.int16)
156
+ )
157
+ del feats, p_len, padding_mask
158
+ if torch.cuda.is_available():
159
+ torch.cuda.empty_cache()
160
+ t2 = ttime()
161
+ times[0] += t1 - t0
162
+ times[2] += t2 - t1
163
+ return audio1
164
+
165
+ def pipeline(
166
+ self,
167
+ model,
168
+ net_g,
169
+ sid,
170
+ audio,
171
+ times,
172
+ f0_up_key,
173
+ f0_method,
174
+ file_index,
175
+ file_big_npy,
176
+ index_rate,
177
+ if_f0,
178
+ f0_file=None,
179
+ ):
180
+ if (
181
+ file_big_npy != ""
182
+ and file_index != ""
183
+ and os.path.exists(file_big_npy) == True
184
+ and os.path.exists(file_index) == True
185
+ and index_rate != 0
186
+ ):
187
+ try:
188
+ index = faiss.read_index(file_index)
189
+ big_npy = np.load(file_big_npy)
190
+ except:
191
+ traceback.print_exc()
192
+ index = big_npy = None
193
+ else:
194
+ index = big_npy = None
195
+ print("Feature retrieval library doesn't exist or ratio is 0")
196
+ audio = signal.filtfilt(bh, ah, audio)
197
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
198
+ opt_ts = []
199
+ if audio_pad.shape[0] > self.t_max:
200
+ audio_sum = np.zeros_like(audio)
201
+ for i in range(self.window):
202
+ audio_sum += audio_pad[i : i - self.window]
203
+ for t in range(self.t_center, audio.shape[0], self.t_center):
204
+ opt_ts.append(
205
+ t
206
+ - self.t_query
207
+ + np.where(
208
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
209
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
210
+ )[0][0]
211
+ )
212
+ s = 0
213
+ audio_opt = []
214
+ t = None
215
+ t1 = ttime()
216
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
217
+ p_len = audio_pad.shape[0] // self.window
218
+ inp_f0 = None
219
+ if hasattr(f0_file, "name") == True:
220
+ try:
221
+ with open(f0_file.name, "r") as f:
222
+ lines = f.read().strip("\n").split("\n")
223
+ inp_f0 = []
224
+ for line in lines:
225
+ inp_f0.append([float(i) for i in line.split(",")])
226
+ inp_f0 = np.array(inp_f0, dtype="float32")
227
+ except:
228
+ traceback.print_exc()
229
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
230
+ pitch, pitchf = None, None
231
+ if if_f0 == 1:
232
+ pitch, pitchf = self.get_f0(audio_pad, p_len, f0_up_key, f0_method, inp_f0)
233
+ pitch = pitch[:p_len]
234
+ pitchf = pitchf[:p_len]
235
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
236
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
237
+ t2 = ttime()
238
+ times[1] += t2 - t1
239
+ for t in opt_ts:
240
+ t = t // self.window * self.window
241
+ if if_f0 == 1:
242
+ audio_opt.append(
243
+ self.vc(
244
+ model,
245
+ net_g,
246
+ sid,
247
+ audio_pad[s : t + self.t_pad2 + self.window],
248
+ pitch[:, s // self.window : (t + self.t_pad2) // self.window],
249
+ pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
250
+ times,
251
+ index,
252
+ big_npy,
253
+ index_rate,
254
+ )[self.t_pad_tgt : -self.t_pad_tgt]
255
+ )
256
+ else:
257
+ audio_opt.append(
258
+ self.vc(
259
+ model,
260
+ net_g,
261
+ sid,
262
+ audio_pad[s : t + self.t_pad2 + self.window],
263
+ None,
264
+ None,
265
+ times,
266
+ index,
267
+ big_npy,
268
+ index_rate,
269
+ )[self.t_pad_tgt : -self.t_pad_tgt]
270
+ )
271
+ s = t
272
+ if if_f0 == 1:
273
+ audio_opt.append(
274
+ self.vc(
275
+ model,
276
+ net_g,
277
+ sid,
278
+ audio_pad[t:],
279
+ pitch[:, t // self.window :] if t is not None else pitch,
280
+ pitchf[:, t // self.window :] if t is not None else pitchf,
281
+ times,
282
+ index,
283
+ big_npy,
284
+ index_rate,
285
+ )[self.t_pad_tgt : -self.t_pad_tgt]
286
+ )
287
+ else:
288
+ audio_opt.append(
289
+ self.vc(
290
+ model,
291
+ net_g,
292
+ sid,
293
+ audio_pad[t:],
294
+ None,
295
+ None,
296
+ times,
297
+ index,
298
+ big_npy,
299
+ index_rate,
300
+ )[self.t_pad_tgt : -self.t_pad_tgt]
301
+ )
302
+ audio_opt = np.concatenate(audio_opt)
303
+ del pitch, pitchf, sid
304
+ if torch.cuda.is_available():
305
+ torch.cuda.empty_cache()
306
+ return audio_opt