From 7075696432a528129cb27dd79638d21770ecd29c Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Thu, 19 Nov 2026 01:34:40 +0400 Subject: [PATCH] Default to the small model and give Claude the whole episode Make small the default whisper model in the presets, CLI, MCP schemas, web UI and Go provisioner. When small is missing and base is on disk, fall back to base with one printed line, decided in one place so the cache key and the real run agree. Send the full transcript to Claude in one prompt up to 400000 chars, ask for twice the clips needed and rank them together. When an episode still needs buckets, ask each for the same count and rank globally. Allow 15% slack on the clip length filter instead of dropping clips at the bounds. --- backend/cli.py | 28 ++-- backend/clip_studio.py | 2 +- backend/main.py | 10 +- backend/presets.py | 2 +- backend/services/claude_suggest.py | 47 ++++--- backend/services/engine_comparison.py | 2 +- backend/services/multicam.py | 2 +- backend/services/multicam_cloud.py | 2 +- backend/services/transcription.py | 40 +++++- cli/internal/provision/provision.go | 5 + cli/main.go | 21 ++- cli/main_test.go | 64 ++++++++- src/handlers/compare-engines.handler.ts | 2 +- src/handlers/transcribe.handler.test.ts | 53 +++++++- src/handlers/transcribe.handler.ts | 27 ++-- src/models/index.ts | 1 + src/server.ts | 6 +- src/services/engine-resolve.test.ts | 28 ++-- src/services/engine-resolve.ts | 27 ++-- src/ui/client/EpisodeWorkspace.jsx | 2 +- src/ui/web-server.ts | 11 +- tests/test_ai_fallback.py | 116 ++++++++++++++++- tests/test_claude_suggest_helpers.py | 80 ++++++++++-- tests/test_whisper_model_default.py | 165 ++++++++++++++++++++++++ 24 files changed, 641 insertions(+), 102 deletions(-) create mode 100644 tests/test_whisper_model_default.py diff --git a/backend/cli.py b/backend/cli.py index 33234e95..cf1c828d 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -182,11 +182,15 @@ def _json_object_arg(raw: str | None, name: str): return parsed -def _transcript_cache_engine(model_size: str | None = None) -> str: +def _transcript_cache_key(model_size: str | None = None) -> dict: 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"] + return resolve_engine_info(None, model_size or DEFAULT_PRESET["whisper_model"]) + + +def _transcript_cache_engine(model_size: str | None = None) -> str: + return _transcript_cache_key(model_size)["engine"] def _cached_transcript(video_path: str) -> dict: @@ -1469,15 +1473,15 @@ def cmd_process(args): save_cached_transcript_for_video, ) - cache_engine = _transcript_cache_engine(config.get("whisper_model", "base")) + cache_key = _transcript_cache_key(config.get("whisper_model", "small")) 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=cache_engine, - model=config.get("whisper_model", "base"), + engine=cache_key["engine"], + model=cache_key["model_size"], language=config.get("language"), ) if cached and not config.get("no_cache", False): @@ -1526,8 +1530,8 @@ def cmd_process(args): # different one that happens to share the file. cached = load_cached_transcript_for_video( video_path, - engine=cache_engine, - model=config.get("whisper_model", "base"), + engine=cache_key["engine"], + model=cache_key["model_size"], language=config.get("language"), ) if cached and not config.get("no_cache", False): @@ -1578,7 +1582,7 @@ def _transcribe_progress(pct, msg): # and AssemblyAI decode the source themselves). result = transcribe_file( file_path=video_path, - model_size=config.get("whisper_model", "base"), + model_size=config.get("whisper_model", "small"), engine=os.environ.get("PODCLI_ENGINE") or None, language=config.get("language") or None, enable_diarization=not config.get("no_speakers", False), @@ -1601,8 +1605,8 @@ def _transcribe_progress(pct, msg): save_cached_transcript_for_video( video_path, result, - engine=result.get("engine") or cache_engine, - model=config.get("whisper_model", "base"), + engine=result.get("engine") or cache_key["engine"], + model=result.get("model_size") or cache_key["model_size"], language=config.get("language"), ) @@ -5409,7 +5413,7 @@ def main(): help="Also build small playback proxies of each camera and a mic mix on the timeline") mc_p.add_argument("--transcript", action="store_true", help="Transcribe the episode with each word credited to whoever's mic was speaking") - mc_p.add_argument("--model", default="base", help="Whisper model for --transcript (default base)") + mc_p.add_argument("--model", default="small", help="Whisper model for --transcript (default small)") mc_p.add_argument("--engine", choices=["whisper-py", "whispercpp", "assemblyai", "omnilingual"], help="Transcription engine for --transcript (default: the one podcli is set up with)") mc_p.add_argument("--activity", action="store_true", help="Report who speaks when (talk time, or spans with --json)") @@ -5750,7 +5754,7 @@ def main(): cmp_p.add_argument("--start", type=float, default=0.0, help="Sample start, seconds into the source (default: 0)") cmp_p.add_argument("--duration", type=float, default=120.0, help="Sample length in seconds (default: 120)") cmp_p.add_argument("--window", type=float, default=20.0, help="Report window size in seconds (default: 20)") - cmp_p.add_argument("--model-size", default="base", help="Model size for engines that take one (default: base)") + cmp_p.add_argument("--model-size", default="small", help="Model size for engines that take one (default: small)") cmp_p.add_argument("--language", help="ISO language code. Auto-detect if omitted.") cmp_p.add_argument("-o", "--output", default="./engine-comparison", help="Output directory for comparison.json/.html") diff --git a/backend/clip_studio.py b/backend/clip_studio.py index 981395ae..b1a0b896 100644 --- a/backend/clip_studio.py +++ b/backend/clip_studio.py @@ -89,7 +89,7 @@ def _transcribe(video: str, language: str | None, engine: str | None): label = "AssemblyAI" if is_assemblyai_engine(engine or os.environ.get("PODCLI_ENGINE", "")) else "Whisper" print(f" [transcribe] running {label}...", flush=True) res = transcribe_file( - file_path=video, model_size="base", engine=engine, language=language, + file_path=video, model_size="small", engine=engine, language=language, enable_diarization=False, progress_callback=lambda p, m: print(f" {p}% {m}", flush=True), ) diff --git a/backend/main.py b/backend/main.py index 4b763795..931616c6 100644 --- a/backend/main.py +++ b/backend/main.py @@ -76,7 +76,7 @@ def handle_resolve_transcribe_engine(task_id: str, params: dict): emit_result( task_id, "success", - data=resolve_engine_info(params.get("engine"), params.get("model_size", "base")), + data=resolve_engine_info(params.get("engine"), params.get("model_size", "small")), ) @@ -89,7 +89,7 @@ def handle_transcribe(task_id: str, params: dict): emit_progress(task_id, "transcribing", 0, "Starting transcription...") file_path = params["file_path"] engine = params.get("engine") - model_size = params.get("model_size", "base") + model_size = params.get("model_size", "small") language = params.get("language") previous_engine = os.environ.get("PODCLI_ENGINE") previous_assemblyai_key = os.environ.get("ASSEMBLYAI_API_KEY") @@ -122,7 +122,7 @@ def handle_transcribe(task_id: str, params: dict): try: result = transcribe_file( file_path=file_path, - model_size=params.get("model_size", "base"), + model_size=params.get("model_size", "small"), engine=engine, language=params.get("language"), enable_diarization=params.get("enable_diarization", True), @@ -163,7 +163,7 @@ def handle_transcribe(task_id: str, params: dict): # Pulls energy data so the packed view includes peak moments for clip reasoning. try: cache_hash = compute_cache_hash(file_path) + cache_key_suffix( - engine=result.get("engine") or engine, model=model_size, language=language + engine=result.get("engine") or engine, model=result.get("model_size") or model_size, language=language ) packed_path, packed_md = write_packed( result, @@ -1150,7 +1150,7 @@ def handle_compare_engines(task_id: str, params: dict): start_seconds=params.get("start_seconds", 0.0) or 0.0, duration_seconds=params.get("duration_seconds", 120.0) or 120.0, window_seconds=params.get("window_seconds", 20.0) or 20.0, - model_size=params.get("model_size", "base"), + model_size=params.get("model_size", "small"), language=params.get("language"), output_dir=output_dir, ) diff --git a/backend/presets.py b/backend/presets.py index 9dc26613..9d092725 100644 --- a/backend/presets.py +++ b/backend/presets.py @@ -37,7 +37,7 @@ "video_path": "", "transcript_path": "", "output_dir": "", - "whisper_model": "base", + "whisper_model": "small", "top_clips": 5, "max_clip_duration": MAX_CLIP_DURATION, "min_clip_duration": MIN_CLIP_DURATION, diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.py index 5a0fb01e..75df8573 100644 --- a/backend/services/claude_suggest.py +++ b/backend/services/claude_suggest.py @@ -108,6 +108,9 @@ def _load_existing_shorts(episodes_path: str) -> list[str]: return shorts +DURATION_SLACK = 0.15 + + # (filename, max_chars) that reach the selection prompt, highest priority first. # Shared with kb_signature so the suggestion cache and the prompt cannot drift. class ClipBounds: @@ -141,6 +144,9 @@ def of(cls, fmt=None, dur_min=None, dur_max=None) -> "ClipBounds": def keeps(self, seconds: float) -> bool: return self.dur_min <= seconds <= self.dur_max + def keeps_with_slack(self, seconds: float, slack: float = DURATION_SLACK) -> bool: + return self.dur_min * (1 - slack) <= seconds <= self.dur_max * (1 + slack) + KB_FILES = [ ("04-shorts-creation-guide.md", 4000), # moment selection criteria, content types @@ -225,6 +231,11 @@ def _sample_transcript(transcript_text: str, limit: int = CODEX_TRANSCRIPT_LIMIT # truncation would have thrown away. if lines[-1] not in sampled[-1:]: sampled.append(lines[-1]) + print( + f"Codex transcript sampled: dropped {len(lines) - len(sampled)} of {len(lines)} lines", + file=sys.stderr, + flush=True, + ) return "\n".join(sampled) @@ -483,6 +494,10 @@ def _split_prompt_for_cache(prompt: str, transcript_text: str) -> tuple[str, str return transcript_text, prompt[: -len(marker)] +FULL_PROMPT_CHAR_BUDGET = 400000 +CANDIDATE_OVERSAMPLE = 2 + + def _build_transcript_text(segments: list[dict]) -> str: """Serialize transcript segments into the prompt-friendly text format.""" lines = [] @@ -505,22 +520,15 @@ def _segments_duration_seconds(segments: list[dict]) -> float: def _should_bucket_initial_selection(segments: list[dict]) -> bool: """ - Use bucketed AI search for long or dense transcripts. + Bucket the search only when the transcript text is too big for one prompt. - This keeps initial clip discovery from spending many minutes on a single - whole-episode prompt for long podcasts. + A single prompt lets the model compare moments across the whole episode, + so buckets are the fallback for transcripts past FULL_PROMPT_CHAR_BUDGET. """ if not segments: return False - duration_seconds = _segments_duration_seconds(segments) - transcript_chars = sum(len(str(seg.get("text", ""))) for seg in segments) - - return bool( - duration_seconds >= 45 * 60 - or len(segments) >= 180 - or transcript_chars >= 18000 - ) + return len(_build_transcript_text(segments)) > FULL_PROMPT_CHAR_BUDGET def _dedupe_clips_by_range(clips: list[dict]) -> list[dict]: @@ -898,7 +906,7 @@ def records(payload: object) -> list[dict]: keep_segments = [{"start": start_sec, "end": end_sec}] kept_duration = sum(seg["end"] - seg["start"] for seg in keep_segments) - if not bounds.keeps(kept_duration): + if not bounds.keeps_with_slack(kept_duration): continue clip_start = keep_segments[0]["start"] if keep_segments else start_sec @@ -959,15 +967,17 @@ def suggest_initial_with_claude( """ Initial clip discovery entry point. - For long podcasts, search transcript buckets first so the AI can return - quickly and cover the full timeline instead of timing out on one giant - prompt. + The whole transcript goes in one prompt when it fits FULL_PROMPT_CHAR_BUDGET, + and the model is asked for twice as many candidates as needed so the final + cut ranks them against each other. Past the budget, every timeline bucket + is asked for the same number of candidates and one global ranking picks the + winners. """ exclude_clips = exclude_clips or [] if not _should_bucket_initial_selection(segments): - return suggest_with_claude( + candidates = suggest_with_claude( segments=segments, - top_n=top_n, + top_n=top_n * CANDIDATE_OVERSAMPLE, exclude_clips=exclude_clips, progress_callback=progress_callback, error_sink=error_sink, @@ -975,6 +985,7 @@ def suggest_initial_with_claude( reaction_times=reaction_times, bounds=bounds, ) + return _select_top_by_score(candidates, top_n) if candidates else None start_bound = float(segments[0].get("start", 0)) end_bound = float(segments[-1].get("end", segments[-1].get("start", 0))) @@ -1013,7 +1024,7 @@ def suggest_initial_with_claude( progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets...") aggregated: list[dict] = [] - per_bucket_top_n = max(2, math.ceil(top_n / max(1, len(buckets)))) + per_bucket_top_n = max(2, top_n) for idx, bucket in enumerate(buckets): bucket_label = ( diff --git a/backend/services/engine_comparison.py b/backend/services/engine_comparison.py index 8429d40f..508d3036 100644 --- a/backend/services/engine_comparison.py +++ b/backend/services/engine_comparison.py @@ -117,7 +117,7 @@ def compare_engines( start_seconds: float = 0.0, duration_seconds: Optional[float] = None, window_seconds: float = 20.0, - model_size: str = "base", + model_size: str = "small", language: Optional[str] = None, output_dir: Optional[str] = None, transcribe_fn=None, diff --git a/backend/services/multicam.py b/backend/services/multicam.py index 2273805d..cf9ef3eb 100644 --- a/backend/services/multicam.py +++ b/backend/services/multicam.py @@ -1878,7 +1878,7 @@ def build_preview(session: MulticamSession, progress_callback: ProgressCallback return latest -def transcript(session: MulticamSession, *, model_size: str = "base", engine: Optional[str] = None, +def transcript(session: MulticamSession, *, model_size: str = "small", engine: Optional[str] = None, language: Optional[str] = None, progress_callback: ProgressCallback = None) -> dict: """Words on the timeline, each credited to the person who said it. diff --git a/backend/services/multicam_cloud.py b/backend/services/multicam_cloud.py index ed0a1ab8..0f876e60 100644 --- a/backend/services/multicam_cloud.py +++ b/backend/services/multicam_cloud.py @@ -67,7 +67,7 @@ def _request(method: str, path: str, body: Optional[dict] = None) -> dict: raise MulticamCloudError(str(exc)) from None -def push(session: mc.MulticamSession, *, model_size: str = "base", engine: Optional[str] = None, +def push(session: mc.MulticamSession, *, model_size: str = "small", engine: Optional[str] = None, progress_callback: ProgressCallback = None) -> mc.MulticamSession: """Builds what the editor plays, sends it, and remembers which cloud edit this session became.""" if not podcli_cloud.signed_in(): diff --git a/backend/services/transcription.py b/backend/services/transcription.py index 7920c0fe..1c55cb9d 100644 --- a/backend/services/transcription.py +++ b/backend/services/transcription.py @@ -58,6 +58,9 @@ def _whispercpp_cli() -> Optional[str]: # builds); provisioning always fetches large-v3, so resolve the same way here. _WHISPERCPP_MODEL_ALIASES = {"large": "large-v3"} +DEFAULT_MODEL_SIZE = "small" +FALLBACK_MODEL_SIZE = "base" + def _whispercpp_model(model_size: str) -> str: resolved = _WHISPERCPP_MODEL_ALIASES.get(model_size, model_size) @@ -66,8 +69,20 @@ def _whispercpp_model(model_size: str) -> str: ) +def resolve_whispercpp_model_size(model_size: str) -> str: + if ( + model_size == DEFAULT_MODEL_SIZE + and not os.path.exists(_whispercpp_model(DEFAULT_MODEL_SIZE)) + and os.path.exists(_whispercpp_model(FALLBACK_MODEL_SIZE)) + ): + return FALLBACK_MODEL_SIZE + return model_size + + def _whispercpp_ready(model_size: str) -> bool: - return _whispercpp_cli() is not None and os.path.exists(_whispercpp_model(model_size)) + return _whispercpp_cli() is not None and os.path.exists( + _whispercpp_model(resolve_whispercpp_model_size(model_size)) + ) def _omnilingual_model() -> str: @@ -125,6 +140,16 @@ def _default_whisper_threads() -> int: def _transcribe_with_whispercpp(file_path, model_size, language, progress_callback, wav_path=None): from services import transcription_whispercpp as wcpp + requested_size = model_size + model_size = resolve_whispercpp_model_size(model_size) + if model_size != requested_size: + print( + f"Whisper model '{requested_size}' is not installed, using '{model_size}' instead. " + f"Run `podcli setup --model {requested_size}` to download it.", + file=sys.stderr, + flush=True, + ) + if progress_callback: progress_callback(10, "Transcribing with whisper.cpp...") @@ -684,7 +709,7 @@ def _resolve_whisper_py_fallback(requested: Optional[str], model_size: str, prob return False, None, e -def resolve_engine_info(requested: Optional[str], model_size: str = "base") -> dict: +def resolve_engine_info(requested: Optional[str], model_size: str = DEFAULT_MODEL_SIZE) -> dict: """Predict which engine transcribe_file will actually use, without doing any transcription work. Callers cache transcripts by engine; the cache key has to match what transcribe_file resolves to, not the raw request, @@ -692,15 +717,19 @@ def resolve_engine_info(requested: Optional[str], model_size: str = "base") -> d """ requested = requested if requested is not None else os.environ.get("PODCLI_ENGINE", "") engine = normalize_engine(requested) + if engine == "whispercpp": + return {"engine": engine, "model_size": resolve_whispercpp_model_size(model_size)} if engine != "whisper-py": return {"engine": engine, "model_size": model_size} fall_back, _model, _error = _resolve_whisper_py_fallback(requested, model_size, probe_model=False) - return {"engine": "whispercpp" if fall_back else "whisper-py", "model_size": model_size} + if fall_back: + return {"engine": "whispercpp", "model_size": resolve_whispercpp_model_size(model_size)} + return {"engine": "whisper-py", "model_size": model_size} def transcribe_file( file_path: str, - model_size: str = "base", + model_size: str = DEFAULT_MODEL_SIZE, engine: Optional[str] = None, language: Optional[str] = None, enable_diarization: bool = True, @@ -786,7 +815,7 @@ def transcribe_file( def _transcribe_file_inner( file_path: str, - model_size: str = "base", + model_size: str = DEFAULT_MODEL_SIZE, engine: Optional[str] = None, language: Optional[str] = None, enable_diarization: bool = True, @@ -844,6 +873,7 @@ def _transcribe_file_inner( file_path, model_size, language, progress_callback, wav_path=wav_path ) base["engine"] = "whispercpp" + base["model_size"] = resolve_whispercpp_model_size(model_size) # whisper.cpp is the no-torch path: importing torch for diarization can # hard-crash native runtimes. Skip diarization, keep face analysis (OpenCV). # Never possible on this engine, see the omnilingual branch above. diff --git a/cli/internal/provision/provision.go b/cli/internal/provision/provision.go index 8b6ab9d1..15560f5b 100644 --- a/cli/internal/provision/provision.go +++ b/cli/internal/provision/provision.go @@ -44,6 +44,11 @@ func whisperCppURL(file string) string { return "https://huggingface.co/ggerganov/whisper.cpp/resolve/" + whisperCppRevision + "/" + file } +const ( + DefaultModelSize = "small" + FallbackModelSize = "base" +) + var models = map[string]model{ "base": { URL: whisperCppURL("ggml-base.bin"), diff --git a/cli/main.go b/cli/main.go index 4ba4ea8e..d308cd56 100644 --- a/cli/main.go +++ b/cli/main.go @@ -232,7 +232,7 @@ func runEngine(args []string) int { if !helpOrVersion { switch transcribeEngine(args) { case "whispercpp": - model, err := provision.EnsureModel(transcribeModel(args)) + model, err := ensureModelWithFallback(transcribeModel(args), provision.EnsureModel) if err != nil { fmt.Fprintln(os.Stderr, "podcli: provisioning model:", err) return 1 @@ -282,6 +282,19 @@ func hasFlag(args []string, names ...string) bool { return false } +func ensureModelWithFallback(size string, ensure func(string) (string, error)) (string, error) { + path, err := ensure(size) + if err == nil || size != provision.DefaultModelSize { + return path, err + } + fallback := provision.ModelPath(provision.FallbackModelSize) + if _, statErr := os.Stat(fallback); statErr != nil { + return "", err + } + fmt.Fprintf(os.Stderr, "podcli: model %q unavailable (%v), using %q instead\n", size, err, provision.FallbackModelSize) + return fallback, nil +} + func transcribeModel(args []string) string { fast := false for _, arg := range args { @@ -291,7 +304,7 @@ func transcribeModel(args []string) string { } } if !fast { - return "base" + return provision.DefaultModelSize } // tiny.en is English-only; unset language runs auto-detection, which // needs the multilingual tiny model same as any non-English request. @@ -374,7 +387,7 @@ func transcribeEngine(args []string) string { } func setup(args []string) int { - size := "base" + size := provision.DefaultModelSize vad := false speakers := false refresh := false @@ -1206,7 +1219,7 @@ Launcher commands: version Print version update Check for and apply a newer release uninstall Remove podcli app files (keeps user data unless --purge) - setup [--model base] [--vad] [--speakers] + setup [--model small] [--vad] [--speakers] Provision runtimes + models (--speakers adds openai-whisper, pyannote, torch, ~2GB) setup --refresh Re-provision runtimes for this launcher version, skipping models mcp Run the MCP server (stdio) for Claude/Codex diff --git a/cli/main_test.go b/cli/main_test.go index 3ba89c8c..08723388 100644 --- a/cli/main_test.go +++ b/cli/main_test.go @@ -1,9 +1,12 @@ package main import ( + "errors" "os" "path/filepath" "testing" + + "podcli/internal/provision" ) func TestIsMetaFlag(t *testing.T) { @@ -60,8 +63,8 @@ func TestHasFlag(t *testing.T) { } func TestTranscribeModel(t *testing.T) { - if got := transcribeModel([]string{"process", "episode.mp4"}); got != "base" { - t.Fatalf("default model = %q, want base", got) + if got := transcribeModel([]string{"process", "episode.mp4"}); got != "small" { + t.Fatalf("default model = %q, want small", got) } if got := transcribeModel([]string{"process", "episode.mp4", "--fast"}); got != "tiny" { t.Fatalf("fast model with unset language = %q, want tiny (multilingual, no language conditioning)", got) @@ -77,6 +80,63 @@ func TestTranscribeModel(t *testing.T) { } } +func TestEnsureModelWithFallbackUsesBaseWhenSmallFails(t *testing.T) { + home := t.TempDir() + old, hadOld := os.LookupEnv("PODCLI_HOME") + os.Setenv("PODCLI_HOME", home) + t.Cleanup(func() { + if hadOld { + os.Setenv("PODCLI_HOME", old) + } else { + os.Unsetenv("PODCLI_HOME") + } + }) + basePath := provision.ModelPath("base") + if err := os.MkdirAll(filepath.Dir(basePath), 0o755); err != nil { + t.Fatalf("mkdir models dir: %v", err) + } + if err := os.WriteFile(basePath, []byte("base bytes"), 0o644); err != nil { + t.Fatalf("seed base model: %v", err) + } + failing := func(string) (string, error) { return "", errors.New("offline") } + + got, err := ensureModelWithFallback("small", failing) + if err != nil { + t.Fatalf("expected a fallback to base, got error %v", err) + } + if got != basePath { + t.Fatalf("fallback path = %q, want %q", got, basePath) + } + if _, err := ensureModelWithFallback("medium", failing); err == nil { + t.Fatal("a non-default model must not fall back to base") + } +} + +func TestEnsureModelWithFallbackFailsWhenBaseIsMissing(t *testing.T) { + home := t.TempDir() + old, hadOld := os.LookupEnv("PODCLI_HOME") + os.Setenv("PODCLI_HOME", home) + t.Cleanup(func() { + if hadOld { + os.Setenv("PODCLI_HOME", old) + } else { + os.Unsetenv("PODCLI_HOME") + } + }) + failing := func(string) (string, error) { return "", errors.New("offline") } + if _, err := ensureModelWithFallback("small", failing); err == nil { + t.Fatal("expected the original error when base is not installed") + } +} + +func TestEnsureModelWithFallbackPassesThroughSuccess(t *testing.T) { + ok := func(size string) (string, error) { return "/models/ggml-" + size + ".bin", nil } + got, err := ensureModelWithFallback("small", ok) + if err != nil || got != "/models/ggml-small.bin" { + t.Fatalf("got %q, %v", got, err) + } +} + func TestTranscribeEngineAssemblyAI(t *testing.T) { old, ok := os.LookupEnv("PODCLI_ENGINE") t.Cleanup(func() { diff --git a/src/handlers/compare-engines.handler.ts b/src/handlers/compare-engines.handler.ts index 2cf82624..932d5256 100644 --- a/src/handlers/compare-engines.handler.ts +++ b/src/handlers/compare-engines.handler.ts @@ -51,7 +51,7 @@ export const compareEnginesToolDef = { model_size: { type: "string", enum: ["tiny", "base", "small", "medium", "large"], - description: "Model size for engines that take one. Default: base.", + description: "Model size for engines that take one. Default: small.", }, language: { type: "string", diff --git a/src/handlers/transcribe.handler.test.ts b/src/handlers/transcribe.handler.test.ts index 07f9a98e..813dbc25 100644 --- a/src/handlers/transcribe.handler.test.ts +++ b/src/handlers/transcribe.handler.test.ts @@ -15,7 +15,7 @@ const deps: TranscribeDeps = { getPackedMarkdown: cacheGetPackedMock, getFileHashForEngine: cacheGetHashForEngineMock, }, - resolveEngine: async () => "whispercpp", + resolveEngine: async () => ({ engine: "whispercpp", model: "small" }), }; describe("handleTranscribe, sample mode", () => { @@ -109,4 +109,55 @@ describe("handleTranscribe, sample mode", () => { expect(cacheGetMock).toHaveBeenCalled(); expect(cacheSetMock).toHaveBeenCalled(); }); + + it("keys the cache by the model the backend says it will run, not the request default", async () => { + cacheGetMock.mockResolvedValue(null); + executeMock.mockResolvedValue({ + data: { transcript: "hi", segments: [], words: [], duration: 400, language: "en", engine: "whispercpp" }, + }); + cacheGetPackedMock.mockResolvedValue("# packed"); + + const baseOnlyDeps: TranscribeDeps = { + ...deps, + resolveEngine: async () => ({ engine: "whispercpp", model: "base" }), + }; + + await handleTranscribe({ file_path: "/video.mp4" }, baseOnlyDeps); + + expect(cacheGetMock).toHaveBeenCalledWith("/video.mp4", { + engine: "whispercpp", + model: "base", + language: undefined, + }); + expect(executeMock).toHaveBeenCalledWith("transcribe", expect.objectContaining({ model_size: "small" })); + expect(cacheSetMock).toHaveBeenCalledWith("/video.mp4", expect.anything(), { + engine: "whispercpp", + model: "base", + language: undefined, + }); + }); + + it("caches under the model the transcript reports it ran with", async () => { + cacheGetMock.mockResolvedValue(null); + executeMock.mockResolvedValue({ + data: { + transcript: "hi", + segments: [], + words: [], + duration: 400, + language: "en", + engine: "whispercpp", + model_size: "base", + }, + }); + cacheGetPackedMock.mockResolvedValue("# packed"); + + await handleTranscribe({ file_path: "/video.mp4" }, deps); + + expect(cacheSetMock).toHaveBeenCalledWith("/video.mp4", expect.anything(), { + engine: "whispercpp", + model: "base", + language: undefined, + }); + }); }); diff --git a/src/handlers/transcribe.handler.ts b/src/handlers/transcribe.handler.ts index dd80d583..7a7c3f22 100644 --- a/src/handlers/transcribe.handler.ts +++ b/src/handlers/transcribe.handler.ts @@ -3,7 +3,7 @@ import { randomUUID } from "crypto"; import { z } from "zod"; import { PythonExecutor, type TaskExecutor } from "../services/python-executor.js"; import { TranscriptCache, needsDiarizationRetry } from "../services/transcript-cache.js"; -import { resolveTranscribeEngine, engineCanDiarize } from "../services/engine-resolve.js"; +import { resolveTranscribeInfo, engineCanDiarize } from "../services/engine-resolve.js"; import { webServerUrl } from "../config/server.js"; import type { TranscriptResult } from "../models/index.js"; @@ -25,10 +25,10 @@ const cache = new TranscriptCache(); export interface TranscribeDeps { executor: TaskExecutor; cache: Pick; - resolveEngine: typeof resolveTranscribeEngine; + resolveEngine: typeof resolveTranscribeInfo; } -const defaultDeps: TranscribeDeps = { executor, cache, resolveEngine: resolveTranscribeEngine }; +const defaultDeps: TranscribeDeps = { executor, cache, resolveEngine: resolveTranscribeInfo }; export interface TranscribeInput { file_path: string; @@ -69,7 +69,7 @@ export const transcribeToolDef = { enum: ["tiny", "base", "small", "medium", "large"], description: "Whisper model size. tiny=fastest, large=most accurate. Default: base", - default: "base", + default: "small", }, language: { type: "string", @@ -116,7 +116,7 @@ export async function handleTranscribe( { executor, cache, resolveEngine }: TranscribeDeps = defaultDeps, ): Promise { const filePath = input.file_path; - const modelSize = input.model_size ?? "base"; + const modelSize = input.model_size ?? "small"; const engine = input.engine; const language = input.language; const enableDiarization = input.enable_diarization !== false; @@ -131,8 +131,9 @@ export async function handleTranscribe( // Resolve before reading the cache: an unset engine is written under // whatever transcribe_file actually ran (e.g. "whispercpp" on a native // install), so reading with the raw unset request always misses. - const resolvedEngine = await resolveEngine(executor, engine, modelSize); - const cacheKey = { engine: resolvedEngine, model: modelSize, language }; + const resolved = await resolveEngine(executor, engine, modelSize); + const resolvedEngine = resolved.engine; + const cacheKey = { engine: resolvedEngine, model: resolved.model, language }; // A sample is a throwaway check on a slice of the file. It must never // serve (or pollute) the main transcript cache, which is keyed by the @@ -147,7 +148,7 @@ export async function handleTranscribe( // Same combo cache.get(filePath, cacheKey) just matched: the packed // view has to be keyed identically, or a backfill here would write it // under a key the next read for this same request won't find. - const packedKey = { engine: cached.engine ?? resolvedEngine, model: modelSize, language }; + const packedKey = { engine: cached.engine ?? resolvedEngine, model: resolved.model, language }; // Backfill packed view if this cache predates auto-packing. let packed = await cache.getPackedMarkdown(filePath, packedKey); @@ -197,7 +198,11 @@ export async function handleTranscribe( // Cache the raw result under what it actually ran with, not the prediction // above: resolveTranscribeEngine can't see a model-load failure that only // shows up once transcribe_file tries it for real. - await cache.set(filePath, data, { engine: actualEngine, model: modelSize, language }); + await cache.set(filePath, data, { + engine: actualEngine, + model: data.model_size ?? resolved.model, + language, + }); const packed = await cache.getPackedMarkdown(filePath, { engine: actualEngine, model: modelSize, language }); return JSON.stringify({ cached: false, packed_ready: !!packed, ...formatResult(data) }); @@ -262,7 +267,7 @@ export const transcribeStartToolDef = { model_size: { type: "string", enum: ["tiny", "base", "small", "medium", "large"], - default: "base", + default: "small", }, language: { type: "string" }, engine: { @@ -293,7 +298,7 @@ export async function handleTranscribeStart(input: TranscribeInput): Promise { +describe("resolveTranscribeInfo", () => { it("returns what the backend predicts it will resolve to", async () => { - const executor = fakeExecutor({ data: { engine: "whispercpp" } }); - const engine = await resolveTranscribeEngine(executor, undefined, "base"); - expect(engine).toBe("whispercpp"); + const executor = fakeExecutor({ data: { engine: "whispercpp", model_size: "base" } }); + const info = await resolveTranscribeInfo(executor, undefined, "small"); + expect(info).toEqual({ engine: "whispercpp", model: "base" }); expect(executor.execute).toHaveBeenCalledWith("resolve_transcribe_engine", { engine: undefined, - model_size: "base", + model_size: "small", }); }); + it("keeps the requested model when the backend omits model_size", async () => { + const executor = fakeExecutor({ data: { engine: "whispercpp" } }); + const info = await resolveTranscribeInfo(executor, undefined, "medium"); + expect(info.model).toBe("medium"); + }); + it("falls back to the raw request if resolution itself fails", async () => { const executor = failingExecutor(); - const engine = await resolveTranscribeEngine(executor, "whisper-py", "base"); - expect(engine).toBe("whisper-py"); + const info = await resolveTranscribeInfo(executor, "whisper-py", "small"); + expect(info).toEqual({ engine: "whisper-py", model: "small" }); }); it("falls back to whisper-py when both the request and the resolution are empty", async () => { const executor = failingExecutor(); - const engine = await resolveTranscribeEngine(executor, undefined, "base"); - expect(engine).toBe("whisper-py"); + const info = await resolveTranscribeInfo(executor, undefined, "small"); + expect(info.engine).toBe("whisper-py"); }); }); diff --git a/src/services/engine-resolve.ts b/src/services/engine-resolve.ts index b97a7082..2915608d 100644 --- a/src/services/engine-resolve.ts +++ b/src/services/engine-resolve.ts @@ -8,7 +8,8 @@ import type { TaskExecutor } from "./python-executor.js"; * request (e.g. undefined, meaning "whisper-py unless this install can't run * it") instead of what transcribe_file resolves to always misses on a native * install, because the write afterward lands under "whispercpp", the key - * the read never looked at. + * the read never looked at. The model is resolved the same way: an install + * without the small whisper.cpp model runs on base, and keys the cache so. */ /** * Whether the resolved engine can ever produce speaker labels. whisper.cpp @@ -22,22 +23,30 @@ export function engineCanDiarize(engine: string | undefined): boolean { return engine !== "whispercpp" && engine !== "omnilingual"; } -export async function resolveTranscribeEngine( +export interface ResolvedTranscribe { + engine: string; + model: string; +} + +export async function resolveTranscribeInfo( executor: TaskExecutor, engine: string | undefined, modelSize: string -): Promise { +): Promise { try { - const result = await executor.execute<{ engine: string }>("resolve_transcribe_engine", { - engine, - model_size: modelSize, - }); + const result = await executor.execute<{ engine: string; model_size?: string }>( + "resolve_transcribe_engine", + { engine, model_size: modelSize } + ); - return result.data?.engine ?? engine ?? "whisper-py"; + return { + engine: result.data?.engine ?? engine ?? "whisper-py", + model: result.data?.model_size ?? modelSize, + }; } catch { // Resolution is a best-effort cache-key optimization; a failure here // should fall through to a normal (possibly-missed) cache lookup rather // than block transcription. - return engine ?? "whisper-py"; + return { engine: engine ?? "whisper-py", model: modelSize }; } } diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsx index 4039276f..85f3cf55 100644 --- a/src/ui/client/EpisodeWorkspace.jsx +++ b/src/ui/client/EpisodeWorkspace.jsx @@ -774,7 +774,7 @@ const onKeyActivate = (fn) => (e) => { const [timeAdjust, setTimeAdjust] = useState(-1); const [transcriptionEngine, setTranscriptionEngine] = useState('whisper'); const [assemblyAiKey, setAssemblyAiKey] = useState(''); - const [whisperModel, setWhisperModel] = useState('base'); + const [whisperModel, setWhisperModel] = useState('small'); const [captionStyle, setCaptionStyle] = useState('branded'); const [captionPosition, setCaptionPosition] = useState('auto'); const [captionFontScale, setCaptionFontScale] = useState(100); diff --git a/src/ui/web-server.ts b/src/ui/web-server.ts index 4697630b..538d119a 100644 --- a/src/ui/web-server.ts +++ b/src/ui/web-server.ts @@ -37,7 +37,7 @@ import { v4 as uuidv4 } from "uuid"; import { createExecutor, terminateProcessTree } from "../services/python-executor.js"; import { needsDiarizationRetry, TranscriptCache } from "../services/transcript-cache.js"; -import { resolveTranscribeEngine, engineCanDiarize } from "../services/engine-resolve.js"; +import { resolveTranscribeInfo, engineCanDiarize } from "../services/engine-resolve.js"; import { FileManager } from "../services/file-manager.js"; import { AssetManager, assetTypeSchema, inferType, safeName } from "../services/asset-manager.js"; import { ClipsHistory, reframeStateSchema } from "../services/clips-history.js"; @@ -1244,7 +1244,7 @@ app.post("/api/parse-transcript", async (req, res) => { app.post("/api/transcribe", async (req, res) => { const { file_path, - model_size = "base", + model_size = "small", engine, assemblyai_api_key, language, @@ -1267,8 +1267,9 @@ app.post("/api/transcribe", async (req, res) => { // Resolve before reading the cache: an unset engine is written under // whatever transcribe_file actually ran (e.g. "whispercpp" on a native // install), so reading with the raw unset request always misses. - const resolvedEngine = await resolveTranscribeEngine(executor, engine, model_size); - const cacheKey = { engine: resolvedEngine, model: model_size, language }; + const resolved = await resolveTranscribeInfo(executor, engine, model_size); + const resolvedEngine = resolved.engine; + const cacheKey = { engine: resolvedEngine, model: resolved.model, language }; // A sample is a throwaway check on a slice of the file. Never serve or // populate the session/UI state from the main cache (keyed by, and @@ -1371,7 +1372,7 @@ app.post("/api/transcribe", async (req, res) => { await cache.set(file_path, transcript, { engine: actualEngine, - model: model_size, + model: transcript.model_size ?? resolved.model, language, }); } catch (err) { diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.py index b017f452..cba48a54 100644 --- a/tests/test_ai_fallback.py +++ b/tests/test_ai_fallback.py @@ -178,7 +178,7 @@ def test_suggest_initial_with_claude_uses_bucket_strategy_for_long_episode(self) "start": start, "end": start + 45.0, "speaker": "SPEAKER_00", - "text": f"Segment {i} with enough text to count as a normal transcript block.", + "text": f"Segment {i} " + "filler " * 3000, }) calls = [] @@ -212,6 +212,120 @@ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, self.assertTrue(all(call["end"] - call["start"] < 2500 for call in calls[:4])) self.assertGreaterEqual(calls[1]["exclude_len"], 1) + def test_a_transcript_that_fits_one_prompt_is_read_whole_and_ranked_down(self): + segments = [] + for i in range(20): + start = float(i * 330) + segments.append({ + "start": start, + "end": start + 45.0, + "speaker": "SPEAKER_00", + "text": f"Segment {i} with enough text to count as a normal transcript block.", + }) + calls = [] + scores = [3.0, 9.0, 5.0, 8.0, 1.0, 7.0] + + def fake_suggest(*, segments, top_n, **kw): + calls.append({"top_n": top_n, "segments": len(segments)}) + return [ + { + "title": f"Clip {i}", + "start_second": 100.0 * i, + "end_second": 100.0 * i + 30.0, + "segments": [{"start": 100.0 * i, "end": 100.0 * i + 30.0}], + "score": score, + } + for i, score in enumerate(scores) + ] + + with mock.patch.object(cs, "suggest_with_claude", side_effect=fake_suggest): + clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) + + self.assertEqual(calls, [{"top_n": 6, "segments": 20}]) + self.assertEqual([c["title"] for c in clips], ["Clip 1", "Clip 3", "Clip 5"]) + self.assertEqual([c["score"] for c in clips], [9.0, 8.0, 7.0]) + + def test_a_failed_single_prompt_search_returns_none(self): + segments = [{"start": 0.0, "end": 40.0, "speaker": "SPEAKER_00", "text": "Short."}] + + with mock.patch.object(cs, "suggest_with_claude", return_value=None) as fake: + clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) + + self.assertIsNone(clips) + self.assertEqual(fake.call_args.kwargs["top_n"], 6) + + def test_every_bucket_is_asked_for_the_same_count_and_one_ranking_picks_winners(self): + segments = [] + for i in range(20): + start = float(i * 330) + segments.append({ + "start": start, + "end": start + 45.0, + "speaker": "SPEAKER_00", + "text": f"Segment {i} " + "filler " * 3000, + }) + calls = [] + + def fake_suggest(*, segments, top_n, **kw): + first_start = segments[0]["start"] + calls.append({"start": first_start, "top_n": top_n}) + strong = first_start == 0.0 + return [ + { + "title": f"Clip {first_start}-{k}", + "start_second": first_start + 40.0 * k, + "end_second": first_start + 40.0 * k + 28.0, + "segments": [{"start": first_start + 40.0 * k, "end": first_start + 40.0 * k + 28.0}], + "score": (90.0 - k) if strong else (10.0 - k), + } + for k in range(top_n) + ] + + with mock.patch.object(cs, "suggest_with_claude", side_effect=fake_suggest): + clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) + + self.assertEqual(len(calls), 5) + self.assertEqual({call["top_n"] for call in calls}, {3}) + self.assertEqual([c["title"] for c in clips], ["Clip 0.0-0", "Clip 0.0-1", "Clip 0.0-2"]) + self.assertEqual([c["score"] for c in clips], [90.0, 89.0, 88.0]) + + def test_suggest_with_claude_allows_slack_on_both_ends_of_the_format_bounds(self): + segments = [ + {"start": 0.0, "end": 12.0, "speaker": "SPEAKER_00", "text": "Warmup context."}, + {"start": 12.0, "end": 40.0, "speaker": "SPEAKER_00", "text": "The best grid connection."}, + ] + + def clip(title, start, length): + return { + "title": title, + "start_second": start, + "end_second": start + length, + "segments": [{"start": start, "end": start + length}], + "content_type": "hot_take", + "scores": {"standalone": 5, "hook": 5, "relevance": 4, "quotability": 4}, + "quote": title, + "why": "Strong.", + } + + payload = json.dumps({"clips": [ + clip("Fifty seconds", 100.0, 50.0), + clip("Fifty three seconds", 200.0, 53.0), + clip("Eighteen seconds", 300.0, 18.0), + clip("Sixteen seconds", 400.0, 16.0), + ]}) + + with mock.patch.object( + ap, "_chain", return_value=[("cli", "/tmp/claude", "claude")], + ), mock.patch.object( + ai, + "_run_ai_command", + return_value=subprocess.CompletedProcess(args=["claude"], returncode=0, stdout=payload, stderr=""), + ): + clips = cs.suggest_with_claude(segments=segments, top_n=10) + + self.assertEqual([c["title"] for c in clips], ["Fifty seconds", "Eighteen seconds"]) + self.assertEqual([c["duration"] for c in clips], [50, 18]) + def test_suggest_with_claude_reports_actual_timeout_limit(self): segments = [ {"start": 0.0, "end": 20.0, "speaker": "SPEAKER_00", "text": "Short segment one."}, diff --git a/tests/test_claude_suggest_helpers.py b/tests/test_claude_suggest_helpers.py index 3d1bbf75..729f67ad 100644 --- a/tests/test_claude_suggest_helpers.py +++ b/tests/test_claude_suggest_helpers.py @@ -95,17 +95,28 @@ def test_short_episode_does_not_bucket(self): segments = [{"start": 0, "end": 10, "text": "short"}] self.assertFalse(cs._should_bucket_initial_selection(segments)) - def test_long_duration_buckets(self): - # 50 minutes: over the 45 min threshold - segments = [{"start": 0, "end": 3000, "text": "x" * 100}] - self.assertTrue(cs._should_bucket_initial_selection(segments)) + def test_a_three_hour_conversation_that_fits_one_prompt_does_not_bucket(self): + segments = [ + {"start": i * 5.4, "end": i * 5.4 + 5.0, "text": "a short spoken line here"} + for i in range(2000) + ] + self.assertGreater(segments[-1]["end"], 10000) + self.assertFalse(cs._should_bucket_initial_selection(segments)) + + def test_many_short_segments_do_not_bucket(self): + segments = [{"start": i, "end": i + 1, "text": "hi"} for i in range(5000)] + self.assertFalse(cs._should_bucket_initial_selection(segments)) + + def test_text_just_under_the_budget_does_not_bucket(self): + segments = [{"start": 0, "end": 60, "text": "x" * 399000}] + self.assertFalse(cs._should_bucket_initial_selection(segments)) - def test_many_segments_buckets(self): - segments = [{"start": i, "end": i + 1, "text": "hi"} for i in range(200)] + def test_text_just_over_the_budget_buckets(self): + segments = [{"start": 0, "end": 60, "text": "x" * 401000}] self.assertTrue(cs._should_bucket_initial_selection(segments)) - def test_dense_text_buckets(self): - segments = [{"start": 0, "end": 60, "text": "x" * 20000}] + def test_the_budget_counts_the_prompt_text_not_just_the_words(self): + segments = [{"start": 0, "end": 1, "speaker": "SPEAKER_00", "text": "x" * 399990}] self.assertTrue(cs._should_bucket_initial_selection(segments)) def test_empty_does_not_bucket(self): @@ -418,6 +429,38 @@ def test_keeps_is_inclusive_at_both_ends(self): self.assertFalse(b.keeps(19.9)) self.assertFalse(b.keeps(45.1)) + def test_slack_keeps_a_vertical_clip_a_little_over_the_max(self): + b = cs.ClipBounds.of("vertical") + self.assertTrue(b.keeps_with_slack(50)) + self.assertTrue(b.keeps_with_slack(51.7)) + self.assertFalse(b.keeps_with_slack(51.8)) + self.assertFalse(b.keeps_with_slack(53)) + + def test_slack_keeps_a_vertical_clip_a_little_under_the_min(self): + b = cs.ClipBounds.of("vertical") + self.assertTrue(b.keeps_with_slack(17.1)) + self.assertFalse(b.keeps_with_slack(16.9)) + self.assertFalse(b.keeps_with_slack(10)) + + def test_slack_scales_with_the_format_bounds(self): + b = cs.ClipBounds.of("horizontal") + self.assertTrue(b.keeps_with_slack(340)) + self.assertFalse(b.keeps_with_slack(346)) + self.assertTrue(b.keeps_with_slack(52)) + self.assertFalse(b.keeps_with_slack(50)) + + def test_slack_follows_an_explicit_override(self): + b = cs.ClipBounds.of("vertical", 30, 40) + self.assertTrue(b.keeps_with_slack(45.9)) + self.assertFalse(b.keeps_with_slack(46.1)) + self.assertTrue(b.keeps_with_slack(25.6)) + self.assertFalse(b.keeps_with_slack(25.4)) + + def test_strict_keeps_is_unchanged_by_the_slack_check(self): + b = cs.ClipBounds.of("vertical") + self.assertFalse(b.keeps(50)) + self.assertFalse(b.keeps(17.1)) + def test_a_horizontal_length_survives_the_filter_that_used_to_drop_it(self): self.assertFalse(cs.ClipBounds.of("vertical").keeps(120)) self.assertTrue(cs.ClipBounds.of("horizontal").keeps(120)) @@ -496,6 +539,27 @@ def test_a_long_transcript_is_thinned_not_truncated(self): # The last line is the half a tail truncation would have thrown away. self.assertIn(f"line {3999}", out) + def test_sampling_logs_how_many_lines_it_dropped(self): + import io + from contextlib import redirect_stderr + + text = self._transcript(4000) + buf = io.StringIO() + with redirect_stderr(buf): + out = cs._sample_transcript(text) + kept = len(out.split("\n")) + self.assertIn(f"dropped {4000 - kept} of 4000 lines", buf.getvalue()) + self.assertGreater(4000 - kept, 0) + + def test_an_untouched_transcript_logs_nothing(self): + import io + from contextlib import redirect_stderr + + buf = io.StringIO() + with redirect_stderr(buf): + cs._sample_transcript(self._transcript(10)) + self.assertEqual(buf.getvalue(), "") + def test_only_codex_is_adapted(self): text = self._transcript() prompt = "RULES\n\n" + text diff --git a/tests/test_whisper_model_default.py b/tests/test_whisper_model_default.py new file mode 100644 index 00000000..2c2016ec --- /dev/null +++ b/tests/test_whisper_model_default.py @@ -0,0 +1,165 @@ +import inspect +import io +import os +import sys +import tempfile +import unittest +from contextlib import redirect_stderr +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 presets +import services.transcription as tr +import services.transcript_packer as tp +from services import transcription_whispercpp as wcpp + + +class DefaultModelTests(unittest.TestCase): + def test_the_default_preset_uses_small(self): + self.assertEqual(presets.DEFAULT_PRESET["whisper_model"], "small") + + def test_the_transcription_entry_points_default_to_small(self): + for fn in (tr.transcribe_file, tr._transcribe_file_inner, tr.resolve_engine_info): + self.assertEqual(inspect.signature(fn).parameters["model_size"].default, "small", fn.__name__) + + def test_small_keys_the_cache_apart_from_base(self): + self.assertEqual(tp.cache_key_suffix("whispercpp", "small", None), "-whispercpp-msmall") + self.assertEqual(tp.cache_key_suffix("whispercpp", "base", None), "-whispercpp") + + +class WhispercppModelFallbackTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.models = os.path.join(self._tmp.name, "models") + os.makedirs(self.models) + self.cli = os.path.join(self._tmp.name, "whisper-cli") + self._touch(self.cli) + env = mock.patch.dict( + os.environ, + {"PODCLI_HOME": self._tmp.name, "PODCLI_WHISPER_CLI": self.cli}, + ) + env.start() + self.addCleanup(env.stop) + os.environ.pop("PODCLI_WHISPERCPP_MODEL", None) + os.environ.pop("PODCLI_ENGINE", None) + self._had_whisper = sys.modules.get("whisper", "__absent__") + sys.modules["whisper"] = None + tr._whisper_py_available.cache_clear() + self.addCleanup(self._restore_whisper) + + def _restore_whisper(self): + if self._had_whisper == "__absent__": + sys.modules.pop("whisper", None) + else: + sys.modules["whisper"] = self._had_whisper + tr._whisper_py_available.cache_clear() + + def _touch(self, path): + with open(path, "wb") as f: + f.write(b"x") + + def _install(self, *sizes): + for size in sizes: + self._touch(os.path.join(self.models, f"ggml-{size}.bin")) + + def test_small_is_used_when_installed(self): + self._install("small", "base") + self.assertEqual(tr.resolve_whispercpp_model_size("small"), "small") + + def test_small_falls_back_to_base_when_only_base_is_installed(self): + self._install("base") + self.assertEqual(tr.resolve_whispercpp_model_size("small"), "base") + + def test_small_stays_small_when_nothing_is_installed(self): + self.assertEqual(tr.resolve_whispercpp_model_size("small"), "small") + + def test_other_sizes_never_fall_back(self): + self._install("base") + self.assertEqual(tr.resolve_whispercpp_model_size("medium"), "medium") + self.assertEqual(tr.resolve_whispercpp_model_size("tiny"), "tiny") + + def test_an_explicit_model_path_disables_the_fallback(self): + self._install("base") + explicit = os.path.join(self._tmp.name, "custom.bin") + self._touch(explicit) + os.environ["PODCLI_WHISPERCPP_MODEL"] = explicit + self.assertEqual(tr.resolve_whispercpp_model_size("small"), "small") + + def test_the_cache_key_prediction_names_the_model_the_run_uses(self): + self._install("base") + info = tr.resolve_engine_info(None, "small") + self.assertEqual(info, {"engine": "whispercpp", "model_size": "base"}) + self.assertEqual( + tp.cache_key_suffix(info["engine"], info["model_size"], None), "-whispercpp" + ) + + def test_the_prediction_keeps_small_once_it_is_installed(self): + self._install("base", "small") + info = tr.resolve_engine_info(None, "small") + self.assertEqual(info, {"engine": "whispercpp", "model_size": "small"}) + self.assertEqual( + tp.cache_key_suffix(info["engine"], info["model_size"], None), "-whispercpp-msmall" + ) + + def test_an_explicit_whispercpp_request_resolves_the_model_too(self): + self._install("base") + info = tr.resolve_engine_info("whispercpp", "small") + self.assertEqual(info, {"engine": "whispercpp", "model_size": "base"}) + + def test_other_engines_report_the_requested_model_untouched(self): + self._install("base") + self.assertEqual( + tr.resolve_engine_info("assemblyai", "small"), + {"engine": "assemblyai", "model_size": "small"}, + ) + + def test_the_run_uses_base_and_prints_one_line_about_it(self): + self._install("base") + seen = {} + + def fake_transcribe(file_path, **kwargs): + seen.update(kwargs) + return {"words": []} + + buf = io.StringIO() + with mock.patch.object(wcpp, "transcribe_file", side_effect=fake_transcribe), redirect_stderr(buf): + tr._transcribe_with_whispercpp("episode.wav", "small", None, None) + + self.assertEqual(os.path.basename(seen["model_path"]), "ggml-base.bin") + lines = [line for line in buf.getvalue().splitlines() if line.strip()] + self.assertEqual(len(lines), 1) + self.assertIn("'small' is not installed, using 'base'", lines[0]) + + def test_the_run_is_silent_when_small_is_installed(self): + self._install("small", "base") + seen = {} + + def fake_transcribe(file_path, **kwargs): + seen.update(kwargs) + return {"words": []} + + buf = io.StringIO() + with mock.patch.object(wcpp, "transcribe_file", side_effect=fake_transcribe), redirect_stderr(buf): + tr._transcribe_with_whispercpp("episode.wav", "small", None, None) + + self.assertEqual(os.path.basename(seen["model_path"]), "ggml-small.bin") + self.assertEqual(buf.getvalue(), "") + + def test_the_transcript_records_the_model_that_actually_ran(self): + self._install("base") + with tempfile.NamedTemporaryFile(suffix=".wav") as media, \ + mock.patch.object(tr, "_transcribe_with_whispercpp", return_value={}), \ + mock.patch.object(tr, "_attach_speakers_and_faces", side_effect=lambda fp, base, *a, **k: base): + result = tr.transcribe_file(media.name, engine="whispercpp", enable_diarization=False) + + self.assertEqual(result["engine"], "whispercpp") + self.assertEqual(result["model_size"], "base") + + +if __name__ == "__main__": + unittest.main()