#!/usr/bin/env python3 """FX-Encoder B2: Style transfer ACE-Step tracks with random MTG reference.""" import os, sys, json, random, time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent / "FXEncoder" / "mixing_style_transfer")) from networks.architectures import FXencoder, TCNModel import torch import torchaudio import soundfile as sf import numpy as np from collections import OrderedDict ACESTEP_DIR = Path("/ssd_data/dataset/haim_dataset/fake/acestep/samples") MTG_DIR = Path("/ssd_data/dataset/haim_dataset/real/MTG") OUT_DIR = Path("/ssd_data/dataset/haim_dataset/B_hybrid/B2_human_mastered_ai_dsp") WEIGHTS = Path("/ssd_data/dataset/haim_dataset/FXEncoder/weights") TARGET = 6000 SR = 44100 SEG_LEN = SR * 10 CFG_ENC = { "channels": [16,32,64,128,256,256,512,512,1024,1024,2048,2048], "kernels": [25,25,15,15,10,10,10,10,5,5,5,5], "strides": [4,4,2,2,2,2,2,2,2,2,1,1], "dilation": [1,1,1,1,1,1,1,1,1,1,1,1], "bias": True, "norm": "batch", "conv_block": "res", "activation": "relu", } CFG_CONV = { "condition_dimension": 2048, "nblocks": 14, "dilation_growth": 2, "kernel_size": 15, "channel_width": 128, "stack_size": 15, "causal": False, } def load_audio(path): wav, sr = torchaudio.load(str(path)) if wav.shape[0] == 1: wav = wav.repeat(2, 1) elif wav.shape[0] > 2: wav = wav[:2, :] if sr != SR: wav = torchaudio.functional.resample(wav, sr, SR) return wav def main(): device = "cuda" if torch.cuda.is_available() else "cpu" # Load models enc = FXencoder(CFG_ENC).to(device) conv = TCNModel(nparams=2048, ninputs=2, noutputs=2, nblocks=14, dilation_growth=2, kernel_size=15, channel_width=128, stack_size=15, cond_dim=2048, causal=False).to(device) for name, model, path in [("enc", enc, WEIGHTS/"FXencoder.pt"), ("conv", conv, WEIGHTS/"MixFXcloner.pt")]: ckpt = torch.load(str(path), map_location=device) state = OrderedDict() for k, v in ckpt["model"].items(): state[k[7:] if k.startswith("module.") else k] = v model.load_state_dict(state) model.eval() print("Models loaded") # Get file lists ai_files = sorted(ACESTEP_DIR.glob("*.mp3")) ref_files = sorted(MTG_DIR.glob("*.mp3")) random.seed(int(time.time())) OUT_DIR.mkdir(parents=True, exist_ok=True) meta_path = OUT_DIR / "metadata.jsonl" existing = len(list(OUT_DIR.glob("*.wav"))) if existing >= TARGET: print(f"Already at {existing}/{TARGET}") return print(f"Existing: {existing}, processing {TARGET - existing} more") meta_f = open(meta_path, "a", encoding="utf-8") done = existing t0 = time.time() with torch.no_grad(): for i, ai_path in enumerate(ai_files): if done >= TARGET: break fname = f"B2_fx_{ai_path.stem}.wav" out_path = OUT_DIR / fname if out_path.exists(): done += 1 continue for attempt in range(3): try: ref_path = random.choice(ref_files) inp = load_audio(ai_path) ref = load_audio(ref_path) # Extract FX embedding from reference ref_gpu = ref.unsqueeze(0).to(device) embs = [] for s in range(0, ref_gpu.shape[2], SEG_LEN): seg = ref_gpu[:, :, s:s+SEG_LEN] if seg.shape[2] < SEG_LEN: seg = torch.nn.functional.pad(seg, (0, SEG_LEN - seg.shape[2])) embs.append(enc(seg)) fx_emb = torch.mean(torch.stack(embs), dim=0) # Apply to input inp_gpu = inp.unsqueeze(0).to(device) T = inp_gpu.shape[2] out_segs = [] for s in range(0, T, SEG_LEN): seg = inp_gpu[:, :, s:s+SEG_LEN] actual = seg.shape[2] if actual < SEG_LEN: seg = torch.nn.functional.pad(seg, (0, SEG_LEN - actual)) out = conv(seg, fx_emb) out_segs.append(out[:, :, :actual].cpu()) result = torch.clamp(torch.cat(out_segs, dim=2).squeeze(0), -1, 1) sf.write(str(out_path), result.numpy().T, SR) meta = { "track_id": f"B2_fx_{ai_path.stem}", "filename": fname, "input_source": ai_path.name, "reference_source": ref_path.name, "method": "fx_encoder_style_transfer", } # Per-track JSON with open(OUT_DIR / f"B2_fx_{ai_path.stem}.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() done += 1 if done % 50 == 0: elapsed = time.time() - t0 eta = (TARGET - done) * elapsed / max(done - existing, 1) print(f"[{done}/{TARGET}] ETA: {eta/3600:.1f}h") except Exception as e: print(f"Error {ai_path.name} (attempt {attempt+1}): {e}") torch.cuda.empty_cache() if attempt < 2: continue break meta_f.close() print(f"Done: {done}/{TARGET}") if __name__ == "__main__": main()