Update inference/style_transfer.py
Browse files- inference/style_transfer.py +163 -388
inference/style_transfer.py
CHANGED
@@ -1,404 +1,179 @@
|
|
1 |
-
"""
|
2 |
-
Inference code of music style transfer
|
3 |
-
of the work "Music Mixing Style Transfer: A Contrastive Learning Approach to Disentangle Audio Effects"
|
4 |
-
Process : converts the mixing style of the input music recording to that of the refernce music.
|
5 |
-
files inside the target directory should be organized as follow
|
6 |
-
"path_to_data_directory"/"song_name_#1"/input.wav
|
7 |
-
"path_to_data_directory"/"song_name_#1"/reference.wav
|
8 |
-
...
|
9 |
-
"path_to_data_directory"/"song_name_#n"/input.wav
|
10 |
-
"path_to_data_directory"/"song_name_#n"/reference.wav
|
11 |
-
where the 'input' and 'reference' should share the same names.
|
12 |
-
"""
|
13 |
-
import numpy as np
|
14 |
-
from glob import glob
|
15 |
import os
|
16 |
-
import
|
17 |
-
|
18 |
-
import sys
|
19 |
-
currentdir = os.path.dirname(os.path.realpath(__file__))
|
20 |
-
sys.path.append(os.path.join(os.path.dirname(currentdir), "mixing_style_transfer"))
|
21 |
-
from networks import FXencoder, TCNModel
|
22 |
-
from data_loader import *
|
23 |
-
import librosa
|
24 |
-
import pyloudnorm
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
class Mixing_Style_Transfer_Inference:
|
29 |
-
def __init__(self, args, trained_w_ddp=True):
|
30 |
-
if torch.cuda.is_available():
|
31 |
-
self.device = torch.device("cuda:0")
|
32 |
-
else:
|
33 |
-
self.device = torch.device("cpu")
|
34 |
-
print(f"using device: {self.device} for inference")
|
35 |
-
|
36 |
-
# inference computational hyperparameters
|
37 |
-
self.args = args
|
38 |
-
self.segment_length = args.segment_length
|
39 |
-
self.batch_size = args.batch_size
|
40 |
-
self.sample_rate = 44100 # sampling rate should be 44100
|
41 |
-
self.time_in_seconds = int(args.segment_length // self.sample_rate)
|
42 |
-
|
43 |
-
# directory configuration
|
44 |
-
self.output_dir = args.target_dir if args.output_dir==None else args.output_dir
|
45 |
-
self.target_dir = args.target_dir
|
46 |
-
|
47 |
-
# load model and its checkpoint weights
|
48 |
-
self.models = {}
|
49 |
-
self.models['effects_encoder'] = FXencoder(args.cfg_encoder).to(self.device)
|
50 |
-
self.models['mixing_converter'] = TCNModel(nparams=args.cfg_converter["condition_dimension"], \
|
51 |
-
ninputs=2, \
|
52 |
-
noutputs=2, \
|
53 |
-
nblocks=args.cfg_converter["nblocks"], \
|
54 |
-
dilation_growth=args.cfg_converter["dilation_growth"], \
|
55 |
-
kernel_size=args.cfg_converter["kernel_size"], \
|
56 |
-
channel_width=args.cfg_converter["channel_width"], \
|
57 |
-
stack_size=args.cfg_converter["stack_size"], \
|
58 |
-
cond_dim=args.cfg_converter["condition_dimension"], \
|
59 |
-
causal=args.cfg_converter["causal"]).to(self.device)
|
60 |
-
|
61 |
-
ckpt_paths = {'effects_encoder' : args.ckpt_path_enc, \
|
62 |
-
'mixing_converter' : args.ckpt_path_conv}
|
63 |
-
# reload saved model weights
|
64 |
-
ddp = trained_w_ddp
|
65 |
-
self.reload_weights(ckpt_paths, ddp=ddp)
|
66 |
-
|
67 |
-
# load data loader for the inference procedure
|
68 |
-
inference_dataset = Song_Dataset_Inference(args)
|
69 |
-
self.data_loader = DataLoader(inference_dataset, \
|
70 |
-
batch_size=1, \
|
71 |
-
shuffle=False, \
|
72 |
-
num_workers=args.workers, \
|
73 |
-
drop_last=False)
|
74 |
-
|
75 |
-
''' check stem-wise result '''
|
76 |
-
if not self.args.do_not_separate:
|
77 |
-
os.environ['MKL_THREADING_LAYER'] = 'GNU'
|
78 |
-
separate_file_names = [args.input_file_name, args.reference_file_name]
|
79 |
-
if self.args.interpolation:
|
80 |
-
separate_file_names.append(args.reference_file_name_2interpolate)
|
81 |
-
for cur_idx, cur_inf_dir in enumerate(sorted(glob(f"{args.target_dir}*/"))):
|
82 |
-
for cur_file_name in separate_file_names:
|
83 |
-
cur_sep_file_path = os.path.join(cur_inf_dir, cur_file_name+'.wav')
|
84 |
-
cur_sep_output_dir = os.path.join(cur_inf_dir, args.stem_level_directory_name)
|
85 |
-
if os.path.exists(os.path.join(cur_sep_output_dir, self.args.separation_model, cur_file_name, 'drums.wav')):
|
86 |
-
print(f'\talready separated current file : {cur_sep_file_path}')
|
87 |
-
else:
|
88 |
-
cur_cmd_line = f"demucs {cur_sep_file_path} -n {self.args.separation_model} -d {self.device} -o {cur_sep_output_dir}"
|
89 |
-
os.system(cur_cmd_line)
|
90 |
-
|
91 |
-
|
92 |
-
# reload model weights from the target checkpoint path
|
93 |
-
def reload_weights(self, ckpt_paths, ddp=True):
|
94 |
-
for cur_model_name in self.models.keys():
|
95 |
-
checkpoint = torch.load(ckpt_paths[cur_model_name], map_location=self.device)
|
96 |
-
|
97 |
-
from collections import OrderedDict
|
98 |
-
new_state_dict = OrderedDict()
|
99 |
-
for k, v in checkpoint["model"].items():
|
100 |
-
# remove `module.` if the model was trained with DDP
|
101 |
-
name = k[7:] if ddp else k
|
102 |
-
new_state_dict[name] = v
|
103 |
-
|
104 |
-
# load params
|
105 |
-
self.models[cur_model_name].load_state_dict(new_state_dict)
|
106 |
-
|
107 |
-
print(f"---reloaded checkpoint weights : {cur_model_name} ---")
|
108 |
-
|
109 |
-
|
110 |
-
# Inference whole song
|
111 |
-
def inference(self, input_track_path, reference_track_path):
|
112 |
-
print("\n======= Start to inference music mixing style transfer =======")
|
113 |
-
# normalized input
|
114 |
-
output_name_tag = 'output' if self.args.normalize_input else 'output_notnormed'
|
115 |
-
|
116 |
-
for step, (input_stems, reference_stems, dir_name) in enumerate(self.data_loader):
|
117 |
-
print(f"---inference file name : {dir_name[0]}---")
|
118 |
-
cur_out_dir = dir_name[0].replace(self.target_dir, self.output_dir)
|
119 |
-
os.makedirs(cur_out_dir, exist_ok=True)
|
120 |
-
''' stem-level inference '''
|
121 |
-
inst_outputs = []
|
122 |
-
for cur_inst_idx, cur_inst_name in enumerate(self.args.instruments):
|
123 |
-
print(f'\t{cur_inst_name}...')
|
124 |
-
''' segmentize whole songs into batch '''
|
125 |
-
if len(input_stems[0][cur_inst_idx][0]) > self.args.segment_length:
|
126 |
-
cur_inst_input_stem = self.batchwise_segmentization(input_stems[0][cur_inst_idx], \
|
127 |
-
dir_name[0], \
|
128 |
-
segment_length=self.args.segment_length, \
|
129 |
-
discard_last=False)
|
130 |
-
else:
|
131 |
-
cur_inst_input_stem = [input_stems[:, cur_inst_idx]]
|
132 |
-
if len(reference_stems[0][cur_inst_idx][0]) > self.args.segment_length*2:
|
133 |
-
cur_inst_reference_stem = self.batchwise_segmentization(reference_stems[0][cur_inst_idx], \
|
134 |
-
dir_name[0], \
|
135 |
-
segment_length=self.args.segment_length_ref, \
|
136 |
-
discard_last=False)
|
137 |
-
else:
|
138 |
-
cur_inst_reference_stem = [reference_stems[:, cur_inst_idx]]
|
139 |
-
|
140 |
-
''' inference '''
|
141 |
-
# first extract reference style embedding
|
142 |
-
infered_ref_data_list = []
|
143 |
-
for cur_ref_data in cur_inst_reference_stem:
|
144 |
-
cur_ref_data = cur_ref_data.to(self.device)
|
145 |
-
# Effects Encoder inference
|
146 |
-
with torch.no_grad():
|
147 |
-
self.models["effects_encoder"].eval()
|
148 |
-
reference_feature = self.models["effects_encoder"](cur_ref_data)
|
149 |
-
infered_ref_data_list.append(reference_feature)
|
150 |
-
# compute average value from the extracted exbeddings
|
151 |
-
infered_ref_data = torch.stack(infered_ref_data_list)
|
152 |
-
infered_ref_data_avg = torch.mean(infered_ref_data.reshape(infered_ref_data.shape[0]*infered_ref_data.shape[1], infered_ref_data.shape[2]), axis=0)
|
153 |
-
|
154 |
-
# mixing style converter
|
155 |
-
infered_data_list = []
|
156 |
-
for cur_data in cur_inst_input_stem:
|
157 |
-
cur_data = cur_data.to(self.device)
|
158 |
-
with torch.no_grad():
|
159 |
-
self.models["mixing_converter"].eval()
|
160 |
-
infered_data = self.models["mixing_converter"](cur_data, infered_ref_data_avg.unsqueeze(0))
|
161 |
-
infered_data_list.append(infered_data.cpu().detach())
|
162 |
-
|
163 |
-
# combine back to whole song
|
164 |
-
for cur_idx, cur_batch_infered_data in enumerate(infered_data_list):
|
165 |
-
cur_infered_data_sequential = torch.cat(torch.unbind(cur_batch_infered_data, dim=0), dim=-1)
|
166 |
-
fin_data_out = cur_infered_data_sequential if cur_idx==0 else torch.cat((fin_data_out, cur_infered_data_sequential), dim=-1)
|
167 |
-
# final output of current instrument
|
168 |
-
fin_data_out_inst = fin_data_out[:, :input_stems[0][cur_inst_idx].shape[-1]].numpy()
|
169 |
-
|
170 |
-
inst_outputs.append(fin_data_out_inst)
|
171 |
-
# save output of each instrument
|
172 |
-
if self.args.save_each_inst:
|
173 |
-
sf.write(os.path.join(cur_out_dir, f"{cur_inst_name}_{output_name_tag}.wav"), fin_data_out_inst.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
174 |
-
|
175 |
-
# remix
|
176 |
-
fin_data_out_mix = sum(inst_outputs)
|
177 |
-
|
178 |
-
# loudness adjusting for mastering purpose
|
179 |
-
if self.args.match_output_loudness:
|
180 |
-
meter = pyloudnorm.Meter(44100)
|
181 |
-
loudness_out = meter.integrated_loudness(fin_data_out_mix.transpose(-1, -2))
|
182 |
-
reference_aud = load_wav_segment(reference_track_path, axis=1)
|
183 |
-
loudness_ref = meter.integrated_loudness(reference_aud)
|
184 |
-
# adjust output loudness to that of the reference
|
185 |
-
fin_data_out_mix = pyloudnorm.normalize.loudness(fin_data_out_mix, loudness_out, loudness_ref)
|
186 |
-
fin_data_out_mix = np.clip(fin_data_out_mix, -1., 1.)
|
187 |
-
|
188 |
-
# save output
|
189 |
-
fin_output_path = os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav")
|
190 |
-
sf.write(fin_output_path, fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
191 |
|
192 |
-
|
|
|
|
|
193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
-
|
196 |
-
def inference_interpolation(self, ):
|
197 |
-
print("\n======= Start to inference interpolation examples =======")
|
198 |
-
# normalized input
|
199 |
-
output_name_tag = 'output_interpolation' if self.args.normalize_input else 'output_notnormed_interpolation'
|
200 |
-
|
201 |
-
for step, (input_stems, reference_stems_A, reference_stems_B, dir_name) in enumerate(self.data_loader):
|
202 |
-
print(f"---inference file name : {dir_name[0]}---")
|
203 |
-
cur_out_dir = dir_name[0].replace(self.target_dir, self.output_dir)
|
204 |
-
os.makedirs(cur_out_dir, exist_ok=True)
|
205 |
-
''' stem-level inference '''
|
206 |
-
inst_outputs = []
|
207 |
-
for cur_inst_idx, cur_inst_name in enumerate(self.args.instruments):
|
208 |
-
print(f'\t{cur_inst_name}...')
|
209 |
-
''' segmentize whole song '''
|
210 |
-
# segmentize input according to number of interpolating segments
|
211 |
-
interpolate_segment_length = input_stems[0][cur_inst_idx].shape[1] // self.args.interpolate_segments + 1
|
212 |
-
cur_inst_input_stem = self.batchwise_segmentization(input_stems[0][cur_inst_idx], \
|
213 |
-
dir_name[0], \
|
214 |
-
segment_length=interpolate_segment_length, \
|
215 |
-
discard_last=False)
|
216 |
-
# batchwise segmentize 2 reference tracks
|
217 |
-
if len(reference_stems_A[0][cur_inst_idx][0]) > self.args.segment_length_ref:
|
218 |
-
cur_inst_reference_stem_A = self.batchwise_segmentization(reference_stems_A[0][cur_inst_idx], \
|
219 |
-
dir_name[0], \
|
220 |
-
segment_length=self.args.segment_length_ref, \
|
221 |
-
discard_last=False)
|
222 |
-
else:
|
223 |
-
cur_inst_reference_stem_A = [reference_stems_A[:, cur_inst_idx]]
|
224 |
-
if len(reference_stems_B[0][cur_inst_idx][0]) > self.args.segment_length_ref:
|
225 |
-
cur_inst_reference_stem_B = self.batchwise_segmentization(reference_stems_B[0][cur_inst_idx], \
|
226 |
-
dir_name[0], \
|
227 |
-
segment_length=self.args.segment_length, \
|
228 |
-
discard_last=False)
|
229 |
-
else:
|
230 |
-
cur_inst_reference_stem_B = [reference_stems_B[:, cur_inst_idx]]
|
231 |
-
|
232 |
-
''' inference '''
|
233 |
-
# first extract reference style embeddings
|
234 |
-
# reference A
|
235 |
-
infered_ref_data_list = []
|
236 |
-
for cur_ref_data in cur_inst_reference_stem_A:
|
237 |
-
cur_ref_data = cur_ref_data.to(self.device)
|
238 |
-
# Effects Encoder inference
|
239 |
-
with torch.no_grad():
|
240 |
-
self.models["effects_encoder"].eval()
|
241 |
-
reference_feature = self.models["effects_encoder"](cur_ref_data)
|
242 |
-
infered_ref_data_list.append(reference_feature)
|
243 |
-
# compute average value from the extracted exbeddings
|
244 |
-
infered_ref_data = torch.stack(infered_ref_data_list)
|
245 |
-
infered_ref_data_avg_A = torch.mean(infered_ref_data.reshape(infered_ref_data.shape[0]*infered_ref_data.shape[1], infered_ref_data.shape[2]), axis=0)
|
246 |
-
|
247 |
-
# reference B
|
248 |
-
infered_ref_data_list = []
|
249 |
-
for cur_ref_data in cur_inst_reference_stem_B:
|
250 |
-
cur_ref_data = cur_ref_data.to(self.device)
|
251 |
-
# Effects Encoder inference
|
252 |
-
with torch.no_grad():
|
253 |
-
self.models["effects_encoder"].eval()
|
254 |
-
reference_feature = self.models["effects_encoder"](cur_ref_data)
|
255 |
-
infered_ref_data_list.append(reference_feature)
|
256 |
-
# compute average value from the extracted exbeddings
|
257 |
-
infered_ref_data = torch.stack(infered_ref_data_list)
|
258 |
-
infered_ref_data_avg_B = torch.mean(infered_ref_data.reshape(infered_ref_data.shape[0]*infered_ref_data.shape[1], infered_ref_data.shape[2]), axis=0)
|
259 |
-
|
260 |
-
# mixing style converter
|
261 |
-
infered_data_list = []
|
262 |
-
for cur_idx, cur_data in enumerate(cur_inst_input_stem):
|
263 |
-
cur_data = cur_data.to(self.device)
|
264 |
-
# perform linear interpolation on embedding space
|
265 |
-
cur_weight = (self.args.interpolate_segments-1-cur_idx) / (self.args.interpolate_segments-1)
|
266 |
-
cur_ref_emb = cur_weight * infered_ref_data_avg_A + (1-cur_weight) * infered_ref_data_avg_B
|
267 |
-
with torch.no_grad():
|
268 |
-
self.models["mixing_converter"].eval()
|
269 |
-
infered_data = self.models["mixing_converter"](cur_data, cur_ref_emb.unsqueeze(0))
|
270 |
-
infered_data_list.append(infered_data.cpu().detach())
|
271 |
-
|
272 |
-
# combine back to whole song
|
273 |
-
for cur_idx, cur_batch_infered_data in enumerate(infered_data_list):
|
274 |
-
cur_infered_data_sequential = torch.cat(torch.unbind(cur_batch_infered_data, dim=0), dim=-1)
|
275 |
-
fin_data_out = cur_infered_data_sequential if cur_idx==0 else torch.cat((fin_data_out, cur_infered_data_sequential), dim=-1)
|
276 |
-
# final output of current instrument
|
277 |
-
fin_data_out_inst = fin_data_out[:, :input_stems[0][cur_inst_idx].shape[-1]].numpy()
|
278 |
-
inst_outputs.append(fin_data_out_inst)
|
279 |
-
|
280 |
-
# save output of each instrument
|
281 |
-
if self.args.save_each_inst:
|
282 |
-
sf.write(os.path.join(cur_out_dir, f"{cur_inst_name}_{output_name_tag}.wav"), fin_data_out_inst.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
283 |
-
# remix
|
284 |
-
fin_data_out_mix = sum(inst_outputs)
|
285 |
-
# fin_output_path = os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav")
|
286 |
-
# sf.write(fin_output_path, fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
287 |
-
|
288 |
-
# return fin_output_path, fin_data_out_mix
|
289 |
-
return fin_data_out_mix
|
290 |
-
|
291 |
-
|
292 |
-
# function that segmentize an entire song into batch
|
293 |
-
def batchwise_segmentization(self, target_song, song_name, segment_length, discard_last=False):
|
294 |
-
assert target_song.shape[-1] >= self.args.segment_length, \
|
295 |
-
f"Error : Insufficient duration!\n\t \
|
296 |
-
Target song's length is shorter than segment length.\n\t \
|
297 |
-
Song name : {song_name}\n\t \
|
298 |
-
Consider changing the 'segment_length' or song with sufficient duration"
|
299 |
-
|
300 |
-
# discard restovers (last segment)
|
301 |
-
if discard_last:
|
302 |
-
target_length = target_song.shape[-1] - target_song.shape[-1] % segment_length
|
303 |
-
target_song = target_song[:, :target_length]
|
304 |
-
# pad last segment
|
305 |
-
else:
|
306 |
-
pad_length = segment_length - target_song.shape[-1] % segment_length
|
307 |
-
target_song = torch.cat((target_song, torch.zeros(2, pad_length)), axis=-1)
|
308 |
-
|
309 |
-
# segmentize according to the given segment_length
|
310 |
-
whole_batch_data = []
|
311 |
-
batch_wise_data = []
|
312 |
-
for cur_segment_idx in range(target_song.shape[-1]//segment_length):
|
313 |
-
batch_wise_data.append(target_song[..., cur_segment_idx*segment_length:(cur_segment_idx+1)*segment_length])
|
314 |
-
if len(batch_wise_data)==self.args.batch_size:
|
315 |
-
whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
|
316 |
-
batch_wise_data = []
|
317 |
-
if batch_wise_data:
|
318 |
-
whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
|
319 |
-
|
320 |
-
return whole_batch_data
|
321 |
-
|
322 |
|
|
|
323 |
|
324 |
-
def trim_audio(target_file_path, start_point_in_second=0, duration_in_second=30, sample_rate=44100):
|
325 |
-
# insure format
|
326 |
-
cur_aud, _ = librosa.load(target_file_path, sr=sample_rate, mono=False)
|
327 |
-
sf.write(target_file_path, cur_aud.transpose(-1, -2), sample_rate, 'PCM_16')
|
328 |
-
# trim if possible
|
329 |
-
cur_wav_length = load_wav_length(target_file_path)
|
330 |
-
if cur_wav_length < duration_in_second*sample_rate:
|
331 |
-
return
|
332 |
-
if cur_wav_length-start_point_in_second*sample_rate < duration_in_second*sample_rate:
|
333 |
-
trimmed_audio = load_wav_segment(target_file_path, start_point=int(start_point_in_second*sample_rate), axis=1)
|
334 |
-
else:
|
335 |
-
trimmed_audio = load_wav_segment(target_file_path, start_point=int(start_point_in_second*sample_rate), duration=int(duration_in_second*sample_rate), axis=1)
|
336 |
-
sf.write(target_file_path, trimmed_audio, sample_rate, 'PCM_16')
|
337 |
|
|
|
|
|
338 |
|
339 |
-
def set_up(start_point_in_second=0, duration_in_second=30):
|
340 |
-
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
341 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
|
342 |
-
os.environ['MASTER_PORT'] = '8888'
|
343 |
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
|
|
|
|
351 |
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
357 |
|
358 |
-
|
359 |
-
|
360 |
-
|
|
|
|
|
|
|
361 |
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
directory_args.add_argument('--input_file_name', type=str, default='input')
|
367 |
-
directory_args.add_argument('--reference_file_name', type=str, default='reference')
|
368 |
-
directory_args.add_argument('--reference_file_name_2interpolate', type=str, default='reference_B')
|
369 |
-
# saved weights
|
370 |
-
directory_args.add_argument('--ckpt_path_enc', type=str, default=default_ckpt_path_enc)
|
371 |
-
directory_args.add_argument('--ckpt_path_conv', type=str, default=default_ckpt_path_conv)
|
372 |
-
directory_args.add_argument('--precomputed_normalization_feature', type=str, default=default_norm_feature_path)
|
373 |
|
374 |
-
inference_args = parser.add_argument_group('Inference args')
|
375 |
-
inference_args.add_argument('--sample_rate', type=int, default=44100)
|
376 |
-
inference_args.add_argument('--segment_length', type=int, default=2**19) # segmentize input according to this duration
|
377 |
-
inference_args.add_argument('--segment_length_ref', type=int, default=2**19) # segmentize reference according to this duration
|
378 |
-
# stem-level instruments & separation
|
379 |
-
inference_args.add_argument('--instruments', type=str2bool, default=["drums", "bass", "other", "vocals"], help='instrumental tracks to perform style transfer')
|
380 |
-
inference_args.add_argument('--stem_level_directory_name', type=str, default='separated')
|
381 |
-
inference_args.add_argument('--save_each_inst', type=str2bool, default=False)
|
382 |
-
inference_args.add_argument('--do_not_separate', type=str2bool, default=False)
|
383 |
-
inference_args.add_argument('--separation_model', type=str, default='htdemucs')
|
384 |
-
# FX normalization
|
385 |
-
inference_args.add_argument('--normalize_input', type=str2bool, default=True)
|
386 |
-
inference_args.add_argument('--normalization_order', type=str2bool, default=['loudness', 'eq', 'compression', 'imager', 'loudness']) # Effects to be normalized, order matters
|
387 |
-
inference_args.add_argument('--match_output_loudness', type=str2bool, default=False)
|
388 |
-
# interpolation
|
389 |
-
inference_args.add_argument('--interpolation', type=str2bool, default=False)
|
390 |
-
inference_args.add_argument('--interpolate_segments', type=int, default=30)
|
391 |
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
397 |
|
398 |
-
# load network configurations
|
399 |
-
with open(os.path.join(currentdir, 'configs.yaml'), 'r') as f:
|
400 |
-
configs = yaml.full_load(f)
|
401 |
-
args.cfg_encoder = configs['Effects_Encoder']['default']
|
402 |
-
args.cfg_converter = configs['TCN']['default']
|
403 |
|
404 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import binascii
|
3 |
+
import warnings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
import json
|
6 |
+
import argparse
|
7 |
+
import copy
|
8 |
|
9 |
+
import numpy as np
|
10 |
+
import matplotlib.pyplot as plt
|
11 |
+
import torch
|
12 |
+
import tqdm
|
13 |
+
import librosa
|
14 |
+
import soundfile as sf
|
15 |
+
import gradio as gr
|
16 |
+
import pytube as pt
|
17 |
|
18 |
+
from pytube.exceptions import VideoUnavailable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
from inference.style_transfer import *
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
yt_video_dir = f"./yt_dir/0"
|
24 |
+
os.makedirs(yt_video_dir, exist_ok=True)
|
25 |
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
def get_audio_from_yt_video_input(yt_link: str, start_point_in_second=0, duration_in_second=30):
|
28 |
+
try:
|
29 |
+
yt = pt.YouTube(yt_link)
|
30 |
+
t = yt.streams.filter(only_audio=True)
|
31 |
+
filename_in = os.path.join(yt_video_dir, "input.wav")
|
32 |
+
t[0].download(filename=filename_in)
|
33 |
+
except VideoUnavailable as e:
|
34 |
+
warnings.warn(f"Video Not Found at {yt_link} ({e})")
|
35 |
+
filename_in = None
|
36 |
|
37 |
+
# trim audio length - due to computation time on HuggingFace environment
|
38 |
+
trim_audio(target_file_path=filename_in, start_point_in_second=start_point_in_second, duration_in_second=duration_in_second)
|
39 |
+
|
40 |
+
return filename_in, filename_in
|
41 |
+
|
42 |
+
def get_audio_from_yt_video_ref(yt_link: str, start_point_in_second=0, duration_in_second=30):
|
43 |
+
try:
|
44 |
+
yt = pt.YouTube(yt_link)
|
45 |
+
t = yt.streams.filter(only_audio=True)
|
46 |
+
filename_ref = os.path.join(yt_video_dir, "reference.wav")
|
47 |
+
t[0].download(filename=filename_ref)
|
48 |
+
except VideoUnavailable as e:
|
49 |
+
warnings.warn(f"Video Not Found at {yt_link} ({e})")
|
50 |
+
filename_ref = None
|
51 |
+
|
52 |
+
# trim audio length - due to computation time on HuggingFace environment
|
53 |
+
trim_audio(target_file_path=filename_ref, start_point_in_second=start_point_in_second, duration_in_second=duration_in_second)
|
54 |
+
|
55 |
+
return filename_ref, filename_ref
|
56 |
|
57 |
+
def inference(file_uploaded_in, file_uploaded_ref):
|
58 |
+
# clear out previously separated results
|
59 |
+
os.system(f"rm -r {yt_video_dir}/separated")
|
60 |
+
# change file path name
|
61 |
+
# os.system(f"cp {file_uploaded_in} {yt_video_dir}/input.wav")
|
62 |
+
# os.system(f"cp {file_uploaded_ref} {yt_video_dir}/reference.wav")
|
63 |
|
64 |
+
sample_rate, data = file_uploaded_in
|
65 |
+
sf.write(f"{yt_video_dir}/input.wav", data, sample_rate)
|
66 |
+
sample_rate, data = file_uploaded_ref
|
67 |
+
sf.write(f"{yt_video_dir}/reference.wav", data, sample_rate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
# Perform music mixing style transfer
|
71 |
+
args = set_up()
|
72 |
+
|
73 |
+
inference_style_transfer = Mixing_Style_Transfer_Inference(args)
|
74 |
+
# output_wav_path, fin_data_out_mix = inference_style_transfer.inference(file_uploaded_in, file_uploaded_ref)
|
75 |
+
output_wav_path, fin_data_out_mix = inference_style_transfer.inference(f"{yt_video_dir}/input.wav", f"{yt_video_dir}/reference.wav")
|
76 |
+
print(fin_data_out_mix.shape)
|
77 |
+
return (44100, fin_data_out_mix.transpose())
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
with gr.Blocks() as demo:
|
82 |
+
gr.HTML(
|
83 |
+
"""
|
84 |
+
<div style="text-align: center; max-width: 700px; margin: 0 auto;">
|
85 |
+
<div
|
86 |
+
style="
|
87 |
+
display: inline-flex;
|
88 |
+
align-items: center;
|
89 |
+
gap: 0.8rem;
|
90 |
+
font-size: 1.75rem;
|
91 |
+
"
|
92 |
+
>
|
93 |
+
<h1 style="font-weight: 900; margin-bottom: 7px;">
|
94 |
+
Music Mixing Style Transfer
|
95 |
+
</h1>
|
96 |
+
</div>
|
97 |
+
"""
|
98 |
+
)
|
99 |
+
gr.Markdown(
|
100 |
+
"""
|
101 |
+
This page is a Hugging Face interactive demo of the paper ["Music Mixing Style Transfer: A Contrastive Learning Approach to Disentangle Audio Effects"](https://huggingface.co/papers/2211.02247) (ICASSP 2023).
|
102 |
+
- [project page](https://jhtonykoo.github.io/MixingStyleTransfer/)
|
103 |
+
- [GitHub](https://github.com/jhtonyKoo/music_mixing_style_transfer)
|
104 |
+
- [supplementary](https://pale-cicada-946.notion.site/Music-Mixing-Style-Transfer-A-Contrastive-Learning-Approach-to-Disentangle-Audio-Effects-Supplemen-e6eccd9a431a4a8fa4fdd5adb2d3f219)
|
105 |
+
"""
|
106 |
+
)
|
107 |
+
with gr.Group():
|
108 |
+
with gr.Column():
|
109 |
+
with gr.Blocks():
|
110 |
+
with gr.Tab("Input Music"):
|
111 |
+
file_uploaded_in = gr.Audio(label="Input track (mix) to be mixing style transferred")
|
112 |
+
with gr.Tab("YouTube url"):
|
113 |
+
with gr.Row():
|
114 |
+
yt_link_in = gr.Textbox(
|
115 |
+
label="Enter YouTube Link of the Video", autofocus=True, lines=3
|
116 |
+
)
|
117 |
+
yt_in_start_sec = gr.Number(
|
118 |
+
value=0,
|
119 |
+
label="starting point of the song (in seconds)"
|
120 |
+
)
|
121 |
+
yt_in_duration_sec = gr.Number(
|
122 |
+
value=30,
|
123 |
+
label="duration of the song (in seconds)"
|
124 |
+
)
|
125 |
+
yt_btn_in = gr.Button("Download Audio from YouTube Link", size="lg")
|
126 |
+
yt_audio_path_in = gr.Audio(
|
127 |
+
label="Input Audio Extracted from the YouTube Video", interactive=False
|
128 |
+
)
|
129 |
+
yt_btn_in.click(
|
130 |
+
get_audio_from_yt_video_input,
|
131 |
+
inputs=[yt_link_in, yt_in_start_sec, yt_in_duration_sec],
|
132 |
+
outputs=[yt_audio_path_in, file_uploaded_in],
|
133 |
+
)
|
134 |
+
with gr.Blocks():
|
135 |
+
with gr.Tab("Reference Music"):
|
136 |
+
file_uploaded_ref = gr.Audio(label="Reference track (mix) to copy mixing style")
|
137 |
+
with gr.Tab("YouTube url"):
|
138 |
+
with gr.Row():
|
139 |
+
yt_link_ref = gr.Textbox(
|
140 |
+
label="Enter YouTube Link of the Video", autofocus=True, lines=3
|
141 |
+
)
|
142 |
+
yt_ref_start_sec = gr.Number(
|
143 |
+
value=0,
|
144 |
+
label="starting point of the song (in seconds)"
|
145 |
+
)
|
146 |
+
yt_ref_duration_sec = gr.Number(
|
147 |
+
value=30,
|
148 |
+
label="duration of the song (in seconds)"
|
149 |
+
)
|
150 |
+
yt_btn_ref = gr.Button("Download Audio from YouTube Link", size="lg")
|
151 |
+
yt_audio_path_ref = gr.Audio(
|
152 |
+
label="Reference Audio Extracted from the YouTube Video", interactive=False
|
153 |
+
)
|
154 |
+
yt_btn_ref.click(
|
155 |
+
get_audio_from_yt_video_ref,
|
156 |
+
inputs=[yt_link_ref, yt_ref_start_sec, yt_ref_duration_sec],
|
157 |
+
outputs=[yt_audio_path_ref, file_uploaded_ref],
|
158 |
+
)
|
159 |
+
|
160 |
+
with gr.Group():
|
161 |
+
gr.HTML(
|
162 |
+
"""
|
163 |
+
<div> <h3> <center> Mixing Style Transfer. Perform stem-wise audio-effects style conversion by first source separating the input mix. The inference computation time takes longer as the input samples' duration. so plz be patient... </h3> </div>
|
164 |
+
"""
|
165 |
+
)
|
166 |
+
with gr.Column():
|
167 |
+
inference_btn = gr.Button("Run Mixing Style Transfer")
|
168 |
+
with gr.Row():
|
169 |
+
output_mix = gr.Audio(label="mixing style transferred music track", type='numpy')
|
170 |
+
inference_btn.click(
|
171 |
+
inference,
|
172 |
+
inputs=[file_uploaded_in, file_uploaded_ref],
|
173 |
+
outputs=[output_mix],
|
174 |
+
)
|
175 |
|
|
|
|
|
|
|
|
|
|
|
176 |
|
177 |
+
|
178 |
+
if __name__ == "__main__":
|
179 |
+
demo.launch(debug=True)
|