File size: 3,545 Bytes
51627ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared bits for the SCNet-Large → Core ML conversion (Wobble Split, #212)."""
from __future__ import annotations

import sys
from pathlib import Path

import numpy as np
import soundfile as sf
import torch
import yaml

W = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(W / "src" / "SCNet"))
from scnet.SCNet import SCNet  # noqa: E402

CKPT = W / "weights" / "scnet-large.ckpt"
CONFIG = W / "weights" / "config-large.yaml"
OUT = W / "out"
SR = 44100
SOURCES = ["drums", "bass", "other", "vocals"]
KIT = Path("/Volumes/Media 2TB/Samples/Bingoshakerz - Organic Jazzy Downtempo/Organic Jazzy Downtempo [WAV]/"
           "Construction Kit 08 Gm 78")


def load_model() -> SCNet:
    cfg = yaml.safe_load(CONFIG.read_text())
    model = SCNet(**cfg["model"])
    state = torch.load(CKPT, map_location="cpu", weights_only=True)["best_state"]
    model.load_state_dict({k.removeprefix("module."): v for k, v in state.items()})
    return model.eval()


def read(name: str, length: int) -> np.ndarray:
    x, sr = sf.read(KIT / f"OJD Construction Kit 08 {name}.wav", dtype="float32", always_2d=True)
    assert sr == SR
    x = x.T
    reps = int(np.ceil(length / x.shape[1]))
    return np.tile(x, reps)[:, :length]


def test_mix() -> tuple[np.ndarray, dict[str, np.ndarray]]:
    """Kit 08 rebuilt from its parts, so every stem has a known right answer. No vocals in it."""
    n = int(24.62 * SR)
    truth = {
        "drums": sum(read(p, n) for p in ["Kick Loop 78", "Snare Loop 78", "Hat Loop 78", "Drum Top Loop 78"]),
        "bass": read("Bass Loop Gm 78", n),
        "other": sum(read(p, n) for p in ["Piano Loop Gm 78", "Guitar Loop Gm 78", "Synth Loop Gm 78",
                                          "Sax Loop Gm 78", "FX Loop 78"]),
    }
    mix = sum(truth.values())
    peak = np.abs(mix).max()
    if peak > 0.99:
        mix, truth = mix / peak * 0.99, {k: v / peak * 0.99 for k, v in truth.items()}
    return mix.astype(np.float32), truth


def sdr(ref: np.ndarray, est: np.ndarray) -> float:
    return float(10 * np.log10((ref ** 2).sum() / max(((ref - est) ** 2).sum(), 1e-12)))


def separate(run_segment, mix: np.ndarray, segment: int, overlap: float = 0.5) -> np.ndarray:
    """Whole-file separation as scnet.apply does it: normalise by the mono mean/std, cut into
    `segment`-sample windows (centre-padded with zeros), cross-fade with a triangle, undo the
    normalisation. `run_segment(x[2, segment]) -> [4, 2, segment]`. This is what the app will do."""
    mono = mix.mean(0)
    mean, std = mono.mean(), mono.std(ddof=1)
    x = (mix - mean) / std
    length = x.shape[1]
    stride = int((1 - overlap) * segment)
    weight = np.concatenate([np.arange(1, segment // 2 + 1), np.arange(segment - segment // 2, 0, -1)]).astype(np.float32)
    weight /= weight.max()
    out = np.zeros((4, 2, length), np.float32)
    total = np.zeros(length, np.float32)
    for offset in range(0, length, stride):
        chunk_len = min(segment, length - offset)
        delta = segment - chunk_len
        start = offset - delta // 2
        lo, hi = max(0, start), min(length, start + segment)
        chunk = np.zeros((2, segment), np.float32)
        chunk[:, lo - start:hi - start] = x[:, lo:hi]
        y = run_segment(chunk)
        # center_trim back to the chunk's own length
        y = y[..., delta // 2: delta // 2 + chunk_len]
        out[..., offset:offset + chunk_len] += weight[:chunk_len] * y
        total[offset:offset + chunk_len] += weight[:chunk_len]
    return out / total * std + mean