File size: 9,908 Bytes
b347b70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
"""
SonicMaster Mastering Wrapper for HAIM Dataset
================================================
AI mastering using SonicMaster (https://arxiv.org/abs/2508.03448).
Wraps the SonicMaster inference pipeline for easy single-file or batch mastering.

Usage:
    # Single file mastering
    python sonic_master.py --input track.wav --output mastered.wav

    # With custom prompt
    python sonic_master.py --input track.wav --output mastered.wav \
        --prompt "Apply warm mastering with balanced EQ and gentle compression"

    # Auto mode (no text prompt)
    python sonic_master.py --input track.wav --output mastered.wav --auto

    # Batch mastering
    python sonic_master.py --input_dir /path/to/tracks --output_dir /path/to/output
"""

import argparse
import os
import sys
from pathlib import Path

# Add SonicMaster repo to path
SONIC_MASTER_DIR = Path(__file__).parent / "SonicMaster"
sys.path.insert(0, str(SONIC_MASTER_DIR))

DEFAULT_CKPT = SONIC_MASTER_DIR / "checkpoints" / "model.safetensors"
DEFAULT_CONFIG = SONIC_MASTER_DIR / "configs" / "tangoflux_config.yaml"
DEFAULT_PROMPT = "Apply professional mastering with balanced EQ, gentle compression, and optimal loudness"


def parse_args():
    p = argparse.ArgumentParser(
        description="SonicMaster AI Mastering for HAIM Dataset",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    # Input/output
    p.add_argument("--input", type=str, help="Path to input audio file.")
    p.add_argument("--output", type=str, help="Path to output audio file.")
    p.add_argument("--input_dir", type=str, help="Directory of input audio files (batch mode).")
    p.add_argument("--output_dir", type=str, help="Directory for output audio files (batch mode).")

    # Mastering control
    p.add_argument("--prompt", type=str, default=DEFAULT_PROMPT,
                   help="Text prompt guiding the mastering.")
    p.add_argument("--auto", action="store_true",
                   help="Auto mode: use default restoration prompt.")

    # Model paths
    p.add_argument("--ckpt", type=str, default=str(DEFAULT_CKPT),
                   help="Path to model.safetensors.")
    p.add_argument("--config", type=str, default=str(DEFAULT_CONFIG),
                   help="Path to tangoflux_config.yaml.")

    # Inference params
    p.add_argument("--fs", type=int, default=44100)
    p.add_argument("--chunk_duration", type=int, default=30)
    p.add_argument("--overlap_duration", type=int, default=10)
    p.add_argument("--num_inference_steps", type=int, default=10)
    p.add_argument("--guidance_scale", type=float, default=1.0)
    p.add_argument("--seed", type=int, default=0)

    return p.parse_args()


def load_model(ckpt_path, config_path, device):
    """Load SonicMaster model and VAE."""
    import torch
    import yaml
    from safetensors.torch import load_file
    from diffusers import AutoencoderOobleck
    from model import TangoFlux

    with open(config_path, "r") as f:
        cfg = yaml.safe_load(f)

    model = TangoFlux(config=cfg["model"])
    weights = load_file(str(ckpt_path))
    model.load_state_dict(weights, strict=False)
    model.to(device).half().eval()

    for p in model.text_encoder.parameters():
        p.requires_grad = False
    model.text_encoder.eval()

    hf_token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_TOKEN")
    # VAE stays fp32 for audio quality — memory managed per-chunk
    vae = AutoencoderOobleck.from_pretrained(
        "stabilityai/stable-audio-open-1.0", subfolder="vae",
        use_auth_token=hf_token,
    ).to(device)
    vae.eval()

    return model, vae


@__import__('torch').no_grad()
def master_single(model, vae, input_path, output_path, prompt, args, device):
    """Master a single audio file."""
    import torch
    import torchaudio
    import soundfile as sf

    fs = args.fs
    chunk_size = args.chunk_duration * fs
    overlap = args.overlap_duration * fs
    stride = chunk_size - overlap

    # Load and standardize (keep on CPU)
    audio, sr = torchaudio.load(str(input_path))
    if audio.shape[0] == 1:
        audio = audio.repeat(2, 1)
    elif audio.shape[0] > 2:
        audio = audio[:2, :]
    if sr != fs:
        audio = torchaudio.functional.resample(audio, sr, fs)

    T = audio.shape[1]

    # Chunk on CPU
    chunks = []
    start = 0
    while start < T:
        end = min(start + chunk_size, T)
        ch = audio[:, start:end]
        if ch.shape[1] < chunk_size:
            ch = torch.nn.functional.pad(ch, (0, chunk_size - ch.shape[1]))
        chunks.append(ch)
        start += stride

    # Process each chunk: encode -> infer -> decode, one at a time
    decoded_chunks = []
    prev_cond = None

    for i, ch in enumerate(chunks):
        torch.cuda.empty_cache()

        # Encode on GPU with autocast for memory savings
        ch_gpu = ch.unsqueeze(0).to(device)
        with torch.amp.autocast('cuda'):
            z = vae.encode(ch_gpu).latent_dist.mode()
        del ch_gpu
        torch.cuda.empty_cache()

        # Inference (transformer is fp16)
        z_in = z.half().transpose(1, 2)
        del z
        result_latent = model.inference_flow(
            z_in, prompt,
            audiocond_latents=prev_cond,
            num_inference_steps=args.num_inference_steps,
            timesteps=None,
            guidance_scale=args.guidance_scale,
            duration=args.chunk_duration,
            seed=args.seed,
            disable_progress=True,
            num_samples_per_prompt=1,
            callback_on_step_end=None,
            solver="Euler",
        )
        del z_in
        torch.cuda.empty_cache()

        # Decode back to waveform (fp32 VAE for quality)
        with torch.amp.autocast('cuda'):
            wav = vae.decode(result_latent.float().transpose(2, 1)).sample.cpu()
        wav = torch.clamp(wav, -1.0, 1.0)
        decoded_chunks.append(wav)

        # Carry conditioning for next chunk
        if i < len(chunks) - 1:
            last = wav[:, :, -overlap:].to(device)
            with torch.amp.autocast('cuda'):
                prev_cond = vae.encode(last).latent_dist.mode().transpose(1, 2).half()
            del last
            torch.cuda.empty_cache()

        del result_latent

    # Crossfade stitch (all on CPU, fp32)
    final = decoded_chunks[0]
    for i in range(1, len(decoded_chunks)):
        prev = final[:, :, -overlap:]
        curr = decoded_chunks[i][:, :, :overlap]
        alpha = torch.linspace(1.0, 0.0, steps=overlap).view(1, 1, -1)
        blended = prev * alpha + curr * (1.0 - alpha)
        final = torch.cat(
            [final[:, :, :-overlap], blended, decoded_chunks[i][:, :, overlap:]],
            dim=2,
        )

    # Trim to original length
    final = final[:, :, :T]

    # Save
    out_path = Path(output_path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    data = final.squeeze(0).float().numpy().T
    sf.write(str(out_path), data, fs)
    return True


def main():
    import torch
    from time import time

    args = parse_args()
    device = "cuda" if torch.cuda.is_available() else "cpu"
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True

    # Validate args
    single_mode = args.input and args.output
    batch_mode = args.input_dir and args.output_dir
    if not single_mode and not batch_mode:
        print("Error: provide --input/--output for single mode or --input_dir/--output_dir for batch mode.")
        sys.exit(1)

    prompt = args.prompt
    if args.auto:
        prompt = "Restore and enhance audio quality"

    # Load model once
    print(f"Loading SonicMaster model from {args.ckpt}...")
    t0 = time()
    model, vae = load_model(args.ckpt, args.config, device)
    print(f"Model loaded in {time()-t0:.1f}s (device={device})")

    if single_mode:
        print(f"Mastering: {args.input}")
        print(f"Prompt: {prompt}")
        t0 = time()
        master_single(model, vae, args.input, args.output, prompt, args, device)
        print(f"Done: {args.output} ({time()-t0:.1f}s)")

    elif batch_mode:
        import json as _json
        input_dir = Path(args.input_dir)
        output_dir = Path(args.output_dir)
        output_dir.mkdir(parents=True, exist_ok=True)

        audio_exts = {'.wav', '.flac', '.mp3', '.ogg'}
        files = sorted([f for f in input_dir.iterdir() if f.suffix.lower() in audio_exts])
        print(f"Found {len(files)} audio files in {input_dir}")

        meta_path = output_dir / "metadata.jsonl"
        meta_f = open(meta_path, "a", encoding="utf-8")

        for i, f in enumerate(files, 1):
            out_file = output_dir / f"{f.stem}_mastered.wav"
            if out_file.exists():
                print(f"[{i}/{len(files)}] Skip (exists): {out_file.name}")
                continue
            print(f"[{i}/{len(files)}] Mastering: {f.name}")
            t0 = time()
            try:
                master_single(model, vae, str(f), str(out_file), prompt, args, device)
                elapsed = time() - t0
                meta = {
                    "track_id": f.stem,
                    "filename": out_file.name,
                    "input_source": f.name,
                    "method": "sonicmaster",
                    "prompt": prompt,
                    "elapsed_sec": round(elapsed, 1),
                }
                # Per-track JSON
                with open(output_dir / f"{f.stem}_mastered.json", "w", encoding="utf-8") as jf:
                    _json.dump(meta, jf, ensure_ascii=False, indent=2)
                meta_f.write(_json.dumps(meta, ensure_ascii=False) + "\n")
                meta_f.flush()
                print(f"  -> {out_file.name} ({elapsed:.1f}s)")
            except Exception as e:
                print(f"  -> FAILED: {e}")

        meta_f.close()


if __name__ == "__main__":
    main()