diff --git a/README.md b/README.md index 1fb8cf2..c6f6bca 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). 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: + +```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). @@ -368,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 dd6cf58..10ece80 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 @@ -83,6 +84,78 @@ def _parse_cache_max_completed_jobs(value: str | None) -> int: Path.home() / ".cache" / "slopsmith-demucs", )) MAX_CONCURRENT = 2 + +# 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: + """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. + + 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. + + 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(file=sys.stdout) + 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] + "…" + 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). # @@ -854,10 +927,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- @@ -867,9 +938,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 [] @@ -877,7 +951,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 @@ -1217,6 +1291,127 @@ 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) + # _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. + import asyncio + try: + # 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): + await asyncio.to_thread(tmp.write, chunk) + await asyncio.to_thread(tmp.close) + except Exception: + tmp.close() + try: + os.unlink(tmp.name) + except OSError: + pass + raise + + 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 = _normalized_language(language) + if normalized_lang: + 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() + ) + # 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 (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} + + 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": _client_safe_error(e, "transcribe")} + finally: + try: + os.unlink(tmp.name) + except OSError: + pass + + 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..8c3792c --- /dev/null +++ b/tests/test_transcribe_endpoint.py @@ -0,0 +1,266 @@ +"""`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" + +# 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")} + +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) + +# 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) + +# 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 + +# 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) +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") + +# 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])) + +# 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) + +# 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. +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) + # 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)