Eempostor commited on
Commit
bd868ce
1 Parent(s): 83eb281

Upload 3 files

Browse files
Files changed (3) hide show
  1. lib/infer.py +221 -0
  2. lib/modules.py +559 -0
  3. lib/pipeline.py +773 -0
lib/infer.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import gc
4
+ import torch
5
+ from multiprocessing 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
+
61
+ if self.n_cpu == 0:
62
+ self.n_cpu = cpu_count()
63
+
64
+ if self.is_half:
65
+ # 6G memory config
66
+ x_pad = 3
67
+ x_query = 10
68
+ x_center = 60
69
+ x_max = 65
70
+ else:
71
+ # 5G memory config
72
+ x_pad = 1
73
+ x_query = 6
74
+ x_center = 38
75
+ x_max = 41
76
+
77
+ if self.gpu_mem != None and self.gpu_mem <= 4:
78
+ x_pad = 1
79
+ x_query = 5
80
+ x_center = 30
81
+ x_max = 32
82
+
83
+ return x_pad, x_query, x_center, x_max
84
+
85
+ def get_model(voice_model):
86
+ model_dir = os.path.join(os.getcwd(), "models", voice_model)
87
+ model_filename, index_filename = None, None
88
+ for file in os.listdir(model_dir):
89
+ ext = os.path.splitext(file)[1]
90
+ if ext == '.pth':
91
+ model_filename = file
92
+ if ext == '.index':
93
+ index_filename = file
94
+
95
+ if model_filename is None:
96
+ print(f'No model file exists in {models_dir}.')
97
+ return None, None
98
+
99
+ return os.path.join(model_dir, model_filename), os.path.join(model_dir, index_filename) if index_filename else ''
100
+
101
+ def infer_audio(
102
+ model_name,
103
+ audio_path,
104
+ f0_change=0,
105
+ f0_method="rmvpe+",
106
+ min_pitch="50",
107
+ max_pitch="1100",
108
+ crepe_hop_length=128,
109
+ index_rate=0.75,
110
+ filter_radius=3,
111
+ rms_mix_rate=0.25,
112
+ protect=0.33,
113
+ split_infer=False,
114
+ min_silence=500,
115
+ silence_threshold=-50,
116
+ seek_step=1,
117
+ keep_silence=100,
118
+ do_formant=False,
119
+ quefrency=0,
120
+ timbre=1,
121
+ f0_autotune=False,
122
+ audio_format="wav",
123
+ resample_sr=0,
124
+ hubert_model_path="assets/hubert/hubert_base.pt",
125
+ rmvpe_model_path="assets/rmvpe/rmvpe.pt",
126
+ fcpe_model_path="assets/fcpe/fcpe.pt"
127
+ ):
128
+ os.environ["rmvpe_model_path"] = rmvpe_model_path
129
+ os.environ["fcpe_model_path"] = fcpe_model_path
130
+ configs = Configs('cuda:0', False)
131
+ vc = VC(configs)
132
+ pth_path, index_path = get_model(model_name)
133
+ vc_data = vc.get_vc(pth_path, protect, 0.5)
134
+
135
+ if split_infer:
136
+ inferred_files = []
137
+ temp_dir = os.path.join(os.getcwd(), "seperate", "temp")
138
+ os.makedirs(temp_dir, exist_ok=True)
139
+ print("Splitting audio to silence and nonsilent segments.")
140
+ silence_files, nonsilent_files = split_silence_nonsilent(audio_path, min_silence, silence_threshold, seek_step, keep_silence)
141
+ print(f"Total silence segments: {len(silence_files)}.\nTotal nonsilent segments: {len(nonsilent_files)}.")
142
+ for i, nonsilent_file in enumerate(nonsilent_files):
143
+ print(f"Inferring nonsilent audio {i+1}")
144
+ inference_info, audio_data, output_path = vc.vc_single(
145
+ 0,
146
+ nonsilent_file,
147
+ f0_change,
148
+ f0_method,
149
+ index_path,
150
+ index_path,
151
+ index_rate,
152
+ filter_radius,
153
+ resample_sr,
154
+ rms_mix_rate,
155
+ protect,
156
+ audio_format,
157
+ crepe_hop_length,
158
+ do_formant,
159
+ quefrency,
160
+ timbre,
161
+ min_pitch,
162
+ max_pitch,
163
+ f0_autotune,
164
+ hubert_model_path
165
+ )
166
+ if inference_info[0] == "Success.":
167
+ print("Inference ran successfully.")
168
+ print(inference_info[1])
169
+ print("Times:\nnpy: %.2fs f0: %.2fs infer: %.2fs\nTotal time: %.2fs" % (*inference_info[2],))
170
+ else:
171
+ print(f"An error occurred while processing.\n{inference_info[0]}")
172
+ return None
173
+ inferred_files.append(output_path)
174
+ print("Adjusting inferred audio lengths.")
175
+ adjusted_inferred_files = adjust_audio_lengths(nonsilent_files, inferred_files)
176
+ print("Combining silence and inferred audios.")
177
+ output_count = 1
178
+ while True:
179
+ 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}")
180
+ if not os.path.exists(output_path):
181
+ break
182
+ output_count += 1
183
+ output_path = combine_silence_nonsilent(silence_files, adjusted_inferred_files, keep_silence, output_path)
184
+ [shutil.move(inferred_file, temp_dir) for inferred_file in inferred_files]
185
+ shutil.rmtree(temp_dir)
186
+ else:
187
+ inference_info, audio_data, output_path = vc.vc_single(
188
+ 0,
189
+ audio_path,
190
+ f0_change,
191
+ f0_method,
192
+ index_path,
193
+ index_path,
194
+ index_rate,
195
+ filter_radius,
196
+ resample_sr,
197
+ rms_mix_rate,
198
+ protect,
199
+ audio_format,
200
+ crepe_hop_length,
201
+ do_formant,
202
+ quefrency,
203
+ timbre,
204
+ min_pitch,
205
+ max_pitch,
206
+ f0_autotune,
207
+ hubert_model_path
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
+ del configs, vc
216
+ gc.collect()
217
+ return inference_info[0]
218
+
219
+ del configs, vc
220
+ gc.collect()
221
+ return output_path
lib/modules.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torchfcpe import spawn_bundled_infer_model
31
+ import torch
32
+ from lib.infer_libs.rmvpe import RMVPE
33
+ from lib.infer_libs.fcpe import FCPE
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_rmvpe(self, x, *args, **kwargs):
200
+ if not hasattr(self, "model_rmvpe"):
201
+ from lib.infer.infer_libs.rmvpe import RMVPE
202
+
203
+ logger.info(
204
+ f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
205
+ )
206
+ self.model_rmvpe = RMVPE(
207
+ os.environ["rmvpe_model_path"],
208
+ is_half=self.is_half,
209
+ device=self.device,
210
+ )
211
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
212
+
213
+ if "privateuseone" in str(self.device): # clean ortruntime memory
214
+ del self.model_rmvpe.model
215
+ del self.model_rmvpe
216
+ logger.info("Cleaning ortruntime memory")
217
+
218
+ return f0
219
+
220
+
221
+ def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
222
+ if not hasattr(self, "model_rmvpe"):
223
+ from lib.infer.infer_libs.rmvpe import RMVPE
224
+
225
+ logger.info(
226
+ f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
227
+ )
228
+ self.model_rmvpe = RMVPE(
229
+ os.environ["rmvpe_model_path"],
230
+ is_half=self.is_half,
231
+ device=self.device,
232
+ )
233
+ f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
234
+ if "privateuseone" in str(self.device): # clean ortruntime memory
235
+ del self.model_rmvpe.model
236
+ del self.model_rmvpe
237
+ logger.info("Cleaning ortruntime memory")
238
+
239
+ return f0
240
+
241
+ def get_fcpe(self, x, f0_min, f0_max, p_len, *args, **kwargs):
242
+ 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)
243
+ f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
244
+ del self.model_fcpe
245
+ gc.collect()
246
+ return f0
247
+
248
+ def get_torchfcpe(self, x, sr, f0_min, f0_max, p_len, *args, **kwargs):
249
+ self.model_torchfcpe = spawn_bundled_infer_model(device=self.device)
250
+ f0 = self.model_torchfcpe.infer(
251
+ torch.from_numpy(x).float().unsqueeze(0).unsqueeze(-1).to(self.device),
252
+ sr=sr,
253
+ decoder_mode="local_argmax",
254
+ threshold=0.03,
255
+ f0_min=f0_min,
256
+ f0_max=f0_max,
257
+ output_interp_target_length=p_len
258
+ )
259
+ return f0.squeeze().cpu().numpy()
260
+
261
+ def autotune_f0(self, f0):
262
+ autotuned_f0 = []
263
+ for freq in f0:
264
+ closest_notes = [x for x in self.note_dict if abs(x - freq) == min(abs(n - freq) for n in self.note_dict)]
265
+ autotuned_f0.append(random.choice(closest_notes))
266
+ return np.array(autotuned_f0, np.float64)
267
+
268
+
269
+ # Fork Feature: Acquire median hybrid f0 estimation calculation
270
+ def get_f0_hybrid_computation(
271
+ self,
272
+ methods_str,
273
+ input_audio_path,
274
+ x,
275
+ f0_min,
276
+ f0_max,
277
+ p_len,
278
+ filter_radius,
279
+ crepe_hop_length,
280
+ time_step,
281
+ ):
282
+ # Get various f0 methods from input to use in the computation stack
283
+ methods_str = re.search('hybrid\[(.+)\]', methods_str)
284
+ if methods_str: # Ensure a match was found
285
+ methods = [method.strip() for method in methods_str.group(1).split('+')]
286
+ f0_computation_stack = []
287
+
288
+ print("Calculating f0 pitch estimations for methods: %s" % str(methods))
289
+ x = x.astype(np.float32)
290
+ x /= np.quantile(np.abs(x), 0.999)
291
+ # Get f0 calculations for all methods specified
292
+ for method in methods:
293
+ f0 = None
294
+ if method == "pm":
295
+ f0 = (
296
+ parselmouth.Sound(x, self.sr)
297
+ .to_pitch_ac(
298
+ time_step=time_step / 1000,
299
+ voicing_threshold=0.6,
300
+ pitch_floor=f0_min,
301
+ pitch_ceiling=f0_max,
302
+ )
303
+ .selected_array["frequency"]
304
+ )
305
+ pad_size = (p_len - len(f0) + 1) // 2
306
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
307
+ f0 = np.pad(
308
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
309
+ )
310
+ elif method == "crepe":
311
+ f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="full")
312
+ f0 = f0[1:]
313
+ elif method == "crepe-tiny":
314
+ f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
315
+ f0 = f0[1:] # Get rid of extra first frame
316
+ elif method == "mangio-crepe":
317
+ f0 = self.get_f0_crepe_computation(
318
+ x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
319
+ )
320
+ elif method == "mangio-crepe-tiny":
321
+ f0 = self.get_f0_crepe_computation(
322
+ x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
323
+ )
324
+ elif method == "harvest":
325
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
326
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
327
+ if filter_radius > 2:
328
+ f0 = signal.medfilt(f0, 3)
329
+ elif method == "dio":
330
+ f0, t = pyworld.dio(
331
+ x.astype(np.double),
332
+ fs=self.sr,
333
+ f0_ceil=f0_max,
334
+ f0_floor=f0_min,
335
+ frame_period=10,
336
+ )
337
+ f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
338
+ f0 = signal.medfilt(f0, 3)
339
+ f0 = f0[1:]
340
+ elif method == "rmvpe":
341
+ f0 = self.get_rmvpe(x)
342
+ f0 = f0[1:]
343
+ elif method == "fcpe":
344
+ f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
345
+ elif method == "torchfcpe":
346
+ f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
347
+ elif method == "pyin":
348
+ f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
349
+ # Push method to the stack
350
+ f0_computation_stack.append(f0)
351
+
352
+ for fc in f0_computation_stack:
353
+ print(len(fc))
354
+
355
+ print("Calculating hybrid median f0 from the stack of: %s" % str(methods))
356
+ f0_median_hybrid = None
357
+ if len(f0_computation_stack) == 1:
358
+ f0_median_hybrid = f0_computation_stack[0]
359
+ else:
360
+ f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
361
+ return f0_median_hybrid
362
+
363
+ def get_f0(
364
+ self,
365
+ input_audio_path,
366
+ x,
367
+ p_len,
368
+ f0_up_key,
369
+ f0_method,
370
+ filter_radius,
371
+ crepe_hop_length,
372
+ f0_autotune,
373
+ inp_f0=None,
374
+ f0_min=50,
375
+ f0_max=1100,
376
+ ):
377
+ global input_audio_path2wav
378
+ time_step = self.window / self.sr * 1000
379
+ f0_min = f0_min
380
+ f0_max = f0_max
381
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
382
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
383
+
384
+ if f0_method == "pm":
385
+ f0 = (
386
+ parselmouth.Sound(x, self.sr)
387
+ .to_pitch_ac(
388
+ time_step=time_step / 1000,
389
+ voicing_threshold=0.6,
390
+ pitch_floor=f0_min,
391
+ pitch_ceiling=f0_max,
392
+ )
393
+ .selected_array["frequency"]
394
+ )
395
+ pad_size = (p_len - len(f0) + 1) // 2
396
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
397
+ f0 = np.pad(
398
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
399
+ )
400
+ elif f0_method == "harvest":
401
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
402
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
403
+ if filter_radius > 2:
404
+ f0 = signal.medfilt(f0, 3)
405
+ elif f0_method == "dio": # Potentially Buggy?
406
+ f0, t = pyworld.dio(
407
+ x.astype(np.double),
408
+ fs=self.sr,
409
+ f0_ceil=f0_max,
410
+ f0_floor=f0_min,
411
+ frame_period=10,
412
+ )
413
+ f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
414
+ f0 = signal.medfilt(f0, 3)
415
+ elif f0_method == "crepe":
416
+ model = "full"
417
+ # Pick a batch size that doesn't cause memory errors on your gpu
418
+ batch_size = 512
419
+ # Compute pitch using first gpu
420
+ audio = torch.tensor(np.copy(x))[None].float()
421
+ f0, pd = torchcrepe.predict(
422
+ audio,
423
+ self.sr,
424
+ self.window,
425
+ f0_min,
426
+ f0_max,
427
+ model,
428
+ batch_size=batch_size,
429
+ device=self.device,
430
+ return_periodicity=True,
431
+ )
432
+ pd = torchcrepe.filter.median(pd, 3)
433
+ f0 = torchcrepe.filter.mean(f0, 3)
434
+ f0[pd < 0.1] = 0
435
+ f0 = f0[0].cpu().numpy()
436
+ elif f0_method == "crepe-tiny":
437
+ f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
438
+ elif f0_method == "mangio-crepe":
439
+ f0 = self.get_f0_crepe_computation(
440
+ x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
441
+ )
442
+ elif f0_method == "mangio-crepe-tiny":
443
+ f0 = self.get_f0_crepe_computation(
444
+ x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
445
+ )
446
+ elif f0_method == "rmvpe":
447
+ if not hasattr(self, "model_rmvpe"):
448
+ from lib.infer.infer_libs.rmvpe import RMVPE
449
+
450
+ logger.info(
451
+ f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
452
+ )
453
+ self.model_rmvpe = RMVPE(
454
+ os.environ["rmvpe_model_path"],
455
+ is_half=self.is_half,
456
+ device=self.device,
457
+ )
458
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
459
+
460
+ if "privateuseone" in str(self.device): # clean ortruntime memory
461
+ del self.model_rmvpe.model
462
+ del self.model_rmvpe
463
+ logger.info("Cleaning ortruntime memory")
464
+ elif f0_method == "rmvpe+":
465
+ params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
466
+ 'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
467
+ 'crepe_hop_length': crepe_hop_length, 'model': "full"
468
+ }
469
+ f0 = self.get_pitch_dependant_rmvpe(**params)
470
+ elif f0_method == "pyin":
471
+ f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
472
+ elif f0_method == "fcpe":
473
+ f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
474
+ elif f0_method == "torchfcpe":
475
+ f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
476
+ elif "hybrid" in f0_method:
477
+ # Perform hybrid median pitch estimation
478
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
479
+ f0 = self.get_f0_hybrid_computation(
480
+ f0_method,
481
+ input_audio_path,
482
+ x,
483
+ f0_min,
484
+ f0_max,
485
+ p_len,
486
+ filter_radius,
487
+ crepe_hop_length,
488
+ time_step,
489
+ )
490
+ #print("Autotune:", f0_autotune)
491
+ if f0_autotune == True:
492
+ print("Autotune:", f0_autotune)
493
+ f0 = self.autotune_f0(f0)
494
+
495
+ f0 *= pow(2, f0_up_key / 12)
496
+ # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
497
+ tf0 = self.sr // self.window # 每秒f0点数
498
+ if inp_f0 is not None:
499
+ delta_t = np.round(
500
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
501
+ ).astype("int16")
502
+ replace_f0 = np.interp(
503
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
504
+ )
505
+ shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
506
+ f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
507
+ :shape
508
+ ]
509
+ # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
510
+ f0bak = f0.copy()
511
+ f0_mel = 1127 * np.log(1 + f0 / 700)
512
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
513
+ f0_mel_max - f0_mel_min
514
+ ) + 1
515
+ f0_mel[f0_mel <= 1] = 1
516
+ f0_mel[f0_mel > 255] = 255
517
+ f0_coarse = np.rint(f0_mel).astype(np.int32)
518
+ return f0_coarse, f0bak # 1-0
519
+
520
+ def vc(
521
+ self,
522
+ model,
523
+ net_g,
524
+ sid,
525
+ audio0,
526
+ pitch,
527
+ pitchf,
528
+ times,
529
+ index,
530
+ big_npy,
531
+ index_rate,
532
+ version,
533
+ protect,
534
+ ): # ,file_index,file_big_npy
535
+ feats = torch.from_numpy(audio0)
536
+ if self.is_half:
537
+ feats = feats.half()
538
+ else:
539
+ feats = feats.float()
540
+ if feats.dim() == 2: # double channels
541
+ feats = feats.mean(-1)
542
+ assert feats.dim() == 1, feats.dim()
543
+ feats = feats.view(1, -1)
544
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
545
+
546
+ inputs = {
547
+ "source": feats.to(self.device),
548
+ "padding_mask": padding_mask,
549
+ "output_layer": 9 if version == "v1" else 12,
550
+ }
551
+ t0 = ttime()
552
+ with torch.no_grad():
553
+ logits = model.extract_features(**inputs)
554
+ feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
555
+ if protect < 0.5 and pitch is not None and pitchf is not None:
556
+ feats0 = feats.clone()
557
+ if (
558
+ not isinstance(index, type(None))
559
+ and not isinstance(big_npy, type(None))
560
+ and index_rate != 0
561
+ ):
562
+ npy = feats[0].cpu().numpy()
563
+ if self.is_half:
564
+ npy = npy.astype("float32")
565
+
566
+ # _, I = index.search(npy, 1)
567
+ # npy = big_npy[I.squeeze()]
568
+
569
+ score, ix = index.search(npy, k=8)
570
+ weight = np.square(1 / score)
571
+ weight /= weight.sum(axis=1, keepdims=True)
572
+ npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
573
+
574
+ if self.is_half:
575
+ npy = npy.astype("float16")
576
+ feats = (
577
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
578
+ + (1 - index_rate) * feats
579
+ )
580
+
581
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
582
+ if protect < 0.5 and pitch is not None and pitchf is not None:
583
+ feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
584
+ 0, 2, 1
585
+ )
586
+ t1 = ttime()
587
+ p_len = audio0.shape[0] // self.window
588
+ if feats.shape[1] < p_len:
589
+ p_len = feats.shape[1]
590
+ if pitch is not None and pitchf is not None:
591
+ pitch = pitch[:, :p_len]
592
+ pitchf = pitchf[:, :p_len]
593
+
594
+ if protect < 0.5 and pitch is not None and pitchf is not None:
595
+ pitchff = pitchf.clone()
596
+ pitchff[pitchf > 0] = 1
597
+ pitchff[pitchf < 1] = protect
598
+ pitchff = pitchff.unsqueeze(-1)
599
+ feats = feats * pitchff + feats0 * (1 - pitchff)
600
+ feats = feats.to(feats0.dtype)
601
+ p_len = torch.tensor([p_len], device=self.device).long()
602
+ with torch.no_grad():
603
+ hasp = pitch is not None and pitchf is not None
604
+ arg = (feats, p_len, pitch, pitchf, sid) if hasp else (feats, p_len, sid)
605
+ audio1 = (net_g.infer(*arg)[0][0, 0]).data.cpu().float().numpy()
606
+ del hasp, arg
607
+ del feats, p_len, padding_mask
608
+ if torch.cuda.is_available():
609
+ torch.cuda.empty_cache()
610
+ t2 = ttime()
611
+ times[0] += t1 - t0
612
+ times[2] += t2 - t1
613
+ return audio1
614
+ 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):
615
+ t = t // window * window
616
+ if if_f0 == 1:
617
+ return self.vc(
618
+ model,
619
+ net_g,
620
+ sid,
621
+ audio_pad[s : t + t_pad_tgt + window],
622
+ pitch[:, s // window : (t + t_pad_tgt) // window],
623
+ pitchf[:, s // window : (t + t_pad_tgt) // window],
624
+ times,
625
+ index,
626
+ big_npy,
627
+ index_rate,
628
+ version,
629
+ protect,
630
+ )[t_pad_tgt : -t_pad_tgt]
631
+ else:
632
+ return self.vc(
633
+ model,
634
+ net_g,
635
+ sid,
636
+ audio_pad[s : t + t_pad_tgt + window],
637
+ None,
638
+ None,
639
+ times,
640
+ index,
641
+ big_npy,
642
+ index_rate,
643
+ version,
644
+ protect,
645
+ )[t_pad_tgt : -t_pad_tgt]
646
+
647
+
648
+ def pipeline(
649
+ self,
650
+ model,
651
+ net_g,
652
+ sid,
653
+ audio,
654
+ input_audio_path,
655
+ times,
656
+ f0_up_key,
657
+ f0_method,
658
+ file_index,
659
+ index_rate,
660
+ if_f0,
661
+ filter_radius,
662
+ tgt_sr,
663
+ resample_sr,
664
+ rms_mix_rate,
665
+ version,
666
+ protect,
667
+ crepe_hop_length,
668
+ f0_autotune,
669
+ f0_min=50,
670
+ f0_max=1100
671
+ ):
672
+ if (
673
+ file_index != ""
674
+ and isinstance(file_index, str)
675
+ # and file_big_npy != ""
676
+ # and os.path.exists(file_big_npy) == True
677
+ and os.path.exists(file_index)
678
+ and index_rate != 0
679
+ ):
680
+ try:
681
+ index = faiss.read_index(file_index)
682
+ # big_npy = np.load(file_big_npy)
683
+ big_npy = index.reconstruct_n(0, index.ntotal)
684
+ except:
685
+ traceback.print_exc()
686
+ index = big_npy = None
687
+ else:
688
+ index = big_npy = None
689
+ audio = signal.filtfilt(bh, ah, audio)
690
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
691
+ opt_ts = []
692
+ if audio_pad.shape[0] > self.t_max:
693
+ audio_sum = np.zeros_like(audio)
694
+ for i in range(self.window):
695
+ audio_sum += audio_pad[i : i - self.window]
696
+ for t in range(self.t_center, audio.shape[0], self.t_center):
697
+ opt_ts.append(
698
+ t
699
+ - self.t_query
700
+ + np.where(
701
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
702
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
703
+ )[0][0]
704
+ )
705
+ s = 0
706
+ audio_opt = []
707
+ t = None
708
+ t1 = ttime()
709
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
710
+ p_len = audio_pad.shape[0] // self.window
711
+ inp_f0 = None
712
+
713
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
714
+ pitch, pitchf = None, None
715
+ if if_f0:
716
+ pitch, pitchf = self.get_f0(
717
+ input_audio_path,
718
+ audio_pad,
719
+ p_len,
720
+ f0_up_key,
721
+ f0_method,
722
+ filter_radius,
723
+ crepe_hop_length,
724
+ f0_autotune,
725
+ inp_f0,
726
+ f0_min,
727
+ f0_max
728
+ )
729
+ pitch = pitch[:p_len]
730
+ pitchf = pitchf[:p_len]
731
+ if "mps" not in str(self.device) or "xpu" not in str(self.device):
732
+ pitchf = pitchf.astype(np.float32)
733
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
734
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
735
+ t2 = ttime()
736
+ times[1] += t2 - t1
737
+
738
+ with tqdm(total=len(opt_ts), desc="Processing", unit="window") as pbar:
739
+ for i, t in enumerate(opt_ts):
740
+ t = t // self.window * self.window
741
+ start = s
742
+ end = t + self.t_pad2 + self.window
743
+ audio_slice = audio_pad[start:end]
744
+ pitch_slice = pitch[:, start // self.window:end // self.window] if if_f0 else None
745
+ pitchf_slice = pitchf[:, start // self.window:end // self.window] if if_f0 else None
746
+ 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])
747
+ s = t
748
+ pbar.update(1)
749
+ pbar.refresh()
750
+
751
+ audio_slice = audio_pad[t:]
752
+ pitch_slice = pitch[:, t // self.window:] if if_f0 and t is not None else pitch
753
+ pitchf_slice = pitchf[:, t // self.window:] if if_f0 and t is not None else pitchf
754
+ 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])
755
+
756
+ audio_opt = np.concatenate(audio_opt)
757
+ if rms_mix_rate != 1:
758
+ audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
759
+ if tgt_sr != resample_sr >= 16000:
760
+ audio_opt = librosa.resample(
761
+ audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
762
+ )
763
+ audio_max = np.abs(audio_opt).max() / 0.99
764
+ max_int16 = 32768
765
+ if audio_max > 1:
766
+ max_int16 /= audio_max
767
+ audio_opt = (audio_opt * max_int16).astype(np.int16)
768
+ del pitch, pitchf, sid
769
+ if torch.cuda.is_available():
770
+ torch.cuda.empty_cache()
771
+
772
+ print("Returning completed audio...")
773
+ return audio_opt