From 15180e210a3843fa57001b011e2cebb14604558a Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 01:25:33 -0400 Subject: [PATCH 1/7] =?UTF-8?q?feat:=20POST=20/transcribe=20=E2=80=94=20tr?= =?UTF-8?q?anscribe=20sung=20audio=20to=20word-level=20timed=20lyrics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feedBack's "transcribe" path has been posting the vocals stem to /align, whose `text` form field is REQUIRED — so FastAPI rejected the request with a 422 before the handler ever ran. Every time, for everyone. Remote transcription never worked at all; the feature was wired to an endpoint that answers a different question, and there was no endpoint that answered the right one (got-feedBack/feedBack-plugin-stem-splitter#17). /align "here are the lyrics — when is each word sung?" (needs text) /transcribe "what are the lyrics, and when is each sung?" (needs only audio) Whisper hears the words; wav2vec2 then force-aligns Whisper's own transcript, which is why this isn't just asr.transcribe(): raw Whisper segments are line-ish and drift, and a karaoke chart built from them sits visibly late. Returns native whisperx.align() output, which is exactly what the client's existing mapper consumes — nothing downstream has to learn a new shape. An instrumental returns {"segments": []} with a 200. A stem with no singing in it is a valid answer, not a failed request, and a 400 there would make callers treat "this song has no vocals" as an error. The test drives a REAL FastAPI app, because the bug lived in the validation layer above the handler: a unit test calling transcribe_audio() directly would have passed while the endpoint 422'd — reproducing the exact blind spot that let this ship. Verified it fails against the unfixed server (404). Signed-off-by: topkoa --- README.md | 29 +++++++ server.py | 93 ++++++++++++++++++++ tests/test_transcribe_endpoint.py | 139 ++++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 tests/test_transcribe_endpoint.py diff --git a/README.md b/README.md index 1fb8cf2..51cc982 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,16 @@ Splits audio into individual stems using [Demucs](https://github.com/facebookres - Per-stem caching, keyed by audio **and model** (avoids re-processing; same song under two models caches separately) - WebSocket progress updates +### Lyrics Transcription (`POST /transcribe`) + +Transcribe sung audio to **word-level timed lyrics** — no lyrics supplied. Whisper hears +the words; wav2vec2 then force-aligns Whisper's own transcript, giving timestamps far tighter +than Whisper's segment boundaries (a chart built from raw Whisper segments sits visibly late). + +- Answers the question `/align` can't: *what are the lyrics, and when is each word sung?* +- Automatic language detection (or manual hint) +- An instrumental track transcribes to `{"segments": []}` — that's an answer, not an error + ### Lyrics Alignment (`POST /align`) Forced alignment of plain text lyrics against an audio file using @@ -360,6 +370,25 @@ Separate audio into stems. | `stems` | Query | Comma-separated stem names (default: `drums,bass,vocals,other`) | | `model` | Query | Override model (optional) | +### `POST /transcribe` + +Transcribe sung audio to word-level timed lyrics using WhisperX (faster-whisper ASR + wav2vec2 forced alignment of its own transcript). Use this when you do **not** have the lyrics; use `/align` when you do. + +| Parameter | Type | Description | +|-----------|------|-------------| +| `file` | Form (file) | Audio file (vocals stem) | +| `language` | Form | ISO 639-1/2 language code hint, e.g. `en`, `es`, `pt` (optional, auto-detected). Must be 2–8 lowercase letters; subtags like `en-US` are not supported. | + +Returns native WhisperX alignment output: + +```json +{"segments": [{"start": 12.3, "end": 15.1, "text": "hello world", + "words": [{"word": "hello", "start": 12.3, "end": 12.8, "score": 0.94}]}], + "language": "en"} +``` + +A stem with no singing in it returns `{"segments": [], "language": "en"}` with a 200 — an instrumental is a valid answer, not a failed request. + ### `POST /align` Forced-align lyrics against audio using WhisperX (faster-whisper transcription + wav2vec2 forced aligner). diff --git a/server.py b/server.py index dd6cf58..ee2ed16 100644 --- a/server.py +++ b/server.py @@ -1217,6 +1217,99 @@ def _do_align(): return result +@app.post("/transcribe") +async def transcribe_audio( + file: UploadFile = File(...), + language: str = Form(""), +): + """Transcribe sung audio to word-level timed lyrics. No lyrics supplied. + + This is the endpoint feedBack's "transcribe" path always meant to call. It was calling + ``/align`` — forced alignment — whose ``text`` field is REQUIRED, so FastAPI rejected the + request with a 422 before the handler ever ran, every single time. Remote transcription had + therefore never worked at all (got-feedBack/feedBack-plugin-stem-splitter#17). The two + operations answer genuinely different questions and both are worth having: + + /align "here are the lyrics — when is each word sung?" (needs text) + /transcribe "what are the lyrics, and when is each sung?" (needs nothing but audio) + + Whisper hears the words; wav2vec2 then force-aligns Whisper's own transcript to get word + timestamps far tighter than Whisper's segment boundaries. That second pass is why this isn't + just ``asr.transcribe()``: raw Whisper segments are line-ish and drift, and a karaoke chart + built from them sits visibly late. + + Returns native ``whisperx.align()`` output — ``{"segments": [{start, end, text, words: + [{word, start, end, score}]}], "language": "en"}`` — which is exactly what the client's + mapper already consumes, so nothing downstream has to learn a new shape. + """ + tmp = tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename or "audio.ogg").suffix) + content = await file.read() + tmp.write(content) + tmp.close() + + def _do_transcribe(): + try: + audio = whisperx.load_audio(tmp.name) + if float(len(audio)) / 16000.0 <= 0: + return {"error": "audio is empty", "_http_status": 400} + + asr_model = _get_whisperx_model() + transcribe_kwargs: dict = {"batch_size": 16} + normalized_lang = "" + if language: + normalized_lang = language.strip().lower() + if not re.fullmatch(r'[a-z]{2,8}', normalized_lang): + raise ValueError(f"Invalid language code: {normalized_lang!r}") + transcribe_kwargs["language"] = normalized_lang + + transcribed = asr_model.transcribe(audio, **transcribe_kwargs) + # The caller's hint wins: Whisper's auto-detection mis-classifies on short clips, + # instrumental intros and non-English vocals, and a wrong guess here loads the wrong + # wav2vec2 aligner — which fails obscurely rather than loudly. + detected_lang = ( + normalized_lang if normalized_lang + else (transcribed.get("language") or "en").lower() + ) + segments = transcribed.get("segments") or [] + + # An instrumental track is not an error. A stem with no singing in it transcribes to + # nothing, and that is the correct answer — returning 400 would make the caller treat + # a successful "this song has no vocals" as a failed request. + if not segments: + return {"segments": [], "language": detected_lang} + + aligner_model, aligner_meta = _get_whisperx_aligner(detected_lang) + aligned = whisperx.align( + segments, + aligner_model, + aligner_meta, + audio, + _whisperx_device(), + return_char_alignments=False, + ) + return {"segments": aligned.get("segments", []) or [], "language": detected_lang} + except ValueError as e: + # Client input problems (bad language code) — 400, so a caller can tell its own + # mistake from a server fault. + return {"error": str(e), "_http_status": 400} + except Exception as e: + return {"error": str(e)} + finally: + try: + os.unlink(tmp.name) + except OSError: + pass + + import asyncio + loop = asyncio.get_running_loop() + result = await loop.run_in_executor(None, _do_transcribe) + + if "error" in result: + status = result.pop("_http_status", 500) + return JSONResponse(result, status) + return result + + # ── Per-syllable pitch extraction (CREPE) ─────────────────────────────── # # /pitch returns one MIDI note per supplied syllable timing. The diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py new file mode 100644 index 0000000..5c6aff9 --- /dev/null +++ b/tests/test_transcribe_endpoint.py @@ -0,0 +1,139 @@ +"""`POST /transcribe` — the endpoint feedBack's transcribe path always meant to call. + +There wasn't one. The client posted the vocals stem to `/align`, whose `text` form field is +REQUIRED, so FastAPI rejected the request with a 422 before the handler ever ran — every time, +for everyone. Remote transcription had never worked +(got-feedBack/feedBack-plugin-stem-splitter#17). + +The bug is a *contract* bug, so the test has to exercise the contract: a real FastAPI app, a real +request, no lyrics in it. A unit test calling `transcribe_audio(...)` directly would pass while +the endpoint 422s, because the rejection happens in FastAPI's validation layer, above the handler +— i.e. it would reproduce exactly the blind spot that let this ship. + +Heavy ML is stubbed (no GPU, no multi-GB downloads); FastAPI is real, which is the whole point. +Runs in a subprocess so the sys.modules stubs can't leak into the rest of the suite. +""" + +import subprocess +import sys +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parent.parent + +_HARNESS = r""" +import sys, types, io +from unittest.mock import MagicMock + +def _fake_torch_load(f, map_location=None, pickle_module=None, *, weights_only=False, **kw): + return None + +_torch = types.ModuleType("torch") +_torch.load = _fake_torch_load +_torch.cuda = MagicMock() +_torch.from_numpy = MagicMock() +sys.modules["torch"] = _torch + +for _name in ("torchcrepe", "librosa", "numpy"): + sys.modules[_name] = MagicMock() + +# whisperx is stubbed, but load_audio must return something with a real length: the handler +# computes a duration from it, and len(MagicMock()) raises. +_whisperx = types.ModuleType("whisperx") +_whisperx.load_audio = lambda path: [0.0] * (16000 * 10) # 10 seconds +_whisperx.align = lambda segments, model, meta, audio, device, return_char_alignments=False: { + "segments": [{ + "start": 1.0, "end": 2.0, "text": "hello world", + "words": [ + {"word": "hello", "start": 1.0, "end": 1.4, "score": 0.9}, + {"word": "world", "start": 1.5, "end": 2.0, "score": 0.8}, + ], + }] +} +sys.modules["whisperx"] = _whisperx + +# fastapi is REAL. If it were stubbed, the 422 this bug is made of could not happen. +import importlib +server = importlib.import_module("server") +from fastapi.testclient import TestClient + +class _ASR: + def __init__(self, segments, language="en"): + self._segments, self._language = segments, language + def transcribe(self, audio, **kw): + return {"segments": self._segments, "language": self._language} + +def _install(segments, language="en"): + server._get_whisperx_model = lambda: _ASR(segments, language) + server._get_whisperx_aligner = lambda lang: (MagicMock(), MagicMock()) + server._whisperx_device = lambda: "cpu" + +client = TestClient(server.app) +AUDIO = {"file": ("vocals.ogg", io.BytesIO(b"not really ogg"), "audio/ogg")} + +def fail(msg): + print("HARNESS_FAIL:" + msg) + sys.exit(3) + +# 1. THE regression. A transcribe request carries no lyrics. That must not be a 422. +_install([{"start": 1.0, "end": 2.0, "text": "hello world"}]) +r = client.post("/transcribe", files=AUDIO) +if r.status_code == 422: + fail("/transcribe 422s on a request with no lyrics - this IS the bug (#17)") +if r.status_code != 200: + fail("/transcribe returned %s: %s" % (r.status_code, r.text[:300])) + +body = r.json() +if not body.get("segments"): + fail("no segments returned") +words = body["segments"][0].get("words") +if not words or words[0].get("word") != "hello": + fail("response is not native whisperx.align() shape (the client's mapper reads .words)") +if body.get("language") != "en": + fail("language missing from response") + +# 2. The language hint is honoured, and a bad one is the CALLER's fault (400, not 500). +_install([{"start": 0.0, "end": 1.0, "text": "hola"}], language="es") +r = client.post("/transcribe", files=AUDIO, data={"language": "es"}) +if r.status_code != 200 or r.json().get("language") != "es": + fail("explicit language hint not honoured: %s %s" % (r.status_code, r.text[:200])) + +r = client.post("/transcribe", files=AUDIO, data={"language": "en-US!!"}) +if r.status_code != 400: + fail("a malformed language code must be a 400, got %s" % r.status_code) + +# 3. An instrumental is an ANSWER, not an error: no vocals -> no words, 200. +_install([]) +r = client.post("/transcribe", files=AUDIO) +if r.status_code != 200: + fail("an instrumental must not be an error, got %s" % r.status_code) +if r.json().get("segments") != []: + fail("an instrumental must return an empty segment list") + +# 4. /align still REQUIRES text — that difference is the whole reason /transcribe exists, and +# if /align ever stopped 422ing here, the original bug would have become invisible instead +# of fixed. +r = client.post("/align", files=AUDIO) +if r.status_code != 422: + fail("/align without text should still be a 422 (it is forced alignment), got %s" % r.status_code) + +print("TRANSCRIBE_OK") +""" + + +def test_transcribe_accepts_audio_with_no_lyrics(): + """The contract #17 broke: transcription takes audio and nothing else.""" + result = subprocess.run( + [sys.executable, "-c", _HARNESS], + capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=180, + ) + combined = result.stdout + "\n" + result.stderr + + if "TRANSCRIBE_OK" in result.stdout: + return + if "HARNESS_FAIL:" in result.stdout: + pytest.fail(combined) + if "ModuleNotFoundError" in combined: + pytest.skip("a dependency we don't stub is missing:\n" + combined) + pytest.fail("harness did not complete:\n" + combined) From 4b5f586361588fac5d1846f578e738e705d98884 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 01:39:32 -0400 Subject: [PATCH 2/7] fix: share the sub-frame filter with /align, don't orphan temp files, don't skip on a broken import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /transcribe passed Whisper's raw segments straight to wav2vec2, while /align filters sub-0.2s ones first and documents why: the aligner returns empty alignments for windows that short, so they degrade the output instead of adding to it. Whisper emits them on breaths, noise and stem bleed. The threshold is now one shared _MIN_SEGMENT_SECONDS — the two endpoints were carrying the same 0.2 independently, which is how they drift. A stem of nothing but sub-frame noise is now an instrumental (empty segments, 200), not a degraded align. - The temp file was only unlinked inside _do_transcribe()'s finally, which never runs if `await file.read()` or the write raises — a client that disconnects mid-upload, or a full disk, left the file behind. One orphan is nothing; one per failed upload on a server that runs for months is a disk quietly filling with nothing. - The test skipped on any ModuleNotFoundError. Every module the harness needs and doesn't stub — fastapi above all — is a hard requirement of server.py, so a missing one means the server cannot import, and skipping there would turn "the server is broken" into a green CI run. - README: the language hint is case-insensitive (the server lowercases before validating), so `EN` works. Documented, and pinned by a test. Found by CodeRabbit and Copilot on #14. Signed-off-by: topkoa --- README.md | 4 ++-- server.py | 40 +++++++++++++++++++++++++------ tests/test_transcribe_endpoint.py | 40 +++++++++++++++++++++++++++++-- 3 files changed, 73 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 51cc982..c6f6bca 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ Transcribe sung audio to word-level timed lyrics using WhisperX (faster-whisper | Parameter | Type | Description | |-----------|------|-------------| | `file` | Form (file) | Audio file (vocals stem) | -| `language` | Form | ISO 639-1/2 language code hint, e.g. `en`, `es`, `pt` (optional, auto-detected). Must be 2–8 lowercase letters; subtags like `en-US` are not supported. | +| `language` | Form | ISO 639-1/2 language code hint, e.g. `en`, `es`, `pt` (optional, auto-detected). Case-insensitive — the value is trimmed and lowercased before validation, so `EN` and `en` both work. Must then be 2–8 letters; subtags like `en-US` are rejected (400) because the hyphen is not a letter. | Returns native WhisperX alignment output: @@ -397,7 +397,7 @@ Forced-align lyrics against audio using WhisperX (faster-whisper transcription + |-----------|------|-------------| | `file` | Form (file) | Audio file (vocals stem) | | `text` | Form | Plain text lyrics | -| `language` | Form | ISO 639-1/2 language code hint, e.g. `en`, `es`, `pt` (optional, auto-detected). Must be 2–8 lowercase letters; subtags like `en-US` are not supported. | +| `language` | Form | ISO 639-1/2 language code hint, e.g. `en`, `es`, `pt` (optional, auto-detected). Case-insensitive — the value is trimmed and lowercased before validation, so `EN` and `en` both work. Must then be 2–8 letters; subtags like `en-US` are rejected (400) because the hyphen is not a letter. | | `granularity` | Form | `line` (default), `word`, `syllable`, or `phoneme` | Granularity behaviour: diff --git a/server.py b/server.py index ee2ed16..dae07fe 100644 --- a/server.py +++ b/server.py @@ -83,6 +83,12 @@ def _parse_cache_max_completed_jobs(value: str | None) -> int: Path.home() / ".cache" / "slopsmith-demucs", )) MAX_CONCURRENT = 2 + +# Whisper segments shorter than this are dropped before wav2vec2 alignment: the aligner tends to +# return empty alignments for sub-frame windows, so passing them in degrades the output instead +# of adding to it. Whisper emits them on breaths, noise and stem bleed. Shared by /align and +# /transcribe — the two used to carry the same 0.2 independently, which is how they drift. +_MIN_SEGMENT_SECONDS = 0.2 CACHE_TTL = os.environ.get("CACHE_TTL", "24h") # Directories under CACHE_DIR that hold model weights (never auto-deleted). # @@ -877,7 +883,7 @@ def _do_align(): # to produce empty alignments for sub-frame windows. speech_segments = [ s for s in raw_speech_segments - if float(s.get("end", 0.0)) - float(s.get("start", 0.0)) > 0.2 + if float(s.get("end", 0.0)) - float(s.get("start", 0.0)) > _MIN_SEGMENT_SECONDS ] # Distribute user-text words across speech segments @@ -1243,9 +1249,21 @@ async def transcribe_audio( mapper already consumes, so nothing downstream has to learn a new shape. """ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename or "audio.ogg").suffix) - content = await file.read() - tmp.write(content) - tmp.close() + # _do_transcribe() unlinks the temp file in its finally — but it only runs if we get that + # far. A client that disconnects mid-upload, or a full disk, raises HERE, and the handler + # exits leaving the file behind. One orphan is nothing; one per failed upload, on a server + # that runs for months, is a disk slowly filling with nothing. + try: + content = await file.read() + tmp.write(content) + tmp.close() + except Exception: + tmp.close() + try: + os.unlink(tmp.name) + except OSError: + pass + raise def _do_transcribe(): try: @@ -1270,11 +1288,19 @@ def _do_transcribe(): normalized_lang if normalized_lang else (transcribed.get("language") or "en").lower() ) - segments = transcribed.get("segments") or [] + # Drop sub-frame segments before aligning, exactly as /align does (and for the same + # reason it documents): wav2vec2 tends to return empty alignments for windows this + # short, so feeding them in produces degraded output instead of no output. Whisper + # emits these on breaths, noise and stem bleed. + segments = [ + s for s in (transcribed.get("segments") or []) + if float(s.get("end", 0.0)) - float(s.get("start", 0.0)) > _MIN_SEGMENT_SECONDS + ] # An instrumental track is not an error. A stem with no singing in it transcribes to - # nothing, and that is the correct answer — returning 400 would make the caller treat - # a successful "this song has no vocals" as a failed request. + # nothing (or to nothing but sub-frame noise), and that is the correct answer — + # returning 400 would make the caller treat a successful "this song has no vocals" + # as a failed request. if not segments: return {"segments": [], "language": detected_lang} diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py index 5c6aff9..aef7405 100644 --- a/tests/test_transcribe_endpoint.py +++ b/tests/test_transcribe_endpoint.py @@ -103,6 +103,13 @@ def fail(msg): if r.status_code != 400: fail("a malformed language code must be a 400, got %s" % r.status_code) +# 2b. The hint is case-insensitive: the server lowercases before validating, and the README now +# says so. "EN" must not be a 400. +_install([{"start": 0.0, "end": 1.0, "text": "hello"}], language="en") +r = client.post("/transcribe", files=AUDIO, data={"language": "EN"}) +if r.status_code != 200: + fail("an uppercase language code must be accepted (it is lowercased), got %s" % r.status_code) + # 3. An instrumental is an ANSWER, not an error: no vocals -> no words, 200. _install([]) r = client.post("/transcribe", files=AUDIO) @@ -111,6 +118,33 @@ def fail(msg): if r.json().get("segments") != []: fail("an instrumental must return an empty segment list") +# 3b. Sub-frame segments are dropped BEFORE alignment, as /align does — wav2vec2 returns empty +# alignments for windows that short, so they degrade the output rather than adding to it. +# A stem of nothing but breaths and bleed is therefore an instrumental, not a bad align. +_captured = {} +def _capture_align(segments, model, meta, audio, device, return_char_alignments=False): + _captured["segments"] = segments + return {"segments": [{"start": 1.0, "end": 2.0, "text": "x", + "words": [{"word": "x", "start": 1.0, "end": 2.0, "score": 0.9}]}]} +_whisperx.align = _capture_align + +_install([ + {"start": 0.00, "end": 0.10, "text": "hm"}, # a breath: below the floor + {"start": 1.00, "end": 2.50, "text": "hello"}, # real singing + {"start": 3.00, "end": 3.05, "text": "s"}, # stem bleed +]) +r = client.post("/transcribe", files=AUDIO) +if r.status_code != 200: + fail("filtered transcribe failed: %s" % r.status_code) +kept = [s["text"] for s in _captured.get("segments", [])] +if kept != ["hello"]: + fail("sub-frame segments must be dropped before alignment, aligner saw %r" % (kept,)) + +_install([{"start": 0.0, "end": 0.1, "text": "hm"}]) # nothing BUT sub-frame noise +r = client.post("/transcribe", files=AUDIO) +if r.status_code != 200 or r.json().get("segments") != []: + fail("a stem of only sub-frame noise is an instrumental, got %s %s" % (r.status_code, r.text[:200])) + # 4. /align still REQUIRES text — that difference is the whole reason /transcribe exists, and # if /align ever stopped 422ing here, the original bug would have become invisible instead # of fixed. @@ -134,6 +168,8 @@ def test_transcribe_accepts_audio_with_no_lyrics(): return if "HARNESS_FAIL:" in result.stdout: pytest.fail(combined) - if "ModuleNotFoundError" in combined: - pytest.skip("a dependency we don't stub is missing:\n" + combined) + # No skip-on-ModuleNotFoundError. Every module this harness needs and does NOT stub — + # fastapi above all — is a hard requirement of server.py, so a missing one means the server + # cannot import, and skipping there would turn "the server is broken" into a green run. The + # heavy ML deps are stubbed precisely so that nothing left over is optional. pytest.fail("harness did not complete:\n" + combined) From d06390891afa8b7bcdff5704761a562e76fe08f3 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 01:47:58 -0400 Subject: [PATCH 3/7] fix: don't warm models in the test harness; don't hand the caller the host's paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TestClient fires FastAPI's startup event, which spawns the warmup thread — model loads and, on a cold cache, multi-GB downloads. In a test whose entire premise is "heavy ML is stubbed", that was the one thing still reaching for the network. skip_warmup is set before the client is built. - /transcribe returned bare str(e) on an unexpected failure, leaking the host's cache path, home directory and container layout to anyone who can reach the endpoint — and this server routinely sits on a LAN. The obvious fix (a flat "internal error") is wrong in the other direction: the caller has no access to these logs, and a message that reaches nobody who can act on it is exactly how the client bug that necessitated this endpoint stayed hidden for so long. So the full traceback goes to the operator's stdout, and the caller gets the exception type and message with absolute paths scrubbed. "CUDA out of memory" survives — it is the answer, and it is not a secret. "/app/cache/models--x/snapshots/…" does not. Found by Copilot on #14. Signed-off-by: topkoa --- server.py | 33 ++++++++++++++++++++++++++++++- tests/test_transcribe_endpoint.py | 24 ++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/server.py b/server.py index dae07fe..f2fab4f 100644 --- a/server.py +++ b/server.py @@ -26,6 +26,7 @@ import subprocess import sys import tempfile +import traceback import threading import time import uuid @@ -89,6 +90,36 @@ def _parse_cache_max_completed_jobs(value: str | None) -> int: # of adding to it. Whisper emits them on breaths, noise and stem bleed. Shared by /align and # /transcribe — the two used to carry the same 0.2 independently, which is how they drift. _MIN_SEGMENT_SECONDS = 0.2 + + +def _client_safe_error(e: Exception, where: str) -> str: + """Log an unexpected exception in full, and return a version fit to hand a caller. + + The tension is real and worth being explicit about. Returning bare ``str(e)`` leaks host + filesystem layout — cache paths, home directory, container internals — to whoever can reach + the endpoint, and this server is routinely exposed on a LAN. But returning a flat "internal + error" throws away the diagnosis, and the caller has no access to these logs: the whole + reason the client bug that necessitated /transcribe stayed hidden for so long is that the + message explaining it never reached anybody who could act on it. + + So: the full traceback goes to the server's stdout, where the operator can see it, and the + caller gets the exception type and message with absolute paths scrubbed. "CUDA out of memory" + survives — it's the answer, and it isn't a secret. "/app/cache/models--foo/snapshots/…" does + not. + """ + traceback.print_exc() + msg = str(e) + for secret, placeholder in ( + (str(CACHE_DIR), ""), + (str(Path.home()), ""), + ): + if secret and secret not in ("/", "\\"): + msg = msg.replace(secret, placeholder) + msg = msg.strip() or e.__class__.__name__ + if len(msg) > 500: + msg = msg[:500] + "…" + print(f"[{where}] ERROR: {e.__class__.__name__}: {e}") + return f"{e.__class__.__name__}: {msg}" CACHE_TTL = os.environ.get("CACHE_TTL", "24h") # Directories under CACHE_DIR that hold model weights (never auto-deleted). # @@ -1319,7 +1350,7 @@ def _do_transcribe(): # mistake from a server fault. return {"error": str(e), "_http_status": 400} except Exception as e: - return {"error": str(e)} + return {"error": _client_safe_error(e, "transcribe")} finally: try: os.unlink(tmp.name) diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py index aef7405..ad0b2ee 100644 --- a/tests/test_transcribe_endpoint.py +++ b/tests/test_transcribe_endpoint.py @@ -69,6 +69,11 @@ def _install(segments, language="en"): server._get_whisperx_aligner = lambda lang: (MagicMock(), MagicMock()) server._whisperx_device = lambda: "cpu" +# TestClient fires FastAPI's startup event, which spawns the warmup thread — i.e. model loads +# and, on a cold cache, multi-GB downloads. In a test whose whole premise is "no heavy ML", that +# would be the one thing still reaching for the network. +server.app.state.skip_warmup = True + client = TestClient(server.app) AUDIO = {"file": ("vocals.ogg", io.BytesIO(b"not really ogg"), "audio/ogg")} @@ -145,6 +150,25 @@ def _capture_align(segments, model, meta, audio, device, return_char_alignments= if r.status_code != 200 or r.json().get("segments") != []: fail("a stem of only sub-frame noise is an instrumental, got %s %s" % (r.status_code, r.text[:200])) +# 3c. An unexpected failure must not hand the caller the host's filesystem layout. This server +# gets exposed on a LAN; the cache path is nobody's business. But the DIAGNOSIS is the +# caller's business — losing it is how the bug this endpoint fixes stayed hidden — so the +# exception type and message survive, minus the paths. +class _Boom: + def transcribe(self, audio, **kw): + raise RuntimeError("CUDA OOM while loading %s/models--x/snapshots/abc/model.bin" + % server.CACHE_DIR) + +server._get_whisperx_model = lambda: _Boom() +r = client.post("/transcribe", files=AUDIO) +if r.status_code != 500: + fail("an unexpected failure should be a 500, got %s" % r.status_code) +err = r.json().get("error", "") +if str(server.CACHE_DIR) in err: + fail("the error leaked the host cache path to the caller: %r" % err) +if "CUDA OOM" not in err or "RuntimeError" not in err: + fail("the diagnosis must survive scrubbing (type + message), got %r" % err) + # 4. /align still REQUIRES text — that difference is the whole reason /transcribe exists, and # if /align ever stopped 422ing here, the original bug would have become invisible instead # of fixed. From 816b8211f899be0b1bb6be2940b66048bc6cf642 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 01:55:36 -0400 Subject: [PATCH 4/7] fix: scrub any absolute path, stream the upload, match the comment to the comparison MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _client_safe_error() promised "absolute paths scrubbed" and scrubbed exactly two roots. A scrubber that only knows about CACHE_DIR and $HOME is one tempfile.gettempdir() away from leaking anyway, and the docstring was writing cheques the code didn't honour. It now scrubs any absolute path, POSIX or Windows — while leaving URLs intact, because "could not reach https://huggingface.co/..." IS the diagnosis for a network failure and mangling it would be its own kind of lost message. Pinned by tests. - The upload was read whole into RAM before a byte reached disk. A lossless 4-minute vocals stem is ~40 MB, MAX_CONCURRENT of those is ~80 MB of pure waste, and nothing stopped a caller uploading 2 GB to see what happened. Streamed in 1 MB chunks. - _MIN_SEGMENT_SECONDS said "shorter than this are dropped" while the filter is a strict `>`, so a segment of exactly 0.2s is dropped too. Comment now matches the comparison. Found by Copilot on #14. Signed-off-by: topkoa --- server.py | 24 +++++++++++++++++++----- tests/test_transcribe_endpoint.py | 10 ++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/server.py b/server.py index f2fab4f..bacc8a4 100644 --- a/server.py +++ b/server.py @@ -85,13 +85,20 @@ def _parse_cache_max_completed_jobs(value: str | None) -> int: )) MAX_CONCURRENT = 2 -# Whisper segments shorter than this are dropped before wav2vec2 alignment: the aligner tends to -# return empty alignments for sub-frame windows, so passing them in degrades the output instead -# of adding to it. Whisper emits them on breaths, noise and stem bleed. Shared by /align and +# A Whisper segment must be LONGER than this to be aligned — the comparison is a strict `>`, so +# a segment of exactly this duration is dropped too. wav2vec2 tends to return empty alignments +# for sub-frame windows, so passing them in degrades the output instead of adding to it, and +# Whisper emits them constantly on breaths, noise and stem bleed. Shared by /align and # /transcribe — the two used to carry the same 0.2 independently, which is how they drift. _MIN_SEGMENT_SECONDS = 0.2 +# Any absolute path: POSIX (/app/cache/...) or Windows (C:\Users\...). The lookbehind keeps +# URLs intact — the "//" in "https://host/x" is not a filesystem path, and mangling it would +# destroy an error that is mostly about which host we failed to reach. +_ABS_PATH_RE = re.compile(r"(? str: """Log an unexpected exception in full, and return a version fit to hand a caller. @@ -109,12 +116,15 @@ def _client_safe_error(e: Exception, where: str) -> str: """ traceback.print_exc() msg = str(e) + # Named roots first, so the common cases read as themselves rather than as . for secret, placeholder in ( (str(CACHE_DIR), ""), (str(Path.home()), ""), ): if secret and secret not in ("/", "\\"): msg = msg.replace(secret, placeholder) + # Then anything else that looks like an absolute path. + msg = _ABS_PATH_RE.sub("", msg) msg = msg.strip() or e.__class__.__name__ if len(msg) > 500: msg = msg[:500] + "…" @@ -1285,8 +1295,12 @@ async def transcribe_audio( # exits leaving the file behind. One orphan is nothing; one per failed upload, on a server # that runs for months, is a disk slowly filling with nothing. try: - content = await file.read() - tmp.write(content) + # Stream it. `await file.read()` pulls the entire stem into RAM before a byte reaches + # disk — a 4-minute lossless vocals stem is ~40 MB, MAX_CONCURRENT of them at once is + # ~80 MB of pure waste, and nothing stops a caller uploading a 2 GB file to find out + # what happens. Chunks cost nothing and cap the exposure. + while chunk := await file.read(1024 * 1024): + tmp.write(chunk) tmp.close() except Exception: tmp.close() diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py index ad0b2ee..1ede96b 100644 --- a/tests/test_transcribe_endpoint.py +++ b/tests/test_transcribe_endpoint.py @@ -169,6 +169,16 @@ def transcribe(self, audio, **kw): if "CUDA OOM" not in err or "RuntimeError" not in err: fail("the diagnosis must survive scrubbing (type + message), got %r" % err) +# 3d. The scrubber must scrub PATHS, not everything path-shaped. A URL is not a filesystem path, +# and mangling one destroys an error that is mostly about which host we could not reach. +_probe = server._ABS_PATH_RE +if _probe.sub("", "Connection refused: https://huggingface.co/api/models/x") != "Connection refused: https://huggingface.co/api/models/x": + fail("the path scrubber ate a URL - that IS the diagnosis for a network failure") +if "" not in _probe.sub("", "PermissionError: /var/lib/secret/thing.bin"): + fail("an absolute path outside CACHE_DIR/home must still be scrubbed") +if _probe.sub("", "failed at 3/4 steps") != "failed at 3/4 steps": + fail("the scrubber mangled ordinary text") + # 4. /align still REQUIRES text — that difference is the whole reason /transcribe exists, and # if /align ever stopped 422ing here, the original bug would have become invisible instead # of fixed. From 1eb3b8ccf64f433a8cd7325a12cacbf21ff59628 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 02:00:23 -0400 Subject: [PATCH 5/7] fix: a blank language hint is no hint, not a bad one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `if language:` is true for " ", which then strips to "" and fails the [a-z]{2,8} pattern — so a request that asked for nothing in particular came back as 400 "Invalid language code: ''". Whitespace is not a language; it is the absence of one. Normalize first, then decide whether a hint was given. /align had the identical bug, so the normalizer is now shared: one _normalized_language() both endpoints call, which is also what stops them drifting apart again. Subtags like `en-US` are still rejected rather than truncated to `en` — silently reinterpreting a request is how you end up aligning Portuguese audio with an English model and wondering why the output is bad. Found by Copilot on #14. Signed-off-by: topkoa --- server.py | 33 ++++++++++++++++++++++--------- tests/test_transcribe_endpoint.py | 20 +++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/server.py b/server.py index bacc8a4..f1f5c8b 100644 --- a/server.py +++ b/server.py @@ -99,6 +99,26 @@ def _parse_cache_max_completed_jobs(value: str | None) -> int: _ABS_PATH_RE = re.compile(r"(? str: + """The caller's language hint, normalized — or "" for no hint at all. + + Normalize BEFORE deciding whether a hint was given. `if language:` is true for `" "`, which + then strips to `""` and fails the pattern, so a blank hint came back as a 400 "invalid + language code" — rejecting a request that asked for nothing in particular. Whitespace is not + a language; it is the absence of one. + + Raises ValueError for a genuinely malformed code (the caller's mistake -> 400). Subtags like + `en-US` are rejected rather than truncated to `en`: silently reinterpreting a request is how + you end up aligning Portuguese audio with an English model and wondering why it's bad. + """ + lang = (language or "").strip().lower() + if not lang: + return "" + if not re.fullmatch(r"[a-z]{2,8}", lang): + raise ValueError(f"Invalid language code: {lang!r}") + return lang + + def _client_safe_error(e: Exception, where: str) -> str: """Log an unexpected exception in full, and return a version fit to hand a caller. @@ -901,10 +921,8 @@ def _do_align(): # speech (no silence misalignment) and short (no OOM). asr_model = _get_whisperx_model() transcribe_kwargs: dict = {"batch_size": 16} - if language: - normalized_lang = language.strip().lower() - if not re.fullmatch(r'[a-z]{2,8}', normalized_lang): - raise ValueError(f"Invalid language code: {normalized_lang!r}") + normalized_lang = _normalized_language(language) + if normalized_lang: transcribe_kwargs["language"] = normalized_lang transcribed = asr_model.transcribe(audio, **transcribe_kwargs) # Caller's explicit hint takes precedence — Whisper's auto- @@ -1318,11 +1336,8 @@ def _do_transcribe(): asr_model = _get_whisperx_model() transcribe_kwargs: dict = {"batch_size": 16} - normalized_lang = "" - if language: - normalized_lang = language.strip().lower() - if not re.fullmatch(r'[a-z]{2,8}', normalized_lang): - raise ValueError(f"Invalid language code: {normalized_lang!r}") + normalized_lang = _normalized_language(language) + if normalized_lang: transcribe_kwargs["language"] = normalized_lang transcribed = asr_model.transcribe(audio, **transcribe_kwargs) diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py index 1ede96b..d081de4 100644 --- a/tests/test_transcribe_endpoint.py +++ b/tests/test_transcribe_endpoint.py @@ -115,6 +115,26 @@ def fail(msg): if r.status_code != 200: fail("an uppercase language code must be accepted (it is lowercased), got %s" % r.status_code) +# 2c. A blank hint is NO hint, not a bad one. `if language:` is true for " ", which then strips +# to "" and fails the pattern — so a request asking for nothing in particular came back as +# 400 "invalid language code". Whitespace is not a language; it is the absence of one. +for blank in ("", " ", " "): + _install([{"start": 0.0, "end": 1.0, "text": "hello"}], language="en") + r = client.post("/transcribe", files=AUDIO, data={"language": blank}) + if r.status_code != 200: + fail("a blank language hint must mean 'no hint', got %s for %r" % (r.status_code, blank)) + +# ...and the normalizer is shared, so /align cannot drift back into the old behaviour. +if server._normalized_language(" ") != "": + fail("whitespace must normalize to no-hint") +if server._normalized_language(" ES ") != "es": + fail("a hint must be trimmed and lowercased") +try: + server._normalized_language("en-US") + fail("a subtag must be rejected, not silently truncated to 'en'") +except ValueError: + pass + # 3. An instrumental is an ANSWER, not an error: no vocals -> no words, 200. _install([]) r = client.post("/transcribe", files=AUDIO) From 2f7bcf4785b275313530361750c834707dc9d643 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 02:10:36 -0400 Subject: [PATCH 6/7] fix: branch on the normalized language, and keep blocking writes off the event loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /align still chose detected_lang with `normalized_lang if language` — the RAW value, which is truthy for " ". So a whitespace hint took the "caller supplied a hint" path with an EMPTY normalized value, and asked _get_whisperx_aligner() for a model in the language named "". I introduced this last round by sharing the normalizer and updating only one of the two call sites. Both branch on the normalized value now. The test I wrote for the blank hint drove /transcribe, which never had the bug — so it passed against the broken code. The new one drives /align, and fails against it ("aligner asked for ''"). - The upload writes ran on the event loop. The heavy transcription is offloaded to an executor, but a chunked write to a slow disk (a NAS, an overloaded container) stalls every other request in the process while one upload dribbles in — including /health, which is what tells a client the server is alive. The careful part was being undone by the careless one. Writes now go through asyncio.to_thread. Found by Copilot on #14. Signed-off-by: topkoa --- server.py | 28 +++++++++++++++-------- tests/test_transcribe_endpoint.py | 37 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/server.py b/server.py index f1f5c8b..d33212c 100644 --- a/server.py +++ b/server.py @@ -932,9 +932,12 @@ def _do_align(): # Use the already-normalised value (strip+lower) when the # caller supplied a language hint, so detected_lang is always # clean before passing to _get_whisperx_aligner(). + # Branch on the NORMALIZED value, not the raw one. `language=" "` is truthy, so the + # raw check took the "caller supplied a hint" path and set detected_lang to "" — + # which then asks _get_whisperx_aligner() for a model in the language named "". + # Whitespace means no hint; fall through to detection. detected_lang = ( - normalized_lang if language - else (transcribed.get("language") or "en").lower() + normalized_lang or (transcribed.get("language") or "en").lower() ) raw_speech_segments = transcribed.get("segments", []) or [] @@ -1312,14 +1315,22 @@ async def transcribe_audio( # far. A client that disconnects mid-upload, or a full disk, raises HERE, and the handler # exits leaving the file behind. One orphan is nothing; one per failed upload, on a server # that runs for months, is a disk slowly filling with nothing. + import asyncio try: - # Stream it. `await file.read()` pulls the entire stem into RAM before a byte reaches - # disk — a 4-minute lossless vocals stem is ~40 MB, MAX_CONCURRENT of them at once is - # ~80 MB of pure waste, and nothing stops a caller uploading a 2 GB file to find out - # what happens. Chunks cost nothing and cap the exposure. + # Stream it, and write OFF the event loop. + # + # `await file.read()` pulls the whole stem into RAM before a byte reaches disk — a + # 4-minute lossless vocals stem is ~40 MB, and nothing stops a caller uploading 2 GB to + # see what happens. Chunks cap that. + # + # But `tmp.write()` is blocking disk I/O, and this handler runs ON the loop: a slow disk + # (a NAS, a spinning volume, an overloaded container) would stall every other request in + # the process while one upload dribbles in — including /health, which is what tells a + # client the server is alive. The heavy transcription is already offloaded; the write + # has to be too, or the careful part is undone by the careless one. while chunk := await file.read(1024 * 1024): - tmp.write(chunk) - tmp.close() + await asyncio.to_thread(tmp.write, chunk) + await asyncio.to_thread(tmp.close) except Exception: tmp.close() try: @@ -1386,7 +1397,6 @@ def _do_transcribe(): except OSError: pass - import asyncio loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, _do_transcribe) diff --git a/tests/test_transcribe_endpoint.py b/tests/test_transcribe_endpoint.py index d081de4..8c3792c 100644 --- a/tests/test_transcribe_endpoint.py +++ b/tests/test_transcribe_endpoint.py @@ -135,6 +135,43 @@ def fail(msg): except ValueError: pass +# 2d. A blank hint must also fall through to DETECTION, not pin the language to "". +# /align branched on the raw `language` (truthy for " ") while normalizing to "" — so a +# whitespace hint set detected_lang="" and then asked for an aligner in the language named +# "". Both endpoints now branch on the normalized value. +_captured_lang = {} +_whisperx.align = lambda segments, model, meta, audio, device, return_char_alignments=False: { + "segments": [{"start": 1.0, "end": 2.0, "text": "hola", + "words": [{"word": "hola", "start": 1.0, "end": 2.0, "score": 0.9}]}] +} +_install([{"start": 0.0, "end": 1.5, "text": "hola"}], language="pt") # what Whisper detects +# AFTER _install, which installs its own aligner stub — this one records what it was asked for. +def _capture_aligner(lang): + _captured_lang["lang"] = lang + return (MagicMock(), MagicMock()) +server._get_whisperx_aligner = _capture_aligner + +r = client.post("/transcribe", files=AUDIO, data={"language": " "}) +if r.status_code != 200: + fail("a whitespace hint must not be an error, got %s" % r.status_code) +if _captured_lang.get("lang") != "pt": + fail("a blank hint must fall through to DETECTION, aligner asked for %r" + % (_captured_lang.get("lang"),)) +if r.json().get("language") != "pt": + fail("the detected language must be reported, got %r" % r.json().get("language")) + +# 2e. The SAME branch in /align — which is where this bug actually lived. It keyed off the raw +# `language` (truthy for " ") while normalizing to "", so a whitespace hint asked +# _get_whisperx_aligner() for a model in the language named "". A test that only drives +# /transcribe cannot see that; this one drives /align. +_captured_lang.clear() +r = client.post("/align", files=AUDIO, data={"text": "hola mundo", "language": " "}) +if r.status_code != 200: + fail("/align with a whitespace hint should still work, got %s: %s" % (r.status_code, r.text[:200])) +if _captured_lang.get("lang") != "pt": + fail("/align: a blank hint must fall through to DETECTION, aligner asked for %r" + % (_captured_lang.get("lang"),)) + # 3. An instrumental is an ANSWER, not an error: no vocals -> no words, 200. _install([]) r = client.post("/transcribe", files=AUDIO) From 5e2ab8c1d75f68d98cfc4569630e920033725be4 Mon Sep 17 00:00:00 2001 From: topkoa Date: Tue, 14 Jul 2026 02:15:08 -0400 Subject: [PATCH 7/7] fix: print the traceback to stdout, as the docstring says MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit traceback.print_exc() defaults to stderr, while the summary line below it goes to stdout — so one error was split across two streams. Under `docker logs` those interleave by arrival, which means the trace and the line naming the failure end up apart, next to unrelated output, in the exact situation where an operator is trying to read them together. Everything else in this server logs with print(), so the traceback follows it. Found by Copilot on #14. Signed-off-by: topkoa --- server.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/server.py b/server.py index d33212c..10ece80 100644 --- a/server.py +++ b/server.py @@ -133,8 +133,14 @@ def _client_safe_error(e: Exception, where: str) -> str: caller gets the exception type and message with absolute paths scrubbed. "CUDA out of memory" survives — it's the answer, and it isn't a secret. "/app/cache/models--foo/snapshots/…" does not. + + The traceback is printed to stdout EXPLICITLY: traceback.print_exc() defaults to stderr, + which would split one error across two streams — the trace on stderr, the summary line below + on stdout — and under `docker logs` those interleave by arrival, so the two halves of the + same failure end up apart, next to unrelated lines. Everything else here logs with print(), + so this follows it. """ - traceback.print_exc() + traceback.print_exc(file=sys.stdout) msg = str(e) # Named roots first, so the common cases read as themselves rather than as . for secret, placeholder in (