forge
Explore
Log in

Don't you dare go Hollow

✨ Speech runs on the GPU too: edith-stt gains a Vulkan whisper.cpp backend (--features vulkan), medium and large-v3(-turbo) join the models, and the model and device are a project setting with a picker, project_settings and a per-call device

Browse files at this commit

bcb4dc5db29b96be7e6ace4ff2f41d65016df705Ahmet Kaan GümüşParent: ef05717

24 changed files +1171 -240

MCP.mdmodified+5 -5
@@ -229,7 +229,7 @@ in **bold**; optional ones follow the name.
229229 | `project_export_timeline` | format, path? | writes the active sequence for another editor: `otio` (OpenTimelineIO: tracks, clips with absolute file paths, gaps, transitions, markers), `fcpxml` (Final Cut Pro XML 1.10, read by Final Cut Pro, Resolve and Premiere) or `edl` (CMX3600: V1 and audio on A1/A2, dissolves as `D`, `FROM CLIP NAME` comments). Default path: beside the project file. Subtitles are left out and the reply says so. Only the file is written; the project does not change. The window's File > Export timeline as does the same into the default export folder |
230230 | `project_import_timeline` | path | reads an `.otio` file as a new sequence of the project and makes it the active one; each clip is relinked by its path, and a missing file becomes an offline clip. One undo step, unsaved until `project_save`. The window takes the same file from File > Import timeline (OTIO) or from the command line |
231231 | `project_status` | history (false) | path, saved or dirty, canvas size, fps, duration, lanes with clip counts, sources, the colour looks (a `looks:` line naming the built-in looks and the saved ones, the names the `look` op takes; `structuredContent` has them as `looks.builtin` and `looks.saved`), undo and redo depth, running exports, settings (and the notes, when there are any); an `OFFLINE: src:N <path>` line per offline source, and the fixes an open made to load (dirty until saved). `history: true` also lists every undo step and every redo step, newest first, each with the `steps` count that `undo` or `redo` needs to reach it (`undo {steps: 3}` takes back the three newest) |
232-| `project_settings` | resolution, fps, tonemap, notes, still_secs, sample_rate, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. `sample_rate` is the sound mix's rate: `"source"` (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), `44100`, `48000` or `96000`, the same rows the GUI offers. Each is one undo step |
232+| `project_settings` | resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, sample_rate, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. `speech_model` is the Whisper model the listen tools run on (`auto` picks the first installed); `speech_device` is `auto`, `cpu` or `gpu` (auto is gpu when edith-stt has a usable GPU and that model is installed, else cpu). Both are saved with the project as format v57, and each call's `device` and `model` args override them. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. `sample_rate` is the sound mix's rate: `"source"` (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), `44100`, `48000` or `96000`, the same rows the GUI offers. Each is one undo step |
233233 | `templates` | save | lists the project templates: the built-ins (YouTube 1080p 30, Vertical 1080×1920 30, Square 1080 30) and the ones saved from the window with File > Save as template, each marked built-in or saved and whether it keeps clips. `save: {name, with_clips?}` saves the open project as a template of that name (replacing one of the same name; a built-in's name is refused). `with_clips: true` keeps the clips and their sources too; the default keeps the settings only. The project does not change |
234234 | `checkpoint` | **name** | save the whole project under a name (letters, digits, `-`, `_`), as a copy in `<project dir>/checkpoints/<stem>/` (the project's path, from `project_new {path}` or `project_save`; with no path at all, the temp dir, lost on reboot) |
235235 | `restore` | **name** | replace the open project with a checkpoint, from this run or an earlier one; first saves the open project as `before-restore-<name>` (a suffix when that name is taken), so the state before the restore stays on disk; the project is dirty afterwards and its undo and redo history is cleared |
@@ -378,9 +378,9 @@ only when asked for (the first call that needs it says so and stops if it is abs
378378
379379 | tool | args | does |
380380 |---|---|---|
381-| `transcript` | target, from, language, model=base\|tiny\|small, range, words, hint, fillers | what is said, as timeline frames; segment lines, or word times with `words:true`. Segment times are reliable; word times are DTW-aligned, and a segment whose words were only spread evenly is `approx:true` |
382-| `find_words` | **query**, target, language, model, hint, cut, keep (first\|last), which, pad, dry_run, lanes | a phrase, case-insensitive, punctuation ignored; returns the matching spans to cut or caption. `keep` with `cut` keeps one word of a repeat (`"I I"`). `cut` lanes default to the target's lane and its linked lanes (every lane for a mix or src target). Filler spellings (uh, um, and their variants) and hallucinated "Thank you"-type segments are handled. `cut:"lift"` removes the matches without ripple: a hole is left where each was and no other lane moves (use it on one speaker's lane, so the other speaker stays in step). With `cut`, each edge snaps to the quietest 10 ms within ±150 ms of Whisper's time (a pause, not a word's sound), never closer than 30 ms to the kept word on its side; `snap:false` cuts at Whisper's times. A match in an `approx:true` segment is a hint: pad it or check it with `frame` |
383-| `auto_captions` | target (default lane A1), lane (default S1), language, model, max_chars, max_secs, path, speakers, hint, replace | transcribes, cuts cues at pauses, sentence ends and the length limits, writes `<stem>.captions.srt` (`-2`, `-3` … when that name is taken; a temp file if the project is untitled), imports it as a subtitle track and places it on the caption lane at frame 0. One undo step. A re-run writes a new file and keeps the old one, so undo can bring the old track back. A lane that already holds captions takes the new run merged in, as one track in time order; a re-run on the same lane replaces the captions that lane made before. `replace:true` also removes overlapping captions that differ from what was heard now (hand edits included); undo brings them back. `speakers` (mix target) sets which audio lanes split the cues. `hint` also corrects near-miss spellings of its words after transcription, and the reply names each correction (`hint corrected: …`). An explicit `path` that a track already holds is refused |
381+| `transcript` | target, from, language, model=base (tiny, small, medium, large-v3, large-v3-turbo), device=auto\|cpu\|gpu, range, words, hint, fillers | what is said, as timeline frames; segment lines, or word times with `words:true`. Segment times are reliable; word times are DTW-aligned, and a segment whose words were only spread evenly is `approx:true` |
382+| `find_words` | **query**, target, language, model, device, hint, cut, keep (first\|last), which, pad, dry_run, lanes | a phrase, case-insensitive, punctuation ignored; returns the matching spans to cut or caption. `keep` with `cut` keeps one word of a repeat (`"I I"`). `cut` lanes default to the target's lane and its linked lanes (every lane for a mix or src target). Filler spellings (uh, um, and their variants) and hallucinated "Thank you"-type segments are handled. `cut:"lift"` removes the matches without ripple: a hole is left where each was and no other lane moves (use it on one speaker's lane, so the other speaker stays in step). With `cut`, each edge snaps to the quietest 10 ms within ±150 ms of Whisper's time (a pause, not a word's sound), never closer than 30 ms to the kept word on its side; `snap:false` cuts at Whisper's times. A match in an `approx:true` segment is a hint: pad it or check it with `frame` |
383+| `auto_captions` | target (default lane A1), lane (default S1), language, model, device, max_chars, max_secs, path, speakers, hint, replace | transcribes, cuts cues at pauses, sentence ends and the length limits, writes `<stem>.captions.srt` (`-2`, `-3` … when that name is taken; a temp file if the project is untitled), imports it as a subtitle track and places it on the caption lane at frame 0. One undo step. A re-run writes a new file and keeps the old one, so undo can bring the old track back. A lane that already holds captions takes the new run merged in, as one track in time order; a re-run on the same lane replaces the captions that lane made before. `replace:true` also removes overlapping captions that differ from what was heard now (hand edits included); undo brings them back. `speakers` (mix target) sets which audio lanes split the cues. `hint` also corrects near-miss spellings of its words after transcription, and the reply names each correction (`hint corrected: …`). An explicit `path` that a track already holds is refused |
384384 | `voices` | language | lists the local Piper voices (name, language, quality, sample rate, speakers). The default is marked `*`: `en_US-ryan-high` when installed, else the first `en_US`, else the first one |
385385 | `voiceover` | **text**, voice, speed=1, pause=0, name, place | speaks `text` into `<project>/voiceover/<name or slug>-<hash8>.wav` and imports it as a source (`src:N`), reporting its duration. Needs a project path (`project_new` or `project_open`): the WAV goes beside the `.edith` file even before `project_save`, and the reply says the source is unsaved until then. Renders are cached by (text, voice, speed, pause, model) in `voiceover/.renders/`: the same text with another `name` reuses the render and only copies it. Piper's duration noise is pinned off, so one text always renders to one length (the waveform keeps piper's usual small variation). `place {lane, at}` places it on a lane as one undo step; the lane must be an existing audio lane, and both are checked before anything is rendered. Text is capped at 5000 characters; `speed` 0.5–2; `pause` is seconds of silence after each sentence (max 10) |
386386 | `record` | **action** (start\|stop\|status), lane, at=playhead, source | records a voice-over from the audio input into `<project stem>_media/voiceover-<n>.wav` beside the project (16-bit stereo WAV, 48 kHz; the folder `project_collect` uses). `start` begins a take at `at` (default the playhead) and needs a project path; `lane` is the audio lane it lands on, or a new one. `stop` ends the take, imports it as `src:N` and places it at the start point as one undo step. `status` reports the clock and the level in dBFS while recording, and the input list (`source` names, monitors marked) when idle. This is the microphone; `voiceover` is text-to-speech (Piper) and never records. Only one take runs at a time |
@@ -410,7 +410,7 @@ Piper's stderr is reported on failure.
410410 | `export_presets` | – | lists the export presets (id, label, format, bitrate_kbps, audio_kbps, size, bit_depth, prores_profile, hdr, loudness): youtube_1080p/1080p60/1080p_hevc/4k/4k60/4k_hevc, shorts_reels, podcast, podcast_ogg and podcast_opus (-16 LUFS, -1 dBTP), archive (10-bit AV1 mkv), archive_prores (ProRes 422 HQ .mov), hdr10_hevc (10-bit HEVC mp4 tagged PQ), archive_flac, archive_wav |
411411 | `export_captions` | format (`srt` or `vtt`, required unless chapters), path, overwrite, chapters | writes the timeline's captions (every cue on the subtitle lanes, in start order) as SRT or WebVTT; picture and empty cues are left out. Without `path`: `<first source> edit.<format>` in the Videos folder. Refuses an existing file unless `overwrite` is true, and writes nothing when there are no captions. `chapters: true` writes nothing and returns the chapter markers as the YouTube description listing (`00:00 Intro`, one line each), the text File > Copy chapters copies, as the reply text and as JSON (`chapters` lines, `text`, `warnings`) |
412412 | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:<n>`, a list or `"all"`) | the editing copies (proxies) of sources. `status` shows each source's state (ready, making with its percent, off, not needed for a sound or still, or why a stand-in failed). `make` starts one in the background and turns that film's switch back on; a film that plays at speed on this machine needs none, and says so. `cancel` stops one being made and leaves the film off, as the Proxies switch on a library row does. `delete` removes the stand-in and keeps the film off. With `auto_proxies` on, each `media_import` starts its stand-ins the same way |
413-| `speech_model` | download (false), model (`tiny`, `base` or `small`; default `base`), cancel (false) | the speech model that `transcript`, `find_words` and `auto_captions` run on: no argument shows which models are installed and the download in progress. `download: true` fetches a model in the background (the GUI's Download model fetches `base`); `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true |
413+| `speech_model` | download (false), model (default `base`), device (default: the one auto picks), cancel (false) | the speech model that `transcript`, `find_words` and `auto_captions` run on: no argument shows the models installed per device (cpu, gpu) and whether a GPU is usable. `download: true` fetches a model in the background: cpu is the Hugging Face folder `whisper-<model>`, gpu the single file `ggml-<model>.bin`. `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true |
414414 | `export_status` | job, out | a queued job (`export_start {queue:true}`) reads `waiting` with the number of exports ahead of it; progress, elapsed, ETA, encoder, outcome of one job; while a stabilised clip is measured before it can encode, the line and `stage`/`stage_progress` name that stage (`Measuring shake`) with its own percent; `out` reports a file this session did not start; omitted, every export so far, with its size when done (decimal: 12,139,083 bytes is 12.1 MB) and the integrated loudness (LUFS) and true peak of the written file (`integrated_lufs`, `true_peak_dbtp`, measured once from the file with the `loudness` measurement), or its error when failed. When a job finishes, a peak over the format's ceiling gets a warning line: -1 dBTP for lossless (wav, flac), -2 dBTP for lossy (the rest, since encoding can overshoot the mix) |
415415 | `export_cancel` | job, all | cancels a running job; a waiting (queued) job is removed from the queue and never starts. `all: true` cancels every unfinished export at once (the queued ones and the running one), as the export queue's Cancel all does. |
416416 | `export_queue` | action (`pause`, `start` or `status`, the default) | `pause` stops the queue after the running export: the running one finishes, and the queued exports (`export_start {queue:true}`) stay waiting. `start` lifts the pause and starts the next queued export now if nothing is running. `status` says whether the queue is paused, the running export and the queued ones in order. A pause holds only queued exports; a direct export (no `queue`) starts at once. `export_status` names a paused queue |
crates/app/src/creator.rsmodified+0 -12
@@ -56,18 +56,6 @@ pub(crate) fn model_label(model: &str) -> String {
5656 }
5757 }
5858
59-/// What a model's tooltip says: what it trades off, and its name on disk so the plain word is
60-/// never a mystery.
61-pub(crate) fn model_tip(model: &str) -> String {
62- let what = match model {
63- "tiny" => "quickest, least accurate",
64- "base" => "a middle ground",
65- "small" => "slowest, most accurate",
66- _ => "a speech model",
67- };
68- format!("{}: {what} ({model} model)", model_label(model))
69-}
70-
7159 // ---- normalize ----------------------------------------------------------------------
7260
7361 /// A minus sign the way the cards print it: U+2212, never a hyphen.
crates/app/src/menus.rsmodified+4 -0
@@ -119,6 +119,8 @@ pub(crate) enum Pick {
119119 /// ([`engine::PlaybackSession::set_sample_rate`]). Opened from the panel,
120120 /// beside the resolution and rate it shares a row style with.
121121 SampleRate,
122+ /// The speech model the project transcribes with, or Auto ([`Choice::SpeechModel`]).
123+ SpeechModel,
122124 Fit(Lane, usize),
123125 /// The colour label of the clip at (lane, index) ([`engine::project::LABELS`]).
124126 Label(Lane, usize),
@@ -201,6 +203,8 @@ pub(crate) enum Choice {
201203 Bin(u32),
202204 /// The autosave period in seconds, `None` for Off ([`Pick::Autosave`]).
203205 Autosave(Option<u64>),
206+ /// The speech model, `None` for Auto ([`engine::speech::MODELS`]).
207+ SpeechModel(Option<&'static str>),
204208 }
205209
206210 /// A status-bar item a shortcut-opened list hangs above.
crates/app/src/player/cards.rsmodified+33 -0
@@ -592,6 +592,30 @@ impl Player {
592592 cx.notify();
593593 }
594594
595+ /// The project's speech model set (`None` for Auto). One undo step.
596+ pub(crate) fn apply_speech_model(&mut self, model: Option<&str>, cx: &mut Context<Self>) {
597+ if self.session.as_mut().is_some_and(|s| s.set_speech_model(model)) {
598+ self.mark_dirty();
599+ }
600+ cx.notify();
601+ }
602+
603+ /// The project's speech device set. One undo step.
604+ pub(crate) fn apply_speech_device(&mut self, device: engine::speech::DeviceChoice, cx: &mut Context<Self>) {
605+ if self.session.as_mut().is_some_and(|s| s.set_speech_device(device)) {
606+ self.mark_dirty();
607+ }
608+ cx.notify();
609+ }
610+
611+ /// Whether a speech model in the picker is not installed for the device the project resolves it to.
612+ pub(crate) fn speech_model_missing(&self, choice: Choice) -> bool {
613+ match (choice, self.session.as_ref()) {
614+ (Choice::SpeechModel(Some(m)), Some(s)) => engine::speech::check_model(m, s.speech_device().resolve(m)).is_err(),
615+ _ => false,
616+ }
617+ }
618+
595619 /// The project's still length set: stills placed from now on take it, and the ones already
596620 /// on the timeline keep theirs. One undo step, and the project reads unsaved.
597621 pub(crate) fn apply_still_secs(&mut self, secs: f64, cx: &mut Context<Self>) {
@@ -706,6 +730,7 @@ impl Player {
706730 Choice::Size(w, h) => self.apply_resolution(w, h, cx),
707731 Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
708732 Choice::SampleRate(rate) => self.apply_sample_rate(rate, cx),
733+ Choice::SpeechModel(model) => self.apply_speech_model(model, cx),
709734 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
710735 Choice::Label(lane, idx, label) => self.apply_label(lane, idx, label, cx),
711736 Choice::MarkerColor(idx, color) => self.set_marker_color(idx, color, cx),
@@ -880,6 +905,14 @@ impl Player {
880905 }
881906 Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()),
882907 Pick::SampleRate => sample_rate_choices(session.sample_rate()),
908+ Pick::SpeechModel => {
909+ let here = session.speech_model();
910+ std::iter::once((Choice::SpeechModel(None), "Auto".into(), "".into(), here.is_none()))
911+ .chain(engine::speech::MODELS.iter().map(|&m| {
912+ (Choice::SpeechModel(Some(m)), crate::creator::model_label(m).into(), "".into(), here == Some(m))
913+ }))
914+ .collect()
915+ }
883916 Pick::Fit(lane, idx) => {
884917 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
885918 }
crates/app/src/player/tools.rsmodified+8 -13
@@ -14,6 +14,7 @@ use engine::speech::{self, Filler, Hear, Job, Spoken};
1414
1515 use crate::creator::{self, LANGUAGES, LUFS_RANGE, LUFS_STEP, PEAK_RANGE, PEAK_STEP, Said};
1616 use crate::player::text_field::FieldKey;
17+use crate::player::transcript;
1718 use crate::ui::kit::{NumberEdit, scrub_value};
1819 use crate::*;
1920
@@ -118,7 +119,6 @@ pub(crate) struct Tools {
118119 pub(crate) each: bool,
119120 // Captions and Fillers
120121 pub(crate) lang: usize,
121- pub(crate) model: usize,
122122 pub(crate) hear: usize,
123123 /// Listen to the sound again even though a transcript is there to read from.
124124 pub(crate) relisten: bool,
@@ -151,7 +151,6 @@ impl Tools {
151151 ceiling: engine::normalize::TARGET_TRUE_PEAK,
152152 each: false,
153153 lang: 0,
154- model: 0,
155154 hear: 0,
156155 relisten: false,
157156 found: Vec::new(),
@@ -428,10 +427,6 @@ impl Player {
428427 self.session.as_ref().map_or_else(Vec::new, creator::hear_choices)
429428 }
430429
431- pub(crate) fn tools_models(&self) -> Vec<&'static str> {
432- speech::installed_models()
433- }
434-
435430 /// Opens a dropdown, or shuts it when it is the one open.
436431 pub(crate) fn tools_toggle_drop(&mut self, what: Cycle, cx: &mut Context<Self>) {
437432 if let Some(t) = self.tools_mut() {
@@ -445,7 +440,6 @@ impl Player {
445440 if let Some(t) = self.tools_mut() {
446441 match what {
447442 Cycle::Language => t.lang = i,
448- Cycle::Model => t.model = i,
449443 Cycle::Hear => t.hear = i,
450444 Cycle::Voice => t.voice = i,
451445 }
@@ -500,14 +494,16 @@ impl Player {
500494 cx.notify();
501495 return;
502496 }
503- let (lang, model_at, hear_at) = (tools.lang, tools.model, tools.hear);
504- if let Err(why) = speech::available() {
497+ let (lang, hear_at) = (tools.lang, tools.hear);
498+ if let Err(why) = speech::stt_bin() {
505499 return self.listen_fail(fillers, &why, cx);
506500 }
507- let models = self.tools_models();
508- let Some(&model) = models.get(model_at).or(models.first()) else {
501+ let Some((model, device)) = transcript::speech_target(self.session.as_ref()) else {
509502 return self.listen_fail(fillers, "No speech model is installed", cx);
510503 };
504+ if let Err(why) = speech::available(device) {
505+ return self.listen_fail(fillers, &why, cx);
506+ }
511507 let hears = self.tools_hears();
512508 let hear = hears.get(hear_at).copied().unwrap_or(Hear::Mix);
513509 let lang = LANGUAGES[lang.min(LANGUAGES.len() - 1)].0;
@@ -533,7 +529,7 @@ impl Player {
533529 }
534530 let work = cx.background_executor().spawn({
535531 let job = job.clone();
536- async move { speech::listen(heard, model, lang, fillers, &job) }
532+ async move { speech::listen(heard, &model, device, lang, fillers, &job) }
537533 });
538534 cx.spawn(async move |this, cx| {
539535 let heard = work.await;
@@ -895,7 +891,6 @@ impl Player {
895891 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
896892 pub(crate) enum Cycle {
897893 Language,
898- Model,
899894 Hear,
900895 Voice,
901896 }
crates/app/src/player/transcript.rsmodified+35 -6
@@ -28,6 +28,31 @@ const KEEP: usize = 64;
2828 /// What identifies a state of the timeline well enough to tell whose words these are.
2929 type Stamp = (usize, u32);
3030
31+/// The model and device a run goes to: the project's pick, else the first one installed for the
32+/// device it allows. `None` when no model is installed there.
33+pub(crate) fn speech_target(session: Option<&PlaybackSession>) -> Option<(String, speech::Device)> {
34+ let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device);
35+ let model = session.and_then(PlaybackSession::speech_model);
36+ speech::plan(choice, model).filter(|(m, d)| speech::check_model(m, *d).is_ok())
37+}
38+
39+/// The model the download button fetches and the device it goes to: the project's pick, else
40+/// large-v3-turbo on a GPU and base on the CPU.
41+pub(crate) fn speech_download(session: Option<&PlaybackSession>) -> (String, speech::Device) {
42+ let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device);
43+ let device = match choice {
44+ speech::DeviceChoice::Cpu => speech::Device::Cpu,
45+ speech::DeviceChoice::Gpu => speech::Device::Gpu,
46+ speech::DeviceChoice::Auto if speech::gpu_available() => speech::Device::Gpu,
47+ speech::DeviceChoice::Auto => speech::Device::Cpu,
48+ };
49+ let model = session.and_then(PlaybackSession::speech_model).unwrap_or(match device {
50+ speech::Device::Gpu => "large-v3-turbo",
51+ speech::Device::Cpu => "base",
52+ });
53+ (model.to_string(), device)
54+}
55+
3156 pub(crate) struct Transcript {
3257 /// The words as the timeline stands (timeline frames), `None` before the first listen.
3358 pub(crate) words: Option<Vec<Spoken>>,
@@ -199,12 +224,15 @@ impl Player {
199224 this.notify_user(why.into());
200225 cx.notify();
201226 };
202- if let Err(why) = speech::available() {
227+ if let Err(why) = speech::stt_bin() {
203228 return fail(self, why, cx);
204229 }
205- let Some(model) = speech::pick_model(|m| speech::check_model(m).is_ok()) else {
230+ let Some((model, device)) = speech_target(self.session.as_ref()) else {
206231 return fail(self, "No speech model is installed".into(), cx);
207232 };
233+ if let Err(why) = speech::available(device) {
234+ return fail(self, why, cx);
235+ }
208236 let Some(session) = self.session.as_ref() else {
209237 return;
210238 };
@@ -219,7 +247,7 @@ impl Player {
219247 self.transcript.status.clear();
220248 let work = cx.background_executor().spawn({
221249 let job = job.clone();
222- async move { speech::listen(heard, model, "auto", true, &job) }
250+ async move { speech::listen(heard, &model, device, "auto", true, &job) }
223251 });
224252 cx.spawn(async move |this, cx| {
225253 let heard = work.await;
@@ -269,12 +297,13 @@ impl Player {
269297 cx.notify();
270298 }
271299
272- /// Fetches the speech model (the base one) with progress, off the UI thread. Nothing is
273- /// started while one is already coming.
300+ /// Fetches the speech model the project chose (see [`speech_download`]) with progress, off the
301+ /// UI thread. Nothing is started while one is already coming.
274302 pub(crate) fn start_model_download(&mut self, cx: &mut Context<Self>) {
275303 if self.transcript.download.is_some() {
276304 return;
277305 }
306+ let (model, device) = speech_download(self.session.as_ref());
278307 let job = Arc::new(Job::default());
279308 let id = self.transcript.runs.wrapping_add(1);
280309 self.transcript.runs = id;
@@ -282,7 +311,7 @@ impl Player {
282311 self.transcript.status.clear();
283312 let work = cx.background_executor().spawn({
284313 let job = job.clone();
285- async move { speech::download_model("base", &job) }
314+ async move { speech::download_model(&model, device, &job) }
286315 });
287316 cx.spawn(async move |this, cx| {
288317 let done = work.await;
crates/app/src/tests/caps.rsmodified+1 -2
@@ -13,12 +13,11 @@ fn a_caption_drag_stays_between_its_neighbours() {
1313 }
1414
1515 #[test]
16-fn speech_models_have_plain_names_and_the_real_one_in_the_tooltip() {
16+fn speech_models_have_plain_names() {
1717 assert_eq!(crate::creator::model_label("tiny"), "Fast");
1818 assert_eq!(crate::creator::model_label("base"), "Balanced");
1919 assert_eq!(crate::creator::model_label("small"), "Accurate");
2020 assert_eq!(crate::creator::model_label("medium"), "Medium");
21- assert!(crate::creator::model_tip("tiny").contains("tiny"));
2221 }
2322
2423 #[test]
crates/app/src/tests/creator.rsmodified+3 -5
@@ -206,7 +206,7 @@ fn speaking_text_makes_a_voiceover_the_timeline_takes() {
206206
207207 #[test]
208208 fn listening_for_captions_runs_end_to_end_when_speech_is_installed() {
209- if speech::available().is_err() {
209+ if speech::available(speech::Device::Cpu).is_err() {
210210 eprintln!("skipped: edith-stt or its model is not installed");
211211 return;
212212 }
@@ -215,10 +215,10 @@ fn listening_for_captions_runs_end_to_end_when_speech_is_installed() {
215215 assert!(hears.contains(&speech::Hear::Mix) && hears.contains(&speech::Hear::Lane(Lane::A1)));
216216 let heard = speech::prepare(&s, speech::Hear::Mix).expect("the fixture has sound");
217217 let job = speech::Job::default();
218- let model = speech::installed_models()[0];
218+ let model = speech::installed_models(speech::Device::Cpu)[0];
219219 // A tone is not speech: whatever comes back, it comes back (and cancel stops it early).
220220 job.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
221- assert_eq!(speech::listen(heard, model, "en", false, &job).unwrap_err(), speech::CANCELLED);
221+ assert_eq!(speech::listen(heard, model, speech::Device::Cpu, "en", false, &job).unwrap_err(), speech::CANCELLED);
222222 }
223223
224224 #[test]
@@ -251,7 +251,6 @@ fn every_creator_tool_has_a_menu_row_a_palette_entry_and_a_card_control() {
251251 "tools-target",
252252 "tools-ceiling",
253253 "tools-lang",
254- "tools-model",
255254 "tools-tab-a",
256255 "tools-tab-b",
257256 "mix-normalize",
@@ -347,6 +346,5 @@ fn a_tool_error_or_a_clock_or_a_model_tip_reads_plainly() {
347346 assert_eq!(creator::clock(0.0), "0:00");
348347 assert_eq!(creator::clock(75.0), "1:15");
349348 assert_eq!(creator::clock(3725.0), "1:02:05");
350- assert!(creator::model_tip("base").contains("a middle ground"));
351349 assert_eq!(creator::lufs_text(-20.0), "\u{2212}20.0");
352350 }
crates/app/src/ui/cards/tools.rsmodified+5 -11
@@ -6,6 +6,7 @@
66 use super::common::*;
77 use crate::creator::{self, LANGUAGES, Said};
88 use crate::player::tools::{Cycle, NumField, Tool, Tools};
9+use crate::player::transcript;
910 use crate::ui::icons::Icon;
1011 use crate::ui::kit::{self, Segment};
1112 use crate::*;
@@ -488,15 +489,14 @@ impl Player {
488489 /// transcript to read from, "From the transcript" is the first and default choice (instant);
489490 /// "Listen again" keeps the sound pickers under it.
490491 fn listen_body(&self, t: &Tools, fillers: bool, list_w: f32, cx: &mut Context<Self>) -> Div {
491- let models = self.tools_models();
492+ let no_model = transcript::speech_target(self.session.as_ref()).is_none();
492493 let hears = self.tools_hears();
493494 let downloading = self.transcript.download.is_some();
494495 let from_transcript = self.transcript_words().is_some() && !t.relisten;
495496 let hear_items: Vec<SharedString> = hears.iter().map(|h| creator::hear_label(*h).into()).collect();
496497 let lang_items: Vec<SharedString> = LANGUAGES.iter().map(|(_, name)| (*name).into()).collect();
497- let model_items: Vec<SharedString> = models.iter().map(|m| creator::model_label(m).into()).collect();
498498 let _ = Hear::Mix;
499- let why = match (models.is_empty() && !from_transcript, t.running.is_some()) {
499+ let why = match (no_model && !from_transcript, t.running.is_some()) {
500500 (true, _) => Some("Install a speech model first"),
501501 (false, true) => Some("Already listening"),
502502 _ => None,
@@ -527,17 +527,11 @@ impl Player {
527527 ));
528528 }
529529 if !from_transcript {
530- let model_row = drop_row("tools-model", "Model", model_items, t.model, t.open == Some(Cycle::Model), Cycle::Model, list_w, busy, cx);
531- let model_tip = models.get(t.model).map(|m| creator::model_tip(m));
532530 body = body
533531 .child(drop_row("tools-hear", "Listen to", hear_items, t.hear, t.open == Some(Cycle::Hear), Cycle::Hear, list_w, busy, cx))
534- .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx))
535- .child(match model_tip {
536- Some(tip) => model_row.id("tools-model-row").tooltip(crate::ui::widgets::overlay_tip_hover("Model", "", Some(&tip))).into_any_element(),
537- None => model_row.into_any_element(),
538- });
532+ .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx));
539533 }
540- if models.is_empty() && !from_transcript {
534+ if no_model && !from_transcript {
541535 body = body.child(missing(
542536 "No speech model is installed yet. Download one, or put one in the models folder.",
543537 vec![
crates/app/src/ui/overlays.rsmodified+2 -0
@@ -788,7 +788,9 @@ impl Player {
788788 // A refused row (a format this timeline cannot be written in) is
789789 // dimmed and says why on hover; it takes no click.
790790 let why = self.export_choice_refusal(choice);
791+ let missing = self.speech_model_missing(choice);
791792 crate::ui::popup::popup_row(("picker-row", n), label, detail, Some(picked), why.as_deref())
793+ .when(missing, |d| d.opacity(0.45))
792794 .when(n == picker.sel, |d| d.bg(rgb(DARK_RAISED())))
793795 .when(why.is_none(), |d| {
794796 d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx)))
crates/app/src/ui/settings_stance.rsmodified+69 -6
@@ -54,6 +54,7 @@ use crate::ui::choice;
5454 use crate::ui::hitmap;
5555 use crate::ui::type_scale;
5656 use crate::*;
57+use engine::speech::{self, DeviceChoice};
5758 use gpui::{AnyElement, KeyDownEvent, SharedString};
5859
5960 /// Which of the page's four sections is showing. Kept on [`Player`] beside
@@ -293,6 +294,24 @@ pub(crate) enum ChoiceRow {
293294 /// The two stand-in switches, Off/On.
294295 Proxies,
295296 AutoProxies,
297+ /// What the speech model runs on ([`device_choices`]).
298+ Device,
299+}
300+
301+/// The devices the picker offers: the GPU only when edith-stt has one.
302+pub(crate) fn device_choices() -> Vec<DeviceChoice> {
303+ match speech::gpu_available() {
304+ true => vec![DeviceChoice::Auto, DeviceChoice::Cpu, DeviceChoice::Gpu],
305+ false => vec![DeviceChoice::Auto, DeviceChoice::Cpu],
306+ }
307+}
308+
309+fn device_label(device: DeviceChoice) -> &'static str {
310+ match device {
311+ DeviceChoice::Auto => "Auto",
312+ DeviceChoice::Cpu => "CPU",
313+ DeviceChoice::Gpu => "GPU",
314+ }
296315 }
297316
298317 /// The two words a switch answers with, and the index each one sits at.
@@ -316,10 +335,11 @@ pub(crate) fn index_of<T: PartialEq>(all: &[T], value: T) -> Option<usize> {
316335 impl ChoiceRow {
317336 /// Every choice row there is, for the guards below.
318337 #[cfg(test)]
319- pub(crate) const ALL: [ChoiceRow; 3] = [
338+ pub(crate) const ALL: [ChoiceRow; 4] = [
320339 ChoiceRow::Tone,
321340 ChoiceRow::Proxies,
322341 ChoiceRow::AutoProxies,
342+ ChoiceRow::Device,
323343 ];
324344
325345 /// The row's chips, in order, each a word read off the same table the
@@ -334,6 +354,7 @@ impl ChoiceRow {
334354 ChoiceRow::Proxies | ChoiceRow::AutoProxies => {
335355 SWITCH.iter().map(|w| w.to_string()).collect()
336356 }
357+ ChoiceRow::Device => device_choices().into_iter().map(|d| device_label(d).to_string()).collect(),
337358 }
338359 }
339360
@@ -343,6 +364,7 @@ impl ChoiceRow {
343364 match self {
344365 ChoiceRow::Tone => player.session.is_some(),
345366 ChoiceRow::Proxies | ChoiceRow::AutoProxies => true,
367+ ChoiceRow::Device => player.session.is_some(),
346368 }
347369 }
348370 }
@@ -352,7 +374,7 @@ impl ChoiceRow {
352374 /// and a song has no Encoder row ([`export_section`]'s own two gates).
353375 pub(crate) fn choice_rows(tab: SettingsTab, _format: Format) -> Vec<ChoiceRow> {
354376 match tab {
355- SettingsTab::Project => vec![ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies],
377+ SettingsTab::Project => vec![ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies],
356378 SettingsTab::Editor | SettingsTab::Keys => Vec::new(),
357379 }
358380 }
@@ -364,6 +386,10 @@ pub(crate) fn current_choice(player: &Player, row: ChoiceRow) -> Option<usize> {
364386 .session
365387 .as_ref()
366388 .and_then(|session| index_of(&Preset::ALL, session.tone())),
389+ ChoiceRow::Device => player
390+ .session
391+ .as_ref()
392+ .and_then(|session| index_of(&device_choices(), session.speech_device())),
367393 ChoiceRow::Proxies => Some(switch_index(player.proxies_on)),
368394 // The import switch waits on editing copies: while they are off it shows off, and its own
369395 // value is kept, so it comes back on when they are turned on again.
@@ -616,6 +642,18 @@ fn project_section(player: &Player, cx: &mut Context<Player>) -> impl IntoElemen
616642 INK1(),
617643 ))
618644 .child(still_row(player, cx))
645+ .child(speech_model_row(player, cx))
646+ .child(choice_row(
647+ "settings-speech-device",
648+ "Speech device",
649+ "where the speech model runs; Auto takes the GPU when this computer has one",
650+ None,
651+ None,
652+ false,
653+ ChoiceRow::Device,
654+ player,
655+ cx,
656+ ))
619657 // Only a project with HDR in it has anything to choose here.
620658 .children(has_hdr.then(|| {
621659 choice_row(
@@ -706,6 +744,25 @@ fn still_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
706744 .child(field)
707745 }
708746
747+/// The speech model the project transcribes with: Auto, or one of [`speech::MODELS`] from a list.
748+/// Models not installed for the device are dimmed in the list.
749+fn speech_model_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
750+ let value = match player.session.as_ref().and_then(|s| s.speech_model()) {
751+ Some(model) => crate::creator::model_label(model),
752+ None => "Auto".to_string(),
753+ };
754+ list_row(
755+ "settings-speech-model",
756+ "Speech model",
757+ value,
758+ "the model that hears the timeline for captions, fillers and the transcript; Auto takes the best one installed",
759+ None,
760+ player,
761+ cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::SpeechModel, event.position(), cx)),
762+ INK1(),
763+ )
764+}
765+
709766 /// A chip of `row` was picked (by a click, or by an arrow through
710767 /// [`settings_arrow`]): the value at `at`, through the same door the row's
711768 /// old cycle press and the keymap's own action go through -- the switches
@@ -729,6 +786,11 @@ fn pick_choice(player: &mut Player, row: ChoiceRow, at: usize, cx: &mut Context<
729786 player.toggle_auto_proxies(cx);
730787 }
731788 }
789+ ChoiceRow::Device => {
790+ if let Some(&device) = device_choices().get(at) {
791+ player.apply_speech_device(device, cx);
792+ }
793+ }
732794 }
733795 }
734796
@@ -1785,7 +1847,7 @@ const SETTINGS_GAP: f32 = 8.;
17851847 /// under the hand (user 2026-09-20: "switching between them feels weird"). A
17861848 /// shorter section leaves air below its last row; a short window still
17871849 /// scrolls, the plate's `max_h` cap shrinking this from `min_h(0)`.
1788-pub(crate) const SETTINGS_ROWS_H: f32 = 7. * CONTROL_H + 36. + 7. * 2.;
1850+pub(crate) const SETTINGS_ROWS_H: f32 = 9. * CONTROL_H + 36. + 9. * 2.;
17891851
17901852 /// The plate's height that is not its rows: the dialog's padding and gaps, the title and the tab
17911853 /// strip. The plate's top is set from it, so the tab strip sits on one line for every tab.
@@ -2019,7 +2081,7 @@ mod tests {
20192081 fn the_choice_rows_sit_in_the_tabs_they_belong_to() {
20202082 assert_eq!(
20212083 choice_rows(SettingsTab::Project, Format::Mp4),
2022- [ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies]
2084+ [ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies]
20232085 );
20242086 assert!(choice_rows(SettingsTab::Editor, Format::Mp4).is_empty());
20252087 assert!(choice_rows(SettingsTab::Keys, Format::Mp4).is_empty());
@@ -2035,7 +2097,7 @@ mod tests {
20352097 fn the_panel_and_its_chip_rows_fit_at_1280_by_720() {
20362098 // PROJECT at its tallest (HDR row and its hint, both switches, the
20372099 // storage line) still fits the rows area.
2038- let project_tallest = 7. * CONTROL_H + 36. + 7. * 2.;
2100+ let project_tallest = 9. * CONTROL_H + 36. + 9. * 2.;
20392101 assert!(project_tallest <= SETTINGS_ROWS_H);
20402102 // Width: a generous measure per glyph, so a real font only has room
20412103 // to spare. (label, chord, tail, row)
@@ -2044,7 +2106,8 @@ mod tests {
20442106 let mono_w = |text: &str| text.chars().count() as f32 * 8.;
20452107 let _ = keys;
20462108 // (label, tail, row); the key lives in the tooltip, the column is empty.
2047- let rows: [(&str, &str, ChoiceRow); 3] = [
2109+ let rows: [(&str, &str, ChoiceRow); 4] = [
2110+ ("Speech device", "", ChoiceRow::Device),
20482111 ("When HDR plays on a normal screen", "", ChoiceRow::Tone),
20492112 ("Editing copies (proxies)", "100%", ChoiceRow::Proxies),
20502113 (" Make them on import", "", ChoiceRow::AutoProxies),
crates/app/src/ui/transcript_panel.rsmodified+13 -6
@@ -4,6 +4,7 @@
44 //! lit. Every state is a background on a word whose box never changes, so nothing moves.
55
66 use crate::layout::redesign as r;
7+use crate::player::transcript;
78 use crate::ui::hitmap;
89 use crate::ui::icons::{Icon, IconSize};
910 use crate::ui::kit::{Button, ButtonSize, ButtonStyle};
@@ -299,11 +300,15 @@ fn paragraph(
299300 /// model on the computer it says so plainly and offers to download one.
300301 fn empty_view(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
301302 let t = tokens();
302- let ready = speech::available();
303- let no_model = speech::stt_bin().is_ok() && speech::installed_models().is_empty();
303+ let target = transcript::speech_target(player.session.as_ref());
304+ let ready = match &target {
305+ Some((_, device)) => speech::available(*device),
306+ None => speech::available(transcript::speech_download(player.session.as_ref()).1),
307+ };
308+ let no_model = speech::stt_bin().is_ok() && target.is_none();
304309 let not_built = speech::stt_bin().is_err();
305310 if let Some((job, _)) = &player.transcript.download {
306- return download_view(job.fraction(), cx).into_any_element();
311+ return download_view(player.session.as_ref(), job.fraction(), cx).into_any_element();
307312 }
308313 let note = match (&ready, player.transcript.status.as_str()) {
309314 (Err(_), status) if no_model && !status.is_empty() => format!("{status}. You can also put a model in the models folder yourself."),
@@ -360,9 +365,11 @@ fn empty_view(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
360365 }
361366
362367 /// While the speech model downloads: how far, and Cancel.
363-fn download_view(fraction: f32, cx: &mut Context<Player>) -> impl IntoElement {
368+fn download_view(session: Option<&PlaybackSession>, fraction: f32, cx: &mut Context<Player>) -> impl IntoElement {
364369 let t = tokens();
365- let mb = speech::model_bytes("base") as f32 * fraction / 1_000_000.;
370+ let (model, device) = transcript::speech_download(session);
371+ let total = speech::model_bytes(&model, device) as f32;
372+ let mb = total * fraction / 1_000_000.;
366373 div()
367374 .id("transcript-downloading")
368375 .flex_1()
@@ -381,7 +388,7 @@ fn download_view(fraction: f32, cx: &mut Context<Player>) -> impl IntoElement {
381388 .type_style(type_scale::body())
382389 .text_color(rgb(t.ink2))
383390 .child("Downloading the speech model")
384- .child(format!("{mb:.0} of {:.0} MB", speech::model_bytes("base") as f32 / 1_000_000.)),
391+ .child(format!("{mb:.0} of {:.0} MB", total / 1_000_000.)),
385392 )
386393 .child(
387394 div()
crates/engine/src/edith.rsmodified+44 -12
@@ -444,11 +444,12 @@ use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, Tr
444444 /// The newest project format version: the `N` in the `edith N` first line that
445445 /// [`save`] writes for a project that uses the newest features. A reader refuses any
446446 /// higher version by name.
447-pub const NEWEST_VERSION: u32 = 56;
447+pub const NEWEST_VERSION: u32 = 57;
448448
449449 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
450450 /// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
451-const MAGIC: &[u8] = b"edith 56";
451+const MAGIC: &[u8] = b"edith 57";
452+const MAGIC_V56: &[u8] = b"edith 56";
452453 const MAGIC_V55: &[u8] = b"edith 55";
453454 const MAGIC_V54: &[u8] = b"edith 54";
454455 const MAGIC_V53: &[u8] = b"edith 53";
@@ -650,6 +651,11 @@ pub struct Document {
650651 /// The length a still is placed at, from the `still` line (v52). `None` for a file that
651652 /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s.
652653 pub still_secs: Option<f64>,
654+ /// The speech model, from the `speech` line (v57). `None` for a file that names none, which
655+ /// means the model is picked.
656+ pub speech_model: Option<String>,
657+ /// The device the speech model runs on, from the `speech` line (v57). Auto for a file without one.
658+ pub speech_device: crate::speech::DeviceChoice,
653659 }
654660
655661 /// A parked sequence read off a v45 file.
@@ -831,7 +837,7 @@ pub fn encode_flagged(
831837 if curved || pitched || titled || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
832838 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
833839 let header = if curved {
834- MAGIC
840+ MAGIC_V56
835841 } else if pitched {
836842 MAGIC_V55
837843 } else if titled {
@@ -939,10 +945,11 @@ pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin
939945 main
940946 }
941947
942-/// `main` with the project notes and the still length after it (v52): a `notes` line when there
943-/// are notes, a `still` line when the length is not the default. A project with neither is `main`
944-/// untouched, so it keeps the bytes it had before v52.
945-pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> {
948+/// `main` with the project notes, the still length and the speech choices after it (v52, v57): a
949+/// `notes` line when there are notes, a `still` line when the length is not the default, a
950+/// `speech` line when a model or a device is picked. A project with none is `main` untouched, so
951+/// it keeps the bytes it had before v52.
952+pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64, speech_model: Option<&str>, speech_device: crate::speech::DeviceChoice) -> Vec<u8> {
946953 let mut lines = Vec::new();
947954 if !notes.is_empty() {
948955 lines.extend_from_slice(b"notes ");
@@ -952,11 +959,19 @@ pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> {
952959 if still_secs != STILL_DEFAULT_SECS {
953960 lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes());
954961 }
962+ let speech = speech_model.is_some() || speech_device != crate::speech::DeviceChoice::Auto;
963+ if speech {
964+ lines.extend_from_slice(format!("speech {}", speech_device.as_str()).as_bytes());
965+ if let Some(m) = speech_model {
966+ lines.extend_from_slice(format!(" {m}").as_bytes());
967+ }
968+ lines.push(b'\n');
969+ }
955970 if lines.is_empty() {
956971 return main;
957972 }
958973 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
959- let header = raise_header(&main[..first_end], MAGIC_V52);
974+ let header = raise_header(&main[..first_end], if speech { MAGIC } else { MAGIC_V52 });
960975 main.splice(..first_end, header);
961976 if main.last() != Some(&b'\n') {
962977 main.push(b'\n');
@@ -1049,7 +1064,8 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se
10491064 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
10501065 // when a part is v46; a newer-only line under an older header is refused.
10511066 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1052- let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1067+ let v57 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1068+ let v56 = v57 || is(&bytes, MAGIC_V56) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V56));
10531069 let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55));
10541070 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
10551071 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
@@ -1060,7 +1076,7 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se
10601076 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
10611077 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
10621078 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1063- let header = if v56 { MAGIC } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
1079+ let header = if v57 { MAGIC } else if v56 { MAGIC_V56 } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
10641080 bytes.splice(..first_end, header.iter().copied());
10651081 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
10661082 escape_text(active.1, &mut bytes);
@@ -2297,7 +2313,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
22972313 // The one that carries a clip's placement animation, as `tkeys` lines...
22982314 // The one that carries a clip's stabilisation, as `stab` lines...
22992315 // The one that carries a clip's pitch shift, as `pitch` lines...
2300- let v56 = first == MAGIC;
2316+ let v57 = first == MAGIC;
2317+ let v56 = v57 || first == MAGIC_V56;
23012318 let v55 = v56 || first == MAGIC_V55;
23022319 let v54 = v55 || first == MAGIC_V54;
23032320 let v53 = v54 || first == MAGIC_V53;
@@ -2454,6 +2471,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
24542471 bins: Vec::new(),
24552472 notes: String::new(),
24562473 still_secs: None,
2474+ speech_model: None,
2475+ speech_device: crate::speech::DeviceChoice::Auto,
24572476 };
24582477 // The block of a parked sequence being read: its id, name and the lines so far.
24592478 let mut block: Option<(u32, String, Vec<u8>)> = None;
@@ -3588,6 +3607,19 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
35883607 }
35893608 doc.still_secs = Some(secs);
35903609 }
3610+ b"speech" if v57 => {
3611+ let text = std::str::from_utf8(rest).map_err(|_| format!("line {n}: speech is not text"))?;
3612+ let f: Vec<&str> = text.split(' ').collect();
3613+ doc.speech_device = f
3614+ .first()
3615+ .and_then(|d| crate::speech::DeviceChoice::parse(d))
3616+ .ok_or_else(|| format!("line {n}: speech wants a device, auto, cpu or gpu"))?;
3617+ doc.speech_model = match f.get(1) {
3618+ None => None,
3619+ Some(m) if crate::speech::MODELS.contains(m) && f.len() == 2 => Some(m.to_string()),
3620+ Some(m) => return Err(format!("line {n}: speech model `{m}` is not one of {}", crate::speech::MODELS.join(", ")).into()),
3621+ };
3622+ }
35913623 b"bin" if v51 => {
35923624 let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect();
35933625 if f.len() != 3 {
@@ -7199,7 +7231,7 @@ mod tests {
71997231 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
72007232 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
72017233 );
7202- let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS);
7234+ let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS, None, crate::speech::DeviceChoice::Auto);
72037235 std::fs::write(&path, &bytes).unwrap();
72047236 String::from_utf8(bytes).unwrap()
72057237 };
crates/engine/src/playback.rsmodified+26 -2
@@ -1436,7 +1436,8 @@ impl PlaybackSession {
14361436 .with_lane_flags(&doc.flags)
14371437 .with_tone(doc.tone)
14381438 .with_notes(doc.notes)
1439- .with_still_secs(doc.still_secs);
1439+ .with_still_secs(doc.still_secs)
1440+ .with_speech(doc.speech_model, doc.speech_device);
14401441 session.counts = counts;
14411442 session.rates = rates;
14421443 Ok(session)
@@ -2296,7 +2297,7 @@ impl PlaybackSession {
22962297 .min(main.timeline_frames().saturating_sub(1));
22972298 let main_bytes = self.encode_sequence(&dir, main, playhead);
22982299 let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins());
2299- let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs());
2300+ let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs(), self.project.speech_model(), self.project.speech_device());
23002301 if !self.project.uses_sequences() {
23012302 return crate::edith::write_atomic(path, &main_bytes);
23022303 }
@@ -5251,6 +5252,26 @@ impl PlaybackSession {
52515252 self.project.set_still_secs(secs)
52525253 }
52535254
5255+ /// The speech model the project names, or `None` for the one picked ([`Project::speech_model`]).
5256+ pub fn speech_model(&self) -> Option<&str> {
5257+ self.project.speech_model()
5258+ }
5259+
5260+ /// Sets it ([`Project::set_speech_model`]).
5261+ pub fn set_speech_model(&mut self, model: Option<&str>) -> bool {
5262+ self.project.set_speech_model(model)
5263+ }
5264+
5265+ /// The device the speech model runs on ([`Project::speech_device`]).
5266+ pub fn speech_device(&self) -> crate::speech::DeviceChoice {
5267+ self.project.speech_device()
5268+ }
5269+
5270+ /// Sets it ([`Project::set_speech_device`]).
5271+ pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool {
5272+ self.project.set_speech_device(device)
5273+ }
5274+
52545275 /// What source 0's own file declared about how bright it gets
52555276 /// ([`ContentLight`]): a property of the film, read once at open, and
52565277 /// entirely absent (every field `None`) for an SDR file, a song or a
@@ -6883,6 +6904,8 @@ impl PlaybackSession {
68836904 caption_style: self.project.caption_style(),
68846905 notes: self.project.notes().to_string(),
68856906 still_secs: self.project.still_secs(),
6907+ speech_model: self.project.speech_model().map(str::to_string),
6908+ speech_device: self.project.speech_device(),
68866909 }
68876910 }
68886911
@@ -7959,6 +7982,7 @@ Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
79597982 .with_tone(doc.tone)
79607983 .with_notes(doc.notes)
79617984 .with_still_secs(doc.still_secs)
7985+ .with_speech(doc.speech_model, doc.speech_device)
79627986 // The palette before what is placed on it: a caption names a row of
79637987 // it, and [`Project::with_subs`] refuses one naming a row that is
79647988 // not there.
crates/engine/src/project.rsmodified+43 -0
@@ -2365,6 +2365,10 @@ pub(crate) struct ProjectSettings {
23652365 pub(crate) notes: String,
23662366 /// How long a still image is placed for, in seconds (v52).
23672367 pub(crate) still_secs: f64,
2368+ /// The speech model the transcript and captions run on; `None` picks one (v57).
2369+ pub(crate) speech_model: Option<String>,
2370+ /// The device the speech model runs on (v57).
2371+ pub(crate) speech_device: crate::speech::DeviceChoice,
23682372 }
23692373
23702374 impl ProjectSettings {
@@ -2387,6 +2391,8 @@ impl ProjectSettings {
23872391 caption_style: crate::captionanim::CaptionStyle::default(),
23882392 notes: String::new(),
23892393 still_secs: STILL_DEFAULT_SECS,
2394+ speech_model: None,
2395+ speech_device: crate::speech::DeviceChoice::Auto,
23902396 }
23912397 }
23922398 }
@@ -4342,6 +4348,43 @@ impl Project {
43424348 self
43434349 }
43444350
4351+ /// The speech model the project names, or `None` for the one picked.
4352+ pub fn speech_model(&self) -> Option<&str> {
4353+ self.settings.speech_model.as_deref()
4354+ }
4355+
4356+ /// Sets it (`None` picks one). `false` for the one already in force; otherwise one undo step.
4357+ pub fn set_speech_model(&mut self, model: Option<&str>) -> bool {
4358+ if self.settings.speech_model.as_deref() == model {
4359+ return false;
4360+ }
4361+ self.snapshot();
4362+ self.settings.speech_model = model.map(str::to_string);
4363+ true
4364+ }
4365+
4366+ /// The device the speech model runs on.
4367+ pub fn speech_device(&self) -> crate::speech::DeviceChoice {
4368+ self.settings.speech_device
4369+ }
4370+
4371+ /// Sets it. `false` for the one already in force; otherwise one undo step.
4372+ pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool {
4373+ if self.settings.speech_device == device {
4374+ return false;
4375+ }
4376+ self.snapshot();
4377+ self.settings.speech_device = device;
4378+ true
4379+ }
4380+
4381+ /// The speech choices a *load* puts back: no undo step, as [`with_still_secs`](Project::with_still_secs).
4382+ pub(crate) fn with_speech(mut self, model: Option<String>, device: crate::speech::DeviceChoice) -> Self {
4383+ self.settings.speech_model = model;
4384+ self.settings.speech_device = device;
4385+ self
4386+ }
4387+
43454388 /// Sets it. `false` for the one already in force, which is what keeps a
43464389 /// re-pick of the current rendition from costing a reseek. One undo step
43474390 /// like every other project-setting pick.
crates/engine/src/speech.rsmodified+217 -73
@@ -9,6 +9,7 @@
99 use std::io::{BufRead, BufReader, Read};
1010 use std::path::{Path, PathBuf};
1111 use std::process::{Command, Stdio};
12+use std::sync::OnceLock;
1213 use std::sync::atomic::{AtomicBool, Ordering};
1314
1415 use crate::project::Lane;
@@ -17,7 +18,7 @@ use crate::{AudioSession, PlaybackSession, subtitle};
1718 /// The sample rate edith-stt is fed.
1819 pub const RATE: u32 = 16_000;
1920 /// The Whisper model sizes edith-stt knows.
20-pub const MODELS: &[&str] = &["tiny", "base", "small"];
21+pub const MODELS: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"];
2122 /// Silence longer than this (seconds) between two words ends a caption cue.
2223 pub const CAPTION_GAP_SECS: f64 = 0.7;
2324 /// Whisper drops disfluencies unless its prompt shows them: this prompt, put before the
@@ -46,7 +47,7 @@ pub fn home() -> PathBuf {
4647 /// The edith-stt binary: `EDITH_STT_BIN`, else the first
4748 /// `tools/edith-stt/target/release/edith-stt` above the running executable.
4849 pub fn stt_bin() -> Result<PathBuf, String> {
49- const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` in the edith repo, or set EDITH_STT_BIN to the binary";
50+ const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` (`--features vulkan` for the GPU) in the edith repo, or set EDITH_STT_BIN to the binary";
5051 if let Some(p) = std::env::var_os("EDITH_STT_BIN") {
5152 let p = PathBuf::from(p);
5253 return if p.is_file() { Ok(p) } else { Err(format!("EDITH_STT_BIN is set to {}, which is not a file. {NOT_BUILT}", p.display())) };
@@ -62,13 +63,99 @@ pub fn stt_bin() -> Result<PathBuf, String> {
6263 Err(NOT_BUILT.into())
6364 }
6465
65-pub fn check_model(model: &str) -> Result<(), String> {
66+/// What edith-stt runs the model on.
67+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68+pub enum Device {
69+ Cpu,
70+ Gpu,
71+}
72+
73+impl Device {
74+ /// The name edith-stt takes for `--device`.
75+ pub fn flag(self) -> &'static str {
76+ match self {
77+ Self::Cpu => "cpu",
78+ Self::Gpu => "gpu",
79+ }
80+ }
81+}
82+
83+/// The device a user picks: auto leaves it to [`DeviceChoice::resolve`].
84+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85+pub enum DeviceChoice {
86+ #[default]
87+ Auto,
88+ Cpu,
89+ Gpu,
90+}
91+
92+impl DeviceChoice {
93+ pub fn parse(s: &str) -> Option<Self> {
94+ match s {
95+ "auto" => Some(Self::Auto),
96+ "cpu" => Some(Self::Cpu),
97+ "gpu" => Some(Self::Gpu),
98+ _ => None,
99+ }
100+ }
101+
102+ pub fn as_str(self) -> &'static str {
103+ match self {
104+ Self::Auto => "auto",
105+ Self::Cpu => "cpu",
106+ Self::Gpu => "gpu",
107+ }
108+ }
109+
110+ /// The device this choice runs `model` on: auto is the GPU when edith-stt has one and the
111+ /// GPU file of `model` is installed, else the CPU.
112+ pub fn resolve(self, model: &str) -> Device {
113+ match self {
114+ Self::Cpu => Device::Cpu,
115+ Self::Gpu => Device::Gpu,
116+ Self::Auto if gpu_available() && check_model(model, Device::Gpu).is_ok() => Device::Gpu,
117+ Self::Auto => Device::Cpu,
118+ }
119+ }
120+}
121+
122+/// Whether edith-stt reports a usable GPU (`--has-gpu` exits 0). An old binary without the flag
123+/// counts as no GPU.
124+pub fn gpu_available() -> bool {
125+ static GPU: OnceLock<bool> = OnceLock::new();
126+ *GPU.get_or_init(|| {
127+ stt_bin().is_ok_and(|bin| {
128+ Command::new(bin)
129+ .arg("--has-gpu")
130+ .stdin(Stdio::null())
131+ .stdout(Stdio::null())
132+ .stderr(Stdio::null())
133+ .status()
134+ .is_ok_and(|st| st.success())
135+ })
136+ })
137+}
138+
139+/// Where a model lives for `device`: the folder `whisper-<model>` for the CPU, the file
140+/// `ggml-<model>.bin` for the GPU.
141+pub fn model_path(model: &str, device: Device) -> PathBuf {
142+ match device {
143+ Device::Cpu => models_dir().join(format!("whisper-{model}")),
144+ Device::Gpu => models_dir().join(format!("ggml-{model}.bin")),
145+ }
146+}
147+
148+pub fn check_model(model: &str, device: Device) -> Result<(), String> {
66149 if !MODELS.contains(&model) {
67150 return Err(format!("model `{model}` is not one of {}", MODELS.join(", ")));
68151 }
69- let dir = home().join(".cache/edith/models").join(format!("whisper-{model}"));
70- if !dir.is_dir() {
71- return Err(format!("the {model} model is not installed at {}; edith-stt downloads it only when asked to", dir.display()));
152+ let at = model_path(model, device);
153+ let there = match device {
154+ Device::Cpu => at.is_dir(),
155+ Device::Gpu => at.is_file(),
156+ };
157+ if !there {
158+ return Err(format!("the {model} model ({}) is not installed at {}; edith-stt downloads it only when asked to", device.flag(), at.display()));
72159 }
73160 Ok(())
74161 }
@@ -78,9 +165,30 @@ pub fn check_lang(lang: &str) -> Result<(), String> {
78165 if ok { Ok(()) } else { Err(format!("language `{lang}` must be auto or a language code such as en")) }
79166 }
80167
81-/// The model when none is named: the first installed of base, small, tiny.
82-pub fn pick_model(installed: impl Fn(&str) -> bool) -> Option<&'static str> {
83- ["base", "small", "tiny"].into_iter().find(|m| installed(m))
168+/// The model when none is named: the first installed in the device's order.
169+pub fn pick_model(installed: impl Fn(&str) -> bool, device: Device) -> Option<&'static str> {
170+ let order: [&'static str; 6] = match device {
171+ Device::Gpu => ["large-v3-turbo", "large-v3", "medium", "small", "base", "tiny"],
172+ Device::Cpu => ["base", "small", "tiny", "medium", "large-v3-turbo", "large-v3"],
173+ };
174+ order.into_iter().find(|m| installed(m))
175+}
176+
177+/// The model and device a request runs on: the named model (its device from `choice`), or with no
178+/// model named the first one installed for the device `choice` allows (auto tries the GPU first).
179+pub fn plan(choice: DeviceChoice, model: Option<&str>) -> Option<(String, Device)> {
180+ if let Some(m) = model {
181+ return Some((m.to_string(), choice.resolve(m)));
182+ }
183+ let on = |d: Device| move |m: &str| check_model(m, d).is_ok();
184+ let gpu = || pick_model(on(Device::Gpu), Device::Gpu).map(|m| (m.to_string(), Device::Gpu));
185+ let cpu = || pick_model(on(Device::Cpu), Device::Cpu).map(|m| (m.to_string(), Device::Cpu));
186+ match choice {
187+ DeviceChoice::Cpu => cpu(),
188+ DeviceChoice::Gpu => gpu(),
189+ DeviceChoice::Auto if gpu_available() => gpu().or_else(cpu),
190+ DeviceChoice::Auto => cpu(),
191+ }
84192 }
85193
86194 #[derive(Clone, Debug)]
@@ -548,10 +656,10 @@ pub const CANCELLED: &str = "cancelled";
548656 /// lines feed `job`; setting `job.cancel` kills it. The last few other stderr lines are kept
549657 /// for the error if the binary fails.
550658 #[allow(clippy::too_many_arguments)]
551-pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> {
659+pub fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> {
552660 let hint_args: Vec<&str> = if hint.is_empty() { Vec::new() } else { vec!["--prompt", hint] };
553661 let mut child = Command::new(bin)
554- .args(["--model", model, "--language", lang, "--offset"])
662+ .args(["--model", model, "--device", device.flag(), "--language", lang, "--offset"])
555663 .arg(format!("{offset:.3}"))
556664 .args(&hint_args)
557665 .arg(wav)
@@ -608,9 +716,9 @@ pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offs
608716 Ok(out)
609717 }
610718
611-/// The models installed, smallest first.
612-pub fn installed_models() -> Vec<&'static str> {
613- MODELS.iter().copied().filter(|m| check_model(m).is_ok()).collect()
719+/// The models installed for `device`, smallest first.
720+pub fn installed_models(device: Device) -> Vec<&'static str> {
721+ MODELS.iter().copied().filter(|m| check_model(m, device).is_ok()).collect()
614722 }
615723
616724 /// Where the speech models live: one folder per model, `whisper-<name>`, here.
@@ -628,80 +736,116 @@ const MODEL_FILES: [(&str, bool); 4] = [
628736 const MODEL_OPTIONAL: &str = "generation_config.json";
629737
630738 /// About how many bytes a model's files add up to, for a progress bar before the sizes are known.
631-pub fn model_bytes(model: &str) -> u64 {
632- match model {
633- "tiny" => 152_000_000,
634- "small" => 970_000_000,
739+pub fn model_bytes(model: &str, device: Device) -> u64 {
740+ match (device, model) {
741+ (Device::Gpu, "tiny") => 78_000_000,
742+ (Device::Gpu, "base") => 148_000_000,
743+ (Device::Gpu, "small") => 488_000_000,
744+ (Device::Gpu, "medium") => 1_530_000_000,
745+ (Device::Gpu, "large-v3") => 3_100_000_000,
746+ (Device::Gpu, "large-v3-turbo") => 1_620_000_000,
747+ (Device::Cpu, "tiny") => 152_000_000,
748+ (Device::Cpu, "small") => 970_000_000,
749+ (Device::Cpu, "medium") => 3_060_000_000,
750+ (Device::Cpu, "large-v3") => 3_090_000_000,
751+ (Device::Cpu, "large-v3-turbo") => 1_620_000_000,
635752 _ => 293_000_000,
636753 }
637754 }
638755
639-/// Downloads the `model` (one of [`MODELS`]) into [`models_dir`] with `curl`, from the same place
640-/// `edith-stt` fetches it (huggingface.co/openai/whisper-<model>). The folder appears only when
756+/// Fetches `url` into `tmp` with curl, reporting the bytes `have` counts against `total` as
757+/// progress. `Ok(false)` when curl fails (`tmp` is removed); a cancel kills it.
758+fn fetch(url: &str, tmp: &Path, job: &Job, total: f64, have: &dyn Fn() -> u64) -> Result<bool, String> {
759+ let mut child = Command::new("curl")
760+ .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"])
761+ .arg(tmp)
762+ .arg(url)
763+ .stdin(Stdio::null())
764+ .stdout(Stdio::null())
765+ .stderr(Stdio::null())
766+ .spawn()
767+ .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", models_dir().display()))?;
768+ let status = loop {
769+ if job.cancelled() {
770+ let _ = child.kill();
771+ let _ = child.wait();
772+ let _ = std::fs::remove_file(tmp);
773+ return Err(CANCELLED.into());
774+ }
775+ if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
776+ break status;
777+ }
778+ job.set((have() as f64 / total).min(0.99));
779+ std::thread::sleep(std::time::Duration::from_millis(150));
780+ };
781+ if !status.success() {
782+ let _ = std::fs::remove_file(tmp);
783+ }
784+ Ok(status.success())
785+}
786+
787+/// Downloads the `model` (one of [`MODELS`]) for `device` into [`models_dir`], from the same place
788+/// `edith-stt` fetches it: huggingface.co/openai/whisper-<model> for the CPU folder, and the
789+/// ggerganov/whisper.cpp `ggml-<model>.bin` file for the GPU. The CPU folder appears only when
641790 /// every file is in, so a half-finished download is never taken for an installed model; the files
642791 /// already fetched are kept for the next try. `job` carries the progress and the cancel.
643-pub fn download_model(model: &str, job: &Job) -> Result<(), String> {
792+pub fn download_model(model: &str, device: Device, job: &Job) -> Result<(), String> {
644793 if !MODELS.contains(&model) {
645794 return Err(format!("model `{model}` is not one of {}", MODELS.join(", ")));
646795 }
647796 let root = models_dir();
648- let part = root.join(format!("whisper-{model}.part"));
649- let done = root.join(format!("whisper-{model}"));
650- std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?;
651- let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main");
652- let total = model_bytes(model) as f64;
653- let have = |dir: &Path| -> u64 {
654- std::fs::read_dir(dir)
655- .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum())
656- .unwrap_or(0)
657- };
658- let files = MODEL_FILES.iter().map(|&(f, need)| (f, need)).chain([(MODEL_OPTIONAL, false)]);
659- for (file, needed) in files {
660- let target = part.join(file);
661- if target.exists() {
662- continue;
663- }
664- let tmp = part.join(format!("{file}.tmp"));
665- let mut child = Command::new("curl")
666- .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"])
667- .arg(&tmp)
668- .arg(format!("{base}/{file}"))
669- .stdin(Stdio::null())
670- .stdout(Stdio::null())
671- .stderr(Stdio::null())
672- .spawn()
673- .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", done.display()))?;
674- let status = loop {
675- if job.cancelled() {
676- let _ = child.kill();
677- let _ = child.wait();
678- let _ = std::fs::remove_file(&tmp);
679- return Err(CANCELLED.into());
680- }
681- if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
682- break status;
797+ std::fs::create_dir_all(&root).map_err(|e| format!("cannot create {}: {e}", root.display()))?;
798+ let total = model_bytes(model, device) as f64;
799+ match device {
800+ Device::Gpu => {
801+ let file = format!("ggml-{model}.bin");
802+ let target = root.join(&file);
803+ let tmp = root.join(format!("{file}.part"));
804+ let url = format!("https://huggingface.co/ggerganov/whisper.cpp/resolve/main/{file}");
805+ let len = || std::fs::metadata(&tmp).map(|m| m.len()).unwrap_or(0);
806+ if !fetch(&url, &tmp, job, total, &len)? {
807+ return Err(format!("could not download {file}: check the internet connection and try again"));
683808 }
684- job.set((have(&part) as f64 / total).min(0.99));
685- std::thread::sleep(std::time::Duration::from_millis(150));
686- };
687- if status.success() {
688809 std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?;
689- } else {
690- let _ = std::fs::remove_file(&tmp);
691- if needed {
692- return Err(format!("could not download {file}: check the internet connection and try again"));
810+ }
811+ Device::Cpu => {
812+ let part = root.join(format!("whisper-{model}.part"));
813+ let done = model_path(model, device);
814+ std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?;
815+ let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main");
816+ let have = || -> u64 {
817+ std::fs::read_dir(&part)
818+ .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum())
819+ .unwrap_or(0)
820+ };
821+ let files = MODEL_FILES.iter().copied().chain([(MODEL_OPTIONAL, false)]);
822+ for (file, needed) in files {
823+ let target = part.join(file);
824+ if target.exists() {
825+ continue;
826+ }
827+ let tmp = part.join(format!("{file}.tmp"));
828+ if fetch(&format!("{base}/{file}"), &tmp, job, total, &have)? {
829+ std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?;
830+ } else if needed {
831+ return Err(format!("could not download {file}: check the internet connection and try again"));
832+ }
693833 }
834+ std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?;
694835 }
695836 }
696- std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?;
697837 job.set(1.0);
698838 Ok(())
699839 }
700840
701-/// Whether speech can run at all here: the edith-stt binary is built and a model is installed.
702-pub fn available() -> Result<(), String> {
841+/// Whether speech can run at all here on `device`: the edith-stt binary is built, the GPU is
842+/// usable for the GPU device, and a model is installed for it.
843+pub fn available(device: Device) -> Result<(), String> {
703844 stt_bin()?;
704- if installed_models().is_empty() {
845+ if device == Device::Gpu && !gpu_available() {
846+ return Err("edith-stt finds no usable GPU".into());
847+ }
848+ if installed_models(device).is_empty() {
705849 return Err("The speech model is not installed yet.".into());
706850 }
707851 Ok(())
@@ -771,8 +915,8 @@ fn silence_hallucination(text: &str, no_speech: Option<f64>, avg_logprob: Option
771915 /// What is said in `hear`, word by word, in timeline frames. `fillers` asks Whisper to keep its
772916 /// disfluencies ([`FILLER_PROMPT`]); without it the model tends to drop them. The model runs on
773917 /// a worker thread of the caller's choosing: this blocks until it is done or `job` is cancelled.
774-pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
775- listen(prepare(s, hear)?, model, lang, fillers, job)
918+pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
919+ listen(prepare(s, hear)?, model, device, lang, fillers, job)
776920 }
777921
778922 /// The sound of `hear` as the speech model takes it, read off the session. Split from
@@ -797,9 +941,9 @@ pub fn prepare(s: &PlaybackSession, hear: Hear) -> Result<Heard, String> {
797941 }
798942
799943 /// Runs the speech model over what [`prepare`] read. Needs no session, so it can run anywhere.
800-pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
944+pub fn listen(heard: Heard, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
801945 let bin = stt_bin()?;
802- check_model(model)?;
946+ check_model(model, device)?;
803947 check_lang(lang)?;
804948 let fps = heard.fps;
805949 if job.cancelled() {
@@ -810,7 +954,7 @@ pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) -
810954 std::fs::write(&wav, wav_bytes(&heard.samples)).map_err(|e| format!("writing {}: {e}", wav.display()))?;
811955 let guard = TempFile(wav.clone());
812956 let hint = if fillers { FILLER_PROMPT } else { "" };
813- let raw = run_stt(&bin, &wav, model, lang, hint, 0.0, &heard.label, job);
957+ let raw = run_stt(&bin, &wav, model, device, lang, hint, 0.0, &heard.label, job);
814958 drop(guard);
815959 let mut words = Vec::new();
816960 for seg in parse_raw(&raw?)? {
crates/engine/tests/it/creator_tools.rsmodified+3 -3
@@ -116,7 +116,7 @@ fn a_voiceover_refuses_empty_text_and_out_of_range_speed() {
116116
117117 #[test]
118118 fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() {
119- if speech::available().is_err() {
119+ if speech::available(speech::Device::Cpu).is_err() {
120120 eprintln!("skipped: edith-stt or its model is not installed");
121121 return;
122122 }
@@ -124,8 +124,8 @@ fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() {
124124 // words (or a silent mix), never crash or hang.
125125 let s = PlaybackSession::open(asset("test_av.mp4")).expect("open");
126126 let job = speech::Job::default();
127- let model = speech::installed_models()[0];
128- match speech::transcribe(&s, speech::Hear::Mix, model, "en", false, &job) {
127+ let model = speech::installed_models(speech::Device::Cpu)[0];
128+ match speech::transcribe(&s, speech::Hear::Mix, model, speech::Device::Cpu, "en", false, &job) {
129129 Ok(words) => assert!(words.len() < 20, "a tone is not a speech: {words:?}"),
130130 Err(e) => assert!(!e.is_empty()),
131131 }
crates/mcp/src/help.rsmodified+2 -2
@@ -360,12 +360,12 @@ PROJECT
360360 project_export_timeline {format, path?} writes the active sequence for another editor: format otio (OpenTimelineIO .otio), fcpxml (Final Cut Pro XML 1.10, for Final Cut Pro, Resolve and Premiere) or edl (CMX3600: V1 and A1/A2). Subtitles are left out and the reply says so. Default path: beside the project file. Only the file is written.
361361 project_import_timeline {path} reads an .otio file as a new sequence of the project and makes it the active one, relinking each clip by its path; a missing file becomes offline. One undo step.
362362 proxies {action:status|make|cancel|delete, source} manages editing copies: make starts one in the background (its progress shows in status), cancel stops it and leaves the film off, delete removes it and keeps the film off. With auto_proxies on, each media_import starts its stand-ins.
363- speech_model {download?, model?, cancel?} shows the speech models installed and any download in progress; download:true fetches one in the background (base by default).
363+ speech_model {download?, model?, device?, cancel?} shows the speech models installed per device (cpu, gpu) and any download in progress; download:true fetches one in the background (base by default).
364364 export_captions {chapters:true} returns the chapter list as the YouTube description text, with JSON lines, writing no file. export_cancel {all:true} cancels every unfinished export.
365365 render_preview {clear:true} deletes every render file in the cache (refused while a render runs).
366366 project_status reports the open project. project_settings sets resolution, fps, tonemap, proxies,
367367 auto_proxies, encoder, the master limiter, the notes (free text, several lines, shown by project_status when set) and the still length
368- (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it). Each change and each refusal is reported.
368+ (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it), the speech model and device (speech_model, speech_device auto|cpu|gpu). Each change and each refusal is reported.
369369 sample_rate sets the mix's rate: \"source\" (unset: the highest rate among the sources, or 48 kHz when every source is below 44.1 kHz), 44100, 48000 or 96000, the rows the GUI offers.
370370 project_status {history:true} also lists every undo and redo step with the steps count that undo or redo takes to reach it (undo {steps:3} takes back the three newest).
371371 templates {save:{name, with_clips?}} saves the open project as a template (settings, and the clips too with with_clips:true); a built-in's name is refused.
crates/mcp/src/tools/listen.rsmodified+125 -72
@@ -19,7 +19,7 @@ use std::time::{Duration, UNIX_EPOCH};
1919
2020 use engine::export::{ExportSettings, Format};
2121 use engine::project::{Lane, LaneKind, Speed, SpeedRamp};
22-use engine::speech::{CAPTION_FILLERS, CAPTION_GAP_SECS, CUE_LOW_P, CUE_MIN_SECS, FILLER_PROMPT, MODELS, RATE, RawWord, attach_word_times, caption_cues, capitalise_sentence_starts, check_lang, check_model, home, i16_bytes, norm, parse_raw, pick_model, resample_linear, speaker_changes, stt_bin, wav_bytes};
22+use engine::speech::{CAPTION_FILLERS, CAPTION_GAP_SECS, CUE_LOW_P, CUE_MIN_SECS, Device, DeviceChoice, FILLER_PROMPT, MODELS, RATE, RawWord, attach_word_times, caption_cues, capitalise_sentence_starts, check_lang, check_model, gpu_available, home, i16_bytes, installed_models, norm, parse_raw, plan, resample_linear, speaker_changes, stt_bin, wav_bytes};
2323 use engine::{AudioSession, Clip, PlaybackSession, subtitle};
2424 use serde_json::{Value, json};
2525
@@ -78,8 +78,8 @@ Silent and hallucinated windows are dropped by edith-stt before they reach this
7878 Whisper usually leaves disfluencies (um, uh, er, hmm, like, you know) out by default, but not always (\"Um, right.\" came through unprompted); fillers:true keeps them, by running with a \
7979 prompt that shows them. That prompt biases the model toward hesitations, so with fillers:true it can mishear content words (\"without a studio\" for \"we're out of studio\"); use the default for captions and reading. hint names words as they should come out (\"Edith, LUFS\"); it helps the transcriber, and a heard word close to a term is respelt to it (the reply names each change). Results are \
8080 cached per source file, model, language and prompt (the hint and any filler prompt); a range an earlier run covered is served from that run, so a repeat, or a call after cuts, is instant. A first run on long audio takes minutes (progress goes to stderr). \
81-Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, or EDITH_STT_BIN) and the model under \
82-~/.cache/edith/models/whisper-<size>.";
81+Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, `--features vulkan` for the GPU, or EDITH_STT_BIN) and the model under \
82+~/.cache/edith/models (whisper-<size> for device cpu, ggml-<size>.bin for gpu).";
8383
8484 const FIND_DOC: &str = "Find a phrase (case-insensitive, punctuation ignored) in the transcript of a target. Each match is numbered \
8585 (#0, #1 ...) and gives its timeline span as [\"450f\",\"512f\"] -- ready for cut_regions or keep -- and each word its own span: \
@@ -129,7 +129,15 @@ fn model_prop() -> Value {
129129 json!({
130130 "type": "string",
131131 "enum": MODELS,
132- "description": "Whisper model size. Default base, or the first installed of base, small, tiny; tiny is fastest and roughest."
132+ "description": "Whisper model size: tiny, base, small, medium, large-v3, large-v3-turbo. Default: the project's speech_model, else the first installed one for the device."
133+ })
134+}
135+
136+fn device_prop() -> Value {
137+ json!({
138+ "type": "string",
139+ "enum": ["auto", "cpu", "gpu"],
140+ "description": "Where the model runs: cpu, gpu (needs a usable GPU and the ggml model file), or auto (gpu when usable and that model is installed, else cpu). Default: the project's speech_device, else auto."
133141 })
134142 }
135143
@@ -147,6 +155,7 @@ fn transcript_schema() -> Value {
147155 "target": target_prop(),
148156 "range": range_prop(),
149157 "model": model_prop(),
158+ "device": device_prop(),
150159 "language": language_prop(),
151160 "hint": hint_prop(),
152161 "words": {"type": "boolean", "description": "List the words of each segment too. Default false."},
@@ -164,6 +173,7 @@ fn find_schema() -> Value {
164173 "query": {"type": "string", "description": "The phrase to find, e.g. \"brown fox\"."},
165174 "target": target_prop(),
166175 "model": model_prop(),
176+ "device": device_prop(),
167177 "language": language_prop(),
168178 "hint": hint_prop(),
169179 "cut": {
@@ -205,6 +215,7 @@ fn captions_schema() -> Value {
205215 "properties": {
206216 "target": target_prop(),
207217 "model": model_prop(),
218+ "device": device_prop(),
208219 "language": language_prop(),
209220 "hint": hint_prop(),
210221 "lane": {"type": "string", "description": "Caption lane (S1, S2 ...) to place the track on. Default S1. A media lane such as A1 is refused: captions go on a caption lane."},
@@ -229,11 +240,12 @@ pub fn tools() -> Vec<Tool> {
229240
230241 // ---- speech model ----------------------------------------------------------
231242
232-const SPEECH_MODEL_DOC: &str = "The speech model that transcript, find_words and auto_captions run on: which are installed, and the download in progress. With no argument it is the status. download:true fetches a model in the background (model is tiny, base or small; default base, the one the GUI's Download model fetches from huggingface.co); the status shows its percent until it is installed, and a download that fails says why. cancel:true stops the download running now and keeps the files already fetched for the next try. Nothing is downloaded unless download is true.";
243+const SPEECH_MODEL_DOC: &str = "The speech models that transcript, find_words and auto_captions run on, per device (cpu, or gpu when edith-stt has a usable GPU): which are installed, and the download in progress. With no argument it is the status. download:true fetches a model in the background (model default base; device default the one auto picks: gpu when usable, else cpu); the status shows its percent until it is installed, and a download that fails says why. cancel:true stops the download running now and keeps the files already fetched for the next try. Nothing is downloaded unless download is true.";
233244
234245 /// A speech model download running in the background, and how it ended once it has.
235246 pub struct SpeechDownload {
236247 pub model: String,
248+ pub device: Device,
237249 pub job: std::sync::Arc<engine::speech::Job>,
238250 pub handle: Option<std::thread::JoinHandle<Result<(), String>>>,
239251 pub outcome: Option<String>,
@@ -244,7 +256,8 @@ fn speech_model_schema() -> Value {
244256 "type": "object",
245257 "properties": {
246258 "download": {"type": "boolean", "description": "true starts downloading the model in the background."},
247- "model": {"type": "string", "enum": ["tiny", "base", "small"], "description": "The model to download. Default base."},
259+ "model": {"type": "string", "enum": MODELS, "description": "The model to download. Default base."},
260+ "device": device_prop(),
248261 "cancel": {"type": "boolean", "description": "true stops the download running now."}
249262 },
250263 "additionalProperties": false
@@ -286,28 +299,41 @@ fn speech_model(srv: &mut Server, args: &Value) -> Reply {
286299 if !MODELS.contains(&model) {
287300 return Reply::err(format!("model `{model}` is not one of {}", MODELS.join(", ")));
288301 }
289- if engine::speech::installed_models().contains(&model) {
290- return Reply::ok(format!("the {model} speech model is already installed"));
302+ let choice = match device_arg(args) {
303+ Ok(c) => c.unwrap_or_else(|| project_choice(srv)),
304+ Err(e) => return Reply::err(e),
305+ };
306+ let device = download_device(choice);
307+ if installed_models(device).contains(&model) {
308+ return Reply::ok(format!("the {model} speech model ({}) is already installed", device.flag()));
291309 }
292- // The same call the GUI's Download model makes, on a thread of its own.
293310 let job = std::sync::Arc::new(engine::speech::Job::default());
294311 let worker = job.clone();
295312 let name = model.to_string();
296313 let thread_name = name.clone();
297- let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, &worker));
298- srv.speech_download = Some(SpeechDownload { model: name, job, handle: Some(handle), outcome: None });
299- return Reply::ok(format!("downloading the {model} speech model in the background; speech_model shows the progress"));
300- }
301- let installed = engine::speech::installed_models();
302- let have = if installed.is_empty() { "none installed".to_string() } else { format!("installed: {}", installed.join(", ")) };
314+ let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, device, &worker));
315+ srv.speech_download = Some(SpeechDownload { model: name, device, job, handle: Some(handle), outcome: None });
316+ return Reply::ok(format!("downloading the {model} ({}) speech model in the background; speech_model shows the progress", device.flag()));
317+ }
318+ let cpu = installed_models(Device::Cpu);
319+ let gpu = installed_models(Device::Gpu);
320+ let list = |v: &[&str]| if v.is_empty() { "none".to_string() } else { v.join(", ") };
321+ let usable = gpu_available();
303322 let state = match srv.speech_download.as_ref() {
304- Some(d) if running => format!("downloading {} {:.0}%", d.model, d.job.fraction() * 100.0),
323+ Some(d) if running => format!("downloading {} ({}) {:.0}%", d.model, d.device.flag(), d.job.fraction() * 100.0),
305324 Some(d) => d.outcome.clone().unwrap_or_default(),
306325 None => "no download started".to_string(),
307326 };
308- let text = format!("speech models: {have} (offered: {}); {state}", MODELS.join(", "));
327+ let text = format!(
328+ "speech models: cpu: {}; gpu: {} (gpu {}); offered: {}; {state}",
329+ list(&cpu),
330+ list(&gpu),
331+ if usable { "usable" } else { "not usable" },
332+ MODELS.join(", ")
333+ );
309334 Reply::ok(text).with(json!({
310- "installed": installed,
335+ "installed": {"cpu": cpu, "gpu": gpu},
336+ "gpu_available": usable,
311337 "offered": MODELS,
312338 "downloading": running,
313339 "progress": srv.speech_download.as_ref().filter(|_| running).map(|d| d.job.fraction()),
@@ -659,20 +685,23 @@ fn fnv1a(bytes: &[u8]) -> u64 {
659685 /// The cache directory name of one source's transcription: file identity (path, mtime, length),
660686 /// the stream, and the model, language and prompt that heard it. `file` is (mtime in ns, length
661687 /// in bytes). The source range is not part of it: each range is an entry inside the directory.
662-fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, lang: &str, hint: &str) -> String {
688+fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> String {
663689 let (mtime_ns, len) = file;
664- let text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}");
690+ let mut text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}");
691+ if device == Device::Gpu {
692+ text.push_str("|gpu");
693+ }
665694 format!("{:016x}", fnv1a(text.as_bytes()))
666695 }
667696
668-fn source_key(path: &Path, stream: usize, model: &str, lang: &str, hint: &str) -> Option<String> {
697+fn source_key(path: &Path, stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> Option<String> {
669698 let meta = fs::metadata(path).ok()?;
670699 let mtime = meta
671700 .modified()
672701 .ok()
673702 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
674703 .map_or(0, |d| d.as_nanos());
675- Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, lang, hint))
704+ Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, device, lang, hint))
676705 }
677706
678707 fn cache_dir() -> PathBuf {
@@ -716,19 +745,40 @@ fn write_entry(dir: &Path, from: f64, to: f64, raw: &str) {
716745 }
717746 }
718747
719-fn model_arg(args: &Value) -> Result<String, String> {
720- match opt_str(args, "model") {
721- Some(m) => {
722- let m = m.trim().to_ascii_lowercase();
723- check_model(&m)?;
724- Ok(m)
725- }
726- None => pick_model(|m| check_model(m).is_ok())
727- .map(str::to_string)
728- .ok_or_else(|| "no whisper model is installed: install base (or small or tiny) under ~/.cache/edith/models".into()),
748+fn device_arg(args: &Value) -> Result<Option<DeviceChoice>, String> {
749+ match opt_str(args, "device") {
750+ None => Ok(None),
751+ Some(d) => DeviceChoice::parse(d.trim()).map(Some).ok_or_else(|| format!("device `{d}` is not auto, cpu or gpu")),
729752 }
730753 }
731754
755+/// The device a download fetches for when none is named: the GPU when edith-stt has one, else the CPU.
756+fn download_device(choice: DeviceChoice) -> Device {
757+ match choice {
758+ DeviceChoice::Auto if gpu_available() => Device::Gpu,
759+ DeviceChoice::Auto | DeviceChoice::Cpu => Device::Cpu,
760+ DeviceChoice::Gpu => Device::Gpu,
761+ }
762+}
763+
764+fn project_choice(srv: &Server) -> DeviceChoice {
765+ srv.session.as_ref().map_or(DeviceChoice::Auto, |s| s.speech_device())
766+}
767+
768+/// The model and device a call runs on: the `model` and `device` args, else the project's
769+/// `speech_model` and `speech_device`, else the picked model and the auto device.
770+fn model_arg(args: &Value, s: &PlaybackSession) -> Result<(String, Device), String> {
771+ let choice = device_arg(args)?.unwrap_or_else(|| s.speech_device());
772+ let named = match opt_str(args, "model") {
773+ Some(m) => Some(m.trim().to_ascii_lowercase()),
774+ None => s.speech_model().map(str::to_string),
775+ };
776+ let (model, device) = plan(choice, named.as_deref())
777+ .ok_or_else(|| "no whisper model is installed for this device: install one with speech_model download".to_string())?;
778+ check_model(&model, device)?;
779+ Ok((model, device))
780+}
781+
732782 /// `hint`: names and jargon as they should come out, handed to edith-stt as its prompt.
733783 fn hint_arg(args: &Value) -> Result<String, String> {
734784 let h = opt_str(args, "hint").unwrap_or("").trim().to_string();
@@ -979,8 +1029,8 @@ impl Drop for TempFile {
9791029
9801030 /// Runs edith-stt on one WAV (see [`engine::speech::run_stt`]); this server has no progress line
9811031 /// and nobody to cancel it.
982-fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str) -> Result<String, String> {
983- engine::speech::run_stt(bin, wav, model, lang, hint, offset, label, &engine::speech::Job::default())
1032+fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str) -> Result<String, String> {
1033+ engine::speech::run_stt(bin, wav, model, device, lang, hint, offset, label, &engine::speech::Job::default())
9841034 }
9851035
9861036 fn temp_path(tag: &str, ext: &str) -> PathBuf {
@@ -1215,8 +1265,8 @@ fn review_text(segs: &[&Seg], fps: f64) -> String {
12151265
12161266 /// Transcribes one piece, through the cache when it can: a cache entry for exactly this range
12171267 /// serves it, and a new run is stored under that range. The output depends only on the piece.
1218-fn run_piece(bin: &Path, p: &Piece, model: &str, lang: &str, hint: &str, fps: f64) -> Result<Vec<Seg>, String> {
1219- let known = if p.mix { None } else { source_key(&p.path, p.stream, model, lang, hint) };
1268+fn run_piece(bin: &Path, p: &Piece, model: &str, device: Device, lang: &str, hint: &str, fps: f64) -> Result<Vec<Seg>, String> {
1269+ let known = if p.mix { None } else { source_key(&p.path, p.stream, model, device, lang, hint) };
12201270 let cached = |dir: &Path| read_exact(dir, p.from, p.to);
12211271 if let Some(raw) = known.as_deref().and_then(|k| cached(&cache_dir().join(k))) {
12221272 return raw_to_segs(&raw, p, fps);
@@ -1230,7 +1280,7 @@ fn run_piece(bin: &Path, p: &Piece, model: &str, lang: &str, hint: &str, fps: f6
12301280 }
12311281 let key = known.unwrap_or_else(|| {
12321282 let bytes = i16_bytes(&samples);
1233- cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, lang, hint)
1283+ cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, device, lang, hint)
12341284 });
12351285 let dir = cache_dir().join(&key);
12361286 if let Some(raw) = cached(&dir) {
@@ -1240,7 +1290,7 @@ fn run_piece(bin: &Path, p: &Piece, model: &str, lang: &str, hint: &str, fps: f6
12401290 let wav = TempFile(temp_path("stt", "wav"));
12411291 // `wav` is removed when this function returns, on success and on every error path.
12421292 fs::write(&wav.0, wav_bytes(&samples)).map_err(|e| temp_write_error(&wav.0, "writing", e))?;
1243- let raw = run_stt(bin, &wav.0, model, lang, hint, p.from, &p.label)?;
1293+ let raw = run_stt(bin, &wav.0, model, device, lang, hint, p.from, &p.label)?;
12441294 let segs = parse_raw(&raw)?.len();
12451295 write_entry(&dir, p.from, p.to, &raw);
12461296 // A segment is one phrase the model timed (start and end), padding included; words are counted inside them.
@@ -1306,18 +1356,20 @@ fn check_sources_online(s: &PlaybackSession, want: &Want) -> Result<(), String>
13061356
13071357 /// The transcript of source `n` in its own frames: what `transcribe` does for a source with no
13081358 /// clip, whether or not the timeline plays it.
1359+#[allow(clippy::too_many_arguments)]
13091360 fn transcribe_source(
13101361 s: &PlaybackSession,
13111362 n: usize,
13121363 range: Option<(u32, u32)>,
13131364 model: &str,
1365+ device: Device,
13141366 lang: &str,
13151367 hint: &str,
13161368 fps: f64,
13171369 ) -> Result<Transcript, String> {
13181370 let bin = stt_bin()?;
1319- check_model(model)?;
1320- let mut segs = source_segs(s, n, range, &bin, model, lang, hint, fps)?;
1371+ check_model(model, device)?;
1372+ let mut segs = source_segs(s, n, range, &bin, model, device, lang, hint, fps)?;
13211373 segs.sort_by_key(|g| (g.start_f, g.end_f));
13221374 let mut segs = drop_overlap_repeats(segs);
13231375 let corrections = correct_hints(&mut segs, hint);
@@ -1337,10 +1389,10 @@ fn source_clips_note(n: usize, clips: &[(Lane, Clip)], fps: f64) -> String {
13371389 format!("\nsrc:{n} times are the file's own clock; used by {}", used.join(", "))
13381390 }
13391391
1340-fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, lang: &str, hint: &str) -> Result<Transcript, String> {
1392+fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, device: Device, lang: &str, hint: &str) -> Result<Transcript, String> {
13411393 let fps = parse::session_fps(s);
13421394 let bin = stt_bin()?;
1343- check_model(model)?;
1395+ check_model(model, device)?;
13441396 let mut segs = Vec::new();
13451397 let mut gaps = Vec::new();
13461398 let pad = (WINDOW_SECS * fps).round() as u32;
@@ -1360,7 +1412,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model:
13601412 map: Map::Mix,
13611413 mix: true,
13621414 };
1363- segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?);
1415+ segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?);
13641416 // Audible sound the model returned no words for: reported, not hidden.
13651417 if let Ok(Some(samples)) = decode_16k(&wav.0, 0, f64::from(lo) / fps, f64::from(hi) / fps) {
13661418 gaps = coverage_gaps(&samples, lo, fps, &segs);
@@ -1372,7 +1424,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model:
13721424 };
13731425 let clips = clips_of(s, want);
13741426 if let (true, Some(n)) = (clips.is_empty(), source) {
1375- segs.extend(source_segs(s, n, range, &bin, model, lang, hint, fps)?);
1427+ segs.extend(source_segs(s, n, range, &bin, model, device, lang, hint, fps)?);
13761428 }
13771429 for (lane, clip) in clips {
13781430 let Some(src) = s.sources().get(clip.source) else {
@@ -1396,7 +1448,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model:
13961448 map: Map::of(&clip),
13971449 mix: false,
13981450 };
1399- segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?);
1451+ segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?);
14001452 }
14011453 }
14021454 segs.sort_by_key(|g| (g.start_f, g.end_f));
@@ -1424,6 +1476,7 @@ fn source_segs(
14241476 range: Option<(u32, u32)>,
14251477 bin: &Path,
14261478 model: &str,
1479+ device: Device,
14271480 lang: &str,
14281481 hint: &str,
14291482 fps: f64,
@@ -1446,7 +1499,7 @@ fn source_segs(
14461499 map: Map::Clip { start: 0, in_frame: 0, speed: Speed::NORMAL },
14471500 mix: false,
14481501 };
1449- run_piece(bin, &piece, model, lang, hint, fps)
1502+ run_piece(bin, &piece, model, device, lang, hint, fps)
14501503 }
14511504
14521505 /// `mm:ss.mmm` for a timeline frame.
@@ -1542,7 +1595,7 @@ fn transcript_run(srv: &Server, args: &Value) -> Result<Reply, String> {
15421595 };
15431596 let range = range_arg(args, fps, end)?;
15441597 check_sources_online(s, &want)?;
1545- let model = model_arg(args)?;
1598+ let (model, device) = model_arg(args, s)?;
15461599 let lang = language_arg(args)?;
15471600 let hint = with_fillers(&hint_arg(args)?, opt_bool(args, "fillers").unwrap_or(false));
15481601 let from = parse::opt_frame_arg(args, "from", fps, end).map_err(|r| r.text)?.unwrap_or(0);
@@ -1555,8 +1608,8 @@ fn transcript_run(srv: &Server, args: &Value) -> Result<Reply, String> {
15551608 _ => None,
15561609 };
15571610 let t = match &want {
1558- Want::Source(n) => transcribe_source(s, *n, range, &model, &lang, &hint, fps)?,
1559- _ => transcribe(s, want, range, &model, &lang, &hint)?,
1611+ Want::Source(n) => transcribe_source(s, *n, range, &model, device, &lang, &hint, fps)?,
1612+ _ => transcribe(s, want, range, &model, device, &lang, &hint)?,
15601613 };
15611614 let (body, shown, next) = page(&t, from, words);
15621615 let mut text = transcript_text(&label, &model, &lang, from, &body, &shown, next);
@@ -2130,12 +2183,12 @@ fn find_run(srv: &mut Server, args: &Value) -> Result<Reply, String> {
21302183 // gap beside a clip, which the ripple would close and shift the clip by.
21312184 let clips = clip_intervals(s, &scope);
21322185 check_sources_online(s, &want)?;
2133- let model = model_arg(args)?;
2186+ let (model, device) = model_arg(args, s)?;
21342187 let lang = language_arg(args)?;
21352188 let fillers = is_filler_query(&qwords);
21362189 let hint = with_fillers(&hint_arg(args)?, fillers);
21372190 let label = want_label(s, &want);
2138- let t = transcribe(s, want, None, &model, &lang, &hint)?;
2191+ let t = transcribe(s, want, None, &model, device, &lang, &hint)?;
21392192 let mut flat: Vec<(&Seg, &Word)> = t.segs.iter().flat_map(|g| g.words.iter().map(move |w| (g, w))).collect();
21402193 flat.sort_by_key(|(_, w)| w.start_f);
21412194 let norms: Vec<String> = flat.iter().map(|(_, w)| norm(&w.w)).collect();
@@ -2826,12 +2879,12 @@ fn cue_names(cues: &[subtitle::Cue]) -> String {
28262879 }
28272880
28282881 fn captions_run(srv: &mut Server, args: &Value) -> Result<Reply, String> {
2829- let (fps, want, model, lang, hint, label, lane, max_chars, max_secs, out, speakers) = {
2882+ let (fps, want, model, device, lang, hint, label, lane, max_chars, max_secs, out, speakers) = {
28302883 let s = session(srv)?;
28312884 let fps = parse::session_fps(s);
28322885 let want = want_arg(s, args)?;
28332886 check_sources_online(s, &want)?;
2834- let model = model_arg(args)?;
2887+ let (model, device) = model_arg(args, s)?;
28352888 let lang = language_arg(args)?;
28362889 let hint = hint_arg(args)?;
28372890 let label = want_label(s, &want);
@@ -2866,11 +2919,11 @@ fn captions_run(srv: &mut Server, args: &Value) -> Result<Reply, String> {
28662919 None => free_caption_path(s, std::env::temp_dir().join(format!("edith-captions-{}.srt", std::process::id()))),
28672920 },
28682921 };
2869- (fps, want, model, lang, hint, label, lane_name, max_chars, max_secs, out, speakers)
2922+ (fps, want, model, device, lang, hint, label, lane_name, max_chars, max_secs, out, speakers)
28702923 };
28712924 let is_mix = matches!(want, Want::Mix);
28722925 let replace = opt_bool(args, "replace").unwrap_or(false);
2873- let t = transcribe(session(srv)?, want.clone(), None, &model, &lang, &hint)?;
2926+ let t = transcribe(session(srv)?, want.clone(), None, &model, device, &lang, &hint)?;
28742927 let s = session(srv)?;
28752928 // Captions carry the words people say: disfluencies are left out, even when the
28762929 // transcript kept them (a hint or the default model can still hear an "um").
@@ -3640,20 +3693,20 @@ mod tests {
36403693
36413694 #[test]
36423695 fn cache_key_follows_every_input() {
3643- let base = cache_key("/a.mp4", (7, 100), 0, "small", "auto", "");
3644- assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", ""));
3645- assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", "auto", ""));
3646- assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", "auto", ""));
3647- assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", "auto", ""));
3648- assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", "auto", ""));
3649- assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "en", ""));
3650- assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", "Edith, LUFS"));
3696+ let base = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "");
3697+ assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", ""));
3698+ assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", Device::Cpu, "auto", ""));
3699+ assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", Device::Cpu, "auto", ""));
3700+ assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", Device::Cpu, "auto", ""));
3701+ assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", Device::Cpu, "auto", ""));
3702+ assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "en", ""));
3703+ assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "Edith, LUFS"));
36513704 assert_eq!(base.len(), 16);
36523705 }
36533706
36543707 #[test]
36553708 fn cache_key_is_versioned_so_older_results_are_not_reused() {
3656- let k = cache_key("/a.mp4", (7, 100), 0, "small", "auto", "");
3709+ let k = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "");
36573710 let v5 = format!("{:016x}", fnv1a(b"v5|/a.mp4|7|100|0|small|auto|"));
36583711 assert_ne!(k, v5);
36593712 assert_eq!(CACHE_VERSION, 9);
@@ -4001,7 +4054,7 @@ mod tests {
40014054 eprintln!("skipping speech_round_trip: {e}");
40024055 return;
40034056 }
4004- if check_model("tiny").is_err() {
4057+ if check_model("tiny", Device::Cpu).is_err() {
40054058 eprintln!("skipping speech_round_trip: the tiny model is not installed");
40064059 return;
40074060 }
@@ -4099,7 +4152,7 @@ mod tests {
40994152
41004153 #[test]
41014154 fn find_cut_removes_the_matched_word_and_undo_restores_it() {
4102- if stt_bin().is_err() || check_model("tiny").is_err() {
4155+ if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() {
41034156 eprintln!("skipping find_cut_removes_the_matched_word_and_undo_restores_it: edith-stt or the tiny model is missing");
41044157 return;
41054158 }
@@ -4282,7 +4335,7 @@ mod tests {
42824335 /// left in place. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing.
42834336 #[test]
42844337 fn find_cut_with_which_names_the_kept_match_and_the_lane_left_in_place() {
4285- if stt_bin().is_err() || check_model("tiny").is_err() {
4338+ if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() {
42864339 eprintln!("skipping find_cut_with_which_names_the_kept_match: edith-stt or the tiny model is missing");
42874340 return;
42884341 }
@@ -4357,7 +4410,7 @@ mod tests {
43574410 /// silence. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing.
43584411 #[test]
43594412 fn unplaced_source_is_heard_as_its_own_file() {
4360- if stt_bin().is_err() || check_model("tiny").is_err() {
4413+ if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() {
43614414 eprintln!("skipping unplaced_source_is_heard_as_its_own_file: edith-stt or the tiny model is missing");
43624415 return;
43634416 }
@@ -4585,10 +4638,10 @@ mod tests {
45854638
45864639 #[test]
45874640 fn default_model_is_base_then_small_then_tiny() {
4588- assert_eq!(pick_model(|_| true), Some("base"));
4589- assert_eq!(pick_model(|m| m != "base"), Some("small"));
4590- assert_eq!(pick_model(|m| m == "tiny"), Some("tiny"));
4591- assert_eq!(pick_model(|_| false), None);
4641+ assert_eq!(engine::speech::pick_model(|_| true, Device::Cpu), Some("base"));
4642+ assert_eq!(engine::speech::pick_model(|m| m != "base", Device::Cpu), Some("small"));
4643+ assert_eq!(engine::speech::pick_model(|m| m == "tiny", Device::Cpu), Some("tiny"));
4644+ assert_eq!(engine::speech::pick_model(|_| false, Device::Cpu), None);
45924645 }
45934646
45944647 #[test]
crates/mcp/src/tools/project.rsmodified+47 -2
@@ -12,6 +12,7 @@ use std::time::{Duration, SystemTime};
1212
1313 use engine::limiter::Limiter;
1414 use engine::project::{Lane, LaneKind, Rate, STILL_MAX_SECS, STILL_MIN_SECS};
15+use engine::speech::{DeviceChoice, MODELS};
1516 use engine::tonemap::Preset;
1617 use engine::export::EncoderSeat;
1718 use engine::PlaybackSession;
@@ -160,6 +161,8 @@ pub fn tools() -> Vec<Tool> {
160161 "tonemap": {"type": "string", "enum": ["reference", "standard", "vivid"], "description": "HDR to SDR rendition."},
161162 "notes": {"type": "string", "examples": ["Cut the intro to 30 s"], "description": "The project's notes: free text, several lines allowed (a newline is \\n in JSON). An empty string clears them. Saved with the project; one undo step."},
162163 "still_secs": {"type": "number", "description": "How long a still image is placed for, in seconds: 0.5 to 600 (default 5). Stills placed after this change take it; clips already placed keep theirs. Saved with the project; one undo step."},
164+ "speech_model": {"type": "string", "enum": MODELS.iter().copied().chain(["auto"]).collect::<Vec<_>>(), "description": "The Whisper model transcript, find_words and auto_captions run on; auto (default) picks the first installed. Saved with the project; one undo step."},
165+ "speech_device": {"type": "string", "enum": ["auto", "cpu", "gpu"], "description": "Where that model runs: auto (gpu when usable and that model is installed, else cpu), cpu or gpu. Saved with the project; one undo step."},
163166 "sample_rate": {"type": ["string", "integer"], "description": "The project's sound mix rate: \"source\" (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), or 44100, 48000 or 96000 in Hz. Saved with the project; one undo step.", "enum": ["source", 44100, 48000, 96000]},
164167 "proxies": {"type": "boolean", "description": "Play and edit through proxy files."},
165168 "auto_proxies": {"type": "boolean", "description": "Make proxies automatically for heavy sources."},
@@ -2294,11 +2297,12 @@ fn status_reply(server: &Server) -> Reply {
22942297 false => format!("\nnotes: {}", s.notes()),
22952298 };
22962299 let render_text = crate::tools::render::status_line(server).map_or_else(String::new, |l| format!("\n{l}"));
2300+ let speech_text = format!("{} on {}", s.speech_model().unwrap_or("auto"), s.speech_device().as_str());
22972301 let text = format!(
22982302 "{path} · {state} · {w}x{h} @{} · {} ({end}f) · undo {undo} · redo {redo} · {running} export job(s) running\n\
22992303 lanes: {lane_text}{ducks_text}{voice_text}\n\
23002304 {recent_text}sources: {} {}{looks_text}\n\
2301- settings: tonemap {tone} · proxies {} · auto proxies {} · encoder {encoder} · limiter {limiter_text} · sample rate {sample_rate} · still {:.1} s{offline_text}{fix_text}{notes_text}{render_text}",
2305+ settings: tonemap {tone} · proxies {} · auto proxies {} · encoder {encoder} · limiter {limiter_text} · sample rate {sample_rate} · still {:.1} s · speech {speech_text}{offline_text}{fix_text}{notes_text}{render_text}",
23022306 fmt_fps(fps),
23032307 parse::clock(end, fps),
23042308 sources.len(),
@@ -2347,6 +2351,8 @@ fn status_reply(server: &Server) -> Reply {
23472351 "limiter": {"on": limiter.on, "ceiling_db": limiter.ceiling_db},
23482352 "sample_rate": s.sample_rate(),
23492353 "still_secs": s.still_secs(),
2354+ "speech_model": s.speech_model(),
2355+ "speech_device": s.speech_device().as_str(),
23502356 "notes": s.notes(),
23512357 }
23522358 });
@@ -2506,6 +2512,45 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply {
25062512 }
25072513 }
25082514
2515+ if let Some(raw) = opt_str(args, "speech_model") {
2516+ asked += 1;
2517+ let v = raw.trim().to_ascii_lowercase();
2518+ if v != "auto" && !MODELS.contains(&v.as_str()) {
2519+ refused += 1;
2520+ lines.push(format!("speech_model {raw}: refused; use one of {}, or auto", MODELS.join(", ")));
2521+ } else {
2522+ let cur = s.speech_model().unwrap_or("auto").to_string();
2523+ let want = (v != "auto").then_some(v.as_str());
2524+ if s.set_speech_model(want) {
2525+ changed += 1;
2526+ named.push(format!("speech_model {cur}→{v}"));
2527+ lines.push(format!("speech model {cur} -> {v}"));
2528+ } else {
2529+ lines.push(format!("speech model already {cur}"));
2530+ }
2531+ }
2532+ }
2533+
2534+ if let Some(raw) = opt_str(args, "speech_device") {
2535+ asked += 1;
2536+ match DeviceChoice::parse(raw.trim()) {
2537+ Some(d) => {
2538+ let cur = s.speech_device();
2539+ if s.set_speech_device(d) {
2540+ changed += 1;
2541+ named.push(format!("speech_device {}→{}", cur.as_str(), d.as_str()));
2542+ lines.push(format!("speech device {} -> {}", cur.as_str(), d.as_str()));
2543+ } else {
2544+ lines.push(format!("speech device already {}", d.as_str()));
2545+ }
2546+ }
2547+ None => {
2548+ refused += 1;
2549+ lines.push(format!("speech_device {raw}: refused; use auto, cpu or gpu"));
2550+ }
2551+ }
2552+ }
2553+
25092554 if let Some(v) = args.get("still_secs") {
25102555 asked += 1;
25112556 match v.as_f64() {
@@ -2668,7 +2713,7 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply {
26682713
26692714 if asked == 0 {
26702715 return Reply::err(
2671- "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, proxies, auto_proxies, encoder, limiter, captions",
2716+ "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, proxies, auto_proxies, encoder, limiter, captions",
26722717 );
26732718 }
26742719 let mut out = Map::new();
tools/edith-stt/Cargo.lockmodified+135 -3
@@ -61,6 +61,26 @@ version = "0.22.1"
6161 source = "registry+https://github.com/rust-lang/crates.io-index"
6262 checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
6363
64+[[package]]
65+name = "bindgen"
66+version = "0.72.1"
67+source = "registry+https://github.com/rust-lang/crates.io-index"
68+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
69+dependencies = [
70+ "bitflags",
71+ "cexpr",
72+ "clang-sys",
73+ "itertools 0.13.0",
74+ "log",
75+ "prettyplease",
76+ "proc-macro2",
77+ "quote",
78+ "regex",
79+ "rustc-hash",
80+ "shlex 1.3.0",
81+ "syn 2.0.119",
82+]
83+
6484 [[package]]
6585 name = "bit-set"
6686 version = "0.8.0"
@@ -185,7 +205,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
185205 checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
186206 dependencies = [
187207 "find-msvc-tools",
188- "shlex",
208+ "shlex 2.0.1",
209+]
210+
211+[[package]]
212+name = "cexpr"
213+version = "0.6.0"
214+source = "registry+https://github.com/rust-lang/crates.io-index"
215+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
216+dependencies = [
217+ "nom",
189218 ]
190219
191220 [[package]]
@@ -194,6 +223,26 @@ version = "1.0.5"
194223 source = "registry+https://github.com/rust-lang/crates.io-index"
195224 checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
196225
226+[[package]]
227+name = "clang-sys"
228+version = "1.9.1"
229+source = "registry+https://github.com/rust-lang/crates.io-index"
230+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
231+dependencies = [
232+ "glob",
233+ "libc",
234+ "libloading",
235+]
236+
237+[[package]]
238+name = "cmake"
239+version = "0.1.58"
240+source = "registry+https://github.com/rust-lang/crates.io-index"
241+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
242+dependencies = [
243+ "cc",
244+]
245+
197246 [[package]]
198247 name = "compact_str"
199248 version = "0.9.1"
@@ -364,6 +413,7 @@ dependencies = [
364413 "serde_json",
365414 "tracing",
366415 "ureq",
416+ "whisper-rs",
367417 ]
368418
369419 [[package]]
@@ -473,6 +523,12 @@ dependencies = [
473523 "percent-encoding",
474524 ]
475525
526+[[package]]
527+name = "fs_extra"
528+version = "1.3.0"
529+source = "registry+https://github.com/rust-lang/crates.io-index"
530+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
531+
476532 [[package]]
477533 name = "gemm"
478534 version = "0.19.0"
@@ -626,6 +682,12 @@ dependencies = [
626682 "r-efi 6.0.0",
627683 ]
628684
685+[[package]]
686+name = "glob"
687+version = "0.3.4"
688+source = "registry+https://github.com/rust-lang/crates.io-index"
689+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
690+
629691 [[package]]
630692 name = "half"
631693 version = "2.7.1"
@@ -798,6 +860,15 @@ dependencies = [
798860 "hashbrown 0.17.1",
799861 ]
800862
863+[[package]]
864+name = "itertools"
865+version = "0.13.0"
866+source = "registry+https://github.com/rust-lang/crates.io-index"
867+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
868+dependencies = [
869+ "either",
870+]
871+
801872 [[package]]
802873 name = "itertools"
803874 version = "0.14.0"
@@ -819,6 +890,16 @@ version = "0.2.190"
819890 source = "registry+https://github.com/rust-lang/crates.io-index"
820891 checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
821892
893+[[package]]
894+name = "libloading"
895+version = "0.8.9"
896+source = "registry+https://github.com/rust-lang/crates.io-index"
897+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
898+dependencies = [
899+ "cfg-if",
900+ "windows-link",
901+]
902+
822903 [[package]]
823904 name = "libm"
824905 version = "0.2.16"
@@ -1029,6 +1110,16 @@ dependencies = [
10291110 "zerocopy",
10301111 ]
10311112
1113+[[package]]
1114+name = "prettyplease"
1115+version = "0.2.37"
1116+source = "registry+https://github.com/rust-lang/crates.io-index"
1117+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
1118+dependencies = [
1119+ "proc-macro2",
1120+ "syn 2.0.119",
1121+]
1122+
10321123 [[package]]
10331124 name = "proc-macro2"
10341125 version = "1.0.107"
@@ -1147,7 +1238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
11471238 checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"
11481239 dependencies = [
11491240 "either",
1150- "itertools",
1241+ "itertools 0.14.0",
11511242 "rayon",
11521243 ]
11531244
@@ -1210,6 +1301,12 @@ dependencies = [
12101301 "windows-sys 0.52.0",
12111302 ]
12121303
1304+[[package]]
1305+name = "rustc-hash"
1306+version = "2.1.3"
1307+source = "registry+https://github.com/rust-lang/crates.io-index"
1308+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
1309+
12131310 [[package]]
12141311 name = "rustix"
12151312 version = "1.1.5"
@@ -1292,6 +1389,12 @@ dependencies = [
12921389 "winapi-util",
12931390 ]
12941391
1392+[[package]]
1393+name = "semver"
1394+version = "1.0.28"
1395+source = "registry+https://github.com/rust-lang/crates.io-index"
1396+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
1397+
12951398 [[package]]
12961399 name = "seq-macro"
12971400 version = "0.3.6"
@@ -1350,6 +1453,12 @@ dependencies = [
13501453 "serde",
13511454 ]
13521455
1456+[[package]]
1457+name = "shlex"
1458+version = "1.3.0"
1459+source = "registry+https://github.com/rust-lang/crates.io-index"
1460+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
1461+
13531462 [[package]]
13541463 name = "shlex"
13551464 version = "2.0.1"
@@ -1527,7 +1636,7 @@ dependencies = [
15271636 "derive_builder",
15281637 "esaxx-rs",
15291638 "getrandom 0.3.4",
1530- "itertools",
1639+ "itertools 0.14.0",
15311640 "log",
15321641 "macro_rules_attribute",
15331642 "monostate",
@@ -1699,6 +1808,29 @@ dependencies = [
16991808 "rustls-pki-types",
17001809 ]
17011810
1811+[[package]]
1812+name = "whisper-rs"
1813+version = "0.16.0"
1814+source = "registry+https://github.com/rust-lang/crates.io-index"
1815+checksum = "2088172d00f936c348d6a72f488dc2660ab3f507263a195df308a3c2383229f6"
1816+dependencies = [
1817+ "libc",
1818+ "whisper-rs-sys",
1819+]
1820+
1821+[[package]]
1822+name = "whisper-rs-sys"
1823+version = "0.15.0"
1824+source = "registry+https://github.com/rust-lang/crates.io-index"
1825+checksum = "6986c0fe081241d391f09b9a071fbcbb59720c3563628c3c829057cf69f2a56f"
1826+dependencies = [
1827+ "bindgen",
1828+ "cfg-if",
1829+ "cmake",
1830+ "fs_extra",
1831+ "semver",
1832+]
1833+
17021834 [[package]]
17031835 name = "winapi-util"
17041836 version = "0.1.11"
tools/edith-stt/Cargo.tomlmodified+5 -0
@@ -18,6 +18,11 @@ hound = "3.5"
1818 tracing = "0.1"
1919 serde_json = "1"
2020 ureq = { version = "2", default-features = false, features = ["tls"] }
21+whisper-rs = { version = "0.16.0", optional = true, features = ["vulkan"] }
22+
23+[features]
24+default = []
25+vulkan = ["dep:whisper-rs"]
2126
2227 [workspace]
2328
tools/edith-stt/src/gpu.rsadded+301 -0
@@ -0,0 +1,301 @@
1+#![forbid(unsafe_code)]
2+
3+use std::io::Write;
4+use std::path::{Path, PathBuf};
5+use std::time::Instant;
6+
7+use anyhow::{bail, Context, Result};
8+use serde_json::json;
9+use whisper_rs::vulkan::list_devices;
10+use whisper_rs::{
11+ DtwMode, DtwModelPreset, DtwParameters, FullParams, SamplingStrategy, WhisperContext,
12+ WhisperContextParameters, WhisperSegment,
13+};
14+
15+use crate::{
16+ fit_words_to_audio, levels, r3, read_wav_16k_mono, silence_reason, span_rel_db, starts_past_end,
17+ Cli, MAX_COMPRESSION_RATIO, MIN_AVG_LOGPROB, NO_SPEECH_PROB, SR,
18+};
19+
20+const GPU_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"];
21+
22+pub fn probe() -> Result<()> {
23+ if list_devices().is_empty() {
24+ bail!("no Vulkan device found");
25+ }
26+ Ok(())
27+}
28+
29+pub fn run(cli: &Cli) -> Result<()> {
30+ let device = list_devices()
31+ .into_iter()
32+ .next()
33+ .context("no Vulkan device found")?;
34+ let (model, preset) = resolve_model(&cli.model)?;
35+ let dtw = if cli.align { preset } else { None };
36+
37+ let mut cp = WhisperContextParameters::new();
38+ cp.use_gpu(true);
39+ if let Some(model_preset) = dtw.clone() {
40+ cp.dtw_parameters(DtwParameters {
41+ mode: DtwMode::ModelPreset { model_preset },
42+ ..Default::default()
43+ });
44+ }
45+ let t_start = Instant::now();
46+ let ctx = WhisperContext::new_with_params(&model, cp)
47+ .with_context(|| format!("failed to load whisper model {}", model.display()))?;
48+ eprintln!(
49+ "model loaded from {} on {} in {:.2}s",
50+ model.display(),
51+ device.name,
52+ t_start.elapsed().as_secs_f64()
53+ );
54+
55+ let pcm = read_wav_16k_mono(&cli.input)?;
56+ let audio_s = pcm.len() as f64 / SR as f64;
57+ let lv = levels(&pcm);
58+ let eot = ctx.token_eot();
59+
60+ let language = if cli.language.eq_ignore_ascii_case("auto") {
61+ None
62+ } else {
63+ Some(cli.language.to_ascii_lowercase())
64+ };
65+ let prompt = cli.prompt.as_deref().map(str::trim).filter(|t| !t.is_empty());
66+ let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
67+
68+ let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
69+ params.set_language(language.as_deref());
70+ params.set_translate(false);
71+ params.set_no_context(true);
72+ params.set_token_timestamps(dtw.is_some());
73+ params.set_temperature(0.0);
74+ params.set_temperature_inc(0.2);
75+ params.set_logprob_thold(MIN_AVG_LOGPROB as f32);
76+ params.set_entropy_thold(MAX_COMPRESSION_RATIO as f32);
77+ params.set_no_speech_thold(NO_SPEECH_PROB as f32);
78+ if let Some(p) = prompt {
79+ params.set_initial_prompt(p);
80+ }
81+ params.set_print_special(false);
82+ params.set_print_progress(false);
83+ params.set_print_realtime(false);
84+ params.set_print_timestamps(false);
85+ params.set_n_threads(threads as i32);
86+ params.set_progress_callback_safe(|p: i32| eprintln!("progress {:.4}", p as f64 / 100.0));
87+
88+ let mut state = ctx.create_state().context("failed to create whisper state")?;
89+ let t_decode = Instant::now();
90+ state.full(params, &pcm).context("whisper inference failed")?;
91+
92+ let offset = cli.offset;
93+ let mut n_segs = 0usize;
94+ for seg in state.as_iter() {
95+ let t0 = seg.start_timestamp() as f64 / 100.0;
96+ let t1 = (seg.end_timestamp() as f64 / 100.0).min(audio_s).max(t0);
97+ if starts_past_end(t0, audio_s) {
98+ eprintln!("dropped segment at {:.2}s: starts at or past the audio end", t0 + offset);
99+ continue;
100+ }
101+ let toks = text_tokens(&seg, eot)?;
102+ let text = String::from_utf8_lossy(&toks.iter().flat_map(|t| t.bytes.iter().copied()).collect::<Vec<u8>>())
103+ .trim()
104+ .to_string();
105+ if text.is_empty() {
106+ continue;
107+ }
108+ let avg = toks.iter().map(|t| t.plog).sum::<f64>() / toks.len() as f64;
109+ let no_speech = seg.no_speech_probability() as f64;
110+ let span = span_rel_db(&lv, t0, t1);
111+ if let Some(reason) = silence_reason(no_speech, avg, span) {
112+ if !cli.keep_all {
113+ eprintln!(
114+ "skipped segment {:.2}-{:.2}s ({reason}, no_speech {no_speech:.2}, avg_logprob {avg:.2}): {text:?}",
115+ t0 + offset,
116+ t1 + offset
117+ );
118+ continue;
119+ }
120+ }
121+
122+ let groups = word_groups(&toks);
123+ let use_dtw = dtw.is_some() && groups.iter().any(|g| g.start > 0.0);
124+ let mut words = if use_dtw {
125+ dtw_words(&groups, t0, t1, offset)
126+ } else {
127+ proportional_words(&groups, t0, t1, offset)
128+ };
129+
130+ let n_words = words.len();
131+ let cut = fit_words_to_audio(&mut words, offset, audio_s);
132+ if n_words > 0 && words.is_empty() {
133+ eprintln!("dropped segment at {:.2}s: every word starts at or past the audio end: {text:?}", t0 + offset);
134+ continue;
135+ }
136+ let text = if cut > 0 {
137+ eprintln!("cut {cut} word(s) at {:.2}s that start at or past the audio end", t0 + offset);
138+ words.iter().filter_map(|w| w["w"].as_str()).collect::<Vec<_>>().join(" ")
139+ } else {
140+ text
141+ };
142+ let (start, end) = match (words.first(), words.last()) {
143+ (Some(f), Some(l)) => (
144+ f["start"].as_f64().unwrap_or(t0 + offset),
145+ l["end"].as_f64().unwrap_or(t1 + offset),
146+ ),
147+ _ => (t0 + offset, t1 + offset),
148+ };
149+ let line = json!({
150+ "start": r3(start),
151+ "end": r3(end),
152+ "text": text,
153+ "words": words,
154+ "approx": !use_dtw,
155+ "no_speech": r3(no_speech),
156+ "avg_logprob": r3(avg),
157+ "span_db": span.map(r3),
158+ });
159+ println!("{line}");
160+ n_segs += 1;
161+ }
162+ std::io::stdout().flush()?;
163+
164+ let elapsed = t_decode.elapsed().as_secs_f64();
165+ eprintln!(
166+ "done: {n_segs} segments, audio {audio_s:.2}s, decode {elapsed:.2}s, RTF {:.3}",
167+ elapsed / audio_s.max(1e-9)
168+ );
169+ Ok(())
170+}
171+
172+fn resolve_model(arg: &str) -> Result<(PathBuf, Option<DtwModelPreset>)> {
173+ let (path, name) = if arg.ends_with(".bin") || Path::new(arg).is_file() {
174+ let path = PathBuf::from(arg);
175+ let name = path
176+ .file_stem()
177+ .and_then(|s| s.to_str())
178+ .unwrap_or_default()
179+ .trim_start_matches("ggml-")
180+ .to_string();
181+ (path, name)
182+ } else {
183+ if !GPU_SIZES.contains(&arg) {
184+ bail!("model '{arg}' is neither a .bin path nor one of {GPU_SIZES:?}");
185+ }
186+ let home = std::env::var("HOME").context("HOME not set")?;
187+ let path = PathBuf::from(home)
188+ .join(".cache/edith/models")
189+ .join(format!("ggml-{arg}.bin"));
190+ (path, arg.to_string())
191+ };
192+ if !path.is_file() {
193+ bail!("GPU model file not found: {} (--device gpu does not download models)", path.display());
194+ }
195+ Ok((path, preset(&name)))
196+}
197+
198+fn preset(name: &str) -> Option<DtwModelPreset> {
199+ Some(match name {
200+ "tiny" => DtwModelPreset::Tiny,
201+ "base" => DtwModelPreset::Base,
202+ "small" => DtwModelPreset::Small,
203+ "medium" => DtwModelPreset::Medium,
204+ "large-v3" => DtwModelPreset::LargeV3,
205+ "large-v3-turbo" => DtwModelPreset::LargeV3Turbo,
206+ _ => return None,
207+ })
208+}
209+
210+struct Tok {
211+ bytes: Vec<u8>,
212+ plog: f64,
213+ dtw: f64,
214+}
215+
216+fn text_tokens(seg: &WhisperSegment<'_>, eot: i32) -> Result<Vec<Tok>> {
217+ let mut out = Vec::new();
218+ for i in 0..seg.n_tokens() {
219+ let Some(tok) = seg.get_token(i) else {
220+ continue;
221+ };
222+ if tok.token_id() >= eot {
223+ continue;
224+ }
225+ let bytes = tok.to_bytes().context("failed to read token text")?.to_vec();
226+ if bytes.is_empty() {
227+ continue;
228+ }
229+ let data = tok.token_data();
230+ out.push(Tok { bytes, plog: data.plog as f64, dtw: data.t_dtw as f64 / 100.0 });
231+ }
232+ Ok(out)
233+}
234+
235+struct Group {
236+ text: String,
237+ p: f64,
238+ start: f64,
239+}
240+
241+fn word_groups(toks: &[Tok]) -> Vec<Group> {
242+ let mut words: Vec<(Vec<u8>, Vec<f64>, f64)> = Vec::new();
243+ for t in toks {
244+ if words.is_empty() || t.bytes[0] == b' ' {
245+ words.push((Vec::new(), Vec::new(), t.dtw));
246+ }
247+ if let Some(w) = words.last_mut() {
248+ w.0.extend_from_slice(&t.bytes);
249+ w.1.push(t.plog);
250+ }
251+ }
252+ words
253+ .into_iter()
254+ .filter_map(|(bytes, plogs, start)| {
255+ let text = String::from_utf8_lossy(&bytes).trim().to_string();
256+ if text.is_empty() {
257+ return None;
258+ }
259+ let p = (plogs.iter().sum::<f64>() / plogs.len().max(1) as f64).exp();
260+ Some(Group { text, p, start })
261+ })
262+ .collect()
263+}
264+
265+fn word_json(text: &str, start: f64, end: f64, p: f64, offset: f64) -> serde_json::Value {
266+ json!({"w": text, "start": r3(start + offset), "end": r3(end + offset), "p": r3(p)})
267+}
268+
269+fn dtw_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> {
270+ let hi = t1.max(t0);
271+ let mut starts: Vec<f64> = Vec::with_capacity(groups.len());
272+ for g in groups {
273+ let s = if g.start > 0.0 { g.start } else { t0 };
274+ let prev = starts.last().copied().unwrap_or(t0);
275+ starts.push(s.clamp(t0, hi).max(prev));
276+ }
277+ groups
278+ .iter()
279+ .enumerate()
280+ .map(|(i, g)| {
281+ let start = starts[i];
282+ let end = starts.get(i + 1).copied().unwrap_or(hi).clamp(start, hi);
283+ word_json(&g.text, start, end, g.p, offset)
284+ })
285+ .collect()
286+}
287+
288+fn proportional_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> {
289+ let total: usize = groups.iter().map(|g| g.text.chars().count()).sum();
290+ let span = (t1 - t0).max(0.0);
291+ let mut t = t0;
292+ groups
293+ .iter()
294+ .map(|g| {
295+ let dur = if total > 0 { span * g.text.chars().count() as f64 / total as f64 } else { 0.0 };
296+ let (start, end) = (t, t + dur);
297+ t = end;
298+ word_json(&g.text, start, end, g.p, offset)
299+ })
300+ .collect()
301+}
tools/edith-stt/src/main.rsmodified+45 -5
@@ -1,6 +1,7 @@
11 //! edith-stt: offline Whisper speech-to-text on CPU (candle), JSON-lines output.
22 //!
3-//! usage: edith-stt --model base|small|tiny|<dir> [--language en|auto] [--offset SECS] [--no-align] [--keep-all] <input.wav>
3+//! usage: edith-stt --model base|small|tiny|<dir> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] <input.wav>
4+//! edith-stt --has-gpu
45 //!
56 //! stdout: one JSON object per segment
67 //! {"start":s,"end":s,"text":"...","words":[{"w":"Hello","start":s,"end":s,"p":prob}],"approx":false,
@@ -15,6 +16,23 @@
1516 //! stderr: progress lines `progress <0..1>` and diagnostics.
1617
1718 mod whisper_model;
19+#[cfg(feature = "vulkan")]
20+mod gpu;
21+#[cfg(not(feature = "vulkan"))]
22+mod gpu {
23+ use crate::Cli;
24+ use anyhow::{bail, Result};
25+
26+ const NO_VULKAN: &str = "edith-stt was built without vulkan; rebuild with --features vulkan";
27+
28+ pub fn probe() -> Result<()> {
29+ bail!(NO_VULKAN)
30+ }
31+
32+ pub fn run(_: &Cli) -> Result<()> {
33+ bail!(NO_VULKAN)
34+ }
35+}
1836
1937 use anyhow::{anyhow, bail, Context, Result};
2038 use candle_core::{DType, Device, IndexOp, Tensor};
@@ -54,7 +72,7 @@ const MAX_PREV_TOKENS: usize = 223;
5472 /// Silence filter thresholds (see `silence_reason`).
5573 const NO_SPEECH_PROB: f64 = 0.6;
5674 const NO_SPEECH_LOGPROB: f64 = -1.0;
57-const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3"];
75+const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"];
5876 const REQUIRED: &[&str] = &[
5977 "config.json",
6078 "model.safetensors",
@@ -81,11 +99,13 @@ struct Cli {
8199 /// `--prompt`: text Whisper sees before the audio, as OpenAI's `initial_prompt`. Names and
82100 /// jargon spelled the way they should come out ("Edith, LUFS") steer the decoder.
83101 prompt: Option<String>,
102+ gpu: bool,
103+ has_gpu: bool,
84104 input: PathBuf,
85105 }
86106
87107 fn usage() -> &'static str {
88- "usage: edith-stt --model base|small|tiny|<dir> [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] <input.wav>"
108+ "usage: edith-stt --model base|small|tiny|<dir>|<file.bin> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] <input.wav>\n edith-stt --has-gpu"
89109 }
90110
91111 fn parse_cli() -> Result<Cli> {
@@ -95,11 +115,21 @@ fn parse_cli() -> Result<Cli> {
95115 let mut align = true;
96116 let mut keep_all = false;
97117 let mut prompt: Option<String> = None;
118+ let mut gpu = false;
119+ let mut has_gpu = false;
98120 let mut input: Option<PathBuf> = None;
99121 let mut args = std::env::args().skip(1);
100122 while let Some(a) = args.next() {
101123 match a.as_str() {
102124 "--model" => model = args.next().context("--model needs a value")?,
125+ "--device" => {
126+ gpu = match args.next().context("--device needs a value")?.as_str() {
127+ "cpu" => false,
128+ "gpu" => true,
129+ other => bail!("--device must be cpu or gpu, got {other}"),
130+ }
131+ }
132+ "--has-gpu" => has_gpu = true,
103133 "--language" => language = args.next().context("--language needs a value")?,
104134 "--offset" => {
105135 offset = args
@@ -124,12 +154,22 @@ fn parse_cli() -> Result<Cli> {
124154 }
125155 }
126156 }
127- let input = input.with_context(|| usage().to_string())?;
128- Ok(Cli { model, language, offset, align, keep_all, prompt, input })
157+ let input = match (has_gpu, input) {
158+ (true, Some(_)) => bail!("--has-gpu takes no input file\n{}", usage()),
159+ (true, None) => PathBuf::new(),
160+ (false, input) => input.with_context(|| usage().to_string())?,
161+ };
162+ Ok(Cli { model, language, offset, align, keep_all, prompt, gpu, has_gpu, input })
129163 }
130164
131165 fn run() -> Result<()> {
132166 let cli = parse_cli()?;
167+ if cli.has_gpu {
168+ return gpu::probe();
169+ }
170+ if cli.gpu {
171+ return gpu::run(&cli);
172+ }
133173 let dir = resolve_model(&cli.model)?;
134174 let t_start = Instant::now();
135175