PhoenixStormJr commited on
Commit
7558871
·
verified ·
1 Parent(s): 0a99765

Update MDXNet.py

Browse files
Files changed (1) hide show
  1. MDXNet.py +274 -274
MDXNet.py CHANGED
@@ -1,274 +1,274 @@
1
- import soundfile as sf
2
- import torch, pdb, time, argparse, os, warnings, sys, librosa
3
- import numpy as np
4
- import onnxruntime as ort
5
- from scipy.io.wavfile import write
6
- from tqdm import tqdm
7
- import torch
8
- import torch.nn as nn
9
-
10
- dim_c = 4
11
-
12
-
13
- class Conv_TDF_net_trim:
14
- def __init__(
15
- self, device, model_name, target_name, L, dim_f, dim_t, n_fft, hop=1024
16
- ):
17
- super(Conv_TDF_net_trim, self).__init__()
18
-
19
- self.dim_f = dim_f
20
- self.dim_t = 2**dim_t
21
- self.n_fft = n_fft
22
- self.hop = hop
23
- self.n_bins = self.n_fft // 2 + 1
24
- self.chunk_size = hop * (self.dim_t - 1)
25
- self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to(
26
- device
27
- )
28
- self.target_name = target_name
29
- self.blender = "blender" in model_name
30
-
31
- out_c = dim_c * 4 if target_name == "*" else dim_c
32
- self.freq_pad = torch.zeros(
33
- [1, out_c, self.n_bins - self.dim_f, self.dim_t]
34
- ).to(device)
35
-
36
- self.n = L // 2
37
-
38
- def stft(self, x):
39
- x = x.reshape([-1, self.chunk_size])
40
- x = torch.stft(
41
- x,
42
- n_fft=self.n_fft,
43
- hop_length=self.hop,
44
- window=self.window,
45
- center=True,
46
- return_complex=True,
47
- )
48
- x = torch.view_as_real(x)
49
- x = x.permute([0, 3, 1, 2])
50
- x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape(
51
- [-1, dim_c, self.n_bins, self.dim_t]
52
- )
53
- return x[:, :, : self.dim_f]
54
-
55
- def istft(self, x, freq_pad=None):
56
- freq_pad = (
57
- self.freq_pad.repeat([x.shape[0], 1, 1, 1])
58
- if freq_pad is None
59
- else freq_pad
60
- )
61
- x = torch.cat([x, freq_pad], -2)
62
- c = 4 * 2 if self.target_name == "*" else 2
63
- x = x.reshape([-1, c, 2, self.n_bins, self.dim_t]).reshape(
64
- [-1, 2, self.n_bins, self.dim_t]
65
- )
66
- x = x.permute([0, 2, 3, 1])
67
- x = x.contiguous()
68
- x = torch.view_as_complex(x)
69
- x = torch.istft(
70
- x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True
71
- )
72
- return x.reshape([-1, c, self.chunk_size])
73
-
74
-
75
- def get_models(device, dim_f, dim_t, n_fft):
76
- return Conv_TDF_net_trim(
77
- device=device,
78
- model_name="Conv-TDF",
79
- target_name="vocals",
80
- L=11,
81
- dim_f=dim_f,
82
- dim_t=dim_t,
83
- n_fft=n_fft,
84
- )
85
-
86
-
87
- warnings.filterwarnings("ignore")
88
- cpu = torch.device("cpu")
89
- if torch.cuda.is_available():
90
- device = torch.device("cuda:0")
91
- elif torch.backends.mps.is_available():
92
- device = torch.device("mps")
93
- else:
94
- device = torch.device("cpu")
95
-
96
-
97
- class Predictor:
98
- def __init__(self, args):
99
- self.args = args
100
- self.model_ = get_models(
101
- device=cpu, dim_f=args.dim_f, dim_t=args.dim_t, n_fft=args.n_fft
102
- )
103
- self.model = ort.InferenceSession(
104
- os.path.join(args.onnx, self.model_.target_name + ".onnx"),
105
- providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
106
- )
107
- print("onnx load done")
108
-
109
- def demix(self, mix):
110
- samples = mix.shape[-1]
111
- margin = self.args.margin
112
- chunk_size = self.args.chunks * 44100
113
- assert not margin == 0, "margin cannot be zero!"
114
- if margin > chunk_size:
115
- margin = chunk_size
116
-
117
- segmented_mix = {}
118
-
119
- if self.args.chunks == 0 or samples < chunk_size:
120
- chunk_size = samples
121
-
122
- counter = -1
123
- for skip in range(0, samples, chunk_size):
124
- counter += 1
125
-
126
- s_margin = 0 if counter == 0 else margin
127
- end = min(skip + chunk_size + margin, samples)
128
-
129
- start = skip - s_margin
130
-
131
- segmented_mix[skip] = mix[:, start:end].copy()
132
- if end == samples:
133
- break
134
-
135
- sources = self.demix_base(segmented_mix, margin_size=margin)
136
- """
137
- mix:(2,big_sample)
138
- segmented_mix:offset->(2,small_sample)
139
- sources:(1,2,big_sample)
140
- """
141
- return sources
142
-
143
- def demix_base(self, mixes, margin_size):
144
- chunked_sources = []
145
- progress_bar = tqdm(total=len(mixes))
146
- progress_bar.set_description("Processing")
147
- for mix in mixes:
148
- cmix = mixes[mix]
149
- sources = []
150
- n_sample = cmix.shape[1]
151
- model = self.model_
152
- trim = model.n_fft // 2
153
- gen_size = model.chunk_size - 2 * trim
154
- pad = gen_size - n_sample % gen_size
155
- mix_p = np.concatenate(
156
- (np.zeros((2, trim)), cmix, np.zeros((2, pad)), np.zeros((2, trim))), 1
157
- )
158
- mix_waves = []
159
- i = 0
160
- while i < n_sample + pad:
161
- waves = np.array(mix_p[:, i : i + model.chunk_size])
162
- mix_waves.append(waves)
163
- i += gen_size
164
- mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(cpu)
165
- with torch.no_grad():
166
- _ort = self.model
167
- spek = model.stft(mix_waves)
168
- if self.args.denoise:
169
- spec_pred = (
170
- -_ort.run(None, {"input": -spek.cpu().numpy()})[0] * 0.5
171
- + _ort.run(None, {"input": spek.cpu().numpy()})[0] * 0.5
172
- )
173
- tar_waves = model.istft(torch.tensor(spec_pred))
174
- else:
175
- tar_waves = model.istft(
176
- torch.tensor(_ort.run(None, {"input": spek.cpu().numpy()})[0])
177
- )
178
- tar_signal = (
179
- tar_waves[:, :, trim:-trim]
180
- .transpose(0, 1)
181
- .reshape(2, -1)
182
- .numpy()[:, :-pad]
183
- )
184
-
185
- start = 0 if mix == 0 else margin_size
186
- end = None if mix == list(mixes.keys())[::-1][0] else -margin_size
187
- if margin_size == 0:
188
- end = None
189
- sources.append(tar_signal[:, start:end])
190
-
191
- progress_bar.update(1)
192
-
193
- chunked_sources.append(sources)
194
- _sources = np.concatenate(chunked_sources, axis=-1)
195
- # del self.model
196
- progress_bar.close()
197
- return _sources
198
-
199
- def prediction(self, m, vocal_root, others_root, format):
200
- os.makedirs(vocal_root, exist_ok=True)
201
- os.makedirs(others_root, exist_ok=True)
202
- basename = os.path.basename(m)
203
- mix, rate = librosa.load(m, mono=False, sr=44100)
204
- if mix.ndim == 1:
205
- mix = np.asfortranarray([mix, mix])
206
- mix = mix.T
207
- sources = self.demix(mix.T)
208
- opt = sources[0].T
209
- if format in ["wav", "flac"]:
210
- sf.write(
211
- "%s/%s_main_vocal.%s" % (vocal_root, basename, format), mix - opt, rate
212
- )
213
- sf.write("%s/%s_others.%s" % (others_root, basename, format), opt, rate)
214
- else:
215
- path_vocal = "%s/%s_main_vocal.wav" % (vocal_root, basename)
216
- path_other = "%s/%s_others.wav" % (others_root, basename)
217
- sf.write(path_vocal, mix - opt, rate)
218
- sf.write(path_other, opt, rate)
219
- if os.path.exists(path_vocal):
220
- os.system(
221
- "ffmpeg -i %s -vn %s -q:a 2 -y"
222
- % (path_vocal, path_vocal[:-4] + ".%s" % format)
223
- )
224
- if os.path.exists(path_other):
225
- os.system(
226
- "ffmpeg -i %s -vn %s -q:a 2 -y"
227
- % (path_other, path_other[:-4] + ".%s" % format)
228
- )
229
-
230
-
231
- class MDXNetDereverb:
232
- def __init__(self, chunks):
233
- self.onnx = "uvr5_weights/onnx_dereverb_By_FoxJoy"
234
- self.shifts = 10 #'Predict with randomised equivariant stabilisation'
235
- self.mixing = "min_mag" # ['default','min_mag','max_mag']
236
- self.chunks = chunks
237
- self.margin = 44100
238
- self.dim_t = 9
239
- self.dim_f = 3072
240
- self.n_fft = 6144
241
- self.denoise = True
242
- self.pred = Predictor(self)
243
-
244
- def _path_audio_(self, input, vocal_root, others_root, format):
245
- self.pred.prediction(input, vocal_root, others_root, format)
246
-
247
-
248
- if __name__ == "__main__":
249
- dereverb = MDXNetDereverb(15)
250
- from time import time as ttime
251
-
252
- t0 = ttime()
253
- dereverb._path_audio_(
254
- "雪雪伴奏对消HP5.wav",
255
- "vocal",
256
- "others",
257
- )
258
- t1 = ttime()
259
- print(t1 - t0)
260
-
261
-
262
- """
263
-
264
- runtime\python.exe MDXNet.py
265
-
266
- 6G:
267
- 15/9:0.8G->6.8G
268
- 14:0.8G->6.5G
269
- 25:炸
270
-
271
- half15:0.7G->6.6G,22.69s
272
- fp32-15:0.7G->6.6G,20.85s
273
-
274
- """
 
1
+ import soundfile as sf
2
+ import torch, pdb, time, argparse, os, warnings, sys, librosa
3
+ import numpy as np
4
+ import onnxruntime as ort
5
+ from scipy.io.wavfile import write
6
+ from tqdm import tqdm
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ dim_c = 4
11
+
12
+
13
+ class Conv_TDF_net_trim:
14
+ def __init__(
15
+ self, device, model_name, target_name, L, dim_f, dim_t, n_fft, hop=1024
16
+ ):
17
+ super(Conv_TDF_net_trim, self).__init__()
18
+
19
+ self.dim_f = dim_f
20
+ self.dim_t = 2**dim_t
21
+ self.n_fft = n_fft
22
+ self.hop = hop
23
+ self.n_bins = self.n_fft // 2 + 1
24
+ self.chunk_size = hop * (self.dim_t - 1)
25
+ self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to(
26
+ device
27
+ )
28
+ self.target_name = target_name
29
+ self.blender = "blender" in model_name
30
+
31
+ out_c = dim_c * 4 if target_name == "*" else dim_c
32
+ self.freq_pad = torch.zeros(
33
+ [1, out_c, self.n_bins - self.dim_f, self.dim_t]
34
+ ).to(device)
35
+
36
+ self.n = L // 2
37
+
38
+ def stft(self, x):
39
+ x = x.reshape([-1, self.chunk_size])
40
+ x = torch.stft(
41
+ x,
42
+ n_fft=self.n_fft,
43
+ hop_length=self.hop,
44
+ window=self.window,
45
+ center=True,
46
+ return_complex=True,
47
+ )
48
+ x = torch.view_as_real(x)
49
+ x = x.permute([0, 3, 1, 2])
50
+ x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape(
51
+ [-1, dim_c, self.n_bins, self.dim_t]
52
+ )
53
+ return x[:, :, : self.dim_f]
54
+
55
+ def istft(self, x, freq_pad=None):
56
+ freq_pad = (
57
+ self.freq_pad.repeat([x.shape[0], 1, 1, 1])
58
+ if freq_pad is None
59
+ else freq_pad
60
+ )
61
+ x = torch.cat([x, freq_pad], -2)
62
+ c = 4 * 2 if self.target_name == "*" else 2
63
+ x = x.reshape([-1, c, 2, self.n_bins, self.dim_t]).reshape(
64
+ [-1, 2, self.n_bins, self.dim_t]
65
+ )
66
+ x = x.permute([0, 2, 3, 1])
67
+ x = x.contiguous()
68
+ x = torch.view_as_complex(x)
69
+ x = torch.istft(
70
+ x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True
71
+ )
72
+ return x.reshape([-1, c, self.chunk_size])
73
+
74
+
75
+ def get_models(device, dim_f, dim_t, n_fft):
76
+ return Conv_TDF_net_trim(
77
+ device=device,
78
+ model_name="Conv-TDF",
79
+ target_name="vocals",
80
+ L=11,
81
+ dim_f=dim_f,
82
+ dim_t=dim_t,
83
+ n_fft=n_fft,
84
+ )
85
+
86
+
87
+ warnings.filterwarnings("ignore")
88
+ cpu = torch.device("cpu")
89
+ if torch.cuda.is_available():
90
+ device = torch.device("cuda:0")
91
+ elif torch.backends.mps.is_available():
92
+ device = torch.device("mps")
93
+ else:
94
+ device = torch.device("cpu")
95
+
96
+
97
+ class Predictor:
98
+ def __init__(self, args):
99
+ self.args = args
100
+ self.model_ = get_models(
101
+ device=cpu, dim_f=args.dim_f, dim_t=args.dim_t, n_fft=args.n_fft
102
+ )
103
+ self.model = ort.InferenceSession(
104
+ os.path.join(args.onnx, self.model_.target_name + ".onnx"),
105
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
106
+ )
107
+ print("onnx load done")
108
+
109
+ def demix(self, mix):
110
+ samples = mix.shape[-1]
111
+ margin = self.args.margin
112
+ chunk_size = self.args.chunks * 44100
113
+ assert not margin == 0, "margin cannot be zero!"
114
+ if margin > chunk_size:
115
+ margin = chunk_size
116
+
117
+ segmented_mix = {}
118
+
119
+ if self.args.chunks == 0 or samples < chunk_size:
120
+ chunk_size = samples
121
+
122
+ counter = -1
123
+ for skip in range(0, samples, chunk_size):
124
+ counter += 1
125
+
126
+ s_margin = 0 if counter == 0 else margin
127
+ end = min(skip + chunk_size + margin, samples)
128
+
129
+ start = skip - s_margin
130
+
131
+ segmented_mix[skip] = mix[:, start:end].copy()
132
+ if end == samples:
133
+ break
134
+
135
+ sources = self.demix_base(segmented_mix, margin_size=margin)
136
+ """
137
+ mix:(2,big_sample)
138
+ segmented_mix:offset->(2,small_sample)
139
+ sources:(1,2,big_sample)
140
+ """
141
+ return sources
142
+
143
+ def demix_base(self, mixes, margin_size):
144
+ chunked_sources = []
145
+ progress_bar = tqdm(total=len(mixes))
146
+ progress_bar.set_description("Processing")
147
+ for mix in mixes:
148
+ cmix = mixes[mix]
149
+ sources = []
150
+ n_sample = cmix.shape[1]
151
+ model = self.model_
152
+ trim = model.n_fft // 2
153
+ gen_size = model.chunk_size - 2 * trim
154
+ pad = gen_size - n_sample % gen_size
155
+ mix_p = np.concatenate(
156
+ (np.zeros((2, trim)), cmix, np.zeros((2, pad)), np.zeros((2, trim))), 1
157
+ )
158
+ mix_waves = []
159
+ i = 0
160
+ while i < n_sample + pad:
161
+ waves = np.array(mix_p[:, i : i + model.chunk_size])
162
+ mix_waves.append(waves)
163
+ i += gen_size
164
+ mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(cpu)
165
+ with torch.no_grad():
166
+ _ort = self.model
167
+ spek = model.stft(mix_waves)
168
+ if self.args.denoise:
169
+ spec_pred = (
170
+ -_ort.run(None, {"input": -spek.cpu().numpy()})[0] * 0.5
171
+ + _ort.run(None, {"input": spek.cpu().numpy()})[0] * 0.5
172
+ )
173
+ tar_waves = model.istft(torch.tensor(spec_pred))
174
+ else:
175
+ tar_waves = model.istft(
176
+ torch.tensor(_ort.run(None, {"input": spek.cpu().numpy()})[0])
177
+ )
178
+ tar_signal = (
179
+ tar_waves[:, :, trim:-trim]
180
+ .transpose(0, 1)
181
+ .reshape(2, -1)
182
+ .numpy()[:, :-pad]
183
+ )
184
+
185
+ start = 0 if mix == 0 else margin_size
186
+ end = None if mix == list(mixes.keys())[::-1][0] else -margin_size
187
+ if margin_size == 0:
188
+ end = None
189
+ sources.append(tar_signal[:, start:end])
190
+
191
+ progress_bar.update(1)
192
+
193
+ chunked_sources.append(sources)
194
+ _sources = np.concatenate(chunked_sources, axis=-1)
195
+ # del self.model
196
+ progress_bar.close()
197
+ return _sources
198
+
199
+ def prediction(self, m, vocal_root, others_root, format):
200
+ os.makedirs(vocal_root, exist_ok=True)
201
+ os.makedirs(others_root, exist_ok=True)
202
+ basename = os.path.basename(m)
203
+ mix, rate = librosa.load(m, mono=False, sr=44100)
204
+ if mix.ndim == 1:
205
+ mix = np.asfortranarray([mix, mix])
206
+ mix = mix.T
207
+ sources = self.demix(mix.T)
208
+ opt = sources[0].T
209
+ if format in ["wav", "flac"]:
210
+ sf.write(
211
+ "%s/%s_main_vocal.%s" % (vocal_root, basename, format), mix - opt, rate
212
+ )
213
+ sf.write("%s/%s_others.%s" % (others_root, basename, format), opt, rate)
214
+ else:
215
+ path_vocal = "%s/%s_main_vocal.wav" % (vocal_root, basename)
216
+ path_other = "%s/%s_others.wav" % (others_root, basename)
217
+ sf.write(path_vocal, mix - opt, rate)
218
+ sf.write(path_other, opt, rate)
219
+ if os.path.exists(path_vocal):
220
+ os.system(
221
+ "ffmpeg -i %s -vn %s -q:a 2 -y"
222
+ % (path_vocal, path_vocal[:-4] + ".%s" % format)
223
+ )
224
+ if os.path.exists(path_other):
225
+ os.system(
226
+ "ffmpeg -i %s -vn %s -q:a 2 -y"
227
+ % (path_other, path_other[:-4] + ".%s" % format)
228
+ )
229
+
230
+
231
+ class MDXNetDereverb:
232
+ def __init__(self, chunks):
233
+ self.onnx = "uvr5_weights/onnx_dereverb_By_FoxJoy"
234
+ self.shifts = 10 #'Predict with randomised equivariant stabilisation'
235
+ self.mixing = "min_mag" # ['default','min_mag','max_mag']
236
+ self.chunks = chunks
237
+ self.margin = 44100
238
+ self.dim_t = 9
239
+ self.dim_f = 3072
240
+ self.n_fft = 6144
241
+ self.denoise = True
242
+ self.pred = Predictor(self)
243
+
244
+ def _path_audio_(self, input, vocal_root, others_root, format):
245
+ self.pred.prediction(input, vocal_root, others_root, format)
246
+
247
+
248
+ if __name__ == "__main__":
249
+ dereverb = MDXNetDereverb(15)
250
+ from time import time as ttime
251
+
252
+ t0 = ttime()
253
+ dereverb._path_audio_(
254
+ "Snowy accompaniment cancellation HP5.wav",
255
+ "vocal",
256
+ "others",
257
+ )
258
+ t1 = ttime()
259
+ print(t1 - t0)
260
+
261
+
262
+ """
263
+
264
+ runtime\python.exe MDXNet.py
265
+
266
+ 6G:
267
+ 15/9:0.8G->6.8G
268
+ 14:0.8G->6.5G
269
+ 25:炸
270
+
271
+ half15:0.7G->6.6G,22.69s
272
+ fp32-15:0.7G->6.6G,20.85s
273
+
274
+ """