File size: 5,241 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
#!/usr/bin/env python3
"""
FX-Encoder Style Transfer for HAIM B2
Minimal inference: loads FXencoder + MixFXcloner directly, no legacy deps needed.

Usage:
    python fx_transfer.py \
        --input /path/to/ai_track.wav \
        --reference /path/to/human_track.wav \
        --output /path/to/output.wav
"""
import argparse
import sys
import os
from pathlib import Path
from collections import OrderedDict

import torch
import torchaudio
import soundfile as sf
import numpy as np

# Add FXEncoder networks to path
sys.path.insert(0, str(Path(__file__).parent / "FXEncoder" / "mixing_style_transfer"))
from networks.architectures import FXencoder, TCNModel

WEIGHTS_DIR = Path(__file__).parent / "FXEncoder" / "weights"

# Default configs from FXEncoder/inference/configs.yaml
CFG_ENCODER = {
    "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_CONVERTER = {
    "condition_dimension": 2048,
    "nblocks": 14,
    "dilation_growth": 2,
    "kernel_size": 15,
    "channel_width": 128,
    "stack_size": 15,
    "causal": False,
}

SAMPLE_RATE = 44100
SEGMENT_LENGTH = SAMPLE_RATE * 10  # 10 seconds per segment


def load_models(device):
    enc = FXencoder(CFG_ENCODER).to(device)
    conv = TCNModel(
        nparams=CFG_CONVERTER["condition_dimension"],
        ninputs=2, noutputs=2,
        nblocks=CFG_CONVERTER["nblocks"],
        dilation_growth=CFG_CONVERTER["dilation_growth"],
        kernel_size=CFG_CONVERTER["kernel_size"],
        channel_width=CFG_CONVERTER["channel_width"],
        stack_size=CFG_CONVERTER["stack_size"],
        cond_dim=CFG_CONVERTER["condition_dimension"],
        causal=CFG_CONVERTER["causal"],
    ).to(device)

    # Load weights (trained with DDP, strip 'module.' prefix)
    for name, model, path in [
        ("FXencoder", enc, WEIGHTS_DIR / "FXencoder.pt"),
        ("MixFXcloner", conv, WEIGHTS_DIR / "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(f"  Loaded {name}: {path.name}")

    return enc, conv


def load_audio(path, sr=SAMPLE_RATE):
    wav, orig_sr = torchaudio.load(str(path))
    if wav.shape[0] == 1:
        wav = wav.repeat(2, 1)
    elif wav.shape[0] > 2:
        wav = wav[:2, :]
    if orig_sr != sr:
        wav = torchaudio.functional.resample(wav, orig_sr, sr)
    return wav


@torch.no_grad()
def transfer(enc, conv, input_wav, ref_wav, device, segment_length=SEGMENT_LENGTH):
    """
    Transfer the mixing style of ref_wav onto input_wav.
    Process in segments to handle long tracks.
    """
    # Extract FX embedding from reference (use whole track, averaged)
    ref = ref_wav.unsqueeze(0).to(device)  # [1, 2, T]

    # Segment reference and average embeddings
    ref_len = ref.shape[2]
    embeddings = []
    for start in range(0, ref_len, segment_length):
        seg = ref[:, :, start:start + segment_length]
        if seg.shape[2] < segment_length:
            seg = torch.nn.functional.pad(seg, (0, segment_length - seg.shape[2]))
        emb = enc(seg)
        embeddings.append(emb)
    fx_embedding = torch.mean(torch.stack(embeddings), dim=0)  # [1, 2048]

    # Apply style to input, segment by segment
    inp = input_wav.unsqueeze(0).to(device)
    inp_len = inp.shape[2]
    output_segments = []

    for start in range(0, inp_len, segment_length):
        seg = inp[:, :, start:start + segment_length]
        actual_len = seg.shape[2]
        if actual_len < segment_length:
            seg = torch.nn.functional.pad(seg, (0, segment_length - seg.shape[2]))

        out = conv(seg, fx_embedding)
        out = out[:, :, :actual_len]
        output_segments.append(out.cpu())

    return torch.cat(output_segments, dim=2).squeeze(0)


def main():
    parser = argparse.ArgumentParser(description="FX-Encoder Mixing Style Transfer")
    parser.add_argument("--input", required=True, help="AI track (input to transform)")
    parser.add_argument("--reference", required=True, help="Human track (style source)")
    parser.add_argument("--output", required=True, help="Output path")
    args = parser.parse_args()

    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Device: {device}")

    print("Loading models...")
    enc, conv = load_models(device)

    print(f"Input (AI): {args.input}")
    print(f"Reference (Human): {args.reference}")

    input_wav = load_audio(args.input)
    ref_wav = load_audio(args.reference)

    print("Transferring mixing style...")
    output_wav = transfer(enc, conv, input_wav, ref_wav, device)
    output_wav = torch.clamp(output_wav, -1.0, 1.0)

    Path(args.output).parent.mkdir(parents=True, exist_ok=True)
    sf.write(args.output, output_wav.numpy().T, SAMPLE_RATE)
    print(f"Saved: {args.output}")


if __name__ == "__main__":
    main()