vc_infer_pipeline.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import numpy as np, parselmouth, torch, pdb, sys, os
  2. from time import time as ttime
  3. import torch.nn.functional as F
  4. import scipy.signal as signal
  5. import pyworld, os, traceback, faiss, librosa, torchcrepe
  6. from scipy import signal
  7. from functools import lru_cache
  8. now_dir = os.getcwd()
  9. sys.path.append(now_dir)
  10. bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
  11. input_audio_path2wav = {}
  12. @lru_cache
  13. def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
  14. audio = input_audio_path2wav[input_audio_path]
  15. f0, t = pyworld.harvest(
  16. audio,
  17. fs=fs,
  18. f0_ceil=f0max,
  19. f0_floor=f0min,
  20. frame_period=frame_period,
  21. )
  22. f0 = pyworld.stonemask(audio, f0, t, fs)
  23. return f0
  24. def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
  25. # print(data1.max(),data2.max())
  26. rms1 = librosa.feature.rms(
  27. y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
  28. ) # 每半秒一个点
  29. rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
  30. rms1 = torch.from_numpy(rms1)
  31. rms1 = F.interpolate(
  32. rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
  33. ).squeeze()
  34. rms2 = torch.from_numpy(rms2)
  35. rms2 = F.interpolate(
  36. rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
  37. ).squeeze()
  38. rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
  39. data2 *= (
  40. torch.pow(rms1, torch.tensor(1 - rate))
  41. * torch.pow(rms2, torch.tensor(rate - 1))
  42. ).numpy()
  43. return data2
  44. class VC(object):
  45. def __init__(self, tgt_sr, config):
  46. self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
  47. config.x_pad,
  48. config.x_query,
  49. config.x_center,
  50. config.x_max,
  51. config.is_half,
  52. )
  53. self.sr = 16000 # hubert输入采样率
  54. self.window = 160 # 每帧点数
  55. self.t_pad = self.sr * self.x_pad # 每条前后pad时间
  56. self.t_pad_tgt = tgt_sr * self.x_pad
  57. self.t_pad2 = self.t_pad * 2
  58. self.t_query = self.sr * self.x_query # 查询切点前后查询时间
  59. self.t_center = self.sr * self.x_center # 查询切点位置
  60. self.t_max = self.sr * self.x_max # 免查询时长阈值
  61. self.device = config.device
  62. def get_f0(
  63. self,
  64. input_audio_path,
  65. x,
  66. p_len,
  67. f0_up_key,
  68. f0_method,
  69. filter_radius,
  70. inp_f0=None,
  71. ):
  72. global input_audio_path2wav
  73. time_step = self.window / self.sr * 1000
  74. f0_min = 50
  75. f0_max = 1100
  76. f0_mel_min = 1127 * np.log(1 + f0_min / 700)
  77. f0_mel_max = 1127 * np.log(1 + f0_max / 700)
  78. if f0_method == "pm":
  79. f0 = (
  80. parselmouth.Sound(x, self.sr)
  81. .to_pitch_ac(
  82. time_step=time_step / 1000,
  83. voicing_threshold=0.6,
  84. pitch_floor=f0_min,
  85. pitch_ceiling=f0_max,
  86. )
  87. .selected_array["frequency"]
  88. )
  89. pad_size = (p_len - len(f0) + 1) // 2
  90. if pad_size > 0 or p_len - len(f0) - pad_size > 0:
  91. f0 = np.pad(
  92. f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
  93. )
  94. elif f0_method == "harvest":
  95. input_audio_path2wav[input_audio_path] = x.astype(np.double)
  96. f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
  97. if filter_radius > 2:
  98. f0 = signal.medfilt(f0, 3)
  99. elif f0_method == "crepe":
  100. model = "full"
  101. # Pick a batch size that doesn't cause memory errors on your gpu
  102. batch_size = 512
  103. # Compute pitch using first gpu
  104. audio = torch.tensor(np.copy(x))[None].float()
  105. f0, pd = torchcrepe.predict(
  106. audio,
  107. self.sr,
  108. self.window,
  109. f0_min,
  110. f0_max,
  111. model,
  112. batch_size=batch_size,
  113. device=self.device,
  114. return_periodicity=True,
  115. )
  116. pd = torchcrepe.filter.median(pd, 3)
  117. f0 = torchcrepe.filter.mean(f0, 3)
  118. f0[pd < 0.1] = 0
  119. f0 = f0[0].cpu().numpy()
  120. elif f0_method == "rmvpe":
  121. if hasattr(self, "model_rmvpe") == False:
  122. from rmvpe import RMVPE
  123. print("loading rmvpe model")
  124. self.model_rmvpe = RMVPE(
  125. "rmvpe.pt", is_half=self.is_half, device=self.device
  126. )
  127. f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
  128. f0 *= pow(2, f0_up_key / 12)
  129. # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
  130. tf0 = self.sr // self.window # 每秒f0点数
  131. if inp_f0 is not None:
  132. delta_t = np.round(
  133. (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
  134. ).astype("int16")
  135. replace_f0 = np.interp(
  136. list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
  137. )
  138. shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
  139. f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
  140. :shape
  141. ]
  142. # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
  143. f0bak = f0.copy()
  144. f0_mel = 1127 * np.log(1 + f0 / 700)
  145. f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
  146. f0_mel_max - f0_mel_min
  147. ) + 1
  148. f0_mel[f0_mel <= 1] = 1
  149. f0_mel[f0_mel > 255] = 255
  150. #f0_coarse = np.rint(f0_mel).astype(np.int)
  151. f0_coarse = np.rint(f0_mel).astype(np.int_)
  152. return f0_coarse, f0bak # 1-0
  153. def vc(
  154. self,
  155. model,
  156. net_g,
  157. sid,
  158. audio0,
  159. pitch,
  160. pitchf,
  161. times,
  162. index,
  163. big_npy,
  164. index_rate,
  165. version,
  166. ): # ,file_index,file_big_npy
  167. feats = torch.from_numpy(audio0)
  168. if self.is_half:
  169. feats = feats.half()
  170. else:
  171. feats = feats.float()
  172. if feats.dim() == 2: # double channels
  173. feats = feats.mean(-1)
  174. assert feats.dim() == 1, feats.dim()
  175. feats = feats.view(1, -1)
  176. padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
  177. inputs = {
  178. "source": feats.to(self.device),
  179. "padding_mask": padding_mask,
  180. "output_layer": 9 if version == "v1" else 12,
  181. }
  182. t0 = ttime()
  183. with torch.no_grad():
  184. logits = model.extract_features(**inputs)
  185. feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
  186. if (
  187. isinstance(index, type(None)) == False
  188. and isinstance(big_npy, type(None)) == False
  189. and index_rate != 0
  190. ):
  191. npy = feats[0].cpu().numpy()
  192. if self.is_half:
  193. npy = npy.astype("float32")
  194. # _, I = index.search(npy, 1)
  195. # npy = big_npy[I.squeeze()]
  196. score, ix = index.search(npy, k=8)
  197. weight = np.square(1 / score)
  198. weight /= weight.sum(axis=1, keepdims=True)
  199. npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
  200. if self.is_half:
  201. npy = npy.astype("float16")
  202. feats = (
  203. torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
  204. + (1 - index_rate) * feats
  205. )
  206. feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
  207. t1 = ttime()
  208. p_len = audio0.shape[0] // self.window
  209. if feats.shape[1] < p_len:
  210. p_len = feats.shape[1]
  211. if pitch != None and pitchf != None:
  212. pitch = pitch[:, :p_len]
  213. pitchf = pitchf[:, :p_len]
  214. p_len = torch.tensor([p_len], device=self.device).long()
  215. with torch.no_grad():
  216. if pitch != None and pitchf != None:
  217. audio1 = (
  218. (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
  219. .data.cpu()
  220. .float()
  221. .numpy()
  222. )
  223. else:
  224. audio1 = (
  225. (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
  226. )
  227. del feats, p_len, padding_mask
  228. if torch.cuda.is_available():
  229. torch.cuda.empty_cache()
  230. t2 = ttime()
  231. times[0] += t1 - t0
  232. times[2] += t2 - t1
  233. return audio1
  234. def pipeline(
  235. self,
  236. model,
  237. net_g,
  238. sid,
  239. audio,
  240. input_audio_path,
  241. times,
  242. f0_up_key,
  243. f0_method,
  244. file_index,
  245. # file_big_npy,
  246. index_rate,
  247. if_f0,
  248. filter_radius,
  249. tgt_sr,
  250. resample_sr,
  251. rms_mix_rate,
  252. version,
  253. f0_file=None,
  254. ):
  255. if (
  256. file_index != ""
  257. # and file_big_npy != ""
  258. # and os.path.exists(file_big_npy) == True
  259. and os.path.exists(file_index) == True
  260. and index_rate != 0
  261. ):
  262. try:
  263. index = faiss.read_index(file_index)
  264. # big_npy = np.load(file_big_npy)
  265. big_npy = index.reconstruct_n(0, index.ntotal)
  266. except:
  267. traceback.print_exc()
  268. index = big_npy = None
  269. else:
  270. index = big_npy = None
  271. audio = signal.filtfilt(bh, ah, audio)
  272. audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
  273. opt_ts = []
  274. if audio_pad.shape[0] > self.t_max:
  275. audio_sum = np.zeros_like(audio)
  276. for i in range(self.window):
  277. audio_sum += audio_pad[i : i - self.window]
  278. for t in range(self.t_center, audio.shape[0], self.t_center):
  279. opt_ts.append(
  280. t
  281. - self.t_query
  282. + np.where(
  283. np.abs(audio_sum[t - self.t_query : t + self.t_query])
  284. == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
  285. )[0][0]
  286. )
  287. s = 0
  288. audio_opt = []
  289. t = None
  290. t1 = ttime()
  291. audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
  292. p_len = audio_pad.shape[0] // self.window
  293. inp_f0 = None
  294. if hasattr(f0_file, "name") == True:
  295. try:
  296. with open(f0_file.name, "r") as f:
  297. lines = f.read().strip("\n").split("\n")
  298. inp_f0 = []
  299. for line in lines:
  300. inp_f0.append([float(i) for i in line.split(",")])
  301. inp_f0 = np.array(inp_f0, dtype="float32")
  302. except:
  303. traceback.print_exc()
  304. sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
  305. pitch, pitchf = None, None
  306. if if_f0 == 1:
  307. pitch, pitchf = self.get_f0(
  308. input_audio_path,
  309. audio_pad,
  310. p_len,
  311. f0_up_key,
  312. f0_method,
  313. filter_radius,
  314. inp_f0,
  315. )
  316. pitch = pitch[:p_len]
  317. pitchf = pitchf[:p_len]
  318. if self.device == "mps":
  319. pitchf = pitchf.astype(np.float32)
  320. pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
  321. pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
  322. t2 = ttime()
  323. times[1] += t2 - t1
  324. for t in opt_ts:
  325. t = t // self.window * self.window
  326. if if_f0 == 1:
  327. audio_opt.append(
  328. self.vc(
  329. model,
  330. net_g,
  331. sid,
  332. audio_pad[s : t + self.t_pad2 + self.window],
  333. pitch[:, s // self.window : (t + self.t_pad2) // self.window],
  334. pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
  335. times,
  336. index,
  337. big_npy,
  338. index_rate,
  339. version,
  340. )[self.t_pad_tgt : -self.t_pad_tgt]
  341. )
  342. else:
  343. audio_opt.append(
  344. self.vc(
  345. model,
  346. net_g,
  347. sid,
  348. audio_pad[s : t + self.t_pad2 + self.window],
  349. None,
  350. None,
  351. times,
  352. index,
  353. big_npy,
  354. index_rate,
  355. version,
  356. )[self.t_pad_tgt : -self.t_pad_tgt]
  357. )
  358. s = t
  359. if if_f0 == 1:
  360. audio_opt.append(
  361. self.vc(
  362. model,
  363. net_g,
  364. sid,
  365. audio_pad[t:],
  366. pitch[:, t // self.window :] if t is not None else pitch,
  367. pitchf[:, t // self.window :] if t is not None else pitchf,
  368. times,
  369. index,
  370. big_npy,
  371. index_rate,
  372. version,
  373. )[self.t_pad_tgt : -self.t_pad_tgt]
  374. )
  375. else:
  376. audio_opt.append(
  377. self.vc(
  378. model,
  379. net_g,
  380. sid,
  381. audio_pad[t:],
  382. None,
  383. None,
  384. times,
  385. index,
  386. big_npy,
  387. index_rate,
  388. version,
  389. )[self.t_pad_tgt : -self.t_pad_tgt]
  390. )
  391. audio_opt = np.concatenate(audio_opt)
  392. if rms_mix_rate != 1:
  393. audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
  394. if resample_sr >= 16000 and tgt_sr != resample_sr:
  395. audio_opt = librosa.resample(
  396. audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
  397. )
  398. audio_max = np.abs(audio_opt).max() / 0.99
  399. max_int16 = 32768
  400. if audio_max > 1:
  401. max_int16 /= audio_max
  402. audio_opt = (audio_opt * max_int16).astype(np.int16)
  403. del pitch, pitchf, sid
  404. if torch.cuda.is_available():
  405. torch.cuda.empty_cache()
  406. return audio_opt