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processing import cpu_count
|
6 |
+
from lib.modules import VC
|
7 |
+
from lib.split_audio import split_silence_nonsilent, adjust_audio_lengths, combine_silence_nonsilent
|
8 |
+
|
9 |
+
class Configs:
|
10 |
+
def __init__(self, device, is_half):
|
11 |
+
self.device = device
|
12 |
+
self.is_half = is_half
|
13 |
+
self.n_cpu = 0
|
14 |
+
self.gpu_name = None
|
15 |
+
self.gpu_mem = None
|
16 |
+
self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
|
17 |
+
|
18 |
+
def device_config(self) -> tuple:
|
19 |
+
if torch.cuda.is_available():
|
20 |
+
i_device = int(self.device.split(":")[-1])
|
21 |
+
self.gpu_name = torch.cuda.get_device_name(i_device)
|
22 |
+
#if (
|
23 |
+
# ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
|
24 |
+
# or "P40" in self.gpu_name.upper()
|
25 |
+
# or "1060" in self.gpu_name
|
26 |
+
# or "1070" in self.gpu_name
|
27 |
+
# or "1080" in self.gpu_name
|
28 |
+
# ):
|
29 |
+
# print("16 series/10 series P40 forced single precision")
|
30 |
+
# self.is_half = False
|
31 |
+
# for config_file in ["32k.json", "40k.json", "48k.json"]:
|
32 |
+
# with open(BASE_DIR / "src" / "configs" / config_file, "r") as f:
|
33 |
+
# strr = f.read().replace("true", "false")
|
34 |
+
# with open(BASE_DIR / "src" / "configs" / config_file, "w") as f:
|
35 |
+
# f.write(strr)
|
36 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
|
37 |
+
# strr = f.read().replace("3.7", "3.0")
|
38 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
|
39 |
+
# f.write(strr)
|
40 |
+
# else:
|
41 |
+
# self.gpu_name = None
|
42 |
+
# self.gpu_mem = int(
|
43 |
+
# torch.cuda.get_device_properties(i_device).total_memory
|
44 |
+
# / 1024
|
45 |
+
# / 1024
|
46 |
+
# / 1024
|
47 |
+
# + 0.4
|
48 |
+
# )
|
49 |
+
# if self.gpu_mem <= 4:
|
50 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "r") as f:
|
51 |
+
# strr = f.read().replace("3.7", "3.0")
|
52 |
+
# with open(BASE_DIR / "src" / "trainset_preprocess_pipeline_print.py", "w") as f:
|
53 |
+
# f.write(strr)
|
54 |
+
elif torch.backends.mps.is_available():
|
55 |
+
print("No supported N-card found, use MPS for inference")
|
56 |
+
self.device = "mps"
|
57 |
+
else:
|
58 |
+
print("No supported N-card found, use CPU for inference")
|
59 |
+
self.device = "cpu"
|
60 |
+
self.is_half = True
|
61 |
+
|
62 |
+
if self.n_cpu == 0:
|
63 |
+
self.n_cpu = cpu_count()
|
64 |
+
|
65 |
+
if self.is_half:
|
66 |
+
# 6G memory config
|
67 |
+
x_pad = 3
|
68 |
+
x_query = 10
|
69 |
+
x_center = 60
|
70 |
+
x_max = 65
|
71 |
+
else:
|
72 |
+
# 5G memory config
|
73 |
+
x_pad = 1
|
74 |
+
x_query = 6
|
75 |
+
x_center = 38
|
76 |
+
x_max = 41
|
77 |
+
|
78 |
+
if self.gpu_mem != None and self.gpu_mem <= 4:
|
79 |
+
x_pad = 1
|
80 |
+
x_query = 5
|
81 |
+
x_center = 30
|
82 |
+
x_max = 32
|
83 |
+
|
84 |
+
return x_pad, x_query, x_center, x_max
|
85 |
+
|
86 |
+
def get_model(voice_model):
|
87 |
+
model_dir = os.path.join(os.getcwd(), "models", voice_model)
|
88 |
+
model_filename, index_filename = None, None
|
89 |
+
for file in os.listdir(model_dir):
|
90 |
+
ext = os.path.splitext(file)[1]
|
91 |
+
if ext == '.pth':
|
92 |
+
model_filename = file
|
93 |
+
if ext == '.index':
|
94 |
+
index_filename = file
|
95 |
+
|
96 |
+
if model_filename is None:
|
97 |
+
print(f'No model file exists in {models_dir}.')
|
98 |
+
return None, None
|
99 |
+
|
100 |
+
return os.path.join(model_dir, model_filename), os.path.join(model_dir, index_filename) if index_filename else ''
|
101 |
+
|
102 |
+
def infer_audio(
|
103 |
+
model_name,
|
104 |
+
audio_path,
|
105 |
+
f0_change=0,
|
106 |
+
f0_method="rmvpe+",
|
107 |
+
min_pitch="50",
|
108 |
+
max_pitch="1100",
|
109 |
+
crepe_hop_length=128,
|
110 |
+
index_rate=0.75,
|
111 |
+
filter_radius=3,
|
112 |
+
rms_mix_rate=0.25,
|
113 |
+
protect=0.33,
|
114 |
+
split_infer=False,
|
115 |
+
min_silence=500,
|
116 |
+
silence_threshold=-50,
|
117 |
+
seek_step=1,
|
118 |
+
keep_silence=100,
|
119 |
+
do_formant=False,
|
120 |
+
quefrency=0,
|
121 |
+
timbre=1,
|
122 |
+
f0_autotune=False,
|
123 |
+
audio_format="wav",
|
124 |
+
resample_sr=0,
|
125 |
+
hubert_model_path="assets/hubert/hubert_base.pt",
|
126 |
+
rmvpe_model_path="assets/rmvpe/rmvpe.pt",
|
127 |
+
fcpe_model_path="assets/fcpe/fcpe.pt"
|
128 |
+
):
|
129 |
+
os.environ["rmvpe_model_path"] = rmvpe_model_path
|
130 |
+
os.environ["fcpe_model_path"] = fcpe_model_path
|
131 |
+
configs = Configs('cuda:0', True)
|
132 |
+
vc = VC(configs)
|
133 |
+
pth_path, index_path = get_model(model_name)
|
134 |
+
vc_data = vc.get_vc(pth_path, protect, 0.5)
|
135 |
+
|
136 |
+
if split_infer:
|
137 |
+
inferred_files = []
|
138 |
+
temp_dir = os.path.join(os.getcwd(), "seperate", "temp")
|
139 |
+
os.makedirs(temp_dir, exist_ok=True)
|
140 |
+
print("Splitting audio to silence and nonsilent segments.")
|
141 |
+
silence_files, nonsilent_files = split_silence_nonsilent(audio_path, min_silence, silence_threshold, seek_step, keep_silence)
|
142 |
+
print(f"Total silence segments: {len(silence_files)}.\nTotal nonsilent segments: {len(nonsilent_files)}.")
|
143 |
+
for i, nonsilent_file in enumerate(nonsilent_files):
|
144 |
+
print(f"Inferring nonsilent audio {i+1}")
|
145 |
+
inference_info, audio_data, output_path = vc.vc_single(
|
146 |
+
0,
|
147 |
+
audio_path,
|
148 |
+
f0_change,
|
149 |
+
f0_method,
|
150 |
+
index_path,
|
151 |
+
index_path,
|
152 |
+
index_rate,
|
153 |
+
filter_radius,
|
154 |
+
resample_sr,
|
155 |
+
rms_mix_rate,
|
156 |
+
protect,
|
157 |
+
audio_format,
|
158 |
+
crepe_hop_length,
|
159 |
+
do_formant,
|
160 |
+
quefrency,
|
161 |
+
timbre,
|
162 |
+
min_pitch,
|
163 |
+
max_pitch,
|
164 |
+
f0_autotune,
|
165 |
+
hubert_model_path
|
166 |
+
)
|
167 |
+
if inference_info[0] == "Success.":
|
168 |
+
print("Inference ran successfully.")
|
169 |
+
print(inference_info[1])
|
170 |
+
print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
|
171 |
+
else:
|
172 |
+
print(f"An error occurred while processing.\n{inference_info[0]}")
|
173 |
+
return None
|
174 |
+
shutil.move(output_path, temp_dir)
|
175 |
+
inferred_files.append(os.path.join(temp_dir, os.path.basename(output_path)))
|
176 |
+
print("Adjusting inferred audio lengths.")
|
177 |
+
adjusted_inferred_files = adjust_audio_lengths(nonsilent_files, inferred_files)
|
178 |
+
print("Combining silence and inferred audios.")
|
179 |
+
output_count = 1
|
180 |
+
while True:
|
181 |
+
output_path = os.path.join(os.getcwd(), "output", f"{os.path.splitext(os.path.basename(audio_path))[0]}{model_name}{f0_method.capitalize()}_{output_count}.{audio_format}")
|
182 |
+
if not os.path.exists(output_path):
|
183 |
+
break
|
184 |
+
output_count += 1
|
185 |
+
inferred_audio = combine_silence_nonsilent(silence_files, adjusted_inferred_files, keep_silence, output_path)
|
186 |
+
shutil.rmtree(os.path.join(main_dir, "seperate", "temp"))
|
187 |
+
else:
|
188 |
+
inference_info, audio_data, output_path = vc.vc_single(
|
189 |
+
0,
|
190 |
+
audio_path,
|
191 |
+
f0_change,
|
192 |
+
f0_method,
|
193 |
+
index_path,
|
194 |
+
index_path,
|
195 |
+
index_rate,
|
196 |
+
filter_radius,
|
197 |
+
resample_sr,
|
198 |
+
rms_mix_rate,
|
199 |
+
protect,
|
200 |
+
audio_format,
|
201 |
+
crepe_hop_length,
|
202 |
+
do_formant,
|
203 |
+
quefrency,
|
204 |
+
timbre,
|
205 |
+
min_pitch,
|
206 |
+
max_pitch,
|
207 |
+
f0_autotune
|
208 |
+
)
|
209 |
+
if inference_info[0] == "Success.":
|
210 |
+
print("Inference ran successfully.")
|
211 |
+
print(inference_info[1])
|
212 |
+
print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
|
213 |
+
else:
|
214 |
+
print(f"An error occurred while processing.\n{inference_info[0]}")
|
215 |
+
return None
|
216 |
+
|
217 |
+
del configs, vc
|
218 |
+
gc.collect()
|
219 |
+
return output_path
|
lib/modules.py
ADDED
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, sys
|
2 |
+
import traceback
|
3 |
+
import logging
|
4 |
+
now_dir = os.getcwd()
|
5 |
+
sys.path.append(now_dir)
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
import numpy as np
|
8 |
+
import soundfile as sf
|
9 |
+
import torch
|
10 |
+
from io import BytesIO
|
11 |
+
from lib.infer_libs.audio import load_audio
|
12 |
+
from lib.infer_libs.audio import wav2
|
13 |
+
from lib.infer_libs.infer_pack.models import (
|
14 |
+
SynthesizerTrnMs256NSFsid,
|
15 |
+
SynthesizerTrnMs256NSFsid_nono,
|
16 |
+
SynthesizerTrnMs768NSFsid,
|
17 |
+
SynthesizerTrnMs768NSFsid_nono,
|
18 |
+
)
|
19 |
+
from lib.pipeline import Pipeline
|
20 |
+
import time
|
21 |
+
import glob
|
22 |
+
from shutil import move
|
23 |
+
from fairseq import checkpoint_utils
|
24 |
+
|
25 |
+
sup_audioext = {
|
26 |
+
"wav",
|
27 |
+
"mp3",
|
28 |
+
"flac",
|
29 |
+
"ogg",
|
30 |
+
"opus",
|
31 |
+
"m4a",
|
32 |
+
"mp4",
|
33 |
+
"aac",
|
34 |
+
"alac",
|
35 |
+
"wma",
|
36 |
+
"aiff",
|
37 |
+
"webm",
|
38 |
+
"ac3",
|
39 |
+
}
|
40 |
+
|
41 |
+
def note_to_hz(note_name):
|
42 |
+
try:
|
43 |
+
SEMITONES = {'C': -9, 'C#': -8, 'D': -7, 'D#': -6, 'E': -5, 'F': -4, 'F#': -3, 'G': -2, 'G#': -1, 'A': 0, 'A#': 1, 'B': 2}
|
44 |
+
pitch_class, octave = note_name[:-1], int(note_name[-1])
|
45 |
+
semitone = SEMITONES[pitch_class]
|
46 |
+
note_number = 12 * (octave - 4) + semitone
|
47 |
+
frequency = 440.0 * (2.0 ** (1.0/12)) ** note_number
|
48 |
+
return frequency
|
49 |
+
except:
|
50 |
+
return None
|
51 |
+
|
52 |
+
def load_hubert(hubert_model_path, config):
|
53 |
+
models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
|
54 |
+
[hubert_model_path],
|
55 |
+
suffix="",
|
56 |
+
)
|
57 |
+
hubert_model = models[0]
|
58 |
+
hubert_model = hubert_model.to(config.device)
|
59 |
+
if config.is_half:
|
60 |
+
hubert_model = hubert_model.half()
|
61 |
+
else:
|
62 |
+
hubert_model = hubert_model.float()
|
63 |
+
return hubert_model.eval()
|
64 |
+
|
65 |
+
class VC:
|
66 |
+
def __init__(self, config):
|
67 |
+
self.n_spk = None
|
68 |
+
self.tgt_sr = None
|
69 |
+
self.net_g = None
|
70 |
+
self.pipeline = None
|
71 |
+
self.cpt = None
|
72 |
+
self.version = None
|
73 |
+
self.if_f0 = None
|
74 |
+
self.version = None
|
75 |
+
self.hubert_model = None
|
76 |
+
|
77 |
+
self.config = config
|
78 |
+
|
79 |
+
def get_vc(self, sid, *to_return_protect):
|
80 |
+
logger.info("Get sid: " + sid)
|
81 |
+
|
82 |
+
to_return_protect0 = {
|
83 |
+
"visible": self.if_f0 != 0,
|
84 |
+
"value": to_return_protect[0]
|
85 |
+
if self.if_f0 != 0 and to_return_protect
|
86 |
+
else 0.5,
|
87 |
+
"__type__": "update",
|
88 |
+
}
|
89 |
+
to_return_protect1 = {
|
90 |
+
"visible": self.if_f0 != 0,
|
91 |
+
"value": to_return_protect[1]
|
92 |
+
if self.if_f0 != 0 and to_return_protect
|
93 |
+
else 0.33,
|
94 |
+
"__type__": "update",
|
95 |
+
}
|
96 |
+
|
97 |
+
if sid == "" or sid == []:
|
98 |
+
if self.hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的
|
99 |
+
logger.info("Clean model cache")
|
100 |
+
del (
|
101 |
+
self.net_g,
|
102 |
+
self.n_spk,
|
103 |
+
self.vc,
|
104 |
+
self.hubert_model,
|
105 |
+
self.tgt_sr,
|
106 |
+
) # ,cpt
|
107 |
+
self.hubert_model = (
|
108 |
+
self.net_g
|
109 |
+
) = self.n_spk = self.vc = self.hubert_model = self.tgt_sr = None
|
110 |
+
if torch.cuda.is_available():
|
111 |
+
torch.cuda.empty_cache()
|
112 |
+
###楼下不这么折腾清理不干净
|
113 |
+
self.if_f0 = self.cpt.get("f0", 1)
|
114 |
+
self.version = self.cpt.get("version", "v1")
|
115 |
+
if self.version == "v1":
|
116 |
+
if self.if_f0 == 1:
|
117 |
+
self.net_g = SynthesizerTrnMs256NSFsid(
|
118 |
+
*self.cpt["config"], is_half=self.config.is_half
|
119 |
+
)
|
120 |
+
else:
|
121 |
+
self.net_g = SynthesizerTrnMs256NSFsid_nono(*self.cpt["config"])
|
122 |
+
elif self.version == "v2":
|
123 |
+
if self.if_f0 == 1:
|
124 |
+
self.net_g = SynthesizerTrnMs768NSFsid(
|
125 |
+
*self.cpt["config"], is_half=self.config.is_half
|
126 |
+
)
|
127 |
+
else:
|
128 |
+
self.net_g = SynthesizerTrnMs768NSFsid_nono(*self.cpt["config"])
|
129 |
+
del self.net_g, self.cpt
|
130 |
+
if torch.cuda.is_available():
|
131 |
+
torch.cuda.empty_cache()
|
132 |
+
return (
|
133 |
+
{"visible": False, "__type__": "update"},
|
134 |
+
{
|
135 |
+
"visible": True,
|
136 |
+
"value": to_return_protect0,
|
137 |
+
"__type__": "update",
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"visible": True,
|
141 |
+
"value": to_return_protect1,
|
142 |
+
"__type__": "update",
|
143 |
+
},
|
144 |
+
"",
|
145 |
+
"",
|
146 |
+
)
|
147 |
+
#person = f'{os.getenv("weight_root")}/{sid}'
|
148 |
+
person = f'{sid}'
|
149 |
+
#logger.info(f"Loading: {person}")
|
150 |
+
logger.info(f"Loading...")
|
151 |
+
self.cpt = torch.load(person, map_location="cpu")
|
152 |
+
self.tgt_sr = self.cpt["config"][-1]
|
153 |
+
self.cpt["config"][-3] = self.cpt["weight"]["emb_g.weight"].shape[0] # n_spk
|
154 |
+
self.if_f0 = self.cpt.get("f0", 1)
|
155 |
+
self.version = self.cpt.get("version", "v1")
|
156 |
+
|
157 |
+
synthesizer_class = {
|
158 |
+
("v1", 1): SynthesizerTrnMs256NSFsid,
|
159 |
+
("v1", 0): SynthesizerTrnMs256NSFsid_nono,
|
160 |
+
("v2", 1): SynthesizerTrnMs768NSFsid,
|
161 |
+
("v2", 0): SynthesizerTrnMs768NSFsid_nono,
|
162 |
+
}
|
163 |
+
|
164 |
+
self.net_g = synthesizer_class.get(
|
165 |
+
(self.version, self.if_f0), SynthesizerTrnMs256NSFsid
|
166 |
+
)(*self.cpt["config"], is_half=self.config.is_half)
|
167 |
+
|
168 |
+
del self.net_g.enc_q
|
169 |
+
|
170 |
+
self.net_g.load_state_dict(self.cpt["weight"], strict=False)
|
171 |
+
self.net_g.eval().to(self.config.device)
|
172 |
+
if self.config.is_half:
|
173 |
+
self.net_g = self.net_g.half()
|
174 |
+
else:
|
175 |
+
self.net_g = self.net_g.float()
|
176 |
+
|
177 |
+
self.pipeline = Pipeline(self.tgt_sr, self.config)
|
178 |
+
n_spk = self.cpt["config"][-3]
|
179 |
+
#index = {"value": get_index_path_from_model(sid), "__type__": "update"}
|
180 |
+
#logger.info("Select index: " + index["value"])
|
181 |
+
|
182 |
+
return (
|
183 |
+
(
|
184 |
+
{"visible": False, "maximum": n_spk, "__type__": "update"},
|
185 |
+
to_return_protect0,
|
186 |
+
to_return_protect1
|
187 |
+
)
|
188 |
+
if to_return_protect
|
189 |
+
else {"visible": False, "maximum": n_spk, "__type__": "update"}
|
190 |
+
)
|
191 |
+
|
192 |
+
def vc_single_dont_save(
|
193 |
+
self,
|
194 |
+
sid,
|
195 |
+
input_audio_path1,
|
196 |
+
f0_up_key,
|
197 |
+
f0_method,
|
198 |
+
file_index,
|
199 |
+
file_index2,
|
200 |
+
index_rate,
|
201 |
+
filter_radius,
|
202 |
+
resample_sr,
|
203 |
+
rms_mix_rate,
|
204 |
+
protect,
|
205 |
+
crepe_hop_length,
|
206 |
+
do_formant,
|
207 |
+
quefrency,
|
208 |
+
timbre,
|
209 |
+
f0_min,
|
210 |
+
f0_max,
|
211 |
+
f0_autotune,
|
212 |
+
hubert_model_path = "assets/hubert/hubert_base.pt"
|
213 |
+
):
|
214 |
+
"""
|
215 |
+
Performs inference without saving
|
216 |
+
|
217 |
+
Parameters:
|
218 |
+
- sid (int)
|
219 |
+
- input_audio_path1 (str)
|
220 |
+
- f0_up_key (int)
|
221 |
+
- f0_method (str)
|
222 |
+
- file_index (str)
|
223 |
+
- file_index2 (str)
|
224 |
+
- index_rate (float)
|
225 |
+
- filter_radius (int)
|
226 |
+
- resample_sr (int)
|
227 |
+
- rms_mix_rate (float)
|
228 |
+
- protect (float)
|
229 |
+
- crepe_hop_length (int)
|
230 |
+
- do_formant (bool)
|
231 |
+
- quefrency (float)
|
232 |
+
- timbre (float)
|
233 |
+
- f0_min (str)
|
234 |
+
- f0_max (str)
|
235 |
+
- f0_autotune (bool)
|
236 |
+
- hubert_model_path (str)
|
237 |
+
|
238 |
+
Returns:
|
239 |
+
Tuple(Tuple(status, index_info, times), Tuple(sr, data)):
|
240 |
+
- Tuple(status, index_info, times):
|
241 |
+
- status (str): either "Success." or an error
|
242 |
+
- index_info (str): index path if used
|
243 |
+
- times (list): [npy_time, f0_time, infer_time, total_time]
|
244 |
+
- Tuple(sr, data): Audio data results.
|
245 |
+
"""
|
246 |
+
global total_time
|
247 |
+
total_time = 0
|
248 |
+
start_time = time.time()
|
249 |
+
|
250 |
+
if not input_audio_path1:
|
251 |
+
return "You need to upload an audio", None
|
252 |
+
|
253 |
+
if not os.path.exists(input_audio_path1):
|
254 |
+
return "Audio was not properly selected or doesn't exist", None
|
255 |
+
|
256 |
+
f0_up_key = int(f0_up_key)
|
257 |
+
if not f0_min.isdigit():
|
258 |
+
f0_min = note_to_hz(f0_min)
|
259 |
+
if f0_min:
|
260 |
+
print(f"Converted Min pitch: freq - {f0_min}")
|
261 |
+
else:
|
262 |
+
f0_min = 50
|
263 |
+
print("Invalid minimum pitch note. Defaulting to 50hz.")
|
264 |
+
else:
|
265 |
+
f0_min = float(f0_min)
|
266 |
+
if not f0_max.isdigit():
|
267 |
+
f0_max = note_to_hz(f0_max)
|
268 |
+
if f0_max:
|
269 |
+
print(f"Converted Max pitch: freq - {f0_max}")
|
270 |
+
else:
|
271 |
+
f0_max = 1100
|
272 |
+
print("Invalid maximum pitch note. Defaulting to 1100hz.")
|
273 |
+
else:
|
274 |
+
f0_max = float(f0_max)
|
275 |
+
|
276 |
+
try:
|
277 |
+
print(f"Attempting to load {input_audio_path1}....")
|
278 |
+
audio = load_audio(file=input_audio_path1,
|
279 |
+
sr=16000,
|
280 |
+
DoFormant=do_formant,
|
281 |
+
Quefrency=quefrency,
|
282 |
+
Timbre=timbre)
|
283 |
+
|
284 |
+
audio_max = np.abs(audio).max() / 0.95
|
285 |
+
if audio_max > 1:
|
286 |
+
audio /= audio_max
|
287 |
+
times = [0, 0, 0]
|
288 |
+
|
289 |
+
if self.hubert_model is None:
|
290 |
+
self.hubert_model = load_hubert(hubert_model_path, self.config)
|
291 |
+
|
292 |
+
try:
|
293 |
+
self.if_f0 = self.cpt.get("f0", 1)
|
294 |
+
except NameError:
|
295 |
+
message = "Model was not properly selected"
|
296 |
+
print(message)
|
297 |
+
return message, None
|
298 |
+
|
299 |
+
if file_index and not file_index == "" and isinstance(file_index, str):
|
300 |
+
file_index = file_index.strip(" ") \
|
301 |
+
.strip('"') \
|
302 |
+
.strip("\n") \
|
303 |
+
.strip('"') \
|
304 |
+
.strip(" ") \
|
305 |
+
.replace("trained", "added")
|
306 |
+
elif file_index2:
|
307 |
+
file_index = file_index2
|
308 |
+
else:
|
309 |
+
file_index = ""
|
310 |
+
|
311 |
+
audio_opt = self.pipeline.pipeline(
|
312 |
+
self.hubert_model,
|
313 |
+
self.net_g,
|
314 |
+
sid,
|
315 |
+
audio,
|
316 |
+
input_audio_path1,
|
317 |
+
times,
|
318 |
+
f0_up_key,
|
319 |
+
f0_method,
|
320 |
+
file_index,
|
321 |
+
index_rate,
|
322 |
+
self.if_f0,
|
323 |
+
filter_radius,
|
324 |
+
self.tgt_sr,
|
325 |
+
resample_sr,
|
326 |
+
rms_mix_rate,
|
327 |
+
self.version,
|
328 |
+
protect,
|
329 |
+
crepe_hop_length,
|
330 |
+
f0_autotune,
|
331 |
+
f0_min=f0_min,
|
332 |
+
f0_max=f0_max
|
333 |
+
)
|
334 |
+
|
335 |
+
if self.tgt_sr != resample_sr >= 16000:
|
336 |
+
tgt_sr = resample_sr
|
337 |
+
else:
|
338 |
+
tgt_sr = self.tgt_sr
|
339 |
+
index_info = (
|
340 |
+
"Index: %s." % file_index
|
341 |
+
if isinstance(file_index, str) and os.path.exists(file_index)
|
342 |
+
else "Index not used."
|
343 |
+
)
|
344 |
+
end_time = time.time()
|
345 |
+
total_time = end_time - start_time
|
346 |
+
times.append(total_time)
|
347 |
+
return (
|
348 |
+
("Success.", index_info, times),
|
349 |
+
(tgt_sr, audio_opt),
|
350 |
+
)
|
351 |
+
except:
|
352 |
+
info = traceback.format_exc()
|
353 |
+
logger.warn(info)
|
354 |
+
return (
|
355 |
+
(info, None, [None, None, None, None]),
|
356 |
+
(None, None)
|
357 |
+
)
|
358 |
+
|
359 |
+
def vc_single(
|
360 |
+
self,
|
361 |
+
sid,
|
362 |
+
input_audio_path1,
|
363 |
+
f0_up_key,
|
364 |
+
f0_method,
|
365 |
+
file_index,
|
366 |
+
file_index2,
|
367 |
+
index_rate,
|
368 |
+
filter_radius,
|
369 |
+
resample_sr,
|
370 |
+
rms_mix_rate,
|
371 |
+
protect,
|
372 |
+
format1,
|
373 |
+
crepe_hop_length,
|
374 |
+
do_formant,
|
375 |
+
quefrency,
|
376 |
+
timbre,
|
377 |
+
f0_min,
|
378 |
+
f0_max,
|
379 |
+
f0_autotune,
|
380 |
+
hubert_model_path = "assets/hubert/hubert_base.pt"
|
381 |
+
):
|
382 |
+
"""
|
383 |
+
Performs inference with saving
|
384 |
+
|
385 |
+
Parameters:
|
386 |
+
- sid (int)
|
387 |
+
- input_audio_path1 (str)
|
388 |
+
- f0_up_key (int)
|
389 |
+
- f0_method (str)
|
390 |
+
- file_index (str)
|
391 |
+
- file_index2 (str)
|
392 |
+
- index_rate (float)
|
393 |
+
- filter_radius (int)
|
394 |
+
- resample_sr (int)
|
395 |
+
- rms_mix_rate (float)
|
396 |
+
- protect (float)
|
397 |
+
- format1 (str)
|
398 |
+
- crepe_hop_length (int)
|
399 |
+
- do_formant (bool)
|
400 |
+
- quefrency (float)
|
401 |
+
- timbre (float)
|
402 |
+
- f0_min (str)
|
403 |
+
- f0_max (str)
|
404 |
+
- f0_autotune (bool)
|
405 |
+
- hubert_model_path (str)
|
406 |
+
|
407 |
+
Returns:
|
408 |
+
Tuple(Tuple(status, index_info, times), Tuple(sr, data), output_path):
|
409 |
+
- Tuple(status, index_info, times):
|
410 |
+
- status (str): either "Success." or an error
|
411 |
+
- index_info (str): index path if used
|
412 |
+
- times (list): [npy_time, f0_time, infer_time, total_time]
|
413 |
+
- Tuple(sr, data): Audio data results.
|
414 |
+
- output_path (str): Audio results path
|
415 |
+
"""
|
416 |
+
global total_time
|
417 |
+
total_time = 0
|
418 |
+
start_time = time.time()
|
419 |
+
|
420 |
+
if not input_audio_path1:
|
421 |
+
return "You need to upload an audio", None, None
|
422 |
+
|
423 |
+
if not os.path.exists(input_audio_path1):
|
424 |
+
return "Audio was not properly selected or doesn't exist", None, None
|
425 |
+
|
426 |
+
f0_up_key = int(f0_up_key)
|
427 |
+
if not f0_min.isdigit():
|
428 |
+
f0_min = note_to_hz(f0_min)
|
429 |
+
if f0_min:
|
430 |
+
print(f"Converted Min pitch: freq - {f0_min}")
|
431 |
+
else:
|
432 |
+
f0_min = 50
|
433 |
+
print("Invalid minimum pitch note. Defaulting to 50hz.")
|
434 |
+
else:
|
435 |
+
f0_min = float(f0_min)
|
436 |
+
if not f0_max.isdigit():
|
437 |
+
f0_max = note_to_hz(f0_max)
|
438 |
+
if f0_max:
|
439 |
+
print(f"Converted Max pitch: freq - {f0_max}")
|
440 |
+
else:
|
441 |
+
f0_max = 1100
|
442 |
+
print("Invalid maximum pitch note. Defaulting to 1100hz.")
|
443 |
+
else:
|
444 |
+
f0_max = float(f0_max)
|
445 |
+
|
446 |
+
try:
|
447 |
+
print(f"Attempting to load {input_audio_path1}...")
|
448 |
+
audio = load_audio(file=input_audio_path1,
|
449 |
+
sr=16000,
|
450 |
+
DoFormant=do_formant,
|
451 |
+
Quefrency=quefrency,
|
452 |
+
Timbre=timbre)
|
453 |
+
|
454 |
+
audio_max = np.abs(audio).max() / 0.95
|
455 |
+
if audio_max > 1:
|
456 |
+
audio /= audio_max
|
457 |
+
times = [0, 0, 0]
|
458 |
+
|
459 |
+
if self.hubert_model is None:
|
460 |
+
self.hubert_model = load_hubert(hubert_model_path, self.config)
|
461 |
+
|
462 |
+
try:
|
463 |
+
self.if_f0 = self.cpt.get("f0", 1)
|
464 |
+
except NameError:
|
465 |
+
message = "Model was not properly selected"
|
466 |
+
print(message)
|
467 |
+
return message, None
|
468 |
+
if file_index and not file_index == "" and isinstance(file_index, str):
|
469 |
+
file_index = file_index.strip(" ") \
|
470 |
+
.strip('"') \
|
471 |
+
.strip("\n") \
|
472 |
+
.strip('"') \
|
473 |
+
.strip(" ") \
|
474 |
+
.replace("trained", "added")
|
475 |
+
elif file_index2:
|
476 |
+
file_index = file_index2
|
477 |
+
else:
|
478 |
+
file_index = ""
|
479 |
+
|
480 |
+
audio_opt = self.pipeline.pipeline(
|
481 |
+
self.hubert_model,
|
482 |
+
self.net_g,
|
483 |
+
sid,
|
484 |
+
audio,
|
485 |
+
input_audio_path1,
|
486 |
+
times,
|
487 |
+
f0_up_key,
|
488 |
+
f0_method,
|
489 |
+
file_index,
|
490 |
+
index_rate,
|
491 |
+
self.if_f0,
|
492 |
+
filter_radius,
|
493 |
+
self.tgt_sr,
|
494 |
+
resample_sr,
|
495 |
+
rms_mix_rate,
|
496 |
+
self.version,
|
497 |
+
protect,
|
498 |
+
crepe_hop_length,
|
499 |
+
f0_autotune,
|
500 |
+
f0_min=f0_min,
|
501 |
+
f0_max=f0_max
|
502 |
+
)
|
503 |
+
|
504 |
+
if self.tgt_sr != resample_sr >= 16000:
|
505 |
+
tgt_sr = resample_sr
|
506 |
+
else:
|
507 |
+
tgt_sr = self.tgt_sr
|
508 |
+
index_info = (
|
509 |
+
"Index: %s." % file_index
|
510 |
+
if isinstance(file_index, str) and os.path.exists(file_index)
|
511 |
+
else "Index not used."
|
512 |
+
)
|
513 |
+
|
514 |
+
opt_root = os.path.join(os.getcwd(), "output")
|
515 |
+
os.makedirs(opt_root, exist_ok=True)
|
516 |
+
output_count = 1
|
517 |
+
|
518 |
+
while True:
|
519 |
+
opt_filename = f"{os.path.splitext(os.path.basename(input_audio_path1))[0]}{os.path.basename(os.path.dirname(file_index))}{f0_method.capitalize()}_{output_count}.{format1}"
|
520 |
+
current_output_path = os.path.join(opt_root, opt_filename)
|
521 |
+
if not os.path.exists(current_output_path):
|
522 |
+
break
|
523 |
+
output_count += 1
|
524 |
+
try:
|
525 |
+
if format1 in ["wav", "flac"]:
|
526 |
+
sf.write(
|
527 |
+
current_output_path,
|
528 |
+
audio_opt,
|
529 |
+
self.tgt_sr,
|
530 |
+
)
|
531 |
+
else:
|
532 |
+
with BytesIO() as wavf:
|
533 |
+
sf.write(
|
534 |
+
wavf,
|
535 |
+
audio_opt,
|
536 |
+
self.tgt_sr,
|
537 |
+
format="wav"
|
538 |
+
)
|
539 |
+
wavf.seek(0, 0)
|
540 |
+
with open(current_output_path, "wb") as outf:
|
541 |
+
wav2(wavf, outf, format1)
|
542 |
+
except:
|
543 |
+
info = traceback.format_exc()
|
544 |
+
end_time = time.time()
|
545 |
+
total_time = end_time - start_time
|
546 |
+
times.append(total_time)
|
547 |
+
return (
|
548 |
+
("Success.", index_info, times),
|
549 |
+
(tgt_sr, audio_opt),
|
550 |
+
current_output_path
|
551 |
+
)
|
552 |
+
except:
|
553 |
+
info = traceback.format_exc()
|
554 |
+
logger.warn(info)
|
555 |
+
return (
|
556 |
+
(info, None, [None, None, None, None]),
|
557 |
+
(None, None),
|
558 |
+
None
|
559 |
+
)
|
lib/pipeline.py
ADDED
@@ -0,0 +1,784 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import gc
|
4 |
+
import traceback
|
5 |
+
import logging
|
6 |
+
|
7 |
+
logger = logging.getLogger(__name__)
|
8 |
+
|
9 |
+
from functools import lru_cache
|
10 |
+
from time import time as ttime
|
11 |
+
from torch import Tensor
|
12 |
+
import faiss
|
13 |
+
import librosa
|
14 |
+
import numpy as np
|
15 |
+
import parselmouth
|
16 |
+
import pyworld
|
17 |
+
import torch.nn.functional as F
|
18 |
+
from scipy import signal
|
19 |
+
from tqdm import tqdm
|
20 |
+
|
21 |
+
import random
|
22 |
+
now_dir = os.getcwd()
|
23 |
+
sys.path.append(now_dir)
|
24 |
+
import re
|
25 |
+
from functools import partial
|
26 |
+
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
|
27 |
+
|
28 |
+
input_audio_path2wav = {}
|
29 |
+
import torchcrepe # Fork Feature. Crepe algo for training and preprocess
|
30 |
+
import torchfcpe # Harmonify Feature.
|
31 |
+
import torch
|
32 |
+
from lib.infer_libs.rmvpe import RMVPE
|
33 |
+
from lib.infer_libs.fcpe import FCPE # Harmonify Feature.
|
34 |
+
|
35 |
+
@lru_cache
|
36 |
+
def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
|
37 |
+
audio = input_audio_path2wav[input_audio_path]
|
38 |
+
f0, t = pyworld.harvest(
|
39 |
+
audio,
|
40 |
+
fs=fs,
|
41 |
+
f0_ceil=f0max,
|
42 |
+
f0_floor=f0min,
|
43 |
+
frame_period=frame_period,
|
44 |
+
)
|
45 |
+
f0 = pyworld.stonemask(audio, f0, t, fs)
|
46 |
+
return f0
|
47 |
+
|
48 |
+
|
49 |
+
def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
|
50 |
+
# print(data1.max(),data2.max())
|
51 |
+
rms1 = librosa.feature.rms(
|
52 |
+
y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
|
53 |
+
) # 每半秒一个点
|
54 |
+
rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
|
55 |
+
rms1 = torch.from_numpy(rms1)
|
56 |
+
rms1 = F.interpolate(
|
57 |
+
rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
|
58 |
+
).squeeze()
|
59 |
+
rms2 = torch.from_numpy(rms2)
|
60 |
+
rms2 = F.interpolate(
|
61 |
+
rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
|
62 |
+
).squeeze()
|
63 |
+
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
|
64 |
+
data2 *= (
|
65 |
+
torch.pow(rms1, torch.tensor(1 - rate))
|
66 |
+
* torch.pow(rms2, torch.tensor(rate - 1))
|
67 |
+
).numpy()
|
68 |
+
return data2
|
69 |
+
|
70 |
+
|
71 |
+
class Pipeline(object):
|
72 |
+
def __init__(self, tgt_sr, config):
|
73 |
+
self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
|
74 |
+
config.x_pad,
|
75 |
+
config.x_query,
|
76 |
+
config.x_center,
|
77 |
+
config.x_max,
|
78 |
+
config.is_half,
|
79 |
+
)
|
80 |
+
self.sr = 16000 # hubert输入采样率
|
81 |
+
self.window = 160 # 每帧点数
|
82 |
+
self.t_pad = self.sr * self.x_pad # 每条前后pad时间
|
83 |
+
self.t_pad_tgt = tgt_sr * self.x_pad
|
84 |
+
self.t_pad2 = self.t_pad * 2
|
85 |
+
self.t_query = self.sr * self.x_query # 查询切点前后查询时间
|
86 |
+
self.t_center = self.sr * self.x_center # 查询切点位置
|
87 |
+
self.t_max = self.sr * self.x_max # 免查询时长阈值
|
88 |
+
self.device = config.device
|
89 |
+
self.model_rmvpe = RMVPE(os.environ["rmvpe_model_path"], is_half=self.is_half, device=self.device)
|
90 |
+
|
91 |
+
self.note_dict = [
|
92 |
+
65.41, 69.30, 73.42, 77.78, 82.41, 87.31,
|
93 |
+
92.50, 98.00, 103.83, 110.00, 116.54, 123.47,
|
94 |
+
130.81, 138.59, 146.83, 155.56, 164.81, 174.61,
|
95 |
+
185.00, 196.00, 207.65, 220.00, 233.08, 246.94,
|
96 |
+
261.63, 277.18, 293.66, 311.13, 329.63, 349.23,
|
97 |
+
369.99, 392.00, 415.30, 440.00, 466.16, 493.88,
|
98 |
+
523.25, 554.37, 587.33, 622.25, 659.25, 698.46,
|
99 |
+
739.99, 783.99, 830.61, 880.00, 932.33, 987.77,
|
100 |
+
1046.50, 1108.73, 1174.66, 1244.51, 1318.51, 1396.91,
|
101 |
+
1479.98, 1567.98, 1661.22, 1760.00, 1864.66, 1975.53,
|
102 |
+
2093.00, 2217.46, 2349.32, 2489.02, 2637.02, 2793.83,
|
103 |
+
2959.96, 3135.96, 3322.44, 3520.00, 3729.31, 3951.07
|
104 |
+
]
|
105 |
+
|
106 |
+
# Fork Feature: Get the best torch device to use for f0 algorithms that require a torch device. Will return the type (torch.device)
|
107 |
+
def get_optimal_torch_device(self, index: int = 0) -> torch.device:
|
108 |
+
if torch.cuda.is_available():
|
109 |
+
return torch.device(
|
110 |
+
f"cuda:{index % torch.cuda.device_count()}"
|
111 |
+
) # Very fast
|
112 |
+
elif torch.backends.mps.is_available():
|
113 |
+
return torch.device("mps")
|
114 |
+
return torch.device("cpu")
|
115 |
+
|
116 |
+
# Fork Feature: Compute f0 with the crepe method
|
117 |
+
def get_f0_crepe_computation(
|
118 |
+
self,
|
119 |
+
x,
|
120 |
+
f0_min,
|
121 |
+
f0_max,
|
122 |
+
p_len,
|
123 |
+
*args, # 512 before. Hop length changes the speed that the voice jumps to a different dramatic pitch. Lower hop lengths means more pitch accuracy but longer inference time.
|
124 |
+
**kwargs, # Either use crepe-tiny "tiny" or crepe "full". Default is full
|
125 |
+
):
|
126 |
+
x = x.astype(
|
127 |
+
np.float32
|
128 |
+
) # fixes the F.conv2D exception. We needed to convert double to float.
|
129 |
+
x /= np.quantile(np.abs(x), 0.999)
|
130 |
+
torch_device = self.get_optimal_torch_device()
|
131 |
+
audio = torch.from_numpy(x).to(torch_device, copy=True)
|
132 |
+
audio = torch.unsqueeze(audio, dim=0)
|
133 |
+
if audio.ndim == 2 and audio.shape[0] > 1:
|
134 |
+
audio = torch.mean(audio, dim=0, keepdim=True).detach()
|
135 |
+
audio = audio.detach()
|
136 |
+
hop_length = kwargs.get('crepe_hop_length', 160)
|
137 |
+
model = kwargs.get('model', 'full')
|
138 |
+
print("Initiating prediction with a crepe_hop_length of: " + str(hop_length))
|
139 |
+
pitch: Tensor = torchcrepe.predict(
|
140 |
+
audio,
|
141 |
+
self.sr,
|
142 |
+
hop_length,
|
143 |
+
f0_min,
|
144 |
+
f0_max,
|
145 |
+
model,
|
146 |
+
batch_size=hop_length * 2,
|
147 |
+
device=torch_device,
|
148 |
+
pad=True,
|
149 |
+
)
|
150 |
+
p_len = p_len or x.shape[0] // hop_length
|
151 |
+
# Resize the pitch for final f0
|
152 |
+
source = np.array(pitch.squeeze(0).cpu().float().numpy())
|
153 |
+
source[source < 0.001] = np.nan
|
154 |
+
target = np.interp(
|
155 |
+
np.arange(0, len(source) * p_len, len(source)) / p_len,
|
156 |
+
np.arange(0, len(source)),
|
157 |
+
source,
|
158 |
+
)
|
159 |
+
f0 = np.nan_to_num(target)
|
160 |
+
return f0 # Resized f0
|
161 |
+
|
162 |
+
def get_f0_official_crepe_computation(
|
163 |
+
self,
|
164 |
+
x,
|
165 |
+
f0_min,
|
166 |
+
f0_max,
|
167 |
+
*args,
|
168 |
+
**kwargs
|
169 |
+
):
|
170 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
171 |
+
batch_size = 512
|
172 |
+
# Compute pitch using first gpu
|
173 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
174 |
+
model = kwargs.get('model', 'full')
|
175 |
+
f0, pd = torchcrepe.predict(
|
176 |
+
audio,
|
177 |
+
self.sr,
|
178 |
+
self.window,
|
179 |
+
f0_min,
|
180 |
+
f0_max,
|
181 |
+
model,
|
182 |
+
batch_size=batch_size,
|
183 |
+
device=self.device,
|
184 |
+
return_periodicity=True,
|
185 |
+
)
|
186 |
+
pd = torchcrepe.filter.median(pd, 3)
|
187 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
188 |
+
f0[pd < 0.1] = 0
|
189 |
+
f0 = f0[0].cpu().numpy()
|
190 |
+
return f0
|
191 |
+
|
192 |
+
# Fork Feature: Compute pYIN f0 method
|
193 |
+
def get_f0_pyin_computation(self, x, f0_min, f0_max):
|
194 |
+
y, sr = librosa.load(x, sr=self.sr, mono=True)
|
195 |
+
f0, _, _ = librosa.pyin(y, fmin=f0_min, fmax=f0_max, sr=self.sr)
|
196 |
+
f0 = f0[1:] # Get rid of extra first frame
|
197 |
+
return f0
|
198 |
+
|
199 |
+
def get_pm(self, x, p_len, *args, **kwargs):
|
200 |
+
f0 = parselmouth.Sound(x, self.sr).to_pitch_ac(
|
201 |
+
time_step=160 / 16000,
|
202 |
+
voicing_threshold=0.6,
|
203 |
+
pitch_floor=kwargs.get('f0_min'),
|
204 |
+
pitch_ceiling=kwargs.get('f0_max'),
|
205 |
+
).selected_array["frequency"]
|
206 |
+
|
207 |
+
return np.pad(
|
208 |
+
f0,
|
209 |
+
[[max(0, (p_len - len(f0) + 1) // 2), max(0, p_len - len(f0) - (p_len - len(f0) + 1) // 2)]],
|
210 |
+
mode="constant"
|
211 |
+
)
|
212 |
+
|
213 |
+
def get_harvest(self, x, *args, **kwargs):
|
214 |
+
f0_spectral = pyworld.harvest(
|
215 |
+
x.astype(np.double),
|
216 |
+
fs=self.sr,
|
217 |
+
f0_ceil=kwargs.get('f0_max'),
|
218 |
+
f0_floor=kwargs.get('f0_min'),
|
219 |
+
frame_period=1000 * kwargs.get('hop_length', 160) / self.sr,
|
220 |
+
)
|
221 |
+
return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.sr)
|
222 |
+
|
223 |
+
def get_dio(self, x, *args, **kwargs):
|
224 |
+
f0_spectral = pyworld.dio(
|
225 |
+
x.astype(np.double),
|
226 |
+
fs=self.sr,
|
227 |
+
f0_ceil=kwargs.get('f0_max'),
|
228 |
+
f0_floor=kwargs.get('f0_min'),
|
229 |
+
frame_period=1000 * kwargs.get('hop_length', 160) / self.sr,
|
230 |
+
)
|
231 |
+
return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.sr)
|
232 |
+
|
233 |
+
|
234 |
+
def get_rmvpe(self, x, *args, **kwargs):
|
235 |
+
if not hasattr(self, "model_rmvpe"):
|
236 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
237 |
+
|
238 |
+
logger.info(
|
239 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
240 |
+
)
|
241 |
+
self.model_rmvpe = RMVPE(
|
242 |
+
os.environ["rmvpe_model_path"],
|
243 |
+
is_half=self.is_half,
|
244 |
+
device=self.device,
|
245 |
+
)
|
246 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
247 |
+
|
248 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
249 |
+
del self.model_rmvpe.model
|
250 |
+
del self.model_rmvpe
|
251 |
+
logger.info("Cleaning ortruntime memory")
|
252 |
+
|
253 |
+
return f0
|
254 |
+
|
255 |
+
|
256 |
+
def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
|
257 |
+
if not hasattr(self, "model_rmvpe"):
|
258 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
259 |
+
|
260 |
+
logger.info(
|
261 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
262 |
+
)
|
263 |
+
self.model_rmvpe = RMVPE(
|
264 |
+
os.environ["rmvpe_model_path"],
|
265 |
+
is_half=self.is_half,
|
266 |
+
device=self.device,
|
267 |
+
)
|
268 |
+
f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
|
269 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
270 |
+
del self.model_rmvpe.model
|
271 |
+
del self.model_rmvpe
|
272 |
+
logger.info("Cleaning ortruntime memory")
|
273 |
+
|
274 |
+
return f0
|
275 |
+
|
276 |
+
def get_fcpe(self, x, f0_min, f0_max, p_len, *args, **kwargs):
|
277 |
+
self.model_fcpe = FCPE(os.environ["fcpe_model_path"], f0_min=f0_min, f0_max=f0_max, dtype=torch.float32, device=self.device, sampling_rate=self.sr, threshold=0.03)
|
278 |
+
f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
|
279 |
+
del self.model_fcpe
|
280 |
+
gc.collect()
|
281 |
+
return f0
|
282 |
+
|
283 |
+
def get_torchfcpe(self, x, sr, f0_min, f0_max, p_len, *args, **kwargs):
|
284 |
+
self.model_torchfcpe = spawn_bundled_infer_model(device=self.device)
|
285 |
+
f0 = self.model_torchfcpe.infer(
|
286 |
+
x,
|
287 |
+
sr=sr,
|
288 |
+
decoder_mode="local_argmax",
|
289 |
+
threshold=0.03,
|
290 |
+
f0_min=f0_min,
|
291 |
+
f0_max=f0_max,
|
292 |
+
output_interp_target_length=p_len
|
293 |
+
)
|
294 |
+
return f0
|
295 |
+
|
296 |
+
def autotune_f0(self, f0):
|
297 |
+
autotuned_f0 = []
|
298 |
+
for freq in f0:
|
299 |
+
closest_notes = [x for x in self.note_dict if abs(x - freq) == min(abs(n - freq) for n in self.note_dict)]
|
300 |
+
autotuned_f0.append(random.choice(closest_notes))
|
301 |
+
return np.array(autotuned_f0, np.float64)
|
302 |
+
|
303 |
+
|
304 |
+
# Fork Feature: Acquire median hybrid f0 estimation calculation
|
305 |
+
def get_f0_hybrid_computation(
|
306 |
+
self,
|
307 |
+
methods_str,
|
308 |
+
input_audio_path,
|
309 |
+
x,
|
310 |
+
f0_min,
|
311 |
+
f0_max,
|
312 |
+
p_len,
|
313 |
+
filter_radius,
|
314 |
+
crepe_hop_length,
|
315 |
+
time_step,
|
316 |
+
):
|
317 |
+
# Get various f0 methods from input to use in the computation stack
|
318 |
+
methods_str = re.search('hybrid\[(.+)\]', methods_str)
|
319 |
+
if methods_str: # Ensure a match was found
|
320 |
+
methods = [method.strip() for method in methods_str.group(1).split('+')]
|
321 |
+
f0_computation_stack = []
|
322 |
+
|
323 |
+
print("Calculating f0 pitch estimations for methods: %s" % str(methods))
|
324 |
+
x = x.astype(np.float32)
|
325 |
+
x /= np.quantile(np.abs(x), 0.999)
|
326 |
+
# Get f0 calculations for all methods specified
|
327 |
+
for method in methods:
|
328 |
+
f0 = None
|
329 |
+
if method == "pm":
|
330 |
+
f0 = self.get_pm(x, p_len=p_len)
|
331 |
+
elif method == "crepe":
|
332 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="full")
|
333 |
+
f0 = f0[1:]
|
334 |
+
elif method == "crepe-tiny":
|
335 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
336 |
+
f0 = f0[1:] # Get rid of extra first frame
|
337 |
+
elif method == "mangio-crepe":
|
338 |
+
f0 = self.get_f0_crepe_computation(
|
339 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
340 |
+
)
|
341 |
+
elif method == "mangio-crepe-tiny":
|
342 |
+
f0 = self.get_f0_crepe_computation(
|
343 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
344 |
+
)
|
345 |
+
elif method == "harvest":
|
346 |
+
f0 = self.get_harvest(x)
|
347 |
+
f0 = f0[1:]
|
348 |
+
elif method == "dio":
|
349 |
+
f0 = self.get_dio(x)
|
350 |
+
f0 = f0[1:]
|
351 |
+
elif method == "rmvpe":
|
352 |
+
f0 = self.get_rmvpe(x)
|
353 |
+
f0 = f0[1:]
|
354 |
+
elif method == "fcpe":
|
355 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
356 |
+
elif method == "torchfcpe":
|
357 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
358 |
+
elif method == "pyin":
|
359 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
360 |
+
# Push method to the stack
|
361 |
+
f0_computation_stack.append(f0)
|
362 |
+
|
363 |
+
for fc in f0_computation_stack:
|
364 |
+
print(len(fc))
|
365 |
+
|
366 |
+
print("Calculating hybrid median f0 from the stack of: %s" % str(methods))
|
367 |
+
f0_median_hybrid = None
|
368 |
+
if len(f0_computation_stack) == 1:
|
369 |
+
f0_median_hybrid = f0_computation_stack[0]
|
370 |
+
else:
|
371 |
+
f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
|
372 |
+
return f0_median_hybrid
|
373 |
+
|
374 |
+
def get_f0(
|
375 |
+
self,
|
376 |
+
input_audio_path,
|
377 |
+
x,
|
378 |
+
p_len,
|
379 |
+
f0_up_key,
|
380 |
+
f0_method,
|
381 |
+
filter_radius,
|
382 |
+
crepe_hop_length,
|
383 |
+
f0_autotune,
|
384 |
+
inp_f0=None,
|
385 |
+
f0_min=50,
|
386 |
+
f0_max=1100,
|
387 |
+
):
|
388 |
+
global input_audio_path2wav
|
389 |
+
time_step = self.window / self.sr * 1000
|
390 |
+
f0_min = f0_min
|
391 |
+
f0_max = f0_max
|
392 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
393 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
394 |
+
|
395 |
+
if f0_method == "pm":
|
396 |
+
f0 = (
|
397 |
+
parselmouth.Sound(x, self.sr)
|
398 |
+
.to_pitch_ac(
|
399 |
+
time_step=time_step / 1000,
|
400 |
+
voicing_threshold=0.6,
|
401 |
+
pitch_floor=f0_min,
|
402 |
+
pitch_ceiling=f0_max,
|
403 |
+
)
|
404 |
+
.selected_array["frequency"]
|
405 |
+
)
|
406 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
407 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
408 |
+
f0 = np.pad(
|
409 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
410 |
+
)
|
411 |
+
elif f0_method == "harvest":
|
412 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
413 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
414 |
+
if filter_radius > 2:
|
415 |
+
f0 = signal.medfilt(f0, 3)
|
416 |
+
elif f0_method == "dio": # Potentially Buggy?
|
417 |
+
f0, t = pyworld.dio(
|
418 |
+
x.astype(np.double),
|
419 |
+
fs=self.sr,
|
420 |
+
f0_ceil=f0_max,
|
421 |
+
f0_floor=f0_min,
|
422 |
+
frame_period=10,
|
423 |
+
)
|
424 |
+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
425 |
+
f0 = signal.medfilt(f0, 3)
|
426 |
+
elif f0_method == "crepe":
|
427 |
+
model = "full"
|
428 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
429 |
+
batch_size = 512
|
430 |
+
# Compute pitch using first gpu
|
431 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
432 |
+
f0, pd = torchcrepe.predict(
|
433 |
+
audio,
|
434 |
+
self.sr,
|
435 |
+
self.window,
|
436 |
+
f0_min,
|
437 |
+
f0_max,
|
438 |
+
model,
|
439 |
+
batch_size=batch_size,
|
440 |
+
device=self.device,
|
441 |
+
return_periodicity=True,
|
442 |
+
)
|
443 |
+
pd = torchcrepe.filter.median(pd, 3)
|
444 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
445 |
+
f0[pd < 0.1] = 0
|
446 |
+
f0 = f0[0].cpu().numpy()
|
447 |
+
elif f0_method == "crepe-tiny":
|
448 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
449 |
+
elif f0_method == "mangio-crepe":
|
450 |
+
f0 = self.get_f0_crepe_computation(
|
451 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
452 |
+
)
|
453 |
+
elif f0_method == "mangio-crepe-tiny":
|
454 |
+
f0 = self.get_f0_crepe_computation(
|
455 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
456 |
+
)
|
457 |
+
elif f0_method == "rmvpe":
|
458 |
+
if not hasattr(self, "model_rmvpe"):
|
459 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
460 |
+
|
461 |
+
logger.info(
|
462 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
463 |
+
)
|
464 |
+
self.model_rmvpe = RMVPE(
|
465 |
+
os.environ["rmvpe_model_path"],
|
466 |
+
is_half=self.is_half,
|
467 |
+
device=self.device,
|
468 |
+
)
|
469 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
470 |
+
|
471 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
472 |
+
del self.model_rmvpe.model
|
473 |
+
del self.model_rmvpe
|
474 |
+
logger.info("Cleaning ortruntime memory")
|
475 |
+
elif f0_method == "rmvpe+":
|
476 |
+
params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
|
477 |
+
'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
|
478 |
+
'crepe_hop_length': crepe_hop_length, 'model': "full"
|
479 |
+
}
|
480 |
+
f0 = self.get_pitch_dependant_rmvpe(**params)
|
481 |
+
elif f0_method == "pyin":
|
482 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
483 |
+
elif f0_method == "fcpe":
|
484 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
485 |
+
elif method == "torchfcpe":
|
486 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
487 |
+
elif "hybrid" in f0_method:
|
488 |
+
# Perform hybrid median pitch estimation
|
489 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
490 |
+
f0 = self.get_f0_hybrid_computation(
|
491 |
+
f0_method,
|
492 |
+
input_audio_path,
|
493 |
+
x,
|
494 |
+
f0_min,
|
495 |
+
f0_max,
|
496 |
+
p_len,
|
497 |
+
filter_radius,
|
498 |
+
crepe_hop_length,
|
499 |
+
time_step,
|
500 |
+
)
|
501 |
+
#print("Autotune:", f0_autotune)
|
502 |
+
if f0_autotune == True:
|
503 |
+
print("Autotune:", f0_autotune)
|
504 |
+
f0 = self.autotune_f0(f0)
|
505 |
+
|
506 |
+
f0 *= pow(2, f0_up_key / 12)
|
507 |
+
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
508 |
+
tf0 = self.sr // self.window # 每秒f0点数
|
509 |
+
if inp_f0 is not None:
|
510 |
+
delta_t = np.round(
|
511 |
+
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
|
512 |
+
).astype("int16")
|
513 |
+
replace_f0 = np.interp(
|
514 |
+
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
|
515 |
+
)
|
516 |
+
shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
|
517 |
+
f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
|
518 |
+
:shape
|
519 |
+
]
|
520 |
+
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
521 |
+
f0bak = f0.copy()
|
522 |
+
f0_mel = 1127 * np.log(1 + f0 / 700)
|
523 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
524 |
+
f0_mel_max - f0_mel_min
|
525 |
+
) + 1
|
526 |
+
f0_mel[f0_mel <= 1] = 1
|
527 |
+
f0_mel[f0_mel > 255] = 255
|
528 |
+
f0_coarse = np.rint(f0_mel).astype(np.int32)
|
529 |
+
return f0_coarse, f0bak # 1-0
|
530 |
+
|
531 |
+
def vc(
|
532 |
+
self,
|
533 |
+
model,
|
534 |
+
net_g,
|
535 |
+
sid,
|
536 |
+
audio0,
|
537 |
+
pitch,
|
538 |
+
pitchf,
|
539 |
+
times,
|
540 |
+
index,
|
541 |
+
big_npy,
|
542 |
+
index_rate,
|
543 |
+
version,
|
544 |
+
protect,
|
545 |
+
): # ,file_index,file_big_npy
|
546 |
+
feats = torch.from_numpy(audio0)
|
547 |
+
if self.is_half:
|
548 |
+
feats = feats.half()
|
549 |
+
else:
|
550 |
+
feats = feats.float()
|
551 |
+
if feats.dim() == 2: # double channels
|
552 |
+
feats = feats.mean(-1)
|
553 |
+
assert feats.dim() == 1, feats.dim()
|
554 |
+
feats = feats.view(1, -1)
|
555 |
+
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
|
556 |
+
|
557 |
+
inputs = {
|
558 |
+
"source": feats.to(self.device),
|
559 |
+
"padding_mask": padding_mask,
|
560 |
+
"output_layer": 9 if version == "v1" else 12,
|
561 |
+
}
|
562 |
+
t0 = ttime()
|
563 |
+
with torch.no_grad():
|
564 |
+
logits = model.extract_features(**inputs)
|
565 |
+
feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
|
566 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
567 |
+
feats0 = feats.clone()
|
568 |
+
if (
|
569 |
+
not isinstance(index, type(None))
|
570 |
+
and not isinstance(big_npy, type(None))
|
571 |
+
and index_rate != 0
|
572 |
+
):
|
573 |
+
npy = feats[0].cpu().numpy()
|
574 |
+
if self.is_half:
|
575 |
+
npy = npy.astype("float32")
|
576 |
+
|
577 |
+
# _, I = index.search(npy, 1)
|
578 |
+
# npy = big_npy[I.squeeze()]
|
579 |
+
|
580 |
+
score, ix = index.search(npy, k=8)
|
581 |
+
weight = np.square(1 / score)
|
582 |
+
weight /= weight.sum(axis=1, keepdims=True)
|
583 |
+
npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
584 |
+
|
585 |
+
if self.is_half:
|
586 |
+
npy = npy.astype("float16")
|
587 |
+
feats = (
|
588 |
+
torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
|
589 |
+
+ (1 - index_rate) * feats
|
590 |
+
)
|
591 |
+
|
592 |
+
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
|
593 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
594 |
+
feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
|
595 |
+
0, 2, 1
|
596 |
+
)
|
597 |
+
t1 = ttime()
|
598 |
+
p_len = audio0.shape[0] // self.window
|
599 |
+
if feats.shape[1] < p_len:
|
600 |
+
p_len = feats.shape[1]
|
601 |
+
if pitch is not None and pitchf is not None:
|
602 |
+
pitch = pitch[:, :p_len]
|
603 |
+
pitchf = pitchf[:, :p_len]
|
604 |
+
|
605 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
606 |
+
pitchff = pitchf.clone()
|
607 |
+
pitchff[pitchf > 0] = 1
|
608 |
+
pitchff[pitchf < 1] = protect
|
609 |
+
pitchff = pitchff.unsqueeze(-1)
|
610 |
+
feats = feats * pitchff + feats0 * (1 - pitchff)
|
611 |
+
feats = feats.to(feats0.dtype)
|
612 |
+
p_len = torch.tensor([p_len], device=self.device).long()
|
613 |
+
with torch.no_grad():
|
614 |
+
hasp = pitch is not None and pitchf is not None
|
615 |
+
arg = (feats, p_len, pitch, pitchf, sid) if hasp else (feats, p_len, sid)
|
616 |
+
audio1 = (net_g.infer(*arg)[0][0, 0]).data.cpu().float().numpy()
|
617 |
+
del hasp, arg
|
618 |
+
del feats, p_len, padding_mask
|
619 |
+
if torch.cuda.is_available():
|
620 |
+
torch.cuda.empty_cache()
|
621 |
+
t2 = ttime()
|
622 |
+
times[0] += t1 - t0
|
623 |
+
times[2] += t2 - t1
|
624 |
+
return audio1
|
625 |
+
def process_t(self, t, s, window, audio_pad, pitch, pitchf, times, index, big_npy, index_rate, version, protect, t_pad_tgt, if_f0, sid, model, net_g):
|
626 |
+
t = t // window * window
|
627 |
+
if if_f0 == 1:
|
628 |
+
return self.vc(
|
629 |
+
model,
|
630 |
+
net_g,
|
631 |
+
sid,
|
632 |
+
audio_pad[s : t + t_pad_tgt + window],
|
633 |
+
pitch[:, s // window : (t + t_pad_tgt) // window],
|
634 |
+
pitchf[:, s // window : (t + t_pad_tgt) // window],
|
635 |
+
times,
|
636 |
+
index,
|
637 |
+
big_npy,
|
638 |
+
index_rate,
|
639 |
+
version,
|
640 |
+
protect,
|
641 |
+
)[t_pad_tgt : -t_pad_tgt]
|
642 |
+
else:
|
643 |
+
return self.vc(
|
644 |
+
model,
|
645 |
+
net_g,
|
646 |
+
sid,
|
647 |
+
audio_pad[s : t + t_pad_tgt + window],
|
648 |
+
None,
|
649 |
+
None,
|
650 |
+
times,
|
651 |
+
index,
|
652 |
+
big_npy,
|
653 |
+
index_rate,
|
654 |
+
version,
|
655 |
+
protect,
|
656 |
+
)[t_pad_tgt : -t_pad_tgt]
|
657 |
+
|
658 |
+
|
659 |
+
def pipeline(
|
660 |
+
self,
|
661 |
+
model,
|
662 |
+
net_g,
|
663 |
+
sid,
|
664 |
+
audio,
|
665 |
+
input_audio_path,
|
666 |
+
times,
|
667 |
+
f0_up_key,
|
668 |
+
f0_method,
|
669 |
+
file_index,
|
670 |
+
index_rate,
|
671 |
+
if_f0,
|
672 |
+
filter_radius,
|
673 |
+
tgt_sr,
|
674 |
+
resample_sr,
|
675 |
+
rms_mix_rate,
|
676 |
+
version,
|
677 |
+
protect,
|
678 |
+
crepe_hop_length,
|
679 |
+
f0_autotune,
|
680 |
+
f0_min=50,
|
681 |
+
f0_max=1100
|
682 |
+
):
|
683 |
+
if (
|
684 |
+
file_index != ""
|
685 |
+
and isinstance(file_index, str)
|
686 |
+
# and file_big_npy != ""
|
687 |
+
# and os.path.exists(file_big_npy) == True
|
688 |
+
and os.path.exists(file_index)
|
689 |
+
and index_rate != 0
|
690 |
+
):
|
691 |
+
try:
|
692 |
+
index = faiss.read_index(file_index)
|
693 |
+
# big_npy = np.load(file_big_npy)
|
694 |
+
big_npy = index.reconstruct_n(0, index.ntotal)
|
695 |
+
except:
|
696 |
+
traceback.print_exc()
|
697 |
+
index = big_npy = None
|
698 |
+
else:
|
699 |
+
index = big_npy = None
|
700 |
+
audio = signal.filtfilt(bh, ah, audio)
|
701 |
+
audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
|
702 |
+
opt_ts = []
|
703 |
+
if audio_pad.shape[0] > self.t_max:
|
704 |
+
audio_sum = np.zeros_like(audio)
|
705 |
+
for i in range(self.window):
|
706 |
+
audio_sum += audio_pad[i : i - self.window]
|
707 |
+
for t in range(self.t_center, audio.shape[0], self.t_center):
|
708 |
+
opt_ts.append(
|
709 |
+
t
|
710 |
+
- self.t_query
|
711 |
+
+ np.where(
|
712 |
+
np.abs(audio_sum[t - self.t_query : t + self.t_query])
|
713 |
+
== np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
|
714 |
+
)[0][0]
|
715 |
+
)
|
716 |
+
s = 0
|
717 |
+
audio_opt = []
|
718 |
+
t = None
|
719 |
+
t1 = ttime()
|
720 |
+
audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
|
721 |
+
p_len = audio_pad.shape[0] // self.window
|
722 |
+
inp_f0 = None
|
723 |
+
|
724 |
+
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
|
725 |
+
pitch, pitchf = None, None
|
726 |
+
if if_f0:
|
727 |
+
pitch, pitchf = self.get_f0(
|
728 |
+
input_audio_path,
|
729 |
+
audio_pad,
|
730 |
+
p_len,
|
731 |
+
f0_up_key,
|
732 |
+
f0_method,
|
733 |
+
filter_radius,
|
734 |
+
crepe_hop_length,
|
735 |
+
f0_autotune,
|
736 |
+
inp_f0,
|
737 |
+
f0_min,
|
738 |
+
f0_max
|
739 |
+
)
|
740 |
+
pitch = pitch[:p_len]
|
741 |
+
pitchf = pitchf[:p_len]
|
742 |
+
if "mps" not in str(self.device) or "xpu" not in str(self.device):
|
743 |
+
pitchf = pitchf.astype(np.float32)
|
744 |
+
pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
|
745 |
+
pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
|
746 |
+
t2 = ttime()
|
747 |
+
times[1] += t2 - t1
|
748 |
+
|
749 |
+
with tqdm(total=len(opt_ts), desc="Processing", unit="window") as pbar:
|
750 |
+
for i, t in enumerate(opt_ts):
|
751 |
+
t = t // self.window * self.window
|
752 |
+
start = s
|
753 |
+
end = t + self.t_pad2 + self.window
|
754 |
+
audio_slice = audio_pad[start:end]
|
755 |
+
pitch_slice = pitch[:, start // self.window:end // self.window] if if_f0 else None
|
756 |
+
pitchf_slice = pitchf[:, start // self.window:end // self.window] if if_f0 else None
|
757 |
+
audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
|
758 |
+
s = t
|
759 |
+
pbar.update(1)
|
760 |
+
pbar.refresh()
|
761 |
+
|
762 |
+
audio_slice = audio_pad[t:]
|
763 |
+
pitch_slice = pitch[:, t // self.window:] if if_f0 and t is not None else pitch
|
764 |
+
pitchf_slice = pitchf[:, t // self.window:] if if_f0 and t is not None else pitchf
|
765 |
+
audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
|
766 |
+
|
767 |
+
audio_opt = np.concatenate(audio_opt)
|
768 |
+
if rms_mix_rate != 1:
|
769 |
+
audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
|
770 |
+
if tgt_sr != resample_sr >= 16000:
|
771 |
+
audio_opt = librosa.resample(
|
772 |
+
audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
|
773 |
+
)
|
774 |
+
audio_max = np.abs(audio_opt).max() / 0.99
|
775 |
+
max_int16 = 32768
|
776 |
+
if audio_max > 1:
|
777 |
+
max_int16 /= audio_max
|
778 |
+
audio_opt = (audio_opt * max_int16).astype(np.int16)
|
779 |
+
del pitch, pitchf, sid
|
780 |
+
if torch.cuda.is_available():
|
781 |
+
torch.cuda.empty_cache()
|
782 |
+
|
783 |
+
print("Returning completed audio...")
|
784 |
+
return audio_opt
|