jhtonyKoo commited on
Commit
2e66664
1 Parent(s): c5080f5

first push

Browse files
README.md CHANGED
@@ -1,14 +1,20 @@
1
- ---
2
- title: ITO Master
3
- emoji: 🐠
4
- colorFrom: purple
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 4.44.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: ITO for Music Mastering Style Transfer
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
+ # Mastering Style Transfer Demo
2
+
3
+ This demo allows you to perform mastering style transfer on audio files or YouTube videos.
4
+
5
+ ## Usage
6
+
7
+ 1. Choose either the "Upload Audio" or "YouTube URLs" tab.
8
+ 2. For audio upload:
9
+ - Upload an input audio file and a reference audio file.
10
+ - Check the "Perform ITO" box if you want to use Inference Time Optimization.
11
+ - Click "Process" to generate the mastered audio.
12
+ 3. For YouTube URLs:
13
+ - Enter the URLs for the input and reference audio.
14
+ - Check the "Perform ITO" box if you want to use Inference Time Optimization.
15
+ - Click "Process" to generate the mastered audio.
16
+ 4. Listen to the output audio and download if desired.
17
+
18
+ ## Note
19
+
20
+ This demo uses pre-trained models for mastering style transfer. The quality of the output may vary depending on the input and reference audio characteristics.
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import soundfile as sf
4
+ import numpy as np
5
+ from inference import MasteringStyleTransfer
6
+ from utils import download_youtube_audio
7
+
8
+ # Initialize MasteringStyleTransfer
9
+ args = type('Args', (), {
10
+ "model_path": "models/mastering_converter.pt",
11
+ "encoder_path": "models/effects_encoder.pt",
12
+ "sample_rate": 44100,
13
+ "path_to_config": "networks/configs.yaml"
14
+ })()
15
+ mastering_transfer = MasteringStyleTransfer(args)
16
+
17
+ def process_audio(input_audio, reference_audio, perform_ito):
18
+ # Process the audio files
19
+ output_audio, predicted_params, ito_output_audio, ito_predicted_params, _, sr, _ = mastering_transfer.process_audio(
20
+ input_audio, reference_audio, reference_audio, {}, perform_ito
21
+ )
22
+
23
+ # Save the output audio
24
+ sf.write("output_mastered.wav", output_audio.T, sr)
25
+ if ito_output_audio is not None:
26
+ sf.write("ito_output_mastered.wav", ito_output_audio.T, sr)
27
+
28
+ return "output_mastered.wav", "ito_output_mastered.wav" if ito_output_audio is not None else None
29
+
30
+ def process_youtube(input_url, reference_url, perform_ito):
31
+ input_audio = download_youtube_audio(input_url)
32
+ reference_audio = download_youtube_audio(reference_url)
33
+ return process_audio(input_audio, reference_audio, perform_ito)
34
+
35
+ with gr.Blocks() as demo:
36
+ gr.Markdown("# Mastering Style Transfer Demo")
37
+ with gr.Tab("Upload Audio"):
38
+ input_audio = gr.Audio(label="Input Audio")
39
+ reference_audio = gr.Audio(label="Reference Audio")
40
+ perform_ito = gr.Checkbox(label="Perform ITO")
41
+ submit_button = gr.Button("Process")
42
+ output_audio = gr.Audio(label="Output Audio")
43
+ ito_output_audio = gr.Audio(label="ITO Output Audio")
44
+ submit_button.click(process_audio, inputs=[input_audio, reference_audio, perform_ito], outputs=[output_audio, ito_output_audio])
45
+
46
+ with gr.Tab("YouTube URLs"):
47
+ input_url = gr.Textbox(label="Input YouTube URL")
48
+ reference_url = gr.Textbox(label="Reference YouTube URL")
49
+ perform_ito_yt = gr.Checkbox(label="Perform ITO")
50
+ submit_button_yt = gr.Button("Process")
51
+ output_audio_yt = gr.Audio(label="Output Audio")
52
+ ito_output_audio_yt = gr.Audio(label="ITO Output Audio")
53
+ submit_button_yt.click(process_youtube, inputs=[input_url, reference_url, perform_ito_yt], outputs=[output_audio_yt, ito_output_audio_yt])
54
+
55
+ demo.launch()
inference.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import soundfile as sf
3
+ import numpy as np
4
+ import argparse
5
+ import os
6
+ import yaml
7
+
8
+ import sys
9
+ currentdir = os.path.dirname(os.path.realpath(__file__))
10
+ sys.path.append(os.path.dirname(currentdir))
11
+ from networks import Dasp_Mastering_Style_Transfer, Effects_Encoder
12
+ from modules import FrontEnd, BackEnd
13
+ from modules.loss import AudioFeatureLoss
14
+
15
+ class MasteringStyleTransfer:
16
+ def __init__(self, args):
17
+ self.args = args
18
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+
20
+ # Load models
21
+ self.effects_encoder = self.load_effects_encoder()
22
+ self.mastering_converter = self.load_mastering_converter()
23
+
24
+ def load_effects_encoder(self):
25
+ effects_encoder = Effects_Encoder(self.args.cfg_enc)
26
+ reload_weights(effects_encoder, self.args.encoder_path, self.device)
27
+ effects_encoder.to(self.device)
28
+ effects_encoder.eval()
29
+ return effects_encoder
30
+
31
+ def load_mastering_converter(self):
32
+ mastering_converter = Dasp_Mastering_Style_Transfer(num_features=2048,
33
+ sample_rate=self.args.sample_rate,
34
+ tgt_fx_names=['eq', 'distortion', 'multiband_comp', 'gain', 'imager', 'limiter'],
35
+ model_type='tcn',
36
+ config=self.args.cfg_converter,
37
+ batch_size=1)
38
+ reload_weights(mastering_converter, self.args.model_path, self.device)
39
+ mastering_converter.to(self.device)
40
+ mastering_converter.eval()
41
+ return mastering_converter
42
+
43
+ def get_reference_embedding(self, reference_tensor):
44
+ with torch.no_grad():
45
+ reference_feature = self.effects_encoder(reference_tensor)
46
+ return reference_feature
47
+
48
+ def mastering_style_transfer(self, input_tensor, reference_feature):
49
+ with torch.no_grad():
50
+ output_audio = self.mastering_converter(input_tensor, reference_feature)
51
+ predicted_params = self.mastering_converter.get_last_predicted_params()
52
+ return output_audio, predicted_params
53
+
54
+ def inference_time_optimization(self, input_tensor, reference_tensor, ito_config, initial_reference_feature):
55
+ fit_embedding = torch.nn.Parameter(initial_reference_feature)
56
+ optimizer = getattr(torch.optim, ito_config['optimizer'])([fit_embedding], lr=ito_config['learning_rate'])
57
+
58
+ af_loss = AudioFeatureLoss(
59
+ weights=ito_config['af_weights'],
60
+ sample_rate=ito_config['sample_rate'],
61
+ stem_separation=False,
62
+ use_clap=False
63
+ )
64
+
65
+ min_loss = float('inf')
66
+ min_loss_step = 0
67
+ min_loss_output = None
68
+ min_loss_params = None
69
+ min_loss_embedding = None
70
+
71
+ loss_history = []
72
+ divergence_counter = 0
73
+
74
+ for step in range(ito_config['num_steps']):
75
+ optimizer.zero_grad()
76
+
77
+ output_audio = self.mastering_converter(input_tensor, fit_embedding)
78
+
79
+ losses = af_loss(output_audio, reference_tensor)
80
+ total_loss = sum(losses.values())
81
+
82
+ loss_history.append(total_loss.item())
83
+
84
+ if total_loss < min_loss:
85
+ min_loss = total_loss.item()
86
+ min_loss_step = step
87
+ min_loss_output = output_audio.detach()
88
+ min_loss_params = self.mastering_converter.get_last_predicted_params()
89
+ min_loss_embedding = fit_embedding.detach().clone()
90
+
91
+ # Check for divergence
92
+ if len(loss_history) > 10 and total_loss > loss_history[-11]:
93
+ divergence_counter += 1
94
+ else:
95
+ divergence_counter = 0
96
+
97
+ print(total_loss, min_loss)
98
+
99
+ if divergence_counter >= 10:
100
+ print(f"Optimization stopped early due to divergence at step {step}")
101
+ break
102
+
103
+ total_loss.backward()
104
+ optimizer.step()
105
+
106
+ return min_loss_output, min_loss_params, min_loss_embedding, min_loss_step + 1
107
+
108
+
109
+
110
+ def process_audio(self, input_path, reference_path, ito_reference_path, ito_config, perform_ito):
111
+ input_audio, sr = sf.read(input_path)
112
+ reference_audio, _ = sf.read(reference_path)
113
+ ito_reference_audio, _ = sf.read(ito_reference_path)
114
+
115
+ input_audio, reference_audio, ito_reference_audio = [
116
+ np.stack([audio, audio]) if audio.ndim == 1 else audio.transpose(1,0)
117
+ for audio in [input_audio, reference_audio, ito_reference_audio]
118
+ ]
119
+
120
+ input_tensor = torch.FloatTensor(input_audio).unsqueeze(0).to(self.device)
121
+ reference_tensor = torch.FloatTensor(reference_audio).unsqueeze(0).to(self.device)
122
+ ito_reference_tensor = torch.FloatTensor(ito_reference_audio).unsqueeze(0).to(self.device)
123
+
124
+ reference_feature = self.get_reference_embedding(reference_tensor)
125
+
126
+ output_audio, predicted_params = self.mastering_style_transfer(input_tensor, reference_feature)
127
+
128
+ if perform_ito:
129
+ ito_output_audio, ito_predicted_params, optimized_reference_feature, ito_steps = self.inference_time_optimization(
130
+ input_tensor, ito_reference_tensor, ito_config, reference_feature
131
+ )
132
+
133
+ ito_output_audio = ito_output_audio.squeeze().cpu().numpy()
134
+ print("\nDifference between initial and ITO predicted parameters:")
135
+ self.print_param_difference(predicted_params, ito_predicted_params)
136
+ else:
137
+ ito_output_audio, ito_predicted_params, optimized_reference_feature, ito_steps = None, None, None, None
138
+
139
+ output_audio = output_audio.squeeze().cpu().numpy()
140
+
141
+ return output_audio, predicted_params, ito_output_audio, ito_predicted_params, optimized_reference_feature, sr, ito_steps
142
+
143
+ def print_param_difference(self, initial_params, ito_params):
144
+ all_diffs = []
145
+
146
+ print("\nAll parameter differences:")
147
+ for fx_name in initial_params.keys():
148
+ print(f"\n{fx_name.upper()}:")
149
+ if isinstance(initial_params[fx_name], dict):
150
+ for param_name in initial_params[fx_name].keys():
151
+ initial_value = initial_params[fx_name][param_name]
152
+ ito_value = ito_params[fx_name][param_name]
153
+
154
+ # Calculate normalized difference
155
+ param_range = self.mastering_converter.fx_processors[fx_name].param_ranges[param_name]
156
+ normalized_diff = abs((ito_value - initial_value) / (param_range[1] - param_range[0]))
157
+
158
+ all_diffs.append((fx_name, param_name, initial_value, ito_value, normalized_diff))
159
+
160
+ print(f" {param_name}:")
161
+ print(f" Initial: {initial_value.item():.4f}")
162
+ print(f" ITO: {ito_value.item():.4f}")
163
+ print(f" Normalized Diff: {normalized_diff.item():.4f}")
164
+ else:
165
+ initial_value = initial_params[fx_name]
166
+ ito_value = ito_params[fx_name]
167
+
168
+ # For 'imager', assume range is 0 to 1
169
+ normalized_diff = abs(ito_value - initial_value)
170
+
171
+ all_diffs.append((fx_name, 'width', initial_value, ito_value, normalized_diff))
172
+
173
+ print(f" width:")
174
+ print(f" Initial: {initial_value.item():.4f}")
175
+ print(f" ITO: {ito_value.item():.4f}")
176
+ print(f" Normalized Diff: {normalized_diff.item():.4f}")
177
+
178
+ # Sort differences by normalized difference and get top 10
179
+ top_diffs = sorted(all_diffs, key=lambda x: x[4], reverse=True)[:10]
180
+
181
+ print("\nTop 10 parameter differences (sorted by normalized difference):")
182
+ for fx_name, param_name, initial_value, ito_value, normalized_diff in top_diffs:
183
+ print(f"{fx_name.upper()} - {param_name}:")
184
+ print(f" Initial: {initial_value.item():.4f}")
185
+ print(f" ITO: {ito_value.item():.4f}")
186
+ print(f" Normalized Diff: {normalized_diff.item():.4f}")
187
+ print()
188
+
189
+ def print_predicted_params(self, predicted_params):
190
+ if predicted_params is None:
191
+ print("No predicted parameters available.")
192
+ return
193
+
194
+ print("Predicted Parameters:")
195
+ for fx_name, fx_params in predicted_params.items():
196
+ print(f"\n{fx_name.upper()}:")
197
+ if isinstance(fx_params, dict):
198
+ for param_name, param_value in fx_params.items():
199
+ if isinstance(param_value, torch.Tensor):
200
+ param_value = param_value.detach().cpu().numpy()
201
+ print(f" {param_name}: {param_value}")
202
+ elif isinstance(fx_params, torch.Tensor):
203
+ param_value = fx_params.detach().cpu().numpy()
204
+ print(f" {param_value}")
205
+ else:
206
+ print(f" {fx_params}")
207
+
208
+ def reload_weights(model, ckpt_path, device):
209
+ checkpoint = torch.load(ckpt_path, map_location=device)
210
+
211
+ from collections import OrderedDict
212
+ new_state_dict = OrderedDict()
213
+ for k, v in checkpoint["model"].items():
214
+ name = k[7:] # remove `module.`
215
+ new_state_dict[name] = v
216
+ model.load_state_dict(new_state_dict, strict=False)
217
+
218
+ if __name__ == "__main__":
219
+ basis_path = '/data2/tony/Mastering_Style_Transfer/results/dasp_tcn_tuneenc_daspman_loudnessnorm/ckpt/1000/'
220
+
221
+ parser = argparse.ArgumentParser(description="Mastering Style Transfer")
222
+ parser.add_argument("--input_path", type=str, required=True, help="Path to input audio file")
223
+ parser.add_argument("--reference_path", type=str, required=True, help="Path to reference audio file")
224
+ parser.add_argument("--ito_reference_path", type=str, required=True, help="Path to ITO reference audio file")
225
+ parser.add_argument("--model_path", type=str, default=f"{basis_path}dasp_tcn_tuneenc_daspman_loudnessnorm_mastering_converter_1000.pt", help="Path to mastering converter model")
226
+ parser.add_argument("--encoder_path", type=str, default=f"{basis_path}dasp_tcn_tuneenc_daspman_loudnessnorm_effects_encoder_1000.pt", help="Path to effects encoder model")
227
+ parser.add_argument("--perform_ito", action="store_true", help="Whether to perform ITO")
228
+ parser.add_argument("--optimizer", type=str, default="RAdam", help="Optimizer for ITO")
229
+ parser.add_argument("--learning_rate", type=float, default=0.001, help="Learning rate for ITO")
230
+ parser.add_argument("--num_steps", type=int, default=100, help="Number of optimization steps for ITO")
231
+ parser.add_argument("--af_weights", nargs='+', type=float, default=[0.1, 0.001, 1.0, 1.0, 0.1], help="Weights for AudioFeatureLoss")
232
+ parser.add_argument("--sample_rate", type=int, default=44100, help="Sample rate for AudioFeatureLoss")
233
+ parser.add_argument("--path_to_config", type=str, default='/home/tony/mastering_transfer/networks/configs.yaml', help="Path to network architecture configuration file")
234
+
235
+ args = parser.parse_args()
236
+
237
+ # load network configurations
238
+ with open(args.path_to_config, 'r') as f:
239
+ configs = yaml.full_load(f)
240
+ args.cfg_converter = configs['TCN']['param_mapping']
241
+ args.cfg_enc = configs['Effects_Encoder']['default']
242
+
243
+ ito_config = {
244
+ 'optimizer': args.optimizer,
245
+ 'learning_rate': args.learning_rate,
246
+ 'num_steps': args.num_steps,
247
+ 'af_weights': args.af_weights,
248
+ 'sample_rate': args.sample_rate
249
+ }
250
+
251
+ mastering_style_transfer = MasteringStyleTransfer(args)
252
+ output_audio, predicted_params, ito_output_audio, ito_predicted_params, optimized_reference_feature, sr, ito_steps = mastering_style_transfer.process_audio(
253
+ args.input_path, args.reference_path, args.ito_reference_path, ito_config, args.perform_ito
254
+ )
255
+
256
+ # Save the output audio
257
+ sf.write("output_mastered.wav", output_audio.T, sr)
258
+ if ito_output_audio is not None:
259
+ sf.write("ito_output_mastered.wav", ito_output_audio.T, sr)
260
+
261
+
262
+
models/mastering_effects_encoder.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b61b6fa0e5f02ef24597509abde21ea97fcc46758a89f746abfabca48b82758
3
+ size 325749562
models/white_box_converter.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6174cd398d250c5908a289673f53ee3e90e19cc20cffb683f151b28ee6a3294
3
+ size 42277602
networks/configs.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model architecture configurations
2
+
3
+ # Music Effects Encoder
4
+ Effects_Encoder:
5
+
6
+ default:
7
+ channels: [16, 32, 64, 128, 256, 256, 512, 512, 1024, 1024, 2048, 2048]
8
+ kernels: [25, 25, 15, 15, 10, 10, 10, 10, 5, 5, 5, 5]
9
+ strides: [4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1]
10
+ dilation: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
11
+ bias: True
12
+ norm: 'batch'
13
+ conv_block: 'res'
14
+ activation: "relu"
15
+
16
+ # TCN
17
+ TCN:
18
+
19
+ default:
20
+ condition_dimension: 2048
21
+ nblocks: 14
22
+ dilation_growth: 2
23
+ kernel_size: 15
24
+ stride: 1
25
+ channel_width: 128
26
+ stack_size: 15
27
+ causal: False
28
+
29
+ param_mapping:
30
+ condition_dimension: 2048
31
+ nblocks: 14
32
+ dilation_growth: 2
33
+ kernel_size: 15
34
+ stride: 2
35
+ channel_width: 128
36
+ stack_size: 15
37
+ causal: False
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ soundfile
4
+ numpy
5
+ pyyaml
6
+ pytube
7
+ librosa
utils.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytube import YouTube
2
+ import librosa
3
+ import numpy as np
4
+
5
+ def download_youtube_audio(url):
6
+ yt = YouTube(url)
7
+ stream = yt.streams.filter(only_audio=True).first()
8
+ filename = stream.download()
9
+ audio, sr = librosa.load(filename, sr=44100, mono=False)
10
+ if audio.ndim == 1:
11
+ audio = np.stack([audio, audio])
12
+ return audio.T