File size: 6,657 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SAM Audio text-prompted extraction, run INSIDE the separate SAM venv (see config.yaml `sam_audio.python`).

Usage (spawned by stemdeck.pipeline.sam_engine, cwd=backend):
  <sam-venv-python> -m stemdeck.sam_runner <input.wav> <prompt> <target_out.wav> --size small --dtype float16
      --chunk 10 --cache-dir <dir>

Prints `PROGRESS <0..1>` and finally `DONE <sample_rate>` or `ERROR <friendly message>` on stdout.
This module must not import anything else from `stemdeck` (that venv lacks the backend's dependencies).
"""

from __future__ import annotations

import argparse
import sys


def _apply_compat_shims() -> None:
    # perception-models imports xformers.ops.AttentionBias at import time, but SAM Audio uses torch SDPA.
    # xformers >= 0.0.36 has no Windows kernels (mslk), so the name is missing: give it a placeholder.
    try:
        import xformers.ops as xops

        if not hasattr(xops, "AttentionBias"):
            xops.AttentionBias = type("AttentionBias", (), {})
    except ImportError:
        pass
    # sam_audio's loader predates huggingface_hub 1.x (proxies/resume_download were removed).
    from sam_audio.model import base

    orig_snapshot = base.snapshot_download
    orig_from_pretrained = base.BaseModel._from_pretrained.__func__

    def snapshot_compat(*args, proxies=None, resume_download=None, **kwargs):  # noqa: ANN001, ANN002, ANN003, ANN202
        return orig_snapshot(*args, **kwargs)

    def from_pretrained_compat(cls, *, proxies=None, resume_download=False, **kwargs):  # noqa: ANN001, ANN003, ANN202
        return orig_from_pretrained(cls, proxies=proxies, resume_download=resume_download, **kwargs)

    base.snapshot_download = snapshot_compat
    base.BaseModel._from_pretrained = classmethod(from_pretrained_compat)

    # Rankers (ImageBind visual, CLAP text, Judge) only re-rank multiple candidates; we always ask for one
    # candidate and lite mode deletes them after loading. Building them costs ~7 GB of downloads and several
    # GB of RAM on a 16 GB machine, so replace each with an empty module.
    import torch
    from sam_audio.ranking import clap, imagebind, judge

    def empty_ranker(self, *_args, **_kwargs):  # noqa: ANN001, ANN002, ANN003, ANN202
        torch.nn.Module.__init__(self)
        self.model = None

    for ranker_cls in (imagebind.ImageBindRanker, clap.ClapRanker, judge.JudgeRanker):
        ranker_cls.__init__ = empty_ranker

    # Same for the span predictor (facebook/pe-a-frame-large, ~6 GB): only used with predict_spans=True.
    from sam_audio.model import model as sam_model

    sam_model.PEAudioFrame.from_config = classmethod(lambda cls, *a, **k: torch.nn.Module())
    sam_model.PEAudioFrameTransform.from_config = classmethod(lambda cls, *a, **k: torch.nn.Module())


def _load_mono(path: str, target_sr: int):  # noqa: ANN202 - numpy array
    import numpy as np
    import soundfile as sf
    import soxr

    data, sr = sf.read(path, dtype="float32", always_2d=True)
    mono = data.mean(axis=1)
    if sr != target_sr:
        mono = soxr.resample(mono, sr, target_sr, quality="HQ")
    return np.ascontiguousarray(mono, dtype=np.float32)


def _to_numpy(tensor):  # noqa: ANN001, ANN202 - torch tensor in, 1-D float32 numpy out (mono)
    import numpy as np

    arr = tensor.detach().float().cpu().numpy()
    if arr.ndim == 2:
        arr = arr.mean(axis=0) if arr.shape[0] < arr.shape[1] else arr.mean(axis=1)
    return np.ascontiguousarray(arr.reshape(-1), dtype=np.float32)


def _say(line: str) -> None:
    print(line, flush=True)


def _friendly(exc: BaseException) -> str:
    text = f"{type(exc).__name__}: {exc}"
    if "GatedRepo" in text or "401" in text or "403" in text:
        return ("No access to the SAM Audio weights. Request access on huggingface.co/facebook/sam-audio-small "
                "and run `hf auth login` on this computer.")
    if "out of memory" in text.lower():
        return "The GPU ran out of memory running SAM Audio. Close other GPU apps or try a shorter song."
    return f"SAM Audio failed ({type(exc).__name__}). Details are in data/logs/worker.log."


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("input")
    ap.add_argument("prompt")
    ap.add_argument("target_out")
    ap.add_argument("--size", default="small")
    ap.add_argument("--dtype", default="float16")
    ap.add_argument("--chunk", type=float, default=10.0)
    ap.add_argument("--cache-dir", default=None)
    ap.add_argument("--ode-step", type=float, default=None, help="flow ODE step size; SAM default 2/32")
    args = ap.parse_args()
    try:
        import truststore

        truststore.inject_into_ssl()
    except ImportError:
        pass
    try:
        import numpy as np
        import soundfile as sf
        import torch

        _apply_compat_shims()
        from sam_audio.model import model as sam_model
        from sam_audio_infer import SamAudioInfer

        if args.ode_step:
            # model.separate() takes DFLT_ODE_OPT as a default argument, so patch that dict in place.
            sam_model.DFLT_ODE_OPT["options"]["step_size"] = args.ode_step

        device = "cuda" if torch.cuda.is_available() else "cpu"
        dtype = args.dtype if device == "cuda" else "float32"
        _say("PROGRESS 0.05")
        model = SamAudioInfer.from_pretrained(args.size, dtype=dtype, device=device, chunk_duration=args.chunk,
                                              cache_dir=args.cache_dir, verbose=False)
        _say("PROGRESS 0.3")
        # Do audio I/O ourselves: torchaudio.load/save go through torchcodec, which on Windows needs
        # FFmpeg 4-7 *shared* DLLs. Passing a numpy array at the model's rate avoids decoding entirely.
        mono = _load_mono(args.input, model.sample_rate)
        target = _to_numpy(model.separate(mono, description=args.prompt).target)
        if not np.all(np.isfinite(target)) and dtype == "float16":
            _say("PROGRESS 0.5")  # fp16 overflowed: redo in fp32
            model = SamAudioInfer.from_pretrained(args.size, dtype="float32", device=device,
                                                  chunk_duration=args.chunk, cache_dir=args.cache_dir, verbose=False)
            target = _to_numpy(model.separate(mono, description=args.prompt).target)
        sf.write(args.target_out, target, model.sample_rate, subtype="FLOAT")
        _say(f"DONE {model.sample_rate}")
        return 0
    except Exception as exc:  # noqa: BLE001
        import traceback

        traceback.print_exc(file=sys.stderr)
        _say(f"ERROR {_friendly(exc)}")
        return 1


if __name__ == "__main__":
    sys.exit(main())