voice-changer/server/voice_changer/RVC/pitchExtractor/CrepePitchExtractor.py

63 lines
2.0 KiB
Python
Raw Normal View History

2023-05-20 10:33:17 +03:00
import torchcrepe
import torch
import numpy as np
2023-05-31 08:30:35 +03:00
from const import EnumPitchExtractorTypes
2023-05-20 10:33:17 +03:00
from voice_changer.RVC.pitchExtractor.PitchExtractor import PitchExtractor
class CrepePitchExtractor(PitchExtractor):
2023-05-31 08:30:35 +03:00
pitchExtractorType: EnumPitchExtractorTypes = EnumPitchExtractorTypes.crepe
2023-05-20 10:33:17 +03:00
def __init__(self):
super().__init__()
if torch.cuda.is_available():
2023-05-22 08:43:25 +03:00
self.device = torch.device("cuda:" + str(torch.cuda.current_device()))
2023-05-20 10:33:17 +03:00
else:
2023-05-22 08:43:25 +03:00
self.device = torch.device("cpu")
2023-05-20 10:33:17 +03:00
def extract(self, audio, f0_up_key, sr, window, silence_front=0):
n_frames = int(len(audio) // window) + 1
start_frame = int(silence_front * sr / window)
real_silence_front = start_frame * window / sr
silence_front_offset = int(np.round(real_silence_front * sr))
audio = audio[silence_front_offset:]
f0_min = 50
f0_max = 1100
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
2023-05-31 17:50:43 +03:00
f0, pd = torchcrepe.predict(
2023-05-28 07:54:57 +03:00
audio.unsqueeze(0),
2023-05-22 08:43:25 +03:00
sr,
hop_length=window,
fmin=f0_min,
fmax=f0_max,
# model="tiny",
model="full",
batch_size=256,
decoder=torchcrepe.decode.weighted_argmax,
device=self.device,
2023-05-31 17:50:43 +03:00
return_periodicity=True,
2023-05-22 08:43:25 +03:00
)
2023-06-01 07:28:45 +03:00
f0 = torchcrepe.filter.median(f0, 3) # 本家だとmeanですが、harvestに合わせmedianフィルタ
2023-05-31 17:50:43 +03:00
pd = torchcrepe.filter.median(pd, 3)
f0[pd < 0.1] = 0
2023-05-28 07:54:57 +03:00
f0 = f0.squeeze()
2023-05-20 10:33:17 +03:00
2023-05-28 07:54:57 +03:00
f0 = torch.nn.functional.pad(
f0, (start_frame, n_frames - f0.shape[0] - start_frame)
2023-05-22 08:43:25 +03:00
)
2023-05-20 10:33:17 +03:00
f0 *= pow(2, f0_up_key / 12)
2023-05-28 07:54:57 +03:00
f0bak = f0.detach().cpu().numpy()
2023-05-29 15:55:02 +03:00
f0_mel = 1127.0 * torch.log(1.0 + f0 / 700.0)
f0_mel = torch.clip(
(f0_mel - f0_mel_min) * 254.0 / (f0_mel_max - f0_mel_min) + 1.0, 1.0, 255.0
)
2023-05-31 14:07:12 +03:00
f0_coarse = f0_mel.round().detach().cpu().numpy().astype(int)
2023-05-20 10:33:17 +03:00
return f0_coarse, f0bak