Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions backend/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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"),
)
Expand Down Expand Up @@ -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"),
)
Expand Down Expand Up @@ -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=result.get("engine") or cache_engine,
model=config.get("whisper_model", "base"),
language=config.get("language"),
)
Expand Down
5 changes: 3 additions & 2 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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))
Expand Down Expand Up @@ -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,
Expand Down
20 changes: 19 additions & 1 deletion backend/services/transcription.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import http.client
import importlib.util
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import time
Expand Down Expand Up @@ -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):
Expand Down
73 changes: 73 additions & 0 deletions scripts/bench_transcribe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
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 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=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


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:
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")

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())
6 changes: 0 additions & 6 deletions src/services/engine-resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
64 changes: 64 additions & 0 deletions tests/test_cli_transcript_cache_engine.py
Original file line number Diff line number Diff line change
@@ -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()
11 changes: 0 additions & 11 deletions tests/test_transcript_cache_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
10 changes: 5 additions & 5 deletions tests/test_transcript_cache_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
34 changes: 0 additions & 34 deletions tests/test_transcription_engine.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading