rmvpe.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import sys, torch, numpy as np, traceback, pdb
  2. import torch.nn as nn
  3. from time import time as ttime
  4. import torch.nn.functional as F
  5. class BiGRU(nn.Module):
  6. def __init__(self, input_features, hidden_features, num_layers):
  7. super(BiGRU, self).__init__()
  8. self.gru = nn.GRU(
  9. input_features,
  10. hidden_features,
  11. num_layers=num_layers,
  12. batch_first=True,
  13. bidirectional=True,
  14. )
  15. def forward(self, x):
  16. return self.gru(x)[0]
  17. class ConvBlockRes(nn.Module):
  18. def __init__(self, in_channels, out_channels, momentum=0.01):
  19. super(ConvBlockRes, self).__init__()
  20. self.conv = nn.Sequential(
  21. nn.Conv2d(
  22. in_channels=in_channels,
  23. out_channels=out_channels,
  24. kernel_size=(3, 3),
  25. stride=(1, 1),
  26. padding=(1, 1),
  27. bias=False,
  28. ),
  29. nn.BatchNorm2d(out_channels, momentum=momentum),
  30. nn.ReLU(),
  31. nn.Conv2d(
  32. in_channels=out_channels,
  33. out_channels=out_channels,
  34. kernel_size=(3, 3),
  35. stride=(1, 1),
  36. padding=(1, 1),
  37. bias=False,
  38. ),
  39. nn.BatchNorm2d(out_channels, momentum=momentum),
  40. nn.ReLU(),
  41. )
  42. if in_channels != out_channels:
  43. self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
  44. self.is_shortcut = True
  45. else:
  46. self.is_shortcut = False
  47. def forward(self, x):
  48. if self.is_shortcut:
  49. return self.conv(x) + self.shortcut(x)
  50. else:
  51. return self.conv(x) + x
  52. class Encoder(nn.Module):
  53. def __init__(
  54. self,
  55. in_channels,
  56. in_size,
  57. n_encoders,
  58. kernel_size,
  59. n_blocks,
  60. out_channels=16,
  61. momentum=0.01,
  62. ):
  63. super(Encoder, self).__init__()
  64. self.n_encoders = n_encoders
  65. self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
  66. self.layers = nn.ModuleList()
  67. self.latent_channels = []
  68. for i in range(self.n_encoders):
  69. self.layers.append(
  70. ResEncoderBlock(
  71. in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
  72. )
  73. )
  74. self.latent_channels.append([out_channels, in_size])
  75. in_channels = out_channels
  76. out_channels *= 2
  77. in_size //= 2
  78. self.out_size = in_size
  79. self.out_channel = out_channels
  80. def forward(self, x):
  81. concat_tensors = []
  82. x = self.bn(x)
  83. for i in range(self.n_encoders):
  84. _, x = self.layers[i](x)
  85. concat_tensors.append(_)
  86. return x, concat_tensors
  87. class ResEncoderBlock(nn.Module):
  88. def __init__(
  89. self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
  90. ):
  91. super(ResEncoderBlock, self).__init__()
  92. self.n_blocks = n_blocks
  93. self.conv = nn.ModuleList()
  94. self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
  95. for i in range(n_blocks - 1):
  96. self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
  97. self.kernel_size = kernel_size
  98. if self.kernel_size is not None:
  99. self.pool = nn.AvgPool2d(kernel_size=kernel_size)
  100. def forward(self, x):
  101. for i in range(self.n_blocks):
  102. x = self.conv[i](x)
  103. if self.kernel_size is not None:
  104. return x, self.pool(x)
  105. else:
  106. return x
  107. class Intermediate(nn.Module): #
  108. def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
  109. super(Intermediate, self).__init__()
  110. self.n_inters = n_inters
  111. self.layers = nn.ModuleList()
  112. self.layers.append(
  113. ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
  114. )
  115. for i in range(self.n_inters - 1):
  116. self.layers.append(
  117. ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
  118. )
  119. def forward(self, x):
  120. for i in range(self.n_inters):
  121. x = self.layers[i](x)
  122. return x
  123. class ResDecoderBlock(nn.Module):
  124. def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
  125. super(ResDecoderBlock, self).__init__()
  126. out_padding = (0, 1) if stride == (1, 2) else (1, 1)
  127. self.n_blocks = n_blocks
  128. self.conv1 = nn.Sequential(
  129. nn.ConvTranspose2d(
  130. in_channels=in_channels,
  131. out_channels=out_channels,
  132. kernel_size=(3, 3),
  133. stride=stride,
  134. padding=(1, 1),
  135. output_padding=out_padding,
  136. bias=False,
  137. ),
  138. nn.BatchNorm2d(out_channels, momentum=momentum),
  139. nn.ReLU(),
  140. )
  141. self.conv2 = nn.ModuleList()
  142. self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
  143. for i in range(n_blocks - 1):
  144. self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
  145. def forward(self, x, concat_tensor):
  146. x = self.conv1(x)
  147. x = torch.cat((x, concat_tensor), dim=1)
  148. for i in range(self.n_blocks):
  149. x = self.conv2[i](x)
  150. return x
  151. class Decoder(nn.Module):
  152. def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
  153. super(Decoder, self).__init__()
  154. self.layers = nn.ModuleList()
  155. self.n_decoders = n_decoders
  156. for i in range(self.n_decoders):
  157. out_channels = in_channels // 2
  158. self.layers.append(
  159. ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
  160. )
  161. in_channels = out_channels
  162. def forward(self, x, concat_tensors):
  163. for i in range(self.n_decoders):
  164. x = self.layers[i](x, concat_tensors[-1 - i])
  165. return x
  166. class DeepUnet(nn.Module):
  167. def __init__(
  168. self,
  169. kernel_size,
  170. n_blocks,
  171. en_de_layers=5,
  172. inter_layers=4,
  173. in_channels=1,
  174. en_out_channels=16,
  175. ):
  176. super(DeepUnet, self).__init__()
  177. self.encoder = Encoder(
  178. in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
  179. )
  180. self.intermediate = Intermediate(
  181. self.encoder.out_channel // 2,
  182. self.encoder.out_channel,
  183. inter_layers,
  184. n_blocks,
  185. )
  186. self.decoder = Decoder(
  187. self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
  188. )
  189. def forward(self, x):
  190. x, concat_tensors = self.encoder(x)
  191. x = self.intermediate(x)
  192. x = self.decoder(x, concat_tensors)
  193. return x
  194. class E2E(nn.Module):
  195. def __init__(
  196. self,
  197. n_blocks,
  198. n_gru,
  199. kernel_size,
  200. en_de_layers=5,
  201. inter_layers=4,
  202. in_channels=1,
  203. en_out_channels=16,
  204. ):
  205. super(E2E, self).__init__()
  206. self.unet = DeepUnet(
  207. kernel_size,
  208. n_blocks,
  209. en_de_layers,
  210. inter_layers,
  211. in_channels,
  212. en_out_channels,
  213. )
  214. self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
  215. if n_gru:
  216. self.fc = nn.Sequential(
  217. BiGRU(3 * 128, 256, n_gru),
  218. nn.Linear(512, 360),
  219. nn.Dropout(0.25),
  220. nn.Sigmoid(),
  221. )
  222. else:
  223. self.fc = nn.Sequential(
  224. nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
  225. )
  226. def forward(self, mel):
  227. mel = mel.transpose(-1, -2).unsqueeze(1)
  228. x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
  229. x = self.fc(x)
  230. return x
  231. from librosa.filters import mel
  232. class MelSpectrogram(torch.nn.Module):
  233. def __init__(
  234. self,
  235. is_half,
  236. n_mel_channels,
  237. sampling_rate,
  238. win_length,
  239. hop_length,
  240. n_fft=None,
  241. mel_fmin=0,
  242. mel_fmax=None,
  243. clamp=1e-5,
  244. ):
  245. super().__init__()
  246. n_fft = win_length if n_fft is None else n_fft
  247. self.hann_window = {}
  248. mel_basis = mel(
  249. sr=sampling_rate,
  250. n_fft=n_fft,
  251. n_mels=n_mel_channels,
  252. fmin=mel_fmin,
  253. fmax=mel_fmax,
  254. htk=True,
  255. )
  256. mel_basis = torch.from_numpy(mel_basis).float()
  257. self.register_buffer("mel_basis", mel_basis)
  258. self.n_fft = win_length if n_fft is None else n_fft
  259. self.hop_length = hop_length
  260. self.win_length = win_length
  261. self.sampling_rate = sampling_rate
  262. self.n_mel_channels = n_mel_channels
  263. self.clamp = clamp
  264. self.is_half = is_half
  265. def forward(self, audio, keyshift=0, speed=1, center=True):
  266. factor = 2 ** (keyshift / 12)
  267. n_fft_new = int(np.round(self.n_fft * factor))
  268. win_length_new = int(np.round(self.win_length * factor))
  269. hop_length_new = int(np.round(self.hop_length * speed))
  270. keyshift_key = str(keyshift) + "_" + str(audio.device)
  271. if keyshift_key not in self.hann_window:
  272. self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
  273. audio.device
  274. )
  275. fft = torch.stft(
  276. audio,
  277. n_fft=n_fft_new,
  278. hop_length=hop_length_new,
  279. win_length=win_length_new,
  280. window=self.hann_window[keyshift_key],
  281. center=center,
  282. return_complex=True,
  283. )
  284. magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
  285. if keyshift != 0:
  286. size = self.n_fft // 2 + 1
  287. resize = magnitude.size(1)
  288. if resize < size:
  289. magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
  290. magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
  291. mel_output = torch.matmul(self.mel_basis, magnitude)
  292. if self.is_half == True:
  293. mel_output = mel_output.half()
  294. log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
  295. return log_mel_spec
  296. class RMVPE:
  297. def __init__(self, model_path, is_half, device=None):
  298. self.resample_kernel = {}
  299. model = E2E(4, 1, (2, 2))
  300. ckpt = torch.load(model_path, map_location="cpu")
  301. model.load_state_dict(ckpt)
  302. model.eval()
  303. if is_half == True:
  304. model = model.half()
  305. self.model = model
  306. self.resample_kernel = {}
  307. self.is_half = is_half
  308. if device is None:
  309. device = "cuda" if torch.cuda.is_available() else "cpu"
  310. self.device = device
  311. self.mel_extractor = MelSpectrogram(
  312. is_half, 128, 16000, 1024, 160, None, 30, 8000
  313. ).to(device)
  314. self.model = self.model.to(device)
  315. cents_mapping = 20 * np.arange(360) + 1997.3794084376191
  316. self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
  317. def mel2hidden(self, mel):
  318. with torch.no_grad():
  319. n_frames = mel.shape[-1]
  320. mel = F.pad(
  321. mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect"
  322. )
  323. hidden = self.model(mel)
  324. return hidden[:, :n_frames]
  325. def decode(self, hidden, thred=0.03):
  326. cents_pred = self.to_local_average_cents(hidden, thred=thred)
  327. f0 = 10 * (2 ** (cents_pred / 1200))
  328. f0[f0 == 10] = 0
  329. # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
  330. return f0
  331. def infer_from_audio(self, audio, thred=0.03):
  332. audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
  333. # torch.cuda.synchronize()
  334. # t0=ttime()
  335. mel = self.mel_extractor(audio, center=True)
  336. # torch.cuda.synchronize()
  337. # t1=ttime()
  338. hidden = self.mel2hidden(mel)
  339. # torch.cuda.synchronize()
  340. # t2=ttime()
  341. hidden = hidden.squeeze(0).cpu().numpy()
  342. if self.is_half == True:
  343. hidden = hidden.astype("float32")
  344. f0 = self.decode(hidden, thred=thred)
  345. # torch.cuda.synchronize()
  346. # t3=ttime()
  347. # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
  348. return f0
  349. def to_local_average_cents(self, salience, thred=0.05):
  350. # t0 = ttime()
  351. center = np.argmax(salience, axis=1) # 帧长#index
  352. salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
  353. # t1 = ttime()
  354. center += 4
  355. todo_salience = []
  356. todo_cents_mapping = []
  357. starts = center - 4
  358. ends = center + 5
  359. for idx in range(salience.shape[0]):
  360. todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
  361. todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
  362. # t2 = ttime()
  363. todo_salience = np.array(todo_salience) # 帧长,9
  364. todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
  365. product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
  366. weight_sum = np.sum(todo_salience, 1) # 帧长
  367. devided = product_sum / weight_sum # 帧长
  368. # t3 = ttime()
  369. maxx = np.max(salience, axis=1) # 帧长
  370. devided[maxx <= thred] = 0
  371. # t4 = ttime()
  372. # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
  373. return devided
  374. # if __name__ == '__main__':
  375. # audio, sampling_rate = sf.read("卢本伟语录~1.wav")
  376. # if len(audio.shape) > 1:
  377. # audio = librosa.to_mono(audio.transpose(1, 0))
  378. # audio_bak = audio.copy()
  379. # if sampling_rate != 16000:
  380. # audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
  381. # model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt"
  382. # thred = 0.03 # 0.01
  383. # device = 'cuda' if torch.cuda.is_available() else 'cpu'
  384. # rmvpe = RMVPE(model_path,is_half=False, device=device)
  385. # t0=ttime()
  386. # f0 = rmvpe.infer_from_audio(audio, thred=thred)
  387. # f0 = rmvpe.infer_from_audio(audio, thred=thred)
  388. # f0 = rmvpe.infer_from_audio(audio, thred=thred)
  389. # f0 = rmvpe.infer_from_audio(audio, thred=thred)
  390. # f0 = rmvpe.infer_from_audio(audio, thred=thred)
  391. # t1=ttime()
  392. # print(f0.shape,t1-t0)