From ffaa9c1105bca736c794d2350a18709a33d8978c Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Thu, 19 Nov 2026 01:34:14 +0400 Subject: [PATCH 1/2] Read the transcript cache under the engine that will actually run A native install with PODCLI_ENGINE unset falls back to whisper.cpp and saved its transcript under the -whispercpp key, but every lookup used the raw env var and read the whisper-py key, so each run transcribed again. Resolve the engine once with resolve_engine_info and use it for the read, the save, and the engine-agnostic lookups in reel and rank. Default whisper.cpp threads on Apple Silicon to the performance core count, add scripts/bench_transcribe.py to time whisper.cpp against mlx-whisper, and prune cache tests that guarded no behavior. --- backend/cli.py | 22 +++++--- backend/main.py | 5 +- backend/services/transcription.py | 20 ++++++- scripts/bench_transcribe.py | 65 +++++++++++++++++++++++ src/services/engine-resolve.test.ts | 6 --- tests/test_cli_transcript_cache_engine.py | 64 ++++++++++++++++++++++ tests/test_transcript_cache_engine.py | 11 ---- tests/test_transcript_cache_key.py | 10 ++-- tests/test_transcription_engine.py | 34 ------------ tests/test_whisper_threads.py | 64 ++++++++++++++++++++++ 10 files changed, 234 insertions(+), 67 deletions(-) create mode 100644 scripts/bench_transcribe.py create mode 100644 tests/test_cli_transcript_cache_engine.py create mode 100644 tests/test_whisper_threads.py diff --git a/backend/cli.py b/backend/cli.py index 907539d0..79ebaacb 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -182,12 +182,19 @@ def _json_object_arg(raw: str | None, name: str): return parsed +def _transcript_cache_engine(model_size: str | None = None) -> str: + from presets import DEFAULT_PRESET + from services.transcription import resolve_engine_info + + return resolve_engine_info(None, model_size or DEFAULT_PRESET["whisper_model"])["engine"] + + def _cached_transcript(video_path: str) -> dict: """The cached transcript for this video, or {} when there is none.""" try: from services.transcript_packer import load_cached_transcript_for_video - return load_cached_transcript_for_video(video_path) or {} + return load_cached_transcript_for_video(video_path, engine=_transcript_cache_engine()) or {} except Exception: return {} @@ -677,7 +684,7 @@ def _show(session): video = _clean_path(args.video) sid = compute_cache_hash(video) out_dir = args.output or os.path.join(os.getcwd(), f"reel_{sid[:8]}") - cached = load_cached_transcript_for_video(video) + cached = load_cached_transcript_for_video(video, engine=_transcript_cache_engine()) words = cached.get("words") if cached else None print(" Detecting moments (one-time)...") session = seed_session( @@ -1462,12 +1469,14 @@ def cmd_process(args): save_cached_transcript_for_video, ) + cache_engine = _transcript_cache_engine(config.get("whisper_model", "base")) + if skip_transcript: # Reuse an existing transcript so highlight boundaries snap to whole sentences; # only skip transcription outright when there is none (true no-dialogue footage). cached = load_cached_transcript_for_video( video_path, - engine=os.environ.get("PODCLI_ENGINE"), + engine=cache_engine, model=config.get("whisper_model", "base"), language=config.get("language"), ) @@ -1517,7 +1526,7 @@ def cmd_process(args): # different one that happens to share the file. cached = load_cached_transcript_for_video( video_path, - engine=os.environ.get("PODCLI_ENGINE"), + engine=cache_engine, model=config.get("whisper_model", "base"), language=config.get("language"), ) @@ -1589,13 +1598,10 @@ def _transcribe_progress(pct, msg): segments = result["segments"] print(f" Done: {len(segments)} segments, {len(words)} words") - # Save to cache for next run, under the same key the read above - # checked. result["engine"] is what actually ran, which can - # differ from the env var on a fallback (see transcribe_file). save_cached_transcript_for_video( video_path, result, - engine=result.get("engine") or os.environ.get("PODCLI_ENGINE"), + engine=cache_engine, model=config.get("whisper_model", "base"), language=config.get("language"), ) diff --git a/backend/main.py b/backend/main.py index e06bc8f8..4b763795 100644 --- a/backend/main.py +++ b/backend/main.py @@ -536,6 +536,7 @@ def payload(session, reel=None): try: if action == "new": from services.transcript_packer import compute_cache_hash, load_cached_transcript_for_video + import cli as cli_mod video_paths = params.get("video_paths") or [] # Auto lets the saliency threshold decide how many moments clear the bar, # capped for sanity, with a wide length range so windows aren't constrained. @@ -558,7 +559,7 @@ def payload(session, reel=None): video = params["video_path"] sid = compute_cache_hash(video) out_dir = params.get("out_dir") or os.path.join(os.getcwd(), f"reel_{sid[:8]}") - cached = load_cached_transcript_for_video(video) + cached = load_cached_transcript_for_video(video, engine=cli_mod._transcript_cache_engine()) words = cached.get("words") if cached else None session = seed_session(sid, video, out_dir, words=words, **common) reel = build_reel(session, progress_callback=lambda p, m: emit_progress(task_id, "building", p, m)) @@ -819,7 +820,7 @@ def handle_rank_candidates(task_id: str, params: dict): if not video_path: emit_result(task_id, "error", error="video_path or segments is required") return - cached = load_cached_transcript_for_video(video_path) + cached = load_cached_transcript_for_video(video_path, engine=cli_mod._transcript_cache_engine()) if not cached: emit_result( task_id, diff --git a/backend/services/transcription.py b/backend/services/transcription.py index 5bac4e30..7920c0fe 100644 --- a/backend/services/transcription.py +++ b/backend/services/transcription.py @@ -13,7 +13,9 @@ import http.client import importlib.util import os +import platform import shutil +import subprocess import sys import tempfile import time @@ -101,7 +103,23 @@ def _whisper_threads() -> int: n = int(raw) except ValueError: n = 0 - return n if n > 0 else 4 + return n if n > 0 else _default_whisper_threads() + + +def _default_whisper_threads() -> int: + if sys.platform == "darwin" and platform.machine() == "arm64": + try: + out = subprocess.run( + ["sysctl", "-n", "hw.perflevel0.physicalcpu"], + capture_output=True, text=True, timeout=5, check=True, + ).stdout.strip() + perf = int(out) + if perf > 0: + return perf + except (OSError, ValueError, subprocess.SubprocessError): + pass + return os.cpu_count() or 4 + return 4 def _transcribe_with_whispercpp(file_path, model_size, language, progress_callback, wav_path=None): diff --git a/scripts/bench_transcribe.py b/scripts/bench_transcribe.py new file mode 100644 index 00000000..b5d23ebe --- /dev/null +++ b/scripts/bench_transcribe.py @@ -0,0 +1,65 @@ +import argparse +import importlib.util +import os +import sys +import time + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +sys.path.insert(0, os.path.join(ROOT, "backend")) + +from services import transcription as tr + + +def bench_whispercpp(path: str, model: str) -> tuple[float, int]: + started = time.perf_counter() + result = tr._transcribe_with_whispercpp(path, model, None, None) + return time.perf_counter() - started, len(result.get("words") or []) + + +def bench_mlx(path: str, model: str) -> tuple[float, int]: + import mlx_whisper + + started = time.perf_counter() + result = mlx_whisper.transcribe( + path, path_or_hf_repo=f"mlx-community/whisper-{model}-mlx", word_timestamps=True + ) + words = sum(len(seg.get("words") or []) for seg in result.get("segments") or []) + return time.perf_counter() - started, words + + +def main() -> int: + parser = argparse.ArgumentParser(description="Time whisper.cpp and mlx-whisper on one file.") + parser.add_argument("file") + parser.add_argument("--model", default="small") + args = parser.parse_args() + + if not os.path.exists(args.file): + print(f"File not found: {args.file}", file=sys.stderr) + return 1 + + print(f"file: {args.file}") + print(f"model: {args.model}") + print(f"whisper.cpp threads: {tr._whisper_threads()}") + + rows = [] + if tr._whispercpp_ready(args.model): + rows.append(("whisper.cpp", *bench_whispercpp(args.file, args.model))) + else: + print(f"whisper.cpp skipped: binary or ggml-{args.model}.bin not found") + + if importlib.util.find_spec("mlx_whisper") is not None: + rows.append(("mlx-whisper", *bench_mlx(args.file, args.model))) + else: + print("mlx-whisper skipped: pip install mlx-whisper to include it") + + for name, seconds, words in rows: + print(f"{name:<12} {seconds:8.1f}s {words} words") + + times = dict((name, seconds) for name, seconds, _ in rows) + if "whisper.cpp" in times and "mlx-whisper" in times: + print(f"mlx speedup: {times['whisper.cpp'] / times['mlx-whisper']:.2f}x") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/services/engine-resolve.test.ts b/src/services/engine-resolve.test.ts index 554b0a20..e881be9a 100644 --- a/src/services/engine-resolve.test.ts +++ b/src/services/engine-resolve.test.ts @@ -21,12 +21,6 @@ describe("resolveTranscribeEngine", () => { }); }); - it("passes an explicit engine through for the backend to normalize", async () => { - const executor = fakeExecutor({ data: { engine: "assemblyai" } }); - const engine = await resolveTranscribeEngine(executor, "assemblyai", "base"); - expect(engine).toBe("assemblyai"); - }); - it("falls back to the raw request if resolution itself fails", async () => { const executor = failingExecutor(); const engine = await resolveTranscribeEngine(executor, "whisper-py", "base"); diff --git a/tests/test_cli_transcript_cache_engine.py b/tests/test_cli_transcript_cache_engine.py new file mode 100644 index 00000000..61296d7f --- /dev/null +++ b/tests/test_cli_transcript_cache_engine.py @@ -0,0 +1,64 @@ +import os +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BACKEND_ROOT = os.path.join(ROOT, "backend") +if BACKEND_ROOT not in sys.path: + sys.path.insert(0, BACKEND_ROOT) + +import cli +from services import transcript_packer as tp +from services import transcription + + +class NativeInstallCacheRoundTripTests(unittest.TestCase): + def setUp(self): + self._saved_engine = os.environ.pop("PODCLI_ENGINE", None) + self._tmp = tempfile.mkdtemp() + self._orig_dir = tp._transcripts_cache_dir + tp._transcripts_cache_dir = lambda: os.path.join(self._tmp, "transcripts") + self.video = os.path.join(self._tmp, "episode.mp4") + with open(self.video, "wb") as f: + f.write(b"not really a video" * 64) + patches = [ + mock.patch.object(transcription, "_whisper_py_available", return_value=False), + mock.patch.object(transcription, "_whispercpp_ready", return_value=True), + ] + for p in patches: + p.start() + self.addCleanup(p.stop) + + def tearDown(self): + tp._transcripts_cache_dir = self._orig_dir + shutil.rmtree(self._tmp, ignore_errors=True) + os.environ.pop("PODCLI_ENGINE", None) + if self._saved_engine is not None: + os.environ["PODCLI_ENGINE"] = self._saved_engine + + def _transcribed(self): + return {"engine": "whispercpp", "words": [{"word": "hi", "start": 0.0, "end": 0.2}], "segments": [{"text": "hi"}]} + + def test_second_run_hits_the_whispercpp_transcript_the_first_run_saved(self): + for model in ("base", "small"): + with self.subTest(model=model): + tp.save_cached_transcript_for_video(self.video, self._transcribed(), engine="whispercpp", model=model, language=None) + hit = tp.load_cached_transcript_for_video( + self.video, engine=cli._transcript_cache_engine(model), model=model, language=None + ) + self.assertIsNotNone(hit) + + def test_engine_agnostic_lookup_finds_the_whispercpp_transcript(self): + tp.save_cached_transcript_for_video(self.video, self._transcribed(), engine="whispercpp", model="base") + self.assertEqual(cli._cached_transcript(self.video).get("engine"), "whispercpp") + + def test_explicit_engine_is_kept(self): + os.environ["PODCLI_ENGINE"] = "assemblyai" + self.assertEqual(cli._transcript_cache_engine("base"), "assemblyai") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_transcript_cache_engine.py b/tests/test_transcript_cache_engine.py index 13e2820c..7d21d40b 100644 --- a/tests/test_transcript_cache_engine.py +++ b/tests/test_transcript_cache_engine.py @@ -44,17 +44,6 @@ def test_assemblyai_is_namespaced(self): f"engine {v!r} not namespaced", ) - def test_engines_do_not_collide(self): - os.environ.pop("PODCLI_ENGINE", None) - py = tp.transcript_json_path("abc123") - os.environ["PODCLI_ENGINE"] = "whispercpp" - cpp = tp.transcript_json_path("abc123") - os.environ["PODCLI_ENGINE"] = "assemblyai" - aai = tp.transcript_json_path("abc123") - self.assertNotEqual(py, cpp) - self.assertNotEqual(py, aai) - self.assertNotEqual(cpp, aai) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_transcript_cache_key.py b/tests/test_transcript_cache_key.py index 209ccb75..bc914099 100644 --- a/tests/test_transcript_cache_key.py +++ b/tests/test_transcript_cache_key.py @@ -79,29 +79,29 @@ def _touch(self, name, mtime=None): def test_prefers_the_engine_only_key_when_present(self): self._touch("abc123.json") self._touch("abc123-msmall-lka.json") - found = tp.find_cached_transcript_path("abc123", engine=None) + found = tp.find_cached_transcript_path("abc123", engine="whisper-py") self.assertEqual(os.path.basename(found), "abc123.json") def test_falls_back_to_the_most_recently_modified_match(self): self._touch("abc123-msmall.json", mtime=1000) self._touch("abc123-mmedium-lka.json", mtime=2000) - found = tp.find_cached_transcript_path("abc123", engine=None) + found = tp.find_cached_transcript_path("abc123", engine="whisper-py") self.assertEqual(os.path.basename(found), "abc123-mmedium-lka.json") def test_never_crosses_into_a_different_engines_files(self): # Only a whispercpp entry exists; a whisper-py (engine-only) lookup # must not adopt it. self._touch("abc123-whispercpp.json") - found = tp.find_cached_transcript_path("abc123", engine=None) + found = tp.find_cached_transcript_path("abc123", engine="whisper-py") self.assertIsNone(found) def test_matches_only_this_hash_not_a_hash_with_extra_suffix(self): self._touch("abc123extra-msmall.json") - found = tp.find_cached_transcript_path("abc123", engine=None) + found = tp.find_cached_transcript_path("abc123", engine="whisper-py") self.assertIsNone(found) def test_no_matches_returns_none(self): - self.assertIsNone(tp.find_cached_transcript_path("nope", engine=None)) + self.assertIsNone(tp.find_cached_transcript_path("nope", engine="whisper-py")) class LoadSaveCachedTranscriptModelLanguageTests(unittest.TestCase): diff --git a/tests/test_transcription_engine.py b/tests/test_transcription_engine.py index 68cf23aa..14f4acae 100644 --- a/tests/test_transcription_engine.py +++ b/tests/test_transcription_engine.py @@ -1,7 +1,6 @@ """Engine selection: native installs auto-use whisper.cpp when openai-whisper is absent, unless the user explicitly asked for the whisper-py engine.""" -import importlib.util import os import sys import tempfile @@ -391,39 +390,6 @@ def test_transcribe_file_falls_back_to_whispercpp_on_a_load_model_failure(self): result = tr.transcribe_file(self._tmp.name, model_size="base", enable_diarization=False) self.assertEqual(result["engine"], "whispercpp") - def test_resolve_engine_info_cannot_see_this_failure_by_design(self): - # Documents the known, acceptable gap: resolve_engine_info only - # checks the import, so it still predicts whisper-py here even - # though transcribe_file will fall back, a one-time cache miss, - # not a wrong cache write (that's keyed by what actually ran). - self.assertEqual(tr.resolve_engine_info(None, "base")["engine"], "whisper-py") - - -class WhisperPyAvailableMemoizationTests(unittest.TestCase): - """resolve_engine_info runs on every transcribe request. The - availability check behind it has to find_spec (not import, which would - pull in torch) and compute that only once per process.""" - - def setUp(self): - tr._whisper_py_available.cache_clear() - self._orig_find_spec = importlib.util.find_spec - self.calls = 0 - - def counting_find_spec(name, *a, **k): - self.calls += 1 - return self._orig_find_spec(name, *a, **k) - - importlib.util.find_spec = counting_find_spec - - def tearDown(self): - importlib.util.find_spec = self._orig_find_spec - tr._whisper_py_available.cache_clear() - - def test_find_spec_runs_at_most_once_across_repeated_calls(self): - for _ in range(5): - tr._whisper_py_available() - self.assertEqual(self.calls, 1) - class WhisperCppModelAliasTests(unittest.TestCase): """"large" alone doesn't name a real ggml file upstream (v1/v2/v3/v3-turbo diff --git a/tests/test_whisper_threads.py b/tests/test_whisper_threads.py new file mode 100644 index 00000000..2cfe09f9 --- /dev/null +++ b/tests/test_whisper_threads.py @@ -0,0 +1,64 @@ +import os +import subprocess +import sys +import unittest +from unittest import mock + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BACKEND_ROOT = os.path.join(ROOT, "backend") +if BACKEND_ROOT not in sys.path: + sys.path.insert(0, BACKEND_ROOT) + +from services import transcription as tr + + +def _sysctl(stdout): + return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout) + + +class WhisperThreadsTests(unittest.TestCase): + def setUp(self): + self._saved = os.environ.pop("PODCLI_WHISPER_THREADS", None) + + def tearDown(self): + os.environ.pop("PODCLI_WHISPER_THREADS", None) + if self._saved is not None: + os.environ["PODCLI_WHISPER_THREADS"] = self._saved + + def _on(self, platform_name, machine): + p1 = mock.patch.object(tr.sys, "platform", platform_name) + p2 = mock.patch.object(tr.platform, "machine", return_value=machine) + for p in (p1, p2): + p.start() + self.addCleanup(p.stop) + + def test_apple_silicon_uses_the_performance_core_count(self): + self._on("darwin", "arm64") + with mock.patch.object(tr.subprocess, "run", return_value=_sysctl("10\n")): + self.assertEqual(tr._whisper_threads(), 10) + + def test_apple_silicon_falls_back_to_cpu_count_when_sysctl_fails(self): + self._on("darwin", "arm64") + with mock.patch.object(tr.subprocess, "run", side_effect=OSError("no sysctl")), \ + mock.patch.object(tr.os, "cpu_count", return_value=8): + self.assertEqual(tr._whisper_threads(), 8) + + def test_apple_silicon_falls_back_to_4_when_nothing_is_known(self): + self._on("darwin", "arm64") + with mock.patch.object(tr.subprocess, "run", return_value=_sysctl("")), \ + mock.patch.object(tr.os, "cpu_count", return_value=None): + self.assertEqual(tr._whisper_threads(), 4) + + def test_other_platforms_keep_4(self): + self._on("linux", "x86_64") + self.assertEqual(tr._whisper_threads(), 4) + + def test_env_override_wins(self): + self._on("darwin", "arm64") + os.environ["PODCLI_WHISPER_THREADS"] = "3" + with mock.patch.object(tr.subprocess, "run", return_value=_sysctl("10\n")): + self.assertEqual(tr._whisper_threads(), 3) + + +if __name__ == "__main__": + unittest.main() From 69282691590c321122687d6a05e984a698dd0c06 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Thu, 19 Nov 2026 01:52:30 +0400 Subject: [PATCH 2/2] Save the transcript under the engine that ran, and time mlx without its download --- backend/cli.py | 2 +- scripts/bench_transcribe.py | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/backend/cli.py b/backend/cli.py index 79ebaacb..33234e95 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -1601,7 +1601,7 @@ def _transcribe_progress(pct, msg): save_cached_transcript_for_video( video_path, result, - engine=cache_engine, + engine=result.get("engine") or cache_engine, model=config.get("whisper_model", "base"), language=config.get("language"), ) diff --git a/scripts/bench_transcribe.py b/scripts/bench_transcribe.py index b5d23ebe..2b22457b 100644 --- a/scripts/bench_transcribe.py +++ b/scripts/bench_transcribe.py @@ -16,13 +16,19 @@ def bench_whispercpp(path: str, model: str) -> tuple[float, int]: return time.perf_counter() - started, len(result.get("words") or []) -def bench_mlx(path: str, model: str) -> tuple[float, int]: +def prepare_mlx(model: str) -> tuple[str, float]: + from huggingface_hub import snapshot_download + + started = time.perf_counter() + local = snapshot_download(f"mlx-community/whisper-{model}-mlx") + return local, time.perf_counter() - started + + +def bench_mlx(path: str, model_dir: str) -> tuple[float, int]: import mlx_whisper started = time.perf_counter() - result = mlx_whisper.transcribe( - path, path_or_hf_repo=f"mlx-community/whisper-{model}-mlx", word_timestamps=True - ) + result = mlx_whisper.transcribe(path, path_or_hf_repo=model_dir, word_timestamps=True) words = sum(len(seg.get("words") or []) for seg in result.get("segments") or []) return time.perf_counter() - started, words @@ -48,7 +54,9 @@ def main() -> int: print(f"whisper.cpp skipped: binary or ggml-{args.model}.bin not found") if importlib.util.find_spec("mlx_whisper") is not None: - rows.append(("mlx-whisper", *bench_mlx(args.file, args.model))) + model_dir, prepare_seconds = prepare_mlx(args.model) + print(f"mlx-whisper model ready in {prepare_seconds:.1f}s (not counted below)") + rows.append(("mlx-whisper", *bench_mlx(args.file, model_dir))) else: print("mlx-whisper skipped: pip install mlx-whisper to include it")