Create style_transfer_hf.py
Browse files- inference/style_transfer_hf.py +390 -0
inference/style_transfer_hf.py
ADDED
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 torch
|
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 |
+
|
24 |
+
|
25 |
+
|
26 |
+
class Mixing_Style_Transfer_Inference:
|
27 |
+
def __init__(self, args, trained_w_ddp=True):
|
28 |
+
if args.inference_device!='cpu' and torch.cuda.is_available():
|
29 |
+
self.device = torch.device("cuda:0")
|
30 |
+
else:
|
31 |
+
self.device = torch.device("cpu")
|
32 |
+
|
33 |
+
# inference computational hyperparameters
|
34 |
+
self.segment_length = 2**19
|
35 |
+
self.batch_size = 1
|
36 |
+
self.sample_rate = 44100 # sampling rate should be 44100
|
37 |
+
self.time_in_seconds = int(self.segment_length // self.sample_rate)
|
38 |
+
|
39 |
+
# directory configuration
|
40 |
+
self.output_dir = "./output_mix_dir/"
|
41 |
+
|
42 |
+
# checkpoint weight paths
|
43 |
+
currentdir = os.path.dirname(os.path.realpath(__file__))
|
44 |
+
ckpt_path_enc = os.path.join(os.path.dirname(currentdir), 'weights', 'FXencoder_ps.pt')
|
45 |
+
ckpt_path_conv = os.path.join(os.path.dirname(currentdir), 'weights', 'MixFXcloner_ps.pt')
|
46 |
+
ckpt_path_mastering = os.path.join(os.path.dirname(currentdir), 'weights', 'MasterFXcloner_ps.pt')
|
47 |
+
norm_feature_path = os.path.join(os.path.dirname(currentdir), 'weights', 'musdb18_fxfeatures_eqcompimagegain.npy')
|
48 |
+
|
49 |
+
# load network configurations
|
50 |
+
with open(os.path.join(currentdir, 'configs.yaml'), 'r') as f:
|
51 |
+
configs = yaml.full_load(f)
|
52 |
+
cfg_encoder = configs['Effects_Encoder']['default']
|
53 |
+
cfg_converter = configs['TCN']['default']
|
54 |
+
|
55 |
+
# load model and its checkpoint weights
|
56 |
+
self.models = {}
|
57 |
+
self.models['effects_encoder'] = FXencoder(cfg_encoder).to(self.device)
|
58 |
+
self.models['mixing_converter'] = TCNModel(nparams=cfg_converter["condition_dimension"], \
|
59 |
+
ninputs=2, \
|
60 |
+
noutputs=2, \
|
61 |
+
nblocks=cfg_converter["nblocks"], \
|
62 |
+
dilation_growth=cfg_converter["dilation_growth"], \
|
63 |
+
kernel_size=cfg_converter["kernel_size"], \
|
64 |
+
channel_width=cfg_converter["channel_width"], \
|
65 |
+
stack_size=cfg_converter["stack_size"], \
|
66 |
+
cond_dim=cfg_converter["condition_dimension"], \
|
67 |
+
causal=cfg_converter["causal"]).to(self.device)
|
68 |
+
|
69 |
+
ckpt_paths = {'effects_encoder' : ckpt_path_enc, \
|
70 |
+
'mixing_converter' : ckpt_path_conv}
|
71 |
+
# reload saved model weights
|
72 |
+
ddp = trained_w_ddp
|
73 |
+
self.reload_weights(ckpt_paths, ddp=ddp)
|
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.args.separation_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, ):
|
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 |
+
# remix
|
175 |
+
fin_data_out_mix = sum(inst_outputs)
|
176 |
+
sf.write(os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav"), fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
177 |
+
|
178 |
+
|
179 |
+
# Inference whole song
|
180 |
+
def inference_interpolation(self, ):
|
181 |
+
print("\n======= Start to inference interpolation examples =======")
|
182 |
+
# normalized input
|
183 |
+
output_name_tag = 'output_interpolation' if self.args.normalize_input else 'output_notnormed_interpolation'
|
184 |
+
|
185 |
+
for step, (input_stems, reference_stems_A, reference_stems_B, dir_name) in enumerate(self.data_loader):
|
186 |
+
print(f"---inference file name : {dir_name[0]}---")
|
187 |
+
cur_out_dir = dir_name[0].replace(self.target_dir, self.output_dir)
|
188 |
+
os.makedirs(cur_out_dir, exist_ok=True)
|
189 |
+
''' stem-level inference '''
|
190 |
+
inst_outputs = []
|
191 |
+
for cur_inst_idx, cur_inst_name in enumerate(self.args.instruments):
|
192 |
+
print(f'\t{cur_inst_name}...')
|
193 |
+
''' segmentize whole song '''
|
194 |
+
# segmentize input according to number of interpolating segments
|
195 |
+
interpolate_segment_length = input_stems[0][cur_inst_idx].shape[1] // self.args.interpolate_segments + 1
|
196 |
+
cur_inst_input_stem = self.batchwise_segmentization(input_stems[0][cur_inst_idx], \
|
197 |
+
dir_name[0], \
|
198 |
+
segment_length=interpolate_segment_length, \
|
199 |
+
discard_last=False)
|
200 |
+
# batchwise segmentize 2 reference tracks
|
201 |
+
if len(reference_stems_A[0][cur_inst_idx][0]) > self.args.segment_length_ref:
|
202 |
+
cur_inst_reference_stem_A = self.batchwise_segmentization(reference_stems_A[0][cur_inst_idx], \
|
203 |
+
dir_name[0], \
|
204 |
+
segment_length=self.args.segment_length_ref, \
|
205 |
+
discard_last=False)
|
206 |
+
else:
|
207 |
+
cur_inst_reference_stem_A = [reference_stems_A[:, cur_inst_idx]]
|
208 |
+
if len(reference_stems_B[0][cur_inst_idx][0]) > self.args.segment_length_ref:
|
209 |
+
cur_inst_reference_stem_B = self.batchwise_segmentization(reference_stems_B[0][cur_inst_idx], \
|
210 |
+
dir_name[0], \
|
211 |
+
segment_length=self.args.segment_length, \
|
212 |
+
discard_last=False)
|
213 |
+
else:
|
214 |
+
cur_inst_reference_stem_B = [reference_stems_B[:, cur_inst_idx]]
|
215 |
+
|
216 |
+
''' inference '''
|
217 |
+
# first extract reference style embeddings
|
218 |
+
# reference A
|
219 |
+
infered_ref_data_list = []
|
220 |
+
for cur_ref_data in cur_inst_reference_stem_A:
|
221 |
+
cur_ref_data = cur_ref_data.to(self.device)
|
222 |
+
# Effects Encoder inference
|
223 |
+
with torch.no_grad():
|
224 |
+
self.models["effects_encoder"].eval()
|
225 |
+
reference_feature = self.models["effects_encoder"](cur_ref_data)
|
226 |
+
infered_ref_data_list.append(reference_feature)
|
227 |
+
# compute average value from the extracted exbeddings
|
228 |
+
infered_ref_data = torch.stack(infered_ref_data_list)
|
229 |
+
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)
|
230 |
+
|
231 |
+
# reference B
|
232 |
+
infered_ref_data_list = []
|
233 |
+
for cur_ref_data in cur_inst_reference_stem_B:
|
234 |
+
cur_ref_data = cur_ref_data.to(self.device)
|
235 |
+
# Effects Encoder inference
|
236 |
+
with torch.no_grad():
|
237 |
+
self.models["effects_encoder"].eval()
|
238 |
+
reference_feature = self.models["effects_encoder"](cur_ref_data)
|
239 |
+
infered_ref_data_list.append(reference_feature)
|
240 |
+
# compute average value from the extracted exbeddings
|
241 |
+
infered_ref_data = torch.stack(infered_ref_data_list)
|
242 |
+
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)
|
243 |
+
|
244 |
+
# mixing style converter
|
245 |
+
infered_data_list = []
|
246 |
+
for cur_idx, cur_data in enumerate(cur_inst_input_stem):
|
247 |
+
cur_data = cur_data.to(self.device)
|
248 |
+
# perform linear interpolation on embedding space
|
249 |
+
cur_weight = (self.args.interpolate_segments-1-cur_idx) / (self.args.interpolate_segments-1)
|
250 |
+
cur_ref_emb = cur_weight * infered_ref_data_avg_A + (1-cur_weight) * infered_ref_data_avg_B
|
251 |
+
with torch.no_grad():
|
252 |
+
self.models["mixing_converter"].eval()
|
253 |
+
infered_data = self.models["mixing_converter"](cur_data, cur_ref_emb.unsqueeze(0))
|
254 |
+
infered_data_list.append(infered_data.cpu().detach())
|
255 |
+
|
256 |
+
# combine back to whole song
|
257 |
+
for cur_idx, cur_batch_infered_data in enumerate(infered_data_list):
|
258 |
+
cur_infered_data_sequential = torch.cat(torch.unbind(cur_batch_infered_data, dim=0), dim=-1)
|
259 |
+
fin_data_out = cur_infered_data_sequential if cur_idx==0 else torch.cat((fin_data_out, cur_infered_data_sequential), dim=-1)
|
260 |
+
# final output of current instrument
|
261 |
+
fin_data_out_inst = fin_data_out[:, :input_stems[0][cur_inst_idx].shape[-1]].numpy()
|
262 |
+
inst_outputs.append(fin_data_out_inst)
|
263 |
+
|
264 |
+
# save output of each instrument
|
265 |
+
if self.args.save_each_inst:
|
266 |
+
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')
|
267 |
+
# remix
|
268 |
+
fin_data_out_mix = sum(inst_outputs)
|
269 |
+
sf.write(os.path.join(cur_out_dir, f"mixture_{output_name_tag}.wav"), fin_data_out_mix.transpose(-1, -2), self.args.sample_rate, 'PCM_16')
|
270 |
+
|
271 |
+
|
272 |
+
# function that segmentize an entire song into batch
|
273 |
+
def batchwise_segmentization(self, target_song, song_name, segment_length, discard_last=False):
|
274 |
+
assert target_song.shape[-1] >= self.args.segment_length, \
|
275 |
+
f"Error : Insufficient duration!\n\t \
|
276 |
+
Target song's length is shorter than segment length.\n\t \
|
277 |
+
Song name : {song_name}\n\t \
|
278 |
+
Consider changing the 'segment_length' or song with sufficient duration"
|
279 |
+
|
280 |
+
# discard restovers (last segment)
|
281 |
+
if discard_last:
|
282 |
+
target_length = target_song.shape[-1] - target_song.shape[-1] % segment_length
|
283 |
+
target_song = target_song[:, :target_length]
|
284 |
+
# pad last segment
|
285 |
+
else:
|
286 |
+
pad_length = segment_length - target_song.shape[-1] % segment_length
|
287 |
+
target_song = torch.cat((target_song, torch.zeros(2, pad_length)), axis=-1)
|
288 |
+
|
289 |
+
# segmentize according to the given segment_length
|
290 |
+
whole_batch_data = []
|
291 |
+
batch_wise_data = []
|
292 |
+
for cur_segment_idx in range(target_song.shape[-1]//segment_length):
|
293 |
+
batch_wise_data.append(target_song[..., cur_segment_idx*segment_length:(cur_segment_idx+1)*segment_length])
|
294 |
+
if len(batch_wise_data)==self.args.batch_size:
|
295 |
+
whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
|
296 |
+
batch_wise_data = []
|
297 |
+
if batch_wise_data:
|
298 |
+
whole_batch_data.append(torch.stack(batch_wise_data, dim=0))
|
299 |
+
|
300 |
+
return whole_batch_data
|
301 |
+
|
302 |
+
|
303 |
+
# save current inference arguments
|
304 |
+
def save_args(self, params):
|
305 |
+
info = '\n[args]\n'
|
306 |
+
for sub_args in parser._action_groups:
|
307 |
+
if sub_args.title in ['positional arguments', 'optional arguments', 'options']:
|
308 |
+
continue
|
309 |
+
size_sub = len(sub_args._group_actions)
|
310 |
+
info += f' {sub_args.title} ({size_sub})\n'
|
311 |
+
for i, arg in enumerate(sub_args._group_actions):
|
312 |
+
prefix = '-'
|
313 |
+
info += f' {prefix} {arg.dest:20s}: {getattr(params, arg.dest)}\n'
|
314 |
+
info += '\n'
|
315 |
+
|
316 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
317 |
+
record_path = f"{self.output_dir}style_transfer_inference_configurations.txt"
|
318 |
+
f = open(record_path, 'w')
|
319 |
+
np.savetxt(f, [info], delimiter=" ", fmt="%s")
|
320 |
+
f.close()
|
321 |
+
|
322 |
+
|
323 |
+
|
324 |
+
if __name__ == '__main__':
|
325 |
+
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
326 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
|
327 |
+
os.environ['MASTER_PORT'] = '8888'
|
328 |
+
|
329 |
+
def str2bool(v):
|
330 |
+
if v.lower() in ('yes', 'true', 't', 'y', '1'):
|
331 |
+
return True
|
332 |
+
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
|
333 |
+
return False
|
334 |
+
else:
|
335 |
+
raise argparse.ArgumentTypeError('Boolean value expected.')
|
336 |
+
|
337 |
+
''' Configurations for music mixing style transfer '''
|
338 |
+
|
339 |
+
import argparse
|
340 |
+
import yaml
|
341 |
+
parser = argparse.ArgumentParser()
|
342 |
+
|
343 |
+
directory_args = parser.add_argument_group('Directory args')
|
344 |
+
# directory paths
|
345 |
+
directory_args.add_argument('--target_dir', type=str, default='./samples/style_transfer/')
|
346 |
+
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')
|
347 |
+
directory_args.add_argument('--input_file_name', type=str, default='input')
|
348 |
+
directory_args.add_argument('--reference_file_name', type=str, default='reference')
|
349 |
+
directory_args.add_argument('--reference_file_name_2interpolate', type=str, default='reference_B')
|
350 |
+
# saved weights
|
351 |
+
directory_args.add_argument('--ckpt_path_enc', type=str, default=default_ckpt_path_enc)
|
352 |
+
directory_args.add_argument('--ckpt_path_conv', type=str, default=default_ckpt_path_conv)
|
353 |
+
directory_args.add_argument('--precomputed_normalization_feature', type=str, default=default_norm_feature_path)
|
354 |
+
|
355 |
+
inference_args = parser.add_argument_group('Inference args')
|
356 |
+
inference_args.add_argument('--sample_rate', type=int, default=44100)
|
357 |
+
inference_args.add_argument('--segment_length', type=int, default=2**19) # segmentize input according to this duration
|
358 |
+
inference_args.add_argument('--segment_length_ref', type=int, default=2**19) # segmentize reference according to this duration
|
359 |
+
# stem-level instruments & separation
|
360 |
+
inference_args.add_argument('--instruments', type=str2bool, default=["drums", "bass", "other", "vocals"], help='instrumental tracks to perform style transfer')
|
361 |
+
inference_args.add_argument('--stem_level_directory_name', type=str, default='separated')
|
362 |
+
inference_args.add_argument('--save_each_inst', type=str2bool, default=False)
|
363 |
+
inference_args.add_argument('--do_not_separate', type=str2bool, default=False)
|
364 |
+
inference_args.add_argument('--separation_model', type=str, default='mdx_extra')
|
365 |
+
# FX normalization
|
366 |
+
inference_args.add_argument('--normalize_input', type=str2bool, default=True)
|
367 |
+
inference_args.add_argument('--normalization_order', type=str2bool, default=['loudness', 'eq', 'compression', 'imager', 'loudness']) # Effects to be normalized, order matters
|
368 |
+
# interpolation
|
369 |
+
inference_args.add_argument('--interpolation', type=str2bool, default=False)
|
370 |
+
inference_args.add_argument('--interpolate_segments', type=int, default=30)
|
371 |
+
|
372 |
+
device_args = parser.add_argument_group('Device args')
|
373 |
+
device_args.add_argument('--workers', type=int, default=1)
|
374 |
+
device_args.add_argument('--inference_device', type=str, default='gpu', help="if this option is not set to 'cpu', inference will happen on gpu only if there is a detected one")
|
375 |
+
device_args.add_argument('--batch_size', type=int, default=1) # for processing long audio
|
376 |
+
device_args.add_argument('--separation_device', type=str, default='cpu', help="device for performing source separation using Demucs")
|
377 |
+
|
378 |
+
args = parser.parse_args()
|
379 |
+
|
380 |
+
|
381 |
+
|
382 |
+
# Perform music mixing style transfer
|
383 |
+
inference_style_transfer = Mixing_Style_Transfer_Inference(args)
|
384 |
+
if args.interpolation:
|
385 |
+
inference_style_transfer.inference_interpolation()
|
386 |
+
else:
|
387 |
+
inference_style_transfer.inference()
|
388 |
+
|
389 |
+
|
390 |
+
|