jhtonyKoo commited on
Commit
077a11b
1 Parent(s): 7748d49

Create mastering_transfer.py

Browse files
Files changed (1) hide show
  1. inference/mastering_transfer.py +378 -0
inference/mastering_transfer.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ Process : converts the mastering style of the input music recording to that of the refernce music.
6
+ files inside the target directory should be organized as follow
7
+ "path_to_data_directory"/"song_name_#1"/input.wav
8
+ "path_to_data_directory"/"song_name_#1"/reference.wav
9
+ ...
10
+ "path_to_data_directory"/"song_name_#n"/input.wav
11
+ "path_to_data_directory"/"song_name_#n"/reference.wav
12
+ where the 'input' and 'reference' should share the same names.
13
+ """
14
+ import numpy as np
15
+ from glob import glob
16
+ import os
17
+ import torch
18
+
19
+ import sys
20
+ currentdir = os.path.dirname(os.path.realpath(__file__))
21
+ sys.path.append(os.path.join(os.path.dirname(currentdir), "mixing_style_transfer"))
22
+ from networks import FXencoder, TCNModel
23
+ from data_loader import *
24
+ import librosa
25
+
26
+
27
+
28
+ class Mastering_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
+
35
+ # inference computational hyperparameters
36
+ self.args = args
37
+ self.segment_length = args.segment_length
38
+ self.batch_size = args.batch_size
39
+ self.sample_rate = 44100 # sampling rate should be 44100
40
+ self.time_in_seconds = int(args.segment_length // self.sample_rate)
41
+
42
+ # directory configuration
43
+ self.output_dir = args.target_dir if args.output_dir==None else args.output_dir
44
+ self.target_dir = args.target_dir
45
+
46
+ # load model and its checkpoint weights
47
+ self.models = {}
48
+ self.models['effects_encoder'] = FXencoder(args.cfg_encoder).to(self.device)
49
+ self.models['mastering_converter'] = TCNModel(nparams=args.cfg_converter["condition_dimension"], \
50
+ ninputs=2, \
51
+ noutputs=2, \
52
+ nblocks=args.cfg_converter["nblocks"], \
53
+ dilation_growth=args.cfg_converter["dilation_growth"], \
54
+ kernel_size=args.cfg_converter["kernel_size"], \
55
+ channel_width=args.cfg_converter["channel_width"], \
56
+ stack_size=args.cfg_converter["stack_size"], \
57
+ cond_dim=args.cfg_converter["condition_dimension"], \
58
+ causal=args.cfg_converter["causal"]).to(self.device)
59
+
60
+ ckpt_paths = {'effects_encoder' : args.ckpt_path_enc, \
61
+ 'mastering_converter' : args.ckpt_path_conv}
62
+ # reload saved model weights
63
+ ddp = trained_w_ddp
64
+ self.reload_weights(ckpt_paths, ddp=ddp)
65
+
66
+ # load data loader for the inference procedure
67
+ inference_dataset = Song_Dataset_Inference(args)
68
+ self.data_loader = DataLoader(inference_dataset, \
69
+ batch_size=1, \
70
+ shuffle=False, \
71
+ num_workers=args.workers, \
72
+ drop_last=False)
73
+
74
+ ''' check stem-wise result '''
75
+ if not self.args.do_not_separate:
76
+ os.environ['MKL_THREADING_LAYER'] = 'GNU'
77
+ separate_file_names = [args.input_file_name, args.reference_file_name]
78
+ if self.args.interpolation:
79
+ separate_file_names.append(args.reference_file_name_2interpolate)
80
+ for cur_idx, cur_inf_dir in enumerate(sorted(glob(f"{args.target_dir}*/"))):
81
+ for cur_file_name in separate_file_names:
82
+ cur_sep_file_path = os.path.join(cur_inf_dir, cur_file_name+'.wav')
83
+ cur_sep_output_dir = os.path.join(cur_inf_dir, args.stem_level_directory_name)
84
+ if os.path.exists(os.path.join(cur_sep_output_dir, self.args.separation_model, cur_file_name, 'drums.wav')):
85
+ print(f'\talready separated current file : {cur_sep_file_path}')
86
+ else:
87
+ cur_cmd_line = f"demucs {cur_sep_file_path} -n {self.args.separation_model} -d {self.device} -o {cur_sep_output_dir}"
88
+ os.system(cur_cmd_line)
89
+
90
+
91
+ # reload model weights from the target checkpoint path
92
+ def reload_weights(self, ckpt_paths, ddp=True):
93
+ for cur_model_name in self.models.keys():
94
+ checkpoint = torch.load(ckpt_paths[cur_model_name], map_location=self.device)
95
+
96
+ from collections import OrderedDict
97
+ new_state_dict = OrderedDict()
98
+ for k, v in checkpoint["model"].items():
99
+ # remove `module.` if the model was trained with DDP
100
+ name = k[7:] if ddp else k
101
+ new_state_dict[name] = v
102
+
103
+ # load params
104
+ self.models[cur_model_name].load_state_dict(new_state_dict)
105
+
106
+ print(f"---reloaded checkpoint weights : {cur_model_name} ---")
107
+
108
+
109
+ # Inference whole song
110
+ def inference(self, input_track_path, reference_track_path):
111
+ print("\n======= Start to inference music mixing style transfer =======")
112
+ # normalized input
113
+ output_name_tag = 'output' if self.args.normalize_input else 'output_notnormed'
114
+
115
+ input_aud = load_wav_segment(input_track_path)
116
+ reference_aud = load_wav_segment(reference_track_path)
117
+
118
+ # input_stems, reference_stems, dir_name
119
+ print(f"---inference file name : {dir_name[0]}---")
120
+ cur_out_dir = dir_name[0].replace(self.target_dir, self.output_dir)
121
+ os.makedirs(cur_out_dir, exist_ok=True)
122
+ ''' stem-level inference '''
123
+ inst_outputs = []
124
+ for cur_inst_idx, cur_inst_name in enumerate(self.args.instruments):
125
+ print(f'\t{cur_inst_name}...')
126
+ ''' segmentize whole songs into batch '''
127
+ if len(input_stems[0][cur_inst_idx][0]) > self.args.segment_length:
128
+ cur_inst_input_stem = self.batchwise_segmentization(input_stems[0][cur_inst_idx], \
129
+ dir_name[0], \
130
+ segment_length=self.args.segment_length, \
131
+ discard_last=False)
132
+ else:
133
+ cur_inst_input_stem = [input_stems[:, cur_inst_idx]]
134
+ if len(reference_stems[0][cur_inst_idx][0]) > self.args.segment_length*2:
135
+ cur_inst_reference_stem = self.batchwise_segmentization(reference_stems[0][cur_inst_idx], \
136
+ dir_name[0], \
137
+ segment_length=self.args.segment_length_ref, \
138
+ discard_last=False)
139
+ else:
140
+ cur_inst_reference_stem = [reference_stems[:, cur_inst_idx]]
141
+
142
+ ''' inference '''
143
+ # first extract reference style embedding
144
+ infered_ref_data_list = []
145
+ for cur_ref_data in cur_inst_reference_stem:
146
+ cur_ref_data = cur_ref_data.to(self.device)
147
+ # Effects Encoder inference
148
+ with torch.no_grad():
149
+ self.models["effects_encoder"].eval()
150
+ reference_feature = self.models["effects_encoder"](cur_ref_data)
151
+ infered_ref_data_list.append(reference_feature)
152
+ # compute average value from the extracted exbeddings
153
+ infered_ref_data = torch.stack(infered_ref_data_list)
154
+ 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)
155
+
156
+ # mixing style converter
157
+ infered_data_list = []
158
+ for cur_data in cur_inst_input_stem:
159
+ cur_data = cur_data.to(self.device)
160
+ with torch.no_grad():
161
+ self.models["mastering_converter"].eval()
162
+ infered_data = self.models["mastering_converter"](cur_data, infered_ref_data_avg.unsqueeze(0))
163
+ infered_data_list.append(infered_data.cpu().detach())
164
+
165
+ # combine back to whole song
166
+ for cur_idx, cur_batch_infered_data in enumerate(infered_data_list):
167
+ cur_infered_data_sequential = torch.cat(torch.unbind(cur_batch_infered_data, dim=0), dim=-1)
168
+ fin_data_out = cur_infered_data_sequential if cur_idx==0 else torch.cat((fin_data_out, cur_infered_data_sequential), dim=-1)
169
+ # final output of current instrument
170
+ fin_data_out_inst = fin_data_out[:, :input_stems[0][cur_inst_idx].shape[-1]].numpy()
171
+
172
+ inst_outputs.append(fin_data_out_inst)
173
+ # save output of each instrument
174
+ if self.args.save_each_inst:
175
+ 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')
176
+ # remix
177
+ fin_data_out_mix = sum(inst_outputs)
178
+ fin_output_path = os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav")
179
+ sf.write(fin_output_path, fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
180
+
181
+ return fin_output_path
182
+
183
+
184
+ # Inference whole song
185
+ def inference_interpolation(self, ):
186
+ print("\n======= Start to inference interpolation examples =======")
187
+ # normalized input
188
+ output_name_tag = 'output_interpolation' if self.args.normalize_input else 'output_notnormed_interpolation'
189
+
190
+ for step, (input_stems, reference_stems_A, reference_stems_B, dir_name) in enumerate(self.data_loader):
191
+ print(f"---inference file name : {dir_name[0]}---")
192
+ cur_out_dir = dir_name[0].replace(self.target_dir, self.output_dir)
193
+ os.makedirs(cur_out_dir, exist_ok=True)
194
+ ''' stem-level inference '''
195
+ inst_outputs = []
196
+ for cur_inst_idx, cur_inst_name in enumerate(self.args.instruments):
197
+ print(f'\t{cur_inst_name}...')
198
+ ''' segmentize whole song '''
199
+ # segmentize input according to number of interpolating segments
200
+ interpolate_segment_length = input_stems[0][cur_inst_idx].shape[1] // self.args.interpolate_segments + 1
201
+ cur_inst_input_stem = self.batchwise_segmentization(input_stems[0][cur_inst_idx], \
202
+ dir_name[0], \
203
+ segment_length=interpolate_segment_length, \
204
+ discard_last=False)
205
+ # batchwise segmentize 2 reference tracks
206
+ if len(reference_stems_A[0][cur_inst_idx][0]) > self.args.segment_length_ref:
207
+ cur_inst_reference_stem_A = self.batchwise_segmentization(reference_stems_A[0][cur_inst_idx], \
208
+ dir_name[0], \
209
+ segment_length=self.args.segment_length_ref, \
210
+ discard_last=False)
211
+ else:
212
+ cur_inst_reference_stem_A = [reference_stems_A[:, cur_inst_idx]]
213
+ if len(reference_stems_B[0][cur_inst_idx][0]) > self.args.segment_length_ref:
214
+ cur_inst_reference_stem_B = self.batchwise_segmentization(reference_stems_B[0][cur_inst_idx], \
215
+ dir_name[0], \
216
+ segment_length=self.args.segment_length, \
217
+ discard_last=False)
218
+ else:
219
+ cur_inst_reference_stem_B = [reference_stems_B[:, cur_inst_idx]]
220
+
221
+ ''' inference '''
222
+ # first extract reference style embeddings
223
+ # reference A
224
+ infered_ref_data_list = []
225
+ for cur_ref_data in cur_inst_reference_stem_A:
226
+ cur_ref_data = cur_ref_data.to(self.device)
227
+ # Effects Encoder inference
228
+ with torch.no_grad():
229
+ self.models["effects_encoder"].eval()
230
+ reference_feature = self.models["effects_encoder"](cur_ref_data)
231
+ infered_ref_data_list.append(reference_feature)
232
+ # compute average value from the extracted exbeddings
233
+ infered_ref_data = torch.stack(infered_ref_data_list)
234
+ 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)
235
+
236
+ # reference B
237
+ infered_ref_data_list = []
238
+ for cur_ref_data in cur_inst_reference_stem_B:
239
+ cur_ref_data = cur_ref_data.to(self.device)
240
+ # Effects Encoder inference
241
+ with torch.no_grad():
242
+ self.models["effects_encoder"].eval()
243
+ reference_feature = self.models["effects_encoder"](cur_ref_data)
244
+ infered_ref_data_list.append(reference_feature)
245
+ # compute average value from the extracted exbeddings
246
+ infered_ref_data = torch.stack(infered_ref_data_list)
247
+ 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)
248
+
249
+ # mixing style converter
250
+ infered_data_list = []
251
+ for cur_idx, cur_data in enumerate(cur_inst_input_stem):
252
+ cur_data = cur_data.to(self.device)
253
+ # perform linear interpolation on embedding space
254
+ cur_weight = (self.args.interpolate_segments-1-cur_idx) / (self.args.interpolate_segments-1)
255
+ cur_ref_emb = cur_weight * infered_ref_data_avg_A + (1-cur_weight) * infered_ref_data_avg_B
256
+ with torch.no_grad():
257
+ self.models["mastering_converter"].eval()
258
+ infered_data = self.models["mastering_converter"](cur_data, cur_ref_emb.unsqueeze(0))
259
+ infered_data_list.append(infered_data.cpu().detach())
260
+
261
+ # combine back to whole song
262
+ for cur_idx, cur_batch_infered_data in enumerate(infered_data_list):
263
+ cur_infered_data_sequential = torch.cat(torch.unbind(cur_batch_infered_data, dim=0), dim=-1)
264
+ fin_data_out = cur_infered_data_sequential if cur_idx==0 else torch.cat((fin_data_out, cur_infered_data_sequential), dim=-1)
265
+ # final output of current instrument
266
+ fin_data_out_inst = fin_data_out[:, :input_stems[0][cur_inst_idx].shape[-1]].numpy()
267
+ inst_outputs.append(fin_data_out_inst)
268
+
269
+ # save output of each instrument
270
+ if self.args.save_each_inst:
271
+ 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')
272
+ # remix
273
+ fin_data_out_mix = sum(inst_outputs)
274
+ fin_output_path = os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav")
275
+ sf.write(fin_output_path, fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
276
+
277
+ return fin_output_path
278
+
279
+
280
+ # function that segmentize an entire song into batch
281
+ def batchwise_segmentization(self, target_song, song_name, segment_length, discard_last=False):
282
+ assert target_song.shape[-1] >= self.args.segment_length, \
283
+ f"Error : Insufficient duration!\n\t \
284
+ Target song's length is shorter than segment length.\n\t \
285
+ Song name : {song_name}\n\t \
286
+ Consider changing the 'segment_length' or song with sufficient duration"
287
+
288
+ # discard restovers (last segment)
289
+ if discard_last:
290
+ target_length = target_song.shape[-1] - target_song.shape[-1] % segment_length
291
+ target_song = target_song[:, :target_length]
292
+ # pad last segment
293
+ else:
294
+ pad_length = segment_length - target_song.shape[-1] % segment_length
295
+ target_song = torch.cat((target_song, torch.zeros(2, pad_length)), axis=-1)
296
+
297
+ # segmentize according to the given segment_length
298
+ whole_batch_data = []
299
+ batch_wise_data = []
300
+ for cur_segment_idx in range(target_song.shape[-1]//segment_length):
301
+ batch_wise_data.append(target_song[..., cur_segment_idx*segment_length:(cur_segment_idx+1)*segment_length])
302
+ if len(batch_wise_data)==self.args.batch_size:
303
+ whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
304
+ batch_wise_data = []
305
+ if batch_wise_data:
306
+ whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
307
+
308
+ return whole_batch_data
309
+
310
+
311
+
312
+ def set_up_mastering(start_point_in_second=0, duration_in_second=30):
313
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
314
+ os.environ["CUDA_VISIBLE_DEVICES"] = '0'
315
+ os.environ['MASTER_PORT'] = '8888'
316
+
317
+ def str2bool(v):
318
+ if v.lower() in ('yes', 'true', 't', 'y', '1'):
319
+ return True
320
+ elif v.lower() in ('no', 'false', 'f', 'n', '0'):
321
+ return False
322
+ else:
323
+ raise argparse.ArgumentTypeError('Boolean value expected.')
324
+
325
+ ''' Configurations for music mixing style transfer '''
326
+ currentdir = os.path.dirname(os.path.realpath(__file__))
327
+ default_ckpt_path_enc = os.path.join(os.path.dirname(currentdir), 'weights', 'FXencoder_ps.pt')
328
+ default_ckpt_path_conv = os.path.join(os.path.dirname(currentdir), 'weights', 'MixFXcloner_ps.pt')
329
+ default_ckpt_path_master = os.path.join(os.path.dirname(currentdir), 'weights', 'MasterFXcloner_ps.pt')
330
+ default_norm_feature_path = os.path.join(os.path.dirname(currentdir), 'weights', 'musdb18_fxfeatures_eqcompimagegain.npy')
331
+
332
+ import argparse
333
+ import yaml
334
+ parser = argparse.ArgumentParser()
335
+
336
+ directory_args = parser.add_argument_group('Directory args')
337
+ # directory paths
338
+ directory_args.add_argument('--target_dir', type=str, default='./yt_dir/')
339
+ directory_args.add_argument('--output_dir', type=str, default=None, help='if no output_dir is specified (None), the results will be saved inside the target_dir')
340
+ directory_args.add_argument('--input_file_name', type=str, default='input')
341
+ directory_args.add_argument('--reference_file_name', type=str, default='reference')
342
+ directory_args.add_argument('--reference_file_name_2interpolate', type=str, default='reference_B')
343
+ # saved weights
344
+ directory_args.add_argument('--ckpt_path_enc', type=str, default=default_ckpt_path_enc)
345
+ directory_args.add_argument('--ckpt_path_conv', type=str, default=default_ckpt_path_master)
346
+ directory_args.add_argument('--precomputed_normalization_feature', type=str, default=default_norm_feature_path)
347
+
348
+ inference_args = parser.add_argument_group('Inference args')
349
+ inference_args.add_argument('--sample_rate', type=int, default=44100)
350
+ inference_args.add_argument('--segment_length', type=int, default=2**19) # segmentize input according to this duration
351
+ inference_args.add_argument('--segment_length_ref', type=int, default=2**19) # segmentize reference according to this duration
352
+ # stem-level instruments & separation
353
+ inference_args.add_argument('--instruments', type=str2bool, default=["drums", "bass", "other", "vocals"], help='instrumental tracks to perform style transfer')
354
+ inference_args.add_argument('--stem_level_directory_name', type=str, default='separated')
355
+ inference_args.add_argument('--save_each_inst', type=str2bool, default=False)
356
+ inference_args.add_argument('--do_not_separate', type=str2bool, default=False)
357
+ inference_args.add_argument('--separation_model', type=str, default='htdemucs')
358
+ # FX normalization
359
+ inference_args.add_argument('--normalize_input', type=str2bool, default=False)
360
+ inference_args.add_argument('--normalization_order', type=str2bool, default=['loudness', 'eq', 'compression', 'imager', 'loudness']) # Effects to be normalized, order matters
361
+ # interpolation
362
+ inference_args.add_argument('--interpolation', type=str2bool, default=False)
363
+ inference_args.add_argument('--interpolate_segments', type=int, default=30)
364
+
365
+ device_args = parser.add_argument_group('Device args')
366
+ device_args.add_argument('--workers', type=int, default=1)
367
+ device_args.add_argument('--batch_size', type=int, default=1) # for processing long audio
368
+
369
+ args = parser.parse_args()
370
+
371
+ # load network configurations
372
+ with open(os.path.join(currentdir, 'configs.yaml'), 'r') as f:
373
+ configs = yaml.full_load(f)
374
+ args.cfg_encoder = configs['Effects_Encoder']['default']
375
+ args.cfg_converter = configs['TCN']['default']
376
+
377
+ return args
378
+