Skip to content

Commit 2207b96

Browse files
authored
Add files via upload
1 parent a7857f1 commit 2207b96

9 files changed

+1889
-0
lines changed

config.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
############离线VC参数
2+
inp_root=r"白鹭霜华长条"#对输入目录下所有音频进行转换,别放非音频文件
3+
opt_root=r"opt"#输出目录
4+
f0_up_key=0#升降调,整数,男转女12,女转男-12
5+
person=r"weights\洛天依v3.pt"#目前只有洛天依v3
6+
############硬件参数
7+
device = "cuda:0"#填写cuda:x或cpu,x指代第几张卡,只支持N卡加速
8+
is_half=True#9-10-20-30-40系显卡无脑True,不影响质量,>=20显卡开启有加速
9+
n_cpu=0#默认0用上所有线程,写数字限制CPU资源使用
10+
############下头别动
11+
import torch
12+
if(torch.cuda.is_available()==False):
13+
print("没有发现支持的N卡,使用CPU进行推理")
14+
device="cpu"
15+
is_half=False
16+
if(device!="cpu"):
17+
gpu_name=torch.cuda.get_device_name(int(device.split(":")[-1]))
18+
if("16"in gpu_name or "MX"in gpu_name):
19+
print("16系显卡/MX系显卡强制单精度")
20+
is_half=False
21+
from multiprocessing import cpu_count
22+
if(n_cpu==0):n_cpu=cpu_count()
23+
if(is_half==True):
24+
#6G显存配置
25+
x_pad = 3
26+
x_query = 10
27+
x_center = 60
28+
x_max = 65
29+
else:
30+
#5G显存配置
31+
x_pad = 1
32+
# x_query = 6
33+
# x_center = 30
34+
# x_max = 32
35+
#6G显存配置
36+
x_query = 6
37+
x_center = 38
38+
x_max = 41

extract_f0_print.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import os,traceback,sys,parselmouth
2+
import librosa
3+
import pyworld
4+
from scipy.io import wavfile
5+
import numpy as np,logging
6+
logging.getLogger('numba').setLevel(logging.WARNING)
7+
from multiprocessing import Process
8+
9+
exp_dir = sys.argv[1]
10+
f = open("%s/extract_f0_feature.log"%exp_dir, "a+")
11+
def printt(strr):
12+
print(strr)
13+
f.write("%s\n" % strr)
14+
f.flush()
15+
16+
n_p = int(sys.argv[2])
17+
f0method = sys.argv[3]
18+
19+
class FeatureInput(object):
20+
def __init__(self, samplerate=16000, hop_size=160):
21+
self.fs = samplerate
22+
self.hop = hop_size
23+
24+
self.f0_bin = 256
25+
self.f0_max = 1100.0
26+
self.f0_min = 50.0
27+
self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
28+
self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
29+
30+
def compute_f0(self, path,f0_method):
31+
x, sr = librosa.load(path, self.fs)
32+
p_len=x.shape[0]//self.hop
33+
assert sr == self.fs
34+
if(f0_method=="pm"):
35+
time_step = 160 / 16000 * 1000
36+
f0_min = 50
37+
f0_max = 1100
38+
f0 = parselmouth.Sound(x, sr).to_pitch_ac(
39+
time_step=time_step / 1000, voicing_threshold=0.6,
40+
pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
41+
pad_size=(p_len - len(f0) + 1) // 2
42+
if(pad_size>0 or p_len - len(f0) - pad_size>0):
43+
f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
44+
elif(f0_method=="harvest"):
45+
f0, t = pyworld.harvest(
46+
x.astype(np.double),
47+
fs=sr,
48+
f0_ceil=1100,
49+
frame_period=1000 * self.hop / sr,
50+
)
51+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.fs)
52+
elif(f0_method=="dio"):
53+
f0, t = pyworld.dio(
54+
x.astype(np.double),
55+
fs=sr,
56+
f0_ceil=1100,
57+
frame_period=1000 * self.hop / sr,
58+
)
59+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.fs)
60+
return f0
61+
62+
def coarse_f0(self, f0):
63+
f0_mel = 1127 * np.log(1 + f0 / 700)
64+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * (
65+
self.f0_bin - 2
66+
) / (self.f0_mel_max - self.f0_mel_min) + 1
67+
68+
# use 0 or 1
69+
f0_mel[f0_mel <= 1] = 1
70+
f0_mel[f0_mel > self.f0_bin - 1] = self.f0_bin - 1
71+
f0_coarse = np.rint(f0_mel).astype(np.int)
72+
assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, (
73+
f0_coarse.max(),
74+
f0_coarse.min(),
75+
)
76+
return f0_coarse
77+
78+
def go(self,paths,f0_method):
79+
if (len(paths) == 0): printt("no-f0-todo")
80+
else:
81+
printt("todo-f0-%s"%len(paths))
82+
n=max(len(paths)//5,1)#每个进程最多打印5条
83+
for idx,(inp_path,opt_path1,opt_path2) in enumerate(paths):
84+
try:
85+
if(idx%n==0):printt("f0ing,now-%s,all-%s,-%s"%(idx,len(paths),inp_path))
86+
if(os.path.exists(opt_path1+".npy")==True and os.path.exists(opt_path2+".npy")==True):continue
87+
featur_pit = self.compute_f0(inp_path,f0_method)
88+
np.save(opt_path2,featur_pit,allow_pickle=False,)#nsf
89+
coarse_pit = self.coarse_f0(featur_pit)
90+
np.save(opt_path1,coarse_pit,allow_pickle=False,)#ori
91+
except:
92+
printt("f0fail-%s-%s-%s" % (idx, inp_path,traceback.format_exc()))
93+
94+
if __name__=='__main__':
95+
# exp_dir=r"E:\codes\py39\dataset\mi-test"
96+
# n_p=16
97+
# f = open("%s/log_extract_f0.log"%exp_dir, "w")
98+
printt(sys.argv)
99+
featureInput = FeatureInput()
100+
paths=[]
101+
inp_root= "%s/1_16k_wavs"%(exp_dir)
102+
opt_root1="%s/2a_f0"%(exp_dir)
103+
opt_root2="%s/2b-f0nsf"%(exp_dir)
104+
105+
os.makedirs(opt_root1,exist_ok=True)
106+
os.makedirs(opt_root2,exist_ok=True)
107+
for name in sorted(list(os.listdir(inp_root))):
108+
inp_path="%s/%s"%(inp_root,name)
109+
if ("spec" in inp_path): continue
110+
opt_path1="%s/%s"%(opt_root1,name)
111+
opt_path2="%s/%s"%(opt_root2,name)
112+
paths.append([inp_path,opt_path1,opt_path2])
113+
114+
ps=[]
115+
for i in range(n_p):
116+
p=Process(target=featureInput.go,args=(paths[i::n_p],f0method,))
117+
p.start()
118+
ps.append(p)
119+
for p in ps:
120+
p.join()

extract_feature_print.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import os,sys,traceback
2+
n_part=int(sys.argv[1])
3+
i_part=int(sys.argv[2])
4+
i_gpu=sys.argv[3]
5+
exp_dir=sys.argv[4]
6+
os.environ["CUDA_VISIBLE_DEVICES"]=str(i_gpu)
7+
8+
import torch
9+
import torch.nn.functional as F
10+
import soundfile as sf
11+
import numpy as np
12+
import joblib
13+
from fairseq import checkpoint_utils
14+
import pdb
15+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16+
17+
f = open("%s/extract_f0_feature.log"%exp_dir, "a+")
18+
def printt(strr):
19+
print(strr)
20+
f.write("%s\n" % strr)
21+
f.flush()
22+
printt(sys.argv)
23+
# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/speech/pretrain/ContentVec_legacy500.pt"
24+
model_path = "hubert_base.pt"
25+
26+
printt(exp_dir)
27+
wavPath = "%s/1_16k_wavs"%exp_dir
28+
outPath = "%s/3_feature256"%exp_dir
29+
os.makedirs(outPath,exist_ok=True)
30+
# wave must be 16k, hop_size=320
31+
def readwave(wav_path, normalize=False):
32+
wav, sr = sf.read(wav_path)
33+
assert sr == 16000
34+
feats = torch.from_numpy(wav).float()
35+
if feats.dim() == 2: # double channels
36+
feats = feats.mean(-1)
37+
assert feats.dim() == 1, feats.dim()
38+
if normalize:
39+
with torch.no_grad():
40+
feats = F.layer_norm(feats, feats.shape)
41+
feats = feats.view(1, -1)
42+
return feats
43+
# HuBERT model
44+
printt("load model(s) from {}".format(model_path))
45+
models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
46+
[model_path],
47+
suffix="",
48+
)
49+
model = models[0]
50+
model = model.to(device)
51+
model = model.half()
52+
model.eval()
53+
54+
todo=sorted(list(os.listdir(wavPath)))[i_part::n_part]
55+
n = max(1,len(todo) // 10) # 最多打印十条
56+
if(len(todo)==0):printt("no-feature-todo")
57+
else:
58+
printt("all-feature-%s"%len(todo))
59+
for idx,file in enumerate(todo):
60+
try:
61+
if file.endswith(".wav"):
62+
wav_path = "%s/%s"%(wavPath,file)
63+
out_path = "%s/%s"%(outPath,file.replace("wav","npy"))
64+
65+
if(os.path.exists(out_path)):continue
66+
67+
feats = readwave(wav_path, normalize=saved_cfg.task.normalize)
68+
padding_mask = torch.BoolTensor(feats.shape).fill_(False)
69+
inputs = {
70+
"source": feats.half().to(device),
71+
"padding_mask": padding_mask.to(device),
72+
"output_layer": 9, # layer 9
73+
}
74+
with torch.no_grad():
75+
logits = model.extract_features(**inputs)
76+
feats = model.final_proj(logits[0])
77+
78+
feats = feats.squeeze(0).float().cpu().numpy()
79+
# feats = np.repeat(feats, 2,0) # 20ms -> 10ms
80+
np.save(out_path, feats, allow_pickle=False)
81+
if (idx % n == 0):printt("now-%s,all-%s,%s,%s"%(len(todo),idx,file,feats.shape))
82+
except:
83+
printt(traceback.format_exc())
84+
printt("all-feature-done")

0 commit comments

Comments
 (0)