Spaces:
Running
Running
MarcusSu1216
commited on
Commit
•
cf62053
1
Parent(s):
8b29255
Upload 7 files
Browse files
inference/__init__.py
ADDED
File without changes
|
inference/__pycache__/__init__.cpython-38.pyc
ADDED
Binary file (127 Bytes). View file
|
|
inference/__pycache__/infer_tool.cpython-38.pyc
ADDED
Binary file (10.4 kB). View file
|
|
inference/__pycache__/slicer.cpython-38.pyc
ADDED
Binary file (3.83 kB). View file
|
|
inference/infer_tool.py
ADDED
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import io
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
from pathlib import Path
|
8 |
+
from inference import slicer
|
9 |
+
|
10 |
+
import librosa
|
11 |
+
import numpy as np
|
12 |
+
# import onnxruntime
|
13 |
+
import parselmouth
|
14 |
+
import soundfile
|
15 |
+
import torch
|
16 |
+
import hashlib
|
17 |
+
import io
|
18 |
+
import json
|
19 |
+
import logging
|
20 |
+
import os
|
21 |
+
import time
|
22 |
+
from pathlib import Path
|
23 |
+
from inference import slicer
|
24 |
+
|
25 |
+
import librosa
|
26 |
+
import numpy as np
|
27 |
+
# import onnxruntime
|
28 |
+
import parselmouth
|
29 |
+
import soundfile
|
30 |
+
import torch
|
31 |
+
import torchaudio
|
32 |
+
|
33 |
+
import cluster
|
34 |
+
from hubert import hubert_model
|
35 |
+
import utils
|
36 |
+
from models import SynthesizerTrn
|
37 |
+
|
38 |
+
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
39 |
+
|
40 |
+
|
41 |
+
def read_temp(file_name):
|
42 |
+
if not os.path.exists(file_name):
|
43 |
+
with open(file_name, "w") as f:
|
44 |
+
f.write(json.dumps({"info": "temp_dict"}))
|
45 |
+
return {}
|
46 |
+
else:
|
47 |
+
try:
|
48 |
+
with open(file_name, "r") as f:
|
49 |
+
data = f.read()
|
50 |
+
data_dict = json.loads(data)
|
51 |
+
if os.path.getsize(file_name) > 50 * 1024 * 1024:
|
52 |
+
f_name = file_name.replace("\\", "/").split("/")[-1]
|
53 |
+
print(f"clean {f_name}")
|
54 |
+
for wav_hash in list(data_dict.keys()):
|
55 |
+
if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600:
|
56 |
+
del data_dict[wav_hash]
|
57 |
+
except Exception as e:
|
58 |
+
print(e)
|
59 |
+
print(f"{file_name} error,auto rebuild file")
|
60 |
+
data_dict = {"info": "temp_dict"}
|
61 |
+
return data_dict
|
62 |
+
|
63 |
+
|
64 |
+
def write_temp(file_name, data):
|
65 |
+
with open(file_name, "w") as f:
|
66 |
+
f.write(json.dumps(data))
|
67 |
+
|
68 |
+
|
69 |
+
def timeit(func):
|
70 |
+
def run(*args, **kwargs):
|
71 |
+
t = time.time()
|
72 |
+
res = func(*args, **kwargs)
|
73 |
+
print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
|
74 |
+
return res
|
75 |
+
|
76 |
+
return run
|
77 |
+
|
78 |
+
|
79 |
+
def format_wav(audio_path):
|
80 |
+
if Path(audio_path).suffix == '.wav':
|
81 |
+
return
|
82 |
+
raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None)
|
83 |
+
soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate)
|
84 |
+
|
85 |
+
|
86 |
+
def get_end_file(dir_path, end):
|
87 |
+
file_lists = []
|
88 |
+
for root, dirs, files in os.walk(dir_path):
|
89 |
+
files = [f for f in files if f[0] != '.']
|
90 |
+
dirs[:] = [d for d in dirs if d[0] != '.']
|
91 |
+
for f_file in files:
|
92 |
+
if f_file.endswith(end):
|
93 |
+
file_lists.append(os.path.join(root, f_file).replace("\\", "/"))
|
94 |
+
return file_lists
|
95 |
+
|
96 |
+
|
97 |
+
def get_md5(content):
|
98 |
+
return hashlib.new("md5", content).hexdigest()
|
99 |
+
|
100 |
+
def fill_a_to_b(a, b):
|
101 |
+
if len(a) < len(b):
|
102 |
+
for _ in range(0, len(b) - len(a)):
|
103 |
+
a.append(a[0])
|
104 |
+
|
105 |
+
def mkdir(paths: list):
|
106 |
+
for path in paths:
|
107 |
+
if not os.path.exists(path):
|
108 |
+
os.mkdir(path)
|
109 |
+
|
110 |
+
def pad_array(arr, target_length):
|
111 |
+
current_length = arr.shape[0]
|
112 |
+
if current_length >= target_length:
|
113 |
+
return arr
|
114 |
+
else:
|
115 |
+
pad_width = target_length - current_length
|
116 |
+
pad_left = pad_width // 2
|
117 |
+
pad_right = pad_width - pad_left
|
118 |
+
padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0))
|
119 |
+
return padded_arr
|
120 |
+
|
121 |
+
def split_list_by_n(list_collection, n, pre=0):
|
122 |
+
for i in range(0, len(list_collection), n):
|
123 |
+
yield list_collection[i-pre if i-pre>=0 else i: i + n]
|
124 |
+
|
125 |
+
|
126 |
+
class F0FilterException(Exception):
|
127 |
+
pass
|
128 |
+
|
129 |
+
class Svc(object):
|
130 |
+
def __init__(self, net_g_path, config_path,
|
131 |
+
device=None,
|
132 |
+
cluster_model_path="logs/44k/kmeans_10000.pt",
|
133 |
+
nsf_hifigan_enhance = False
|
134 |
+
):
|
135 |
+
self.net_g_path = net_g_path
|
136 |
+
if device is None:
|
137 |
+
self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
138 |
+
else:
|
139 |
+
self.dev = torch.device(device)
|
140 |
+
self.net_g_ms = None
|
141 |
+
self.hps_ms = utils.get_hparams_from_file(config_path)
|
142 |
+
self.target_sample = self.hps_ms.data.sampling_rate
|
143 |
+
self.hop_size = self.hps_ms.data.hop_length
|
144 |
+
self.spk2id = self.hps_ms.spk
|
145 |
+
self.nsf_hifigan_enhance = nsf_hifigan_enhance
|
146 |
+
# 加载hubert
|
147 |
+
self.hubert_model = utils.get_hubert_model().to(self.dev)
|
148 |
+
self.load_model()
|
149 |
+
if os.path.exists(cluster_model_path):
|
150 |
+
self.cluster_model = cluster.get_cluster_model(cluster_model_path)
|
151 |
+
if self.nsf_hifigan_enhance:
|
152 |
+
from modules.enhancer import Enhancer
|
153 |
+
self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model',device=self.dev)
|
154 |
+
|
155 |
+
def load_model(self):
|
156 |
+
# 获取模型配置
|
157 |
+
self.net_g_ms = SynthesizerTrn(
|
158 |
+
self.hps_ms.data.filter_length // 2 + 1,
|
159 |
+
self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
|
160 |
+
**self.hps_ms.model)
|
161 |
+
_ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
|
162 |
+
if "half" in self.net_g_path and torch.cuda.is_available():
|
163 |
+
_ = self.net_g_ms.half().eval().to(self.dev)
|
164 |
+
else:
|
165 |
+
_ = self.net_g_ms.eval().to(self.dev)
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
def get_unit_f0(self, in_path, tran, cluster_infer_ratio, speaker, f0_filter ,F0_mean_pooling):
|
170 |
+
|
171 |
+
wav, sr = librosa.load(in_path, sr=self.target_sample)
|
172 |
+
|
173 |
+
if F0_mean_pooling == True:
|
174 |
+
f0, uv = utils.compute_f0_uv_torchcrepe(torch.FloatTensor(wav), sampling_rate=self.target_sample, hop_length=self.hop_size,device=self.dev)
|
175 |
+
if f0_filter and sum(f0) == 0:
|
176 |
+
raise F0FilterException("未检测到人声")
|
177 |
+
f0 = torch.FloatTensor(list(f0))
|
178 |
+
uv = torch.FloatTensor(list(uv))
|
179 |
+
if F0_mean_pooling == False:
|
180 |
+
f0 = utils.compute_f0_parselmouth(wav, sampling_rate=self.target_sample, hop_length=self.hop_size)
|
181 |
+
if f0_filter and sum(f0) == 0:
|
182 |
+
raise F0FilterException("未检测到人声")
|
183 |
+
f0, uv = utils.interpolate_f0(f0)
|
184 |
+
f0 = torch.FloatTensor(f0)
|
185 |
+
uv = torch.FloatTensor(uv)
|
186 |
+
|
187 |
+
f0 = f0 * 2 ** (tran / 12)
|
188 |
+
f0 = f0.unsqueeze(0).to(self.dev)
|
189 |
+
uv = uv.unsqueeze(0).to(self.dev)
|
190 |
+
|
191 |
+
wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000)
|
192 |
+
wav16k = torch.from_numpy(wav16k).to(self.dev)
|
193 |
+
c = utils.get_hubert_content(self.hubert_model, wav_16k_tensor=wav16k)
|
194 |
+
c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
|
195 |
+
|
196 |
+
if cluster_infer_ratio !=0:
|
197 |
+
cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T
|
198 |
+
cluster_c = torch.FloatTensor(cluster_c).to(self.dev)
|
199 |
+
c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c
|
200 |
+
|
201 |
+
c = c.unsqueeze(0)
|
202 |
+
return c, f0, uv
|
203 |
+
|
204 |
+
def infer(self, speaker, tran, raw_path,
|
205 |
+
cluster_infer_ratio=0,
|
206 |
+
auto_predict_f0=False,
|
207 |
+
noice_scale=0.4,
|
208 |
+
f0_filter=False,
|
209 |
+
F0_mean_pooling=False,
|
210 |
+
enhancer_adaptive_key = 0
|
211 |
+
):
|
212 |
+
|
213 |
+
speaker_id = self.spk2id.__dict__.get(speaker)
|
214 |
+
if not speaker_id and type(speaker) is int:
|
215 |
+
if len(self.spk2id.__dict__) >= speaker:
|
216 |
+
speaker_id = speaker
|
217 |
+
sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0)
|
218 |
+
c, f0, uv = self.get_unit_f0(raw_path, tran, cluster_infer_ratio, speaker, f0_filter,F0_mean_pooling)
|
219 |
+
if "half" in self.net_g_path and torch.cuda.is_available():
|
220 |
+
c = c.half()
|
221 |
+
with torch.no_grad():
|
222 |
+
start = time.time()
|
223 |
+
audio = self.net_g_ms.infer(c, f0=f0, g=sid, uv=uv, predict_f0=auto_predict_f0, noice_scale=noice_scale)[0,0].data.float()
|
224 |
+
if self.nsf_hifigan_enhance:
|
225 |
+
audio, _ = self.enhancer.enhance(
|
226 |
+
audio[None,:],
|
227 |
+
self.target_sample,
|
228 |
+
f0[:,:,None],
|
229 |
+
self.hps_ms.data.hop_length,
|
230 |
+
adaptive_key = enhancer_adaptive_key)
|
231 |
+
use_time = time.time() - start
|
232 |
+
print("vits use time:{}".format(use_time))
|
233 |
+
return audio, audio.shape[-1]
|
234 |
+
|
235 |
+
def clear_empty(self):
|
236 |
+
# 清理显存
|
237 |
+
torch.cuda.empty_cache()
|
238 |
+
|
239 |
+
def slice_inference(self,
|
240 |
+
raw_audio_path,
|
241 |
+
spk,
|
242 |
+
tran,
|
243 |
+
slice_db,
|
244 |
+
cluster_infer_ratio,
|
245 |
+
auto_predict_f0,
|
246 |
+
noice_scale,
|
247 |
+
pad_seconds=0.5,
|
248 |
+
clip_seconds=0,
|
249 |
+
lg_num=0,
|
250 |
+
lgr_num =0.75,
|
251 |
+
F0_mean_pooling = False,
|
252 |
+
enhancer_adaptive_key = 0
|
253 |
+
):
|
254 |
+
wav_path = raw_audio_path
|
255 |
+
chunks = slicer.cut(wav_path, db_thresh=slice_db)
|
256 |
+
audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks)
|
257 |
+
per_size = int(clip_seconds*audio_sr)
|
258 |
+
lg_size = int(lg_num*audio_sr)
|
259 |
+
lg_size_r = int(lg_size*lgr_num)
|
260 |
+
lg_size_c_l = (lg_size-lg_size_r)//2
|
261 |
+
lg_size_c_r = lg_size-lg_size_r-lg_size_c_l
|
262 |
+
lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0
|
263 |
+
|
264 |
+
audio = []
|
265 |
+
for (slice_tag, data) in audio_data:
|
266 |
+
print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
|
267 |
+
# padd
|
268 |
+
length = int(np.ceil(len(data) / audio_sr * self.target_sample))
|
269 |
+
if slice_tag:
|
270 |
+
print('jump empty segment')
|
271 |
+
_audio = np.zeros(length)
|
272 |
+
audio.extend(list(pad_array(_audio, length)))
|
273 |
+
continue
|
274 |
+
if per_size != 0:
|
275 |
+
datas = split_list_by_n(data, per_size,lg_size)
|
276 |
+
else:
|
277 |
+
datas = [data]
|
278 |
+
for k,dat in enumerate(datas):
|
279 |
+
per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds!=0 else length
|
280 |
+
if clip_seconds!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
|
281 |
+
# padd
|
282 |
+
pad_len = int(audio_sr * pad_seconds)
|
283 |
+
dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
|
284 |
+
raw_path = io.BytesIO()
|
285 |
+
soundfile.write(raw_path, dat, audio_sr, format="wav")
|
286 |
+
raw_path.seek(0)
|
287 |
+
out_audio, out_sr = self.infer(spk, tran, raw_path,
|
288 |
+
cluster_infer_ratio=cluster_infer_ratio,
|
289 |
+
auto_predict_f0=auto_predict_f0,
|
290 |
+
noice_scale=noice_scale,
|
291 |
+
F0_mean_pooling = F0_mean_pooling,
|
292 |
+
enhancer_adaptive_key = enhancer_adaptive_key
|
293 |
+
)
|
294 |
+
_audio = out_audio.cpu().numpy()
|
295 |
+
pad_len = int(self.target_sample * pad_seconds)
|
296 |
+
_audio = _audio[pad_len:-pad_len]
|
297 |
+
_audio = pad_array(_audio, per_length)
|
298 |
+
if lg_size!=0 and k!=0:
|
299 |
+
lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr_num != 1 else audio[-lg_size:]
|
300 |
+
lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr_num != 1 else _audio[0:lg_size]
|
301 |
+
lg_pre = lg1*(1-lg)+lg2*lg
|
302 |
+
audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr_num != 1 else audio[0:-lg_size]
|
303 |
+
audio.extend(lg_pre)
|
304 |
+
_audio = _audio[lg_size_c_l+lg_size_r:] if lgr_num != 1 else _audio[lg_size:]
|
305 |
+
audio.extend(list(_audio))
|
306 |
+
return np.array(audio)
|
307 |
+
|
308 |
+
class RealTimeVC:
|
309 |
+
def __init__(self):
|
310 |
+
self.last_chunk = None
|
311 |
+
self.last_o = None
|
312 |
+
self.chunk_len = 16000 # 区块长度
|
313 |
+
self.pre_len = 3840 # 交叉淡化长度,640的倍数
|
314 |
+
|
315 |
+
"""输入输出都是1维numpy 音频波形数组"""
|
316 |
+
|
317 |
+
def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path,
|
318 |
+
cluster_infer_ratio=0,
|
319 |
+
auto_predict_f0=False,
|
320 |
+
noice_scale=0.4,
|
321 |
+
f0_filter=False):
|
322 |
+
|
323 |
+
import maad
|
324 |
+
audio, sr = torchaudio.load(input_wav_path)
|
325 |
+
audio = audio.cpu().numpy()[0]
|
326 |
+
temp_wav = io.BytesIO()
|
327 |
+
if self.last_chunk is None:
|
328 |
+
input_wav_path.seek(0)
|
329 |
+
|
330 |
+
audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path,
|
331 |
+
cluster_infer_ratio=cluster_infer_ratio,
|
332 |
+
auto_predict_f0=auto_predict_f0,
|
333 |
+
noice_scale=noice_scale,
|
334 |
+
f0_filter=f0_filter)
|
335 |
+
|
336 |
+
audio = audio.cpu().numpy()
|
337 |
+
self.last_chunk = audio[-self.pre_len:]
|
338 |
+
self.last_o = audio
|
339 |
+
return audio[-self.chunk_len:]
|
340 |
+
else:
|
341 |
+
audio = np.concatenate([self.last_chunk, audio])
|
342 |
+
soundfile.write(temp_wav, audio, sr, format="wav")
|
343 |
+
temp_wav.seek(0)
|
344 |
+
|
345 |
+
audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav,
|
346 |
+
cluster_infer_ratio=cluster_infer_ratio,
|
347 |
+
auto_predict_f0=auto_predict_f0,
|
348 |
+
noice_scale=noice_scale,
|
349 |
+
f0_filter=f0_filter)
|
350 |
+
|
351 |
+
audio = audio.cpu().numpy()
|
352 |
+
ret = maad.util.crossfade(self.last_o, audio, self.pre_len)
|
353 |
+
self.last_chunk = audio[-self.pre_len:]
|
354 |
+
self.last_o = audio
|
355 |
+
return ret[self.chunk_len:2 * self.chunk_len]
|
inference/infer_tool_grad.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import time
|
6 |
+
from pathlib import Path
|
7 |
+
import io
|
8 |
+
import librosa
|
9 |
+
import maad
|
10 |
+
import numpy as np
|
11 |
+
from inference import slicer
|
12 |
+
import parselmouth
|
13 |
+
import soundfile
|
14 |
+
import torch
|
15 |
+
import torchaudio
|
16 |
+
|
17 |
+
from hubert import hubert_model
|
18 |
+
import utils
|
19 |
+
from models import SynthesizerTrn
|
20 |
+
logging.getLogger('numba').setLevel(logging.WARNING)
|
21 |
+
logging.getLogger('matplotlib').setLevel(logging.WARNING)
|
22 |
+
|
23 |
+
def resize2d_f0(x, target_len):
|
24 |
+
source = np.array(x)
|
25 |
+
source[source < 0.001] = np.nan
|
26 |
+
target = np.interp(np.arange(0, len(source) * target_len, len(source)) / target_len, np.arange(0, len(source)),
|
27 |
+
source)
|
28 |
+
res = np.nan_to_num(target)
|
29 |
+
return res
|
30 |
+
|
31 |
+
def get_f0(x, p_len,f0_up_key=0):
|
32 |
+
|
33 |
+
time_step = 160 / 16000 * 1000
|
34 |
+
f0_min = 50
|
35 |
+
f0_max = 1100
|
36 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
37 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
38 |
+
|
39 |
+
f0 = parselmouth.Sound(x, 16000).to_pitch_ac(
|
40 |
+
time_step=time_step / 1000, voicing_threshold=0.6,
|
41 |
+
pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
|
42 |
+
|
43 |
+
pad_size=(p_len - len(f0) + 1) // 2
|
44 |
+
if(pad_size>0 or p_len - len(f0) - pad_size>0):
|
45 |
+
f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
|
46 |
+
|
47 |
+
f0 *= pow(2, f0_up_key / 12)
|
48 |
+
f0_mel = 1127 * np.log(1 + f0 / 700)
|
49 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (f0_mel_max - f0_mel_min) + 1
|
50 |
+
f0_mel[f0_mel <= 1] = 1
|
51 |
+
f0_mel[f0_mel > 255] = 255
|
52 |
+
f0_coarse = np.rint(f0_mel).astype(np.int)
|
53 |
+
return f0_coarse, f0
|
54 |
+
|
55 |
+
def clean_pitch(input_pitch):
|
56 |
+
num_nan = np.sum(input_pitch == 1)
|
57 |
+
if num_nan / len(input_pitch) > 0.9:
|
58 |
+
input_pitch[input_pitch != 1] = 1
|
59 |
+
return input_pitch
|
60 |
+
|
61 |
+
|
62 |
+
def plt_pitch(input_pitch):
|
63 |
+
input_pitch = input_pitch.astype(float)
|
64 |
+
input_pitch[input_pitch == 1] = np.nan
|
65 |
+
return input_pitch
|
66 |
+
|
67 |
+
|
68 |
+
def f0_to_pitch(ff):
|
69 |
+
f0_pitch = 69 + 12 * np.log2(ff / 440)
|
70 |
+
return f0_pitch
|
71 |
+
|
72 |
+
|
73 |
+
def fill_a_to_b(a, b):
|
74 |
+
if len(a) < len(b):
|
75 |
+
for _ in range(0, len(b) - len(a)):
|
76 |
+
a.append(a[0])
|
77 |
+
|
78 |
+
|
79 |
+
def mkdir(paths: list):
|
80 |
+
for path in paths:
|
81 |
+
if not os.path.exists(path):
|
82 |
+
os.mkdir(path)
|
83 |
+
|
84 |
+
|
85 |
+
class VitsSvc(object):
|
86 |
+
def __init__(self):
|
87 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
88 |
+
self.SVCVITS = None
|
89 |
+
self.hps = None
|
90 |
+
self.speakers = None
|
91 |
+
self.hubert_soft = utils.get_hubert_model()
|
92 |
+
|
93 |
+
def set_device(self, device):
|
94 |
+
self.device = torch.device(device)
|
95 |
+
self.hubert_soft.to(self.device)
|
96 |
+
if self.SVCVITS != None:
|
97 |
+
self.SVCVITS.to(self.device)
|
98 |
+
|
99 |
+
def loadCheckpoint(self, path):
|
100 |
+
self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
|
101 |
+
self.SVCVITS = SynthesizerTrn(
|
102 |
+
self.hps.data.filter_length // 2 + 1,
|
103 |
+
self.hps.train.segment_size // self.hps.data.hop_length,
|
104 |
+
**self.hps.model)
|
105 |
+
_ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.SVCVITS, None)
|
106 |
+
_ = self.SVCVITS.eval().to(self.device)
|
107 |
+
self.speakers = self.hps.spk
|
108 |
+
|
109 |
+
def get_units(self, source, sr):
|
110 |
+
source = source.unsqueeze(0).to(self.device)
|
111 |
+
with torch.inference_mode():
|
112 |
+
units = self.hubert_soft.units(source)
|
113 |
+
return units
|
114 |
+
|
115 |
+
|
116 |
+
def get_unit_pitch(self, in_path, tran):
|
117 |
+
source, sr = torchaudio.load(in_path)
|
118 |
+
source = torchaudio.functional.resample(source, sr, 16000)
|
119 |
+
if len(source.shape) == 2 and source.shape[1] >= 2:
|
120 |
+
source = torch.mean(source, dim=0).unsqueeze(0)
|
121 |
+
soft = self.get_units(source, sr).squeeze(0).cpu().numpy()
|
122 |
+
f0_coarse, f0 = get_f0(source.cpu().numpy()[0], soft.shape[0]*2, tran)
|
123 |
+
return soft, f0
|
124 |
+
|
125 |
+
def infer(self, speaker_id, tran, raw_path):
|
126 |
+
speaker_id = self.speakers[speaker_id]
|
127 |
+
sid = torch.LongTensor([int(speaker_id)]).to(self.device).unsqueeze(0)
|
128 |
+
soft, pitch = self.get_unit_pitch(raw_path, tran)
|
129 |
+
f0 = torch.FloatTensor(clean_pitch(pitch)).unsqueeze(0).to(self.device)
|
130 |
+
stn_tst = torch.FloatTensor(soft)
|
131 |
+
with torch.no_grad():
|
132 |
+
x_tst = stn_tst.unsqueeze(0).to(self.device)
|
133 |
+
x_tst = torch.repeat_interleave(x_tst, repeats=2, dim=1).transpose(1, 2)
|
134 |
+
audio = self.SVCVITS.infer(x_tst, f0=f0, g=sid)[0,0].data.float()
|
135 |
+
return audio, audio.shape[-1]
|
136 |
+
|
137 |
+
def inference(self,srcaudio,chara,tran,slice_db):
|
138 |
+
sampling_rate, audio = srcaudio
|
139 |
+
audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
|
140 |
+
if len(audio.shape) > 1:
|
141 |
+
audio = librosa.to_mono(audio.transpose(1, 0))
|
142 |
+
if sampling_rate != 16000:
|
143 |
+
audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
|
144 |
+
soundfile.write("tmpwav.wav", audio, 16000, format="wav")
|
145 |
+
chunks = slicer.cut("tmpwav.wav", db_thresh=slice_db)
|
146 |
+
audio_data, audio_sr = slicer.chunks2audio("tmpwav.wav", chunks)
|
147 |
+
audio = []
|
148 |
+
for (slice_tag, data) in audio_data:
|
149 |
+
length = int(np.ceil(len(data) / audio_sr * self.hps.data.sampling_rate))
|
150 |
+
raw_path = io.BytesIO()
|
151 |
+
soundfile.write(raw_path, data, audio_sr, format="wav")
|
152 |
+
raw_path.seek(0)
|
153 |
+
if slice_tag:
|
154 |
+
_audio = np.zeros(length)
|
155 |
+
else:
|
156 |
+
out_audio, out_sr = self.infer(chara, tran, raw_path)
|
157 |
+
_audio = out_audio.cpu().numpy()
|
158 |
+
audio.extend(list(_audio))
|
159 |
+
audio = (np.array(audio) * 32768.0).astype('int16')
|
160 |
+
return (self.hps.data.sampling_rate,audio)
|
inference/slicer.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import librosa
|
2 |
+
import torch
|
3 |
+
import torchaudio
|
4 |
+
|
5 |
+
|
6 |
+
class Slicer:
|
7 |
+
def __init__(self,
|
8 |
+
sr: int,
|
9 |
+
threshold: float = -40.,
|
10 |
+
min_length: int = 5000,
|
11 |
+
min_interval: int = 300,
|
12 |
+
hop_size: int = 20,
|
13 |
+
max_sil_kept: int = 5000):
|
14 |
+
if not min_length >= min_interval >= hop_size:
|
15 |
+
raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
|
16 |
+
if not max_sil_kept >= hop_size:
|
17 |
+
raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
|
18 |
+
min_interval = sr * min_interval / 1000
|
19 |
+
self.threshold = 10 ** (threshold / 20.)
|
20 |
+
self.hop_size = round(sr * hop_size / 1000)
|
21 |
+
self.win_size = min(round(min_interval), 4 * self.hop_size)
|
22 |
+
self.min_length = round(sr * min_length / 1000 / self.hop_size)
|
23 |
+
self.min_interval = round(min_interval / self.hop_size)
|
24 |
+
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
|
25 |
+
|
26 |
+
def _apply_slice(self, waveform, begin, end):
|
27 |
+
if len(waveform.shape) > 1:
|
28 |
+
return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
|
29 |
+
else:
|
30 |
+
return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
|
31 |
+
|
32 |
+
# @timeit
|
33 |
+
def slice(self, waveform):
|
34 |
+
if len(waveform.shape) > 1:
|
35 |
+
samples = librosa.to_mono(waveform)
|
36 |
+
else:
|
37 |
+
samples = waveform
|
38 |
+
if samples.shape[0] <= self.min_length:
|
39 |
+
return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}}
|
40 |
+
rms_list = librosa.feature.rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
|
41 |
+
sil_tags = []
|
42 |
+
silence_start = None
|
43 |
+
clip_start = 0
|
44 |
+
for i, rms in enumerate(rms_list):
|
45 |
+
# Keep looping while frame is silent.
|
46 |
+
if rms < self.threshold:
|
47 |
+
# Record start of silent frames.
|
48 |
+
if silence_start is None:
|
49 |
+
silence_start = i
|
50 |
+
continue
|
51 |
+
# Keep looping while frame is not silent and silence start has not been recorded.
|
52 |
+
if silence_start is None:
|
53 |
+
continue
|
54 |
+
# Clear recorded silence start if interval is not enough or clip is too short
|
55 |
+
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
|
56 |
+
need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
|
57 |
+
if not is_leading_silence and not need_slice_middle:
|
58 |
+
silence_start = None
|
59 |
+
continue
|
60 |
+
# Need slicing. Record the range of silent frames to be removed.
|
61 |
+
if i - silence_start <= self.max_sil_kept:
|
62 |
+
pos = rms_list[silence_start: i + 1].argmin() + silence_start
|
63 |
+
if silence_start == 0:
|
64 |
+
sil_tags.append((0, pos))
|
65 |
+
else:
|
66 |
+
sil_tags.append((pos, pos))
|
67 |
+
clip_start = pos
|
68 |
+
elif i - silence_start <= self.max_sil_kept * 2:
|
69 |
+
pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
|
70 |
+
pos += i - self.max_sil_kept
|
71 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
72 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
73 |
+
if silence_start == 0:
|
74 |
+
sil_tags.append((0, pos_r))
|
75 |
+
clip_start = pos_r
|
76 |
+
else:
|
77 |
+
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
|
78 |
+
clip_start = max(pos_r, pos)
|
79 |
+
else:
|
80 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
81 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
82 |
+
if silence_start == 0:
|
83 |
+
sil_tags.append((0, pos_r))
|
84 |
+
else:
|
85 |
+
sil_tags.append((pos_l, pos_r))
|
86 |
+
clip_start = pos_r
|
87 |
+
silence_start = None
|
88 |
+
# Deal with trailing silence.
|
89 |
+
total_frames = rms_list.shape[0]
|
90 |
+
if silence_start is not None and total_frames - silence_start >= self.min_interval:
|
91 |
+
silence_end = min(total_frames, silence_start + self.max_sil_kept)
|
92 |
+
pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
|
93 |
+
sil_tags.append((pos, total_frames + 1))
|
94 |
+
# Apply and return slices.
|
95 |
+
if len(sil_tags) == 0:
|
96 |
+
return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}}
|
97 |
+
else:
|
98 |
+
chunks = []
|
99 |
+
# 第一段静音并非从头开始,补上有声片段
|
100 |
+
if sil_tags[0][0]:
|
101 |
+
chunks.append(
|
102 |
+
{"slice": False, "split_time": f"0,{min(waveform.shape[0], sil_tags[0][0] * self.hop_size)}"})
|
103 |
+
for i in range(0, len(sil_tags)):
|
104 |
+
# 标识有声片段(跳过第一段)
|
105 |
+
if i:
|
106 |
+
chunks.append({"slice": False,
|
107 |
+
"split_time": f"{sil_tags[i - 1][1] * self.hop_size},{min(waveform.shape[0], sil_tags[i][0] * self.hop_size)}"})
|
108 |
+
# 标识所有静音片段
|
109 |
+
chunks.append({"slice": True,
|
110 |
+
"split_time": f"{sil_tags[i][0] * self.hop_size},{min(waveform.shape[0], sil_tags[i][1] * self.hop_size)}"})
|
111 |
+
# 最后一段静音并非结尾,补上结尾片段
|
112 |
+
if sil_tags[-1][1] * self.hop_size < len(waveform):
|
113 |
+
chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1] * self.hop_size},{len(waveform)}"})
|
114 |
+
chunk_dict = {}
|
115 |
+
for i in range(len(chunks)):
|
116 |
+
chunk_dict[str(i)] = chunks[i]
|
117 |
+
return chunk_dict
|
118 |
+
|
119 |
+
|
120 |
+
def cut(audio_path, db_thresh=-30, min_len=5000):
|
121 |
+
audio, sr = librosa.load(audio_path, sr=None)
|
122 |
+
slicer = Slicer(
|
123 |
+
sr=sr,
|
124 |
+
threshold=db_thresh,
|
125 |
+
min_length=min_len
|
126 |
+
)
|
127 |
+
chunks = slicer.slice(audio)
|
128 |
+
return chunks
|
129 |
+
|
130 |
+
|
131 |
+
def chunks2audio(audio_path, chunks):
|
132 |
+
chunks = dict(chunks)
|
133 |
+
audio, sr = torchaudio.load(audio_path)
|
134 |
+
if len(audio.shape) == 2 and audio.shape[1] >= 2:
|
135 |
+
audio = torch.mean(audio, dim=0).unsqueeze(0)
|
136 |
+
audio = audio.cpu().numpy()[0]
|
137 |
+
result = []
|
138 |
+
for k, v in chunks.items():
|
139 |
+
tag = v["split_time"].split(",")
|
140 |
+
if tag[0] != tag[1]:
|
141 |
+
result.append((v["slice"], audio[int(tag[0]):int(tag[1])]))
|
142 |
+
return result, sr
|