aboutsummaryrefslogtreecommitdiffstats
path: root/inference.py
blob: ea5f5c074f02872e54c57ba769de36f3c13868c4 (plain) (blame)
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
288
289
290
291
292
293
294
295
296
297
298
import argparse
from pathlib import Path

from huggingface_hub import hf_hub_download
import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F

import look2hear.models


SAMPLE_RATE = 44_100
DEVICE_CHOICES = ("auto", "cuda", "mps", "cpu")
OFFICIAL_CHECKPOINT = "JusperLee/Apollo"
LOCAL_CHECKPOINT_SUFFIXES = {".bin", ".ckpt", ".pt", ".pth", ".safetensors"}


def select_device(requested):
    """Resolve an inference device, preferring CUDA, then MPS, then CPU."""
    if requested == "auto":
        if torch.cuda.is_available():
            return torch.device("cuda")
        if torch.backends.mps.is_available():
            return torch.device("mps")
        return torch.device("cpu")

    if requested == "cuda" and not torch.cuda.is_available():
        raise RuntimeError("CUDA was requested but is not available.")
    if requested == "mps" and not torch.backends.mps.is_available():
        raise RuntimeError("MPS was requested but is not available.")
    return torch.device(requested)


def resolve_checkpoint(reference):
    """Resolve the official remote checkpoint or an existing local file."""
    reference = str(reference)
    if reference == OFFICIAL_CHECKPOINT:
        return Path(
            hf_hub_download(
                repo_id=OFFICIAL_CHECKPOINT, filename="pytorch_model.bin"
            )
        )

    path = Path(reference).expanduser()
    if path.is_file():
        return path
    if path.exists():
        raise IsADirectoryError(f"Checkpoint must be a file, not a directory: {path}")
    if (
        path.suffix.lower() in LOCAL_CHECKPOINT_SUFFIXES
        or path.is_absolute()
        or reference.startswith(("./", "../", "~/"))
    ):
        raise FileNotFoundError(f"Local checkpoint not found: {path}")
    raise ValueError(
        "Unsupported checkpoint source. Use JusperLee/Apollo or an existing "
        "local checkpoint file."
    )


def load_audio(file_path):
    audio, sample_rate = sf.read(
        file_path, dtype="float32", always_2d=True
    )
    if sample_rate != SAMPLE_RATE:
        raise ValueError(
            f"Apollo expects {SAMPLE_RATE} Hz audio, got {sample_rate} Hz."
        )
    if audio.shape[0] == 0 or audio.shape[1] == 0:
        raise ValueError("Input audio must contain at least one sample and channel.")
    if not np.isfinite(audio).all():
        raise ValueError("Input audio contains NaN or infinite values.")
    # SoundFile uses [samples, channels]; Apollo uses [batch, channels, samples].
    audio = torch.from_numpy(np.ascontiguousarray(audio.T)).unsqueeze(0)
    return audio, sample_rate


def save_audio(file_path, audio, sample_rate):
    output_path = Path(file_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    audio = audio.detach().squeeze(0).to("cpu").numpy().T
    sf.write(output_path, audio, sample_rate, subtype="FLOAT")


def resolve_chunking(chunk_seconds, overlap_seconds):
    """Convert optional chunk settings to samples and validate crossfades."""
    if chunk_seconds is None:
        return None, 0
    if not np.isfinite(chunk_seconds) or chunk_seconds <= 0:
        raise ValueError("Chunk duration must be a positive finite number.")
    if not np.isfinite(overlap_seconds) or overlap_seconds < 0:
        raise ValueError("Overlap duration must be a non-negative finite number.")

    chunk_samples = int(round(chunk_seconds * SAMPLE_RATE))
    overlap_samples = int(round(overlap_seconds * SAMPLE_RATE))
    if chunk_samples < 1:
        raise ValueError("Chunk duration is shorter than one sample.")
    if overlap_samples * 2 > chunk_samples:
        raise ValueError("Overlap duration must not exceed half the chunk duration.")
    return chunk_samples, overlap_samples


def validate_chunk_batch_size(chunk_batch_size):
    """Require a fixed positive number of chunks per model forward pass."""
    if (
        isinstance(chunk_batch_size, bool)
        or not isinstance(chunk_batch_size, int)
        or chunk_batch_size < 1
    ):
        raise ValueError("Chunk batch size must be a positive integer.")
    return chunk_batch_size


def chunk_starts(total_samples, chunk_samples, overlap_samples):
    """Return starts that cover the signal without a redundant final chunk."""
    hop_samples = chunk_samples - overlap_samples
    starts = [0]
    while starts[-1] + chunk_samples < total_samples:
        starts.append(starts[-1] + hop_samples)
    return starts


def crossfade_weights(length, overlap_samples, fade_in, fade_out, dtype):
    """Create linear edge weights for normalized overlap-add."""
    weights = torch.ones(length, dtype=dtype)
    fade_samples = min(overlap_samples, length)
    if fade_samples:
        ramp = torch.linspace(0.0, 1.0, fade_samples, dtype=dtype)
        if fade_in:
            weights[:fade_samples] = ramp
        if fade_out:
            weights[-fade_samples:] = torch.flip(ramp, dims=(0,))
    return weights.view(1, 1, -1)


def run_model(
    model,
    audio,
    device,
    chunk_samples=None,
    overlap_samples=0,
    chunk_batch_size=1,
):
    """Run full-file or batched normalized overlap-add chunked inference."""
    chunk_batch_size = validate_chunk_batch_size(chunk_batch_size)

    total_samples = audio.shape[-1]
    if chunk_samples is None or total_samples <= chunk_samples:
        return model(audio.to(device)).detach().to("cpu")

    output_sum = torch.zeros_like(audio, device="cpu")
    weight_sum = torch.zeros((1, 1, total_samples), dtype=audio.dtype)
    starts = chunk_starts(total_samples, chunk_samples, overlap_samples)

    for batch_start in range(0, len(starts), chunk_batch_size):
        batch_starts = starts[batch_start : batch_start + chunk_batch_size]
        batch_chunks = []
        valid_lengths = []
        for start in batch_starts:
            end = min(start + chunk_samples, total_samples)
            valid_samples = end - start
            chunk = audio[..., start:end]
            if valid_samples < chunk_samples:
                chunk = F.pad(chunk, (0, chunk_samples - valid_samples))
            batch_chunks.append(chunk)
            valid_lengths.append(valid_samples)

        chunk_batch = torch.cat(batch_chunks, dim=0)
        batch_output = model(chunk_batch.to(device)).detach().to("cpu")
        expected_shape = (len(batch_starts), audio.shape[1])
        if batch_output.ndim != 3 or batch_output.shape[:2] != expected_shape:
            raise RuntimeError(
                "Chunk output must preserve the input batch and channel dimensions."
            )
        if batch_output.shape[-1] < max(valid_lengths):
            raise RuntimeError(
                "Chunk output is shorter than the corresponding input segment."
            )

        for offset, (start, valid_samples) in enumerate(
            zip(batch_starts, valid_lengths)
        ):
            end = start + valid_samples
            chunk_output = batch_output[offset : offset + 1, ..., :valid_samples]
            index = batch_start + offset
            weights = crossfade_weights(
                valid_samples,
                overlap_samples,
                fade_in=index > 0,
                fade_out=index < len(starts) - 1,
                dtype=audio.dtype,
            )
            output_sum[..., start:end] += chunk_output * weights
            weight_sum[..., start:end] += weights

    if torch.any(weight_sum <= 0):
        raise RuntimeError("Chunk overlap-add left uncovered output samples.")
    return output_sum / weight_sum


def run_inference(
    input_wav,
    output_wav,
    checkpoint,
    requested_device="auto",
    chunk_seconds=None,
    overlap_seconds=1.0,
    chunk_batch_size=1,
):
    input_path = Path(input_wav)
    output_path = Path(output_wav)
    if input_path.resolve() == output_path.resolve():
        raise ValueError("Input and output paths must be different.")
    if output_path.exists() and input_path.samefile(output_path):
        raise ValueError("Input and output paths must not reference the same file.")

    chunk_samples, overlap_samples = resolve_chunking(
        chunk_seconds, overlap_seconds
    )
    chunk_batch_size = validate_chunk_batch_size(chunk_batch_size)
    device = select_device(requested_device)
    test_data, sample_rate = load_audio(input_path)
    checkpoint_path = resolve_checkpoint(checkpoint)

    model = look2hear.models.BaseModel.from_pretrain(
        str(checkpoint_path),
        sr=SAMPLE_RATE,
        win=20,
        feature_dim=256,
        layer=6,
    ).to(device).eval()
    with torch.inference_mode():
        output = run_model(
            model,
            test_data,
            device,
            chunk_samples=chunk_samples,
            overlap_samples=overlap_samples,
            chunk_batch_size=chunk_batch_size,
        )
    save_audio(output_path, output, sample_rate)
    return device


def main():
    parser = argparse.ArgumentParser(description="Audio Inference Script")
    parser.add_argument(
        "--in_wav", type=Path, required=True, help="Path to input WAV file"
    )
    parser.add_argument(
        "--out_wav", type=Path, required=True, help="Path to output WAV file"
    )
    parser.add_argument(
        "--checkpoint",
        default=OFFICIAL_CHECKPOINT,
        help="JusperLee/Apollo or an existing local checkpoint file",
    )
    parser.add_argument(
        "--device",
        choices=DEVICE_CHOICES,
        default="auto",
        help="Inference device (auto prefers CUDA, then MPS, then CPU)",
    )
    parser.add_argument(
        "--chunk-seconds",
        type=float,
        default=None,
        help="Optional chunk duration for long audio; disabled by default",
    )
    parser.add_argument(
        "--overlap-seconds",
        type=float,
        default=1.0,
        help="Chunk crossfade duration (default: 1.0; at most half a chunk)",
    )
    parser.add_argument(
        "--chunk-batch-size",
        type=int,
        default=1,
        help="Chunks per model forward pass (default: 1; higher uses more memory)",
    )
    args = parser.parse_args()

    device = run_inference(
        args.in_wav,
        args.out_wav,
        args.checkpoint,
        args.device,
        args.chunk_seconds,
        args.overlap_seconds,
        args.chunk_batch_size,
    )
    print(f"Inference completed on {device}: {args.out_wav}")


if __name__ == "__main__":
    main()