From bcb4dc5db29b96be7e6ace4ff2f41d65016df705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 10 Nov 2026 05:33:30 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Speech=20runs=20on=20the=20GPU=20to?= =?UTF-8?q?o:=20edith-stt=20gains=20a=20Vulkan=20whisper.cpp=20backend=20(?= =?UTF-8?q?--features=20vulkan),=20medium=20and=20large-v3(-turbo)=20join?= =?UTF-8?q?=20the=20models,=20and=20the=20model=20and=20device=20are=20a?= =?UTF-8?q?=20project=20setting=20with=20a=20picker,=20project=5Fsettings?= =?UTF-8?q?=20and=20a=20per-call=20device?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MCP.md | 10 +- crates/app/src/creator.rs | 12 - crates/app/src/menus.rs | 4 + crates/app/src/player/cards.rs | 33 +++ crates/app/src/player/tools.rs | 21 +- crates/app/src/player/transcript.rs | 41 +++- crates/app/src/tests/caps.rs | 3 +- crates/app/src/tests/creator.rs | 8 +- crates/app/src/ui/cards/tools.rs | 16 +- crates/app/src/ui/overlays.rs | 2 + crates/app/src/ui/settings_stance.rs | 75 +++++- crates/app/src/ui/transcript_panel.rs | 19 +- crates/engine/src/edith.rs | 56 ++++- crates/engine/src/playback.rs | 28 ++- crates/engine/src/project.rs | 43 ++++ crates/engine/src/speech.rs | 290 +++++++++++++++++------ crates/engine/tests/it/creator_tools.rs | 6 +- crates/mcp/src/help.rs | 4 +- crates/mcp/src/tools/listen.rs | 197 ++++++++++------ crates/mcp/src/tools/project.rs | 49 +++- tools/edith-stt/Cargo.lock | 138 ++++++++++- tools/edith-stt/Cargo.toml | 5 + tools/edith-stt/src/gpu.rs | 301 ++++++++++++++++++++++++ tools/edith-stt/src/main.rs | 50 +++- 24 files changed, 1171 insertions(+), 240 deletions(-) create mode 100644 tools/edith-stt/src/gpu.rs diff --git a/MCP.md b/MCP.md index ffdcf23..e84d386 100644 --- a/MCP.md +++ b/MCP.md @@ -229,7 +229,7 @@ in **bold**; optional ones follow the name. | `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 | | `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 | | `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 ` 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) | -| `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 | +| `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 | | `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 | | `checkpoint` | **name** | save the whole project under a name (letters, digits, `-`, `_`), as a copy in `/checkpoints//` (the project's path, from `project_new {path}` or `project_save`; with no path at all, the temp dir, lost on reboot) | | `restore` | **name** | replace the open project with a checkpoint, from this run or an earlier one; first saves the open project as `before-restore-` (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 | tool | args | does | |---|---|---| -| `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` | -| `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` | -| `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 `.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 | +| `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` | +| `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` | +| `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 `.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 | | `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 | | `voiceover` | **text**, voice, speed=1, pause=0, name, place | speaks `text` into `/voiceover/-.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) | | `record` | **action** (start\|stop\|status), lane, at=playhead, source | records a voice-over from the audio input into `_media/voiceover-.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. | `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 | | `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`: ` edit.` 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`) | | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:`, 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 | -| `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 | +| `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-`, gpu the single file `ggml-.bin`. `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true | | `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) | | `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. | | `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 | diff --git a/crates/app/src/creator.rs b/crates/app/src/creator.rs index 21a0d33..90cdc03 100644 --- a/crates/app/src/creator.rs +++ b/crates/app/src/creator.rs @@ -56,18 +56,6 @@ pub(crate) fn model_label(model: &str) -> String { } } -/// What a model's tooltip says: what it trades off, and its name on disk so the plain word is -/// never a mystery. -pub(crate) fn model_tip(model: &str) -> String { - let what = match model { - "tiny" => "quickest, least accurate", - "base" => "a middle ground", - "small" => "slowest, most accurate", - _ => "a speech model", - }; - format!("{}: {what} ({model} model)", model_label(model)) -} - // ---- normalize ---------------------------------------------------------------------- /// A minus sign the way the cards print it: U+2212, never a hyphen. diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs index 15f0864..eb10502 100644 --- a/crates/app/src/menus.rs +++ b/crates/app/src/menus.rs @@ -119,6 +119,8 @@ pub(crate) enum Pick { /// ([`engine::PlaybackSession::set_sample_rate`]). Opened from the panel, /// beside the resolution and rate it shares a row style with. SampleRate, + /// The speech model the project transcribes with, or Auto ([`Choice::SpeechModel`]). + SpeechModel, Fit(Lane, usize), /// The colour label of the clip at (lane, index) ([`engine::project::LABELS`]). Label(Lane, usize), @@ -201,6 +203,8 @@ pub(crate) enum Choice { Bin(u32), /// The autosave period in seconds, `None` for Off ([`Pick::Autosave`]). Autosave(Option), + /// The speech model, `None` for Auto ([`engine::speech::MODELS`]). + SpeechModel(Option<&'static str>), } /// A status-bar item a shortcut-opened list hangs above. diff --git a/crates/app/src/player/cards.rs b/crates/app/src/player/cards.rs index cf82702..50ade7e 100644 --- a/crates/app/src/player/cards.rs +++ b/crates/app/src/player/cards.rs @@ -592,6 +592,30 @@ impl Player { cx.notify(); } + /// The project's speech model set (`None` for Auto). One undo step. + pub(crate) fn apply_speech_model(&mut self, model: Option<&str>, cx: &mut Context) { + if self.session.as_mut().is_some_and(|s| s.set_speech_model(model)) { + self.mark_dirty(); + } + cx.notify(); + } + + /// The project's speech device set. One undo step. + pub(crate) fn apply_speech_device(&mut self, device: engine::speech::DeviceChoice, cx: &mut Context) { + if self.session.as_mut().is_some_and(|s| s.set_speech_device(device)) { + self.mark_dirty(); + } + cx.notify(); + } + + /// Whether a speech model in the picker is not installed for the device the project resolves it to. + pub(crate) fn speech_model_missing(&self, choice: Choice) -> bool { + match (choice, self.session.as_ref()) { + (Choice::SpeechModel(Some(m)), Some(s)) => engine::speech::check_model(m, s.speech_device().resolve(m)).is_err(), + _ => false, + } + } + /// The project's still length set: stills placed from now on take it, and the ones already /// on the timeline keep theirs. One undo step, and the project reads unsaved. pub(crate) fn apply_still_secs(&mut self, secs: f64, cx: &mut Context) { @@ -706,6 +730,7 @@ impl Player { Choice::Size(w, h) => self.apply_resolution(w, h, cx), Choice::Fps(fps) => self.apply_frame_rate(fps, cx), Choice::SampleRate(rate) => self.apply_sample_rate(rate, cx), + Choice::SpeechModel(model) => self.apply_speech_model(model, cx), Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), Choice::Label(lane, idx, label) => self.apply_label(lane, idx, label, cx), Choice::MarkerColor(idx, color) => self.set_marker_color(idx, color, cx), @@ -880,6 +905,14 @@ impl Player { } Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()), Pick::SampleRate => sample_rate_choices(session.sample_rate()), + Pick::SpeechModel => { + let here = session.speech_model(); + std::iter::once((Choice::SpeechModel(None), "Auto".into(), "".into(), here.is_none())) + .chain(engine::speech::MODELS.iter().map(|&m| { + (Choice::SpeechModel(Some(m)), crate::creator::model_label(m).into(), "".into(), here == Some(m)) + })) + .collect() + } Pick::Fit(lane, idx) => { fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) } diff --git a/crates/app/src/player/tools.rs b/crates/app/src/player/tools.rs index 30bb366..49d1d32 100644 --- a/crates/app/src/player/tools.rs +++ b/crates/app/src/player/tools.rs @@ -14,6 +14,7 @@ use engine::speech::{self, Filler, Hear, Job, Spoken}; use crate::creator::{self, LANGUAGES, LUFS_RANGE, LUFS_STEP, PEAK_RANGE, PEAK_STEP, Said}; use crate::player::text_field::FieldKey; +use crate::player::transcript; use crate::ui::kit::{NumberEdit, scrub_value}; use crate::*; @@ -118,7 +119,6 @@ pub(crate) struct Tools { pub(crate) each: bool, // Captions and Fillers pub(crate) lang: usize, - pub(crate) model: usize, pub(crate) hear: usize, /// Listen to the sound again even though a transcript is there to read from. pub(crate) relisten: bool, @@ -151,7 +151,6 @@ impl Tools { ceiling: engine::normalize::TARGET_TRUE_PEAK, each: false, lang: 0, - model: 0, hear: 0, relisten: false, found: Vec::new(), @@ -428,10 +427,6 @@ impl Player { self.session.as_ref().map_or_else(Vec::new, creator::hear_choices) } - pub(crate) fn tools_models(&self) -> Vec<&'static str> { - speech::installed_models() - } - /// Opens a dropdown, or shuts it when it is the one open. pub(crate) fn tools_toggle_drop(&mut self, what: Cycle, cx: &mut Context) { if let Some(t) = self.tools_mut() { @@ -445,7 +440,6 @@ impl Player { if let Some(t) = self.tools_mut() { match what { Cycle::Language => t.lang = i, - Cycle::Model => t.model = i, Cycle::Hear => t.hear = i, Cycle::Voice => t.voice = i, } @@ -500,14 +494,16 @@ impl Player { cx.notify(); return; } - let (lang, model_at, hear_at) = (tools.lang, tools.model, tools.hear); - if let Err(why) = speech::available() { + let (lang, hear_at) = (tools.lang, tools.hear); + if let Err(why) = speech::stt_bin() { return self.listen_fail(fillers, &why, cx); } - let models = self.tools_models(); - let Some(&model) = models.get(model_at).or(models.first()) else { + let Some((model, device)) = transcript::speech_target(self.session.as_ref()) else { return self.listen_fail(fillers, "No speech model is installed", cx); }; + if let Err(why) = speech::available(device) { + return self.listen_fail(fillers, &why, cx); + } let hears = self.tools_hears(); let hear = hears.get(hear_at).copied().unwrap_or(Hear::Mix); let lang = LANGUAGES[lang.min(LANGUAGES.len() - 1)].0; @@ -533,7 +529,7 @@ impl Player { } let work = cx.background_executor().spawn({ let job = job.clone(); - async move { speech::listen(heard, model, lang, fillers, &job) } + async move { speech::listen(heard, &model, device, lang, fillers, &job) } }); cx.spawn(async move |this, cx| { let heard = work.await; @@ -895,7 +891,6 @@ impl Player { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Cycle { Language, - Model, Hear, Voice, } diff --git a/crates/app/src/player/transcript.rs b/crates/app/src/player/transcript.rs index 4104c6b..d27cb19 100644 --- a/crates/app/src/player/transcript.rs +++ b/crates/app/src/player/transcript.rs @@ -28,6 +28,31 @@ const KEEP: usize = 64; /// What identifies a state of the timeline well enough to tell whose words these are. type Stamp = (usize, u32); +/// The model and device a run goes to: the project's pick, else the first one installed for the +/// device it allows. `None` when no model is installed there. +pub(crate) fn speech_target(session: Option<&PlaybackSession>) -> Option<(String, speech::Device)> { + let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device); + let model = session.and_then(PlaybackSession::speech_model); + speech::plan(choice, model).filter(|(m, d)| speech::check_model(m, *d).is_ok()) +} + +/// The model the download button fetches and the device it goes to: the project's pick, else +/// large-v3-turbo on a GPU and base on the CPU. +pub(crate) fn speech_download(session: Option<&PlaybackSession>) -> (String, speech::Device) { + let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device); + let device = match choice { + speech::DeviceChoice::Cpu => speech::Device::Cpu, + speech::DeviceChoice::Gpu => speech::Device::Gpu, + speech::DeviceChoice::Auto if speech::gpu_available() => speech::Device::Gpu, + speech::DeviceChoice::Auto => speech::Device::Cpu, + }; + let model = session.and_then(PlaybackSession::speech_model).unwrap_or(match device { + speech::Device::Gpu => "large-v3-turbo", + speech::Device::Cpu => "base", + }); + (model.to_string(), device) +} + pub(crate) struct Transcript { /// The words as the timeline stands (timeline frames), `None` before the first listen. pub(crate) words: Option>, @@ -199,12 +224,15 @@ impl Player { this.notify_user(why.into()); cx.notify(); }; - if let Err(why) = speech::available() { + if let Err(why) = speech::stt_bin() { return fail(self, why, cx); } - let Some(model) = speech::pick_model(|m| speech::check_model(m).is_ok()) else { + let Some((model, device)) = speech_target(self.session.as_ref()) else { return fail(self, "No speech model is installed".into(), cx); }; + if let Err(why) = speech::available(device) { + return fail(self, why, cx); + } let Some(session) = self.session.as_ref() else { return; }; @@ -219,7 +247,7 @@ impl Player { self.transcript.status.clear(); let work = cx.background_executor().spawn({ let job = job.clone(); - async move { speech::listen(heard, model, "auto", true, &job) } + async move { speech::listen(heard, &model, device, "auto", true, &job) } }); cx.spawn(async move |this, cx| { let heard = work.await; @@ -269,12 +297,13 @@ impl Player { cx.notify(); } - /// Fetches the speech model (the base one) with progress, off the UI thread. Nothing is - /// started while one is already coming. + /// Fetches the speech model the project chose (see [`speech_download`]) with progress, off the + /// UI thread. Nothing is started while one is already coming. pub(crate) fn start_model_download(&mut self, cx: &mut Context) { if self.transcript.download.is_some() { return; } + let (model, device) = speech_download(self.session.as_ref()); let job = Arc::new(Job::default()); let id = self.transcript.runs.wrapping_add(1); self.transcript.runs = id; @@ -282,7 +311,7 @@ impl Player { self.transcript.status.clear(); let work = cx.background_executor().spawn({ let job = job.clone(); - async move { speech::download_model("base", &job) } + async move { speech::download_model(&model, device, &job) } }); cx.spawn(async move |this, cx| { let done = work.await; diff --git a/crates/app/src/tests/caps.rs b/crates/app/src/tests/caps.rs index feed5b1..911dcb8 100644 --- a/crates/app/src/tests/caps.rs +++ b/crates/app/src/tests/caps.rs @@ -13,12 +13,11 @@ fn a_caption_drag_stays_between_its_neighbours() { } #[test] -fn speech_models_have_plain_names_and_the_real_one_in_the_tooltip() { +fn speech_models_have_plain_names() { assert_eq!(crate::creator::model_label("tiny"), "Fast"); assert_eq!(crate::creator::model_label("base"), "Balanced"); assert_eq!(crate::creator::model_label("small"), "Accurate"); assert_eq!(crate::creator::model_label("medium"), "Medium"); - assert!(crate::creator::model_tip("tiny").contains("tiny")); } #[test] diff --git a/crates/app/src/tests/creator.rs b/crates/app/src/tests/creator.rs index 9d376e7..c9a8a3f 100644 --- a/crates/app/src/tests/creator.rs +++ b/crates/app/src/tests/creator.rs @@ -206,7 +206,7 @@ fn speaking_text_makes_a_voiceover_the_timeline_takes() { #[test] fn listening_for_captions_runs_end_to_end_when_speech_is_installed() { - if speech::available().is_err() { + if speech::available(speech::Device::Cpu).is_err() { eprintln!("skipped: edith-stt or its model is not installed"); return; } @@ -215,10 +215,10 @@ fn listening_for_captions_runs_end_to_end_when_speech_is_installed() { assert!(hears.contains(&speech::Hear::Mix) && hears.contains(&speech::Hear::Lane(Lane::A1))); let heard = speech::prepare(&s, speech::Hear::Mix).expect("the fixture has sound"); let job = speech::Job::default(); - let model = speech::installed_models()[0]; + let model = speech::installed_models(speech::Device::Cpu)[0]; // A tone is not speech: whatever comes back, it comes back (and cancel stops it early). job.cancel.store(true, std::sync::atomic::Ordering::Relaxed); - assert_eq!(speech::listen(heard, model, "en", false, &job).unwrap_err(), speech::CANCELLED); + assert_eq!(speech::listen(heard, model, speech::Device::Cpu, "en", false, &job).unwrap_err(), speech::CANCELLED); } #[test] @@ -251,7 +251,6 @@ fn every_creator_tool_has_a_menu_row_a_palette_entry_and_a_card_control() { "tools-target", "tools-ceiling", "tools-lang", - "tools-model", "tools-tab-a", "tools-tab-b", "mix-normalize", @@ -347,6 +346,5 @@ fn a_tool_error_or_a_clock_or_a_model_tip_reads_plainly() { assert_eq!(creator::clock(0.0), "0:00"); assert_eq!(creator::clock(75.0), "1:15"); assert_eq!(creator::clock(3725.0), "1:02:05"); - assert!(creator::model_tip("base").contains("a middle ground")); assert_eq!(creator::lufs_text(-20.0), "\u{2212}20.0"); } diff --git a/crates/app/src/ui/cards/tools.rs b/crates/app/src/ui/cards/tools.rs index 641d3e6..dc7f1bc 100644 --- a/crates/app/src/ui/cards/tools.rs +++ b/crates/app/src/ui/cards/tools.rs @@ -6,6 +6,7 @@ use super::common::*; use crate::creator::{self, LANGUAGES, Said}; use crate::player::tools::{Cycle, NumField, Tool, Tools}; +use crate::player::transcript; use crate::ui::icons::Icon; use crate::ui::kit::{self, Segment}; use crate::*; @@ -488,15 +489,14 @@ impl Player { /// transcript to read from, "From the transcript" is the first and default choice (instant); /// "Listen again" keeps the sound pickers under it. fn listen_body(&self, t: &Tools, fillers: bool, list_w: f32, cx: &mut Context) -> Div { - let models = self.tools_models(); + let no_model = transcript::speech_target(self.session.as_ref()).is_none(); let hears = self.tools_hears(); let downloading = self.transcript.download.is_some(); let from_transcript = self.transcript_words().is_some() && !t.relisten; let hear_items: Vec = hears.iter().map(|h| creator::hear_label(*h).into()).collect(); let lang_items: Vec = LANGUAGES.iter().map(|(_, name)| (*name).into()).collect(); - let model_items: Vec = models.iter().map(|m| creator::model_label(m).into()).collect(); let _ = Hear::Mix; - let why = match (models.is_empty() && !from_transcript, t.running.is_some()) { + let why = match (no_model && !from_transcript, t.running.is_some()) { (true, _) => Some("Install a speech model first"), (false, true) => Some("Already listening"), _ => None, @@ -527,17 +527,11 @@ impl Player { )); } if !from_transcript { - let model_row = drop_row("tools-model", "Model", model_items, t.model, t.open == Some(Cycle::Model), Cycle::Model, list_w, busy, cx); - let model_tip = models.get(t.model).map(|m| creator::model_tip(m)); body = body .child(drop_row("tools-hear", "Listen to", hear_items, t.hear, t.open == Some(Cycle::Hear), Cycle::Hear, list_w, busy, cx)) - .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx)) - .child(match model_tip { - Some(tip) => model_row.id("tools-model-row").tooltip(crate::ui::widgets::overlay_tip_hover("Model", "", Some(&tip))).into_any_element(), - None => model_row.into_any_element(), - }); + .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx)); } - if models.is_empty() && !from_transcript { + if no_model && !from_transcript { body = body.child(missing( "No speech model is installed yet. Download one, or put one in the models folder.", vec![ diff --git a/crates/app/src/ui/overlays.rs b/crates/app/src/ui/overlays.rs index 5d6ca35..397b609 100644 --- a/crates/app/src/ui/overlays.rs +++ b/crates/app/src/ui/overlays.rs @@ -788,7 +788,9 @@ impl Player { // A refused row (a format this timeline cannot be written in) is // dimmed and says why on hover; it takes no click. let why = self.export_choice_refusal(choice); + let missing = self.speech_model_missing(choice); crate::ui::popup::popup_row(("picker-row", n), label, detail, Some(picked), why.as_deref()) + .when(missing, |d| d.opacity(0.45)) .when(n == picker.sel, |d| d.bg(rgb(DARK_RAISED()))) .when(why.is_none(), |d| { d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx))) diff --git a/crates/app/src/ui/settings_stance.rs b/crates/app/src/ui/settings_stance.rs index cfddc49..a406499 100644 --- a/crates/app/src/ui/settings_stance.rs +++ b/crates/app/src/ui/settings_stance.rs @@ -54,6 +54,7 @@ use crate::ui::choice; use crate::ui::hitmap; use crate::ui::type_scale; use crate::*; +use engine::speech::{self, DeviceChoice}; use gpui::{AnyElement, KeyDownEvent, SharedString}; /// Which of the page's four sections is showing. Kept on [`Player`] beside @@ -293,6 +294,24 @@ pub(crate) enum ChoiceRow { /// The two stand-in switches, Off/On. Proxies, AutoProxies, + /// What the speech model runs on ([`device_choices`]). + Device, +} + +/// The devices the picker offers: the GPU only when edith-stt has one. +pub(crate) fn device_choices() -> Vec { + match speech::gpu_available() { + true => vec![DeviceChoice::Auto, DeviceChoice::Cpu, DeviceChoice::Gpu], + false => vec![DeviceChoice::Auto, DeviceChoice::Cpu], + } +} + +fn device_label(device: DeviceChoice) -> &'static str { + match device { + DeviceChoice::Auto => "Auto", + DeviceChoice::Cpu => "CPU", + DeviceChoice::Gpu => "GPU", + } } /// The two words a switch answers with, and the index each one sits at. @@ -316,10 +335,11 @@ pub(crate) fn index_of(all: &[T], value: T) -> Option { impl ChoiceRow { /// Every choice row there is, for the guards below. #[cfg(test)] - pub(crate) const ALL: [ChoiceRow; 3] = [ + pub(crate) const ALL: [ChoiceRow; 4] = [ ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies, + ChoiceRow::Device, ]; /// The row's chips, in order, each a word read off the same table the @@ -334,6 +354,7 @@ impl ChoiceRow { ChoiceRow::Proxies | ChoiceRow::AutoProxies => { SWITCH.iter().map(|w| w.to_string()).collect() } + ChoiceRow::Device => device_choices().into_iter().map(|d| device_label(d).to_string()).collect(), } } @@ -343,6 +364,7 @@ impl ChoiceRow { match self { ChoiceRow::Tone => player.session.is_some(), ChoiceRow::Proxies | ChoiceRow::AutoProxies => true, + ChoiceRow::Device => player.session.is_some(), } } } @@ -352,7 +374,7 @@ impl ChoiceRow { /// and a song has no Encoder row ([`export_section`]'s own two gates). pub(crate) fn choice_rows(tab: SettingsTab, _format: Format) -> Vec { match tab { - SettingsTab::Project => vec![ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies], + SettingsTab::Project => vec![ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies], SettingsTab::Editor | SettingsTab::Keys => Vec::new(), } } @@ -364,6 +386,10 @@ pub(crate) fn current_choice(player: &Player, row: ChoiceRow) -> Option { .session .as_ref() .and_then(|session| index_of(&Preset::ALL, session.tone())), + ChoiceRow::Device => player + .session + .as_ref() + .and_then(|session| index_of(&device_choices(), session.speech_device())), ChoiceRow::Proxies => Some(switch_index(player.proxies_on)), // The import switch waits on editing copies: while they are off it shows off, and its own // 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) -> impl IntoElemen INK1(), )) .child(still_row(player, cx)) + .child(speech_model_row(player, cx)) + .child(choice_row( + "settings-speech-device", + "Speech device", + "where the speech model runs; Auto takes the GPU when this computer has one", + None, + None, + false, + ChoiceRow::Device, + player, + cx, + )) // Only a project with HDR in it has anything to choose here. .children(has_hdr.then(|| { choice_row( @@ -706,6 +744,25 @@ fn still_row(player: &Player, cx: &mut Context) -> impl IntoElement { .child(field) } +/// The speech model the project transcribes with: Auto, or one of [`speech::MODELS`] from a list. +/// Models not installed for the device are dimmed in the list. +fn speech_model_row(player: &Player, cx: &mut Context) -> impl IntoElement { + let value = match player.session.as_ref().and_then(|s| s.speech_model()) { + Some(model) => crate::creator::model_label(model), + None => "Auto".to_string(), + }; + list_row( + "settings-speech-model", + "Speech model", + value, + "the model that hears the timeline for captions, fillers and the transcript; Auto takes the best one installed", + None, + player, + cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::SpeechModel, event.position(), cx)), + INK1(), + ) +} + /// A chip of `row` was picked (by a click, or by an arrow through /// [`settings_arrow`]): the value at `at`, through the same door the row's /// 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< player.toggle_auto_proxies(cx); } } + ChoiceRow::Device => { + if let Some(&device) = device_choices().get(at) { + player.apply_speech_device(device, cx); + } + } } } @@ -1785,7 +1847,7 @@ const SETTINGS_GAP: f32 = 8.; /// under the hand (user 2026-09-20: "switching between them feels weird"). A /// shorter section leaves air below its last row; a short window still /// scrolls, the plate's `max_h` cap shrinking this from `min_h(0)`. -pub(crate) const SETTINGS_ROWS_H: f32 = 7. * CONTROL_H + 36. + 7. * 2.; +pub(crate) const SETTINGS_ROWS_H: f32 = 9. * CONTROL_H + 36. + 9. * 2.; /// The plate's height that is not its rows: the dialog's padding and gaps, the title and the tab /// 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 { fn the_choice_rows_sit_in_the_tabs_they_belong_to() { assert_eq!( choice_rows(SettingsTab::Project, Format::Mp4), - [ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies] + [ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies] ); assert!(choice_rows(SettingsTab::Editor, Format::Mp4).is_empty()); assert!(choice_rows(SettingsTab::Keys, Format::Mp4).is_empty()); @@ -2035,7 +2097,7 @@ mod tests { fn the_panel_and_its_chip_rows_fit_at_1280_by_720() { // PROJECT at its tallest (HDR row and its hint, both switches, the // storage line) still fits the rows area. - let project_tallest = 7. * CONTROL_H + 36. + 7. * 2.; + let project_tallest = 9. * CONTROL_H + 36. + 9. * 2.; assert!(project_tallest <= SETTINGS_ROWS_H); // Width: a generous measure per glyph, so a real font only has room // to spare. (label, chord, tail, row) @@ -2044,7 +2106,8 @@ mod tests { let mono_w = |text: &str| text.chars().count() as f32 * 8.; let _ = keys; // (label, tail, row); the key lives in the tooltip, the column is empty. - let rows: [(&str, &str, ChoiceRow); 3] = [ + let rows: [(&str, &str, ChoiceRow); 4] = [ + ("Speech device", "", ChoiceRow::Device), ("When HDR plays on a normal screen", "", ChoiceRow::Tone), ("Editing copies (proxies)", "100%", ChoiceRow::Proxies), (" Make them on import", "", ChoiceRow::AutoProxies), diff --git a/crates/app/src/ui/transcript_panel.rs b/crates/app/src/ui/transcript_panel.rs index d49c535..7f0b4ab 100644 --- a/crates/app/src/ui/transcript_panel.rs +++ b/crates/app/src/ui/transcript_panel.rs @@ -4,6 +4,7 @@ //! lit. Every state is a background on a word whose box never changes, so nothing moves. use crate::layout::redesign as r; +use crate::player::transcript; use crate::ui::hitmap; use crate::ui::icons::{Icon, IconSize}; use crate::ui::kit::{Button, ButtonSize, ButtonStyle}; @@ -299,11 +300,15 @@ fn paragraph( /// model on the computer it says so plainly and offers to download one. fn empty_view(player: &Player, cx: &mut Context) -> impl IntoElement { let t = tokens(); - let ready = speech::available(); - let no_model = speech::stt_bin().is_ok() && speech::installed_models().is_empty(); + let target = transcript::speech_target(player.session.as_ref()); + let ready = match &target { + Some((_, device)) => speech::available(*device), + None => speech::available(transcript::speech_download(player.session.as_ref()).1), + }; + let no_model = speech::stt_bin().is_ok() && target.is_none(); let not_built = speech::stt_bin().is_err(); if let Some((job, _)) = &player.transcript.download { - return download_view(job.fraction(), cx).into_any_element(); + return download_view(player.session.as_ref(), job.fraction(), cx).into_any_element(); } let note = match (&ready, player.transcript.status.as_str()) { (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) -> impl IntoElement { } /// While the speech model downloads: how far, and Cancel. -fn download_view(fraction: f32, cx: &mut Context) -> impl IntoElement { +fn download_view(session: Option<&PlaybackSession>, fraction: f32, cx: &mut Context) -> impl IntoElement { let t = tokens(); - let mb = speech::model_bytes("base") as f32 * fraction / 1_000_000.; + let (model, device) = transcript::speech_download(session); + let total = speech::model_bytes(&model, device) as f32; + let mb = total * fraction / 1_000_000.; div() .id("transcript-downloading") .flex_1() @@ -381,7 +388,7 @@ fn download_view(fraction: f32, cx: &mut Context) -> impl IntoElement { .type_style(type_scale::body()) .text_color(rgb(t.ink2)) .child("Downloading the speech model") - .child(format!("{mb:.0} of {:.0} MB", speech::model_bytes("base") as f32 / 1_000_000.)), + .child(format!("{mb:.0} of {:.0} MB", total / 1_000_000.)), ) .child( div() diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 0e7716a..d433622 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -444,11 +444,12 @@ use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, Tr /// The newest project format version: the `N` in the `edith N` first line that /// [`save`] writes for a project that uses the newest features. A reader refuses any /// higher version by name. -pub const NEWEST_VERSION: u32 = 56; +pub const NEWEST_VERSION: u32 = 57; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`]. -const MAGIC: &[u8] = b"edith 56"; +const MAGIC: &[u8] = b"edith 57"; +const MAGIC_V56: &[u8] = b"edith 56"; const MAGIC_V55: &[u8] = b"edith 55"; const MAGIC_V54: &[u8] = b"edith 54"; const MAGIC_V53: &[u8] = b"edith 53"; @@ -650,6 +651,11 @@ pub struct Document { /// The length a still is placed at, from the `still` line (v52). `None` for a file that /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s. pub still_secs: Option, + /// The speech model, from the `speech` line (v57). `None` for a file that names none, which + /// means the model is picked. + pub speech_model: Option, + /// The device the speech model runs on, from the `speech` line (v57). Auto for a file without one. + pub speech_device: crate::speech::DeviceChoice, } /// A parked sequence read off a v45 file. @@ -831,7 +837,7 @@ pub fn encode_flagged( 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() { let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len()); let header = if curved { - MAGIC + MAGIC_V56 } else if pitched { MAGIC_V55 } else if titled { @@ -939,10 +945,11 @@ pub fn binned(mut main: Vec, sources: &[Source], bins: &[crate::project::Bin main } -/// `main` with the project notes and the still length after it (v52): a `notes` line when there -/// are notes, a `still` line when the length is not the default. A project with neither is `main` -/// untouched, so it keeps the bytes it had before v52. -pub fn noted(mut main: Vec, notes: &str, still_secs: f64) -> Vec { +/// `main` with the project notes, the still length and the speech choices after it (v52, v57): a +/// `notes` line when there are notes, a `still` line when the length is not the default, a +/// `speech` line when a model or a device is picked. A project with none is `main` untouched, so +/// it keeps the bytes it had before v52. +pub fn noted(mut main: Vec, notes: &str, still_secs: f64, speech_model: Option<&str>, speech_device: crate::speech::DeviceChoice) -> Vec { let mut lines = Vec::new(); if !notes.is_empty() { lines.extend_from_slice(b"notes "); @@ -952,11 +959,19 @@ pub fn noted(mut main: Vec, notes: &str, still_secs: f64) -> Vec { if still_secs != STILL_DEFAULT_SECS { lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes()); } + let speech = speech_model.is_some() || speech_device != crate::speech::DeviceChoice::Auto; + if speech { + lines.extend_from_slice(format!("speech {}", speech_device.as_str()).as_bytes()); + if let Some(m) = speech_model { + lines.extend_from_slice(format!(" {m}").as_bytes()); + } + lines.push(b'\n'); + } if lines.is_empty() { return main; } let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len()); - let header = raise_header(&main[..first_end], MAGIC_V52); + let header = raise_header(&main[..first_end], if speech { MAGIC } else { MAGIC_V52 }); main.splice(..first_end, header); if main.last() != Some(&b'\n') { main.push(b'\n'); @@ -1049,7 +1064,8 @@ pub fn sequenced(main: Vec, active: (u32, &str), order: &[u32], blocks: &[Se // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46 // when a part is v46; a newer-only line under an older header is refused. let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n'); - let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); + let v57 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); + let v56 = v57 || is(&bytes, MAGIC_V56) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V56)); let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55)); let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54)); 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, active: (u32, &str), order: &[u32], blocks: &[Se let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48)); let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47)); let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46)); - 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 }; + 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 }; bytes.splice(..first_end, header.iter().copied()); bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes()); escape_text(active.1, &mut bytes); @@ -2297,7 +2313,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The one that carries a clip's placement animation, as `tkeys` lines... // The one that carries a clip's stabilisation, as `stab` lines... // The one that carries a clip's pitch shift, as `pitch` lines... - let v56 = first == MAGIC; + let v57 = first == MAGIC; + let v56 = v57 || first == MAGIC_V56; let v55 = v56 || first == MAGIC_V55; let v54 = v55 || first == MAGIC_V54; let v53 = v54 || first == MAGIC_V53; @@ -2454,6 +2471,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { bins: Vec::new(), notes: String::new(), still_secs: None, + speech_model: None, + speech_device: crate::speech::DeviceChoice::Auto, }; // The block of a parked sequence being read: its id, name and the lines so far. let mut block: Option<(u32, String, Vec)> = None; @@ -3588,6 +3607,19 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } doc.still_secs = Some(secs); } + b"speech" if v57 => { + let text = std::str::from_utf8(rest).map_err(|_| format!("line {n}: speech is not text"))?; + let f: Vec<&str> = text.split(' ').collect(); + doc.speech_device = f + .first() + .and_then(|d| crate::speech::DeviceChoice::parse(d)) + .ok_or_else(|| format!("line {n}: speech wants a device, auto, cpu or gpu"))?; + doc.speech_model = match f.get(1) { + None => None, + Some(m) if crate::speech::MODELS.contains(m) && f.len() == 2 => Some(m.to_string()), + Some(m) => return Err(format!("line {n}: speech model `{m}` is not one of {}", crate::speech::MODELS.join(", ")).into()), + }; + } b"bin" if v51 => { let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect(); if f.len() != 3 { @@ -7199,7 +7231,7 @@ mod tests { crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(), Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[], ); - let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS); + let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS, None, crate::speech::DeviceChoice::Auto); std::fs::write(&path, &bytes).unwrap(); String::from_utf8(bytes).unwrap() }; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index c4467da..109b205 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1436,7 +1436,8 @@ impl PlaybackSession { .with_lane_flags(&doc.flags) .with_tone(doc.tone) .with_notes(doc.notes) - .with_still_secs(doc.still_secs); + .with_still_secs(doc.still_secs) + .with_speech(doc.speech_model, doc.speech_device); session.counts = counts; session.rates = rates; Ok(session) @@ -2296,7 +2297,7 @@ impl PlaybackSession { .min(main.timeline_frames().saturating_sub(1)); let main_bytes = self.encode_sequence(&dir, main, playhead); let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins()); - let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs()); + let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs(), self.project.speech_model(), self.project.speech_device()); if !self.project.uses_sequences() { return crate::edith::write_atomic(path, &main_bytes); } @@ -5251,6 +5252,26 @@ impl PlaybackSession { self.project.set_still_secs(secs) } + /// The speech model the project names, or `None` for the one picked ([`Project::speech_model`]). + pub fn speech_model(&self) -> Option<&str> { + self.project.speech_model() + } + + /// Sets it ([`Project::set_speech_model`]). + pub fn set_speech_model(&mut self, model: Option<&str>) -> bool { + self.project.set_speech_model(model) + } + + /// The device the speech model runs on ([`Project::speech_device`]). + pub fn speech_device(&self) -> crate::speech::DeviceChoice { + self.project.speech_device() + } + + /// Sets it ([`Project::set_speech_device`]). + pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool { + self.project.set_speech_device(device) + } + /// What source 0's own file declared about how bright it gets /// ([`ContentLight`]): a property of the film, read once at open, and /// entirely absent (every field `None`) for an SDR file, a song or a @@ -6883,6 +6904,8 @@ impl PlaybackSession { caption_style: self.project.caption_style(), notes: self.project.notes().to_string(), still_secs: self.project.still_secs(), + speech_model: self.project.speech_model().map(str::to_string), + speech_device: self.project.speech_device(), } } @@ -7959,6 +7982,7 @@ Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? .with_tone(doc.tone) .with_notes(doc.notes) .with_still_secs(doc.still_secs) + .with_speech(doc.speech_model, doc.speech_device) // The palette before what is placed on it: a caption names a row of // it, and [`Project::with_subs`] refuses one naming a row that is // not there. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index d2a7fab..d6bfab1 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2365,6 +2365,10 @@ pub(crate) struct ProjectSettings { pub(crate) notes: String, /// How long a still image is placed for, in seconds (v52). pub(crate) still_secs: f64, + /// The speech model the transcript and captions run on; `None` picks one (v57). + pub(crate) speech_model: Option, + /// The device the speech model runs on (v57). + pub(crate) speech_device: crate::speech::DeviceChoice, } impl ProjectSettings { @@ -2387,6 +2391,8 @@ impl ProjectSettings { caption_style: crate::captionanim::CaptionStyle::default(), notes: String::new(), still_secs: STILL_DEFAULT_SECS, + speech_model: None, + speech_device: crate::speech::DeviceChoice::Auto, } } } @@ -4342,6 +4348,43 @@ impl Project { self } + /// The speech model the project names, or `None` for the one picked. + pub fn speech_model(&self) -> Option<&str> { + self.settings.speech_model.as_deref() + } + + /// Sets it (`None` picks one). `false` for the one already in force; otherwise one undo step. + pub fn set_speech_model(&mut self, model: Option<&str>) -> bool { + if self.settings.speech_model.as_deref() == model { + return false; + } + self.snapshot(); + self.settings.speech_model = model.map(str::to_string); + true + } + + /// The device the speech model runs on. + pub fn speech_device(&self) -> crate::speech::DeviceChoice { + self.settings.speech_device + } + + /// Sets it. `false` for the one already in force; otherwise one undo step. + pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool { + if self.settings.speech_device == device { + return false; + } + self.snapshot(); + self.settings.speech_device = device; + true + } + + /// The speech choices a *load* puts back: no undo step, as [`with_still_secs`](Project::with_still_secs). + pub(crate) fn with_speech(mut self, model: Option, device: crate::speech::DeviceChoice) -> Self { + self.settings.speech_model = model; + self.settings.speech_device = device; + self + } + /// Sets it. `false` for the one already in force, which is what keeps a /// re-pick of the current rendition from costing a reseek. One undo step /// like every other project-setting pick. diff --git a/crates/engine/src/speech.rs b/crates/engine/src/speech.rs index 881ccc7..5cfafc2 100644 --- a/crates/engine/src/speech.rs +++ b/crates/engine/src/speech.rs @@ -9,6 +9,7 @@ use std::io::{BufRead, BufReader, Read}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; use crate::project::Lane; @@ -17,7 +18,7 @@ use crate::{AudioSession, PlaybackSession, subtitle}; /// The sample rate edith-stt is fed. pub const RATE: u32 = 16_000; /// The Whisper model sizes edith-stt knows. -pub const MODELS: &[&str] = &["tiny", "base", "small"]; +pub const MODELS: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; /// Silence longer than this (seconds) between two words ends a caption cue. pub const CAPTION_GAP_SECS: f64 = 0.7; /// Whisper drops disfluencies unless its prompt shows them: this prompt, put before the @@ -46,7 +47,7 @@ pub fn home() -> PathBuf { /// The edith-stt binary: `EDITH_STT_BIN`, else the first /// `tools/edith-stt/target/release/edith-stt` above the running executable. pub fn stt_bin() -> Result { - 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"; + 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"; if let Some(p) = std::env::var_os("EDITH_STT_BIN") { let p = PathBuf::from(p); 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 { Err(NOT_BUILT.into()) } -pub fn check_model(model: &str) -> Result<(), String> { +/// What edith-stt runs the model on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Device { + Cpu, + Gpu, +} + +impl Device { + /// The name edith-stt takes for `--device`. + pub fn flag(self) -> &'static str { + match self { + Self::Cpu => "cpu", + Self::Gpu => "gpu", + } + } +} + +/// The device a user picks: auto leaves it to [`DeviceChoice::resolve`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DeviceChoice { + #[default] + Auto, + Cpu, + Gpu, +} + +impl DeviceChoice { + pub fn parse(s: &str) -> Option { + match s { + "auto" => Some(Self::Auto), + "cpu" => Some(Self::Cpu), + "gpu" => Some(Self::Gpu), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::Cpu => "cpu", + Self::Gpu => "gpu", + } + } + + /// The device this choice runs `model` on: auto is the GPU when edith-stt has one and the + /// GPU file of `model` is installed, else the CPU. + pub fn resolve(self, model: &str) -> Device { + match self { + Self::Cpu => Device::Cpu, + Self::Gpu => Device::Gpu, + Self::Auto if gpu_available() && check_model(model, Device::Gpu).is_ok() => Device::Gpu, + Self::Auto => Device::Cpu, + } + } +} + +/// Whether edith-stt reports a usable GPU (`--has-gpu` exits 0). An old binary without the flag +/// counts as no GPU. +pub fn gpu_available() -> bool { + static GPU: OnceLock = OnceLock::new(); + *GPU.get_or_init(|| { + stt_bin().is_ok_and(|bin| { + Command::new(bin) + .arg("--has-gpu") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|st| st.success()) + }) + }) +} + +/// Where a model lives for `device`: the folder `whisper-` for the CPU, the file +/// `ggml-.bin` for the GPU. +pub fn model_path(model: &str, device: Device) -> PathBuf { + match device { + Device::Cpu => models_dir().join(format!("whisper-{model}")), + Device::Gpu => models_dir().join(format!("ggml-{model}.bin")), + } +} + +pub fn check_model(model: &str, device: Device) -> Result<(), String> { if !MODELS.contains(&model) { return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); } - let dir = home().join(".cache/edith/models").join(format!("whisper-{model}")); - if !dir.is_dir() { - return Err(format!("the {model} model is not installed at {}; edith-stt downloads it only when asked to", dir.display())); + let at = model_path(model, device); + let there = match device { + Device::Cpu => at.is_dir(), + Device::Gpu => at.is_file(), + }; + if !there { + return Err(format!("the {model} model ({}) is not installed at {}; edith-stt downloads it only when asked to", device.flag(), at.display())); } Ok(()) } @@ -78,9 +165,30 @@ pub fn check_lang(lang: &str) -> Result<(), String> { if ok { Ok(()) } else { Err(format!("language `{lang}` must be auto or a language code such as en")) } } -/// The model when none is named: the first installed of base, small, tiny. -pub fn pick_model(installed: impl Fn(&str) -> bool) -> Option<&'static str> { - ["base", "small", "tiny"].into_iter().find(|m| installed(m)) +/// The model when none is named: the first installed in the device's order. +pub fn pick_model(installed: impl Fn(&str) -> bool, device: Device) -> Option<&'static str> { + let order: [&'static str; 6] = match device { + Device::Gpu => ["large-v3-turbo", "large-v3", "medium", "small", "base", "tiny"], + Device::Cpu => ["base", "small", "tiny", "medium", "large-v3-turbo", "large-v3"], + }; + order.into_iter().find(|m| installed(m)) +} + +/// The model and device a request runs on: the named model (its device from `choice`), or with no +/// model named the first one installed for the device `choice` allows (auto tries the GPU first). +pub fn plan(choice: DeviceChoice, model: Option<&str>) -> Option<(String, Device)> { + if let Some(m) = model { + return Some((m.to_string(), choice.resolve(m))); + } + let on = |d: Device| move |m: &str| check_model(m, d).is_ok(); + let gpu = || pick_model(on(Device::Gpu), Device::Gpu).map(|m| (m.to_string(), Device::Gpu)); + let cpu = || pick_model(on(Device::Cpu), Device::Cpu).map(|m| (m.to_string(), Device::Cpu)); + match choice { + DeviceChoice::Cpu => cpu(), + DeviceChoice::Gpu => gpu(), + DeviceChoice::Auto if gpu_available() => gpu().or_else(cpu), + DeviceChoice::Auto => cpu(), + } } #[derive(Clone, Debug)] @@ -548,10 +656,10 @@ pub const CANCELLED: &str = "cancelled"; /// lines feed `job`; setting `job.cancel` kills it. The last few other stderr lines are kept /// for the error if the binary fails. #[allow(clippy::too_many_arguments)] -pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result { +pub fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result { let hint_args: Vec<&str> = if hint.is_empty() { Vec::new() } else { vec!["--prompt", hint] }; let mut child = Command::new(bin) - .args(["--model", model, "--language", lang, "--offset"]) + .args(["--model", model, "--device", device.flag(), "--language", lang, "--offset"]) .arg(format!("{offset:.3}")) .args(&hint_args) .arg(wav) @@ -608,9 +716,9 @@ pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offs Ok(out) } -/// The models installed, smallest first. -pub fn installed_models() -> Vec<&'static str> { - MODELS.iter().copied().filter(|m| check_model(m).is_ok()).collect() +/// The models installed for `device`, smallest first. +pub fn installed_models(device: Device) -> Vec<&'static str> { + MODELS.iter().copied().filter(|m| check_model(m, device).is_ok()).collect() } /// Where the speech models live: one folder per model, `whisper-`, here. @@ -628,80 +736,116 @@ const MODEL_FILES: [(&str, bool); 4] = [ const MODEL_OPTIONAL: &str = "generation_config.json"; /// About how many bytes a model's files add up to, for a progress bar before the sizes are known. -pub fn model_bytes(model: &str) -> u64 { - match model { - "tiny" => 152_000_000, - "small" => 970_000_000, +pub fn model_bytes(model: &str, device: Device) -> u64 { + match (device, model) { + (Device::Gpu, "tiny") => 78_000_000, + (Device::Gpu, "base") => 148_000_000, + (Device::Gpu, "small") => 488_000_000, + (Device::Gpu, "medium") => 1_530_000_000, + (Device::Gpu, "large-v3") => 3_100_000_000, + (Device::Gpu, "large-v3-turbo") => 1_620_000_000, + (Device::Cpu, "tiny") => 152_000_000, + (Device::Cpu, "small") => 970_000_000, + (Device::Cpu, "medium") => 3_060_000_000, + (Device::Cpu, "large-v3") => 3_090_000_000, + (Device::Cpu, "large-v3-turbo") => 1_620_000_000, _ => 293_000_000, } } -/// Downloads the `model` (one of [`MODELS`]) into [`models_dir`] with `curl`, from the same place -/// `edith-stt` fetches it (huggingface.co/openai/whisper-). The folder appears only when +/// Fetches `url` into `tmp` with curl, reporting the bytes `have` counts against `total` as +/// progress. `Ok(false)` when curl fails (`tmp` is removed); a cancel kills it. +fn fetch(url: &str, tmp: &Path, job: &Job, total: f64, have: &dyn Fn() -> u64) -> Result { + let mut child = Command::new("curl") + .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"]) + .arg(tmp) + .arg(url) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", models_dir().display()))?; + let status = loop { + if job.cancelled() { + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_file(tmp); + return Err(CANCELLED.into()); + } + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { + break status; + } + job.set((have() as f64 / total).min(0.99)); + std::thread::sleep(std::time::Duration::from_millis(150)); + }; + if !status.success() { + let _ = std::fs::remove_file(tmp); + } + Ok(status.success()) +} + +/// Downloads the `model` (one of [`MODELS`]) for `device` into [`models_dir`], from the same place +/// `edith-stt` fetches it: huggingface.co/openai/whisper- for the CPU folder, and the +/// ggerganov/whisper.cpp `ggml-.bin` file for the GPU. The CPU folder appears only when /// every file is in, so a half-finished download is never taken for an installed model; the files /// already fetched are kept for the next try. `job` carries the progress and the cancel. -pub fn download_model(model: &str, job: &Job) -> Result<(), String> { +pub fn download_model(model: &str, device: Device, job: &Job) -> Result<(), String> { if !MODELS.contains(&model) { return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); } let root = models_dir(); - let part = root.join(format!("whisper-{model}.part")); - let done = root.join(format!("whisper-{model}")); - std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?; - let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main"); - let total = model_bytes(model) as f64; - let have = |dir: &Path| -> u64 { - std::fs::read_dir(dir) - .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()) - .unwrap_or(0) - }; - let files = MODEL_FILES.iter().map(|&(f, need)| (f, need)).chain([(MODEL_OPTIONAL, false)]); - for (file, needed) in files { - let target = part.join(file); - if target.exists() { - continue; - } - let tmp = part.join(format!("{file}.tmp")); - let mut child = Command::new("curl") - .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"]) - .arg(&tmp) - .arg(format!("{base}/{file}")) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", done.display()))?; - let status = loop { - if job.cancelled() { - let _ = child.kill(); - let _ = child.wait(); - let _ = std::fs::remove_file(&tmp); - return Err(CANCELLED.into()); - } - if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { - break status; + std::fs::create_dir_all(&root).map_err(|e| format!("cannot create {}: {e}", root.display()))?; + let total = model_bytes(model, device) as f64; + match device { + Device::Gpu => { + let file = format!("ggml-{model}.bin"); + let target = root.join(&file); + let tmp = root.join(format!("{file}.part")); + let url = format!("https://huggingface.co/ggerganov/whisper.cpp/resolve/main/{file}"); + let len = || std::fs::metadata(&tmp).map(|m| m.len()).unwrap_or(0); + if !fetch(&url, &tmp, job, total, &len)? { + return Err(format!("could not download {file}: check the internet connection and try again")); } - job.set((have(&part) as f64 / total).min(0.99)); - std::thread::sleep(std::time::Duration::from_millis(150)); - }; - if status.success() { std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; - } else { - let _ = std::fs::remove_file(&tmp); - if needed { - return Err(format!("could not download {file}: check the internet connection and try again")); + } + Device::Cpu => { + let part = root.join(format!("whisper-{model}.part")); + let done = model_path(model, device); + std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?; + let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main"); + let have = || -> u64 { + std::fs::read_dir(&part) + .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()) + .unwrap_or(0) + }; + let files = MODEL_FILES.iter().copied().chain([(MODEL_OPTIONAL, false)]); + for (file, needed) in files { + let target = part.join(file); + if target.exists() { + continue; + } + let tmp = part.join(format!("{file}.tmp")); + if fetch(&format!("{base}/{file}"), &tmp, job, total, &have)? { + std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; + } else if needed { + return Err(format!("could not download {file}: check the internet connection and try again")); + } } + std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?; } } - std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?; job.set(1.0); Ok(()) } -/// Whether speech can run at all here: the edith-stt binary is built and a model is installed. -pub fn available() -> Result<(), String> { +/// Whether speech can run at all here on `device`: the edith-stt binary is built, the GPU is +/// usable for the GPU device, and a model is installed for it. +pub fn available(device: Device) -> Result<(), String> { stt_bin()?; - if installed_models().is_empty() { + if device == Device::Gpu && !gpu_available() { + return Err("edith-stt finds no usable GPU".into()); + } + if installed_models(device).is_empty() { return Err("The speech model is not installed yet.".into()); } Ok(()) @@ -771,8 +915,8 @@ fn silence_hallucination(text: &str, no_speech: Option, avg_logprob: Option /// What is said in `hear`, word by word, in timeline frames. `fillers` asks Whisper to keep its /// disfluencies ([`FILLER_PROMPT`]); without it the model tends to drop them. The model runs on /// a worker thread of the caller's choosing: this blocks until it is done or `job` is cancelled. -pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, lang: &str, fillers: bool, job: &Job) -> Result, String> { - listen(prepare(s, hear)?, model, lang, fillers, job) +pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result, String> { + listen(prepare(s, hear)?, model, device, lang, fillers, job) } /// 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 { } /// Runs the speech model over what [`prepare`] read. Needs no session, so it can run anywhere. -pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) -> Result, String> { +pub fn listen(heard: Heard, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result, String> { let bin = stt_bin()?; - check_model(model)?; + check_model(model, device)?; check_lang(lang)?; let fps = heard.fps; if job.cancelled() { @@ -810,7 +954,7 @@ pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) - std::fs::write(&wav, wav_bytes(&heard.samples)).map_err(|e| format!("writing {}: {e}", wav.display()))?; let guard = TempFile(wav.clone()); let hint = if fillers { FILLER_PROMPT } else { "" }; - let raw = run_stt(&bin, &wav, model, lang, hint, 0.0, &heard.label, job); + let raw = run_stt(&bin, &wav, model, device, lang, hint, 0.0, &heard.label, job); drop(guard); let mut words = Vec::new(); for seg in parse_raw(&raw?)? { diff --git a/crates/engine/tests/it/creator_tools.rs b/crates/engine/tests/it/creator_tools.rs index 5313102..4bac160 100644 --- a/crates/engine/tests/it/creator_tools.rs +++ b/crates/engine/tests/it/creator_tools.rs @@ -116,7 +116,7 @@ fn a_voiceover_refuses_empty_text_and_out_of_range_speed() { #[test] fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() { - if speech::available().is_err() { + if speech::available(speech::Device::Cpu).is_err() { eprintln!("skipped: edith-stt or its model is not installed"); return; } @@ -124,8 +124,8 @@ fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() { // words (or a silent mix), never crash or hang. let s = PlaybackSession::open(asset("test_av.mp4")).expect("open"); let job = speech::Job::default(); - let model = speech::installed_models()[0]; - match speech::transcribe(&s, speech::Hear::Mix, model, "en", false, &job) { + let model = speech::installed_models(speech::Device::Cpu)[0]; + match speech::transcribe(&s, speech::Hear::Mix, model, speech::Device::Cpu, "en", false, &job) { Ok(words) => assert!(words.len() < 20, "a tone is not a speech: {words:?}"), Err(e) => assert!(!e.is_empty()), } diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index 3878fef..9c1579a 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -360,12 +360,12 @@ PROJECT 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. 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. 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. - 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). + 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). 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. render_preview {clear:true} deletes every render file in the cache (refused while a render runs). project_status reports the open project. project_settings sets resolution, fps, tonemap, proxies, auto_proxies, encoder, the master limiter, the notes (free text, several lines, shown by project_status when set) and the still length - (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it). Each change and each refusal is reported. + (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. 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. 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). 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. diff --git a/crates/mcp/src/tools/listen.rs b/crates/mcp/src/tools/listen.rs index a65ee91..d8d81d9 100644 --- a/crates/mcp/src/tools/listen.rs +++ b/crates/mcp/src/tools/listen.rs @@ -19,7 +19,7 @@ use std::time::{Duration, UNIX_EPOCH}; use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Speed, SpeedRamp}; -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}; +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}; use engine::{AudioSession, Clip, PlaybackSession, subtitle}; use serde_json::{Value, json}; @@ -78,8 +78,8 @@ Silent and hallucinated windows are dropped by edith-stt before they reach this 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 \ 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 \ 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). \ -Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, or EDITH_STT_BIN) and the model under \ -~/.cache/edith/models/whisper-."; +Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, `--features vulkan` for the GPU, or EDITH_STT_BIN) and the model under \ +~/.cache/edith/models (whisper- for device cpu, ggml-.bin for gpu)."; const FIND_DOC: &str = "Find a phrase (case-insensitive, punctuation ignored) in the transcript of a target. Each match is numbered \ (#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 { json!({ "type": "string", "enum": MODELS, - "description": "Whisper model size. Default base, or the first installed of base, small, tiny; tiny is fastest and roughest." + "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." + }) +} + +fn device_prop() -> Value { + json!({ + "type": "string", + "enum": ["auto", "cpu", "gpu"], + "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." }) } @@ -147,6 +155,7 @@ fn transcript_schema() -> Value { "target": target_prop(), "range": range_prop(), "model": model_prop(), + "device": device_prop(), "language": language_prop(), "hint": hint_prop(), "words": {"type": "boolean", "description": "List the words of each segment too. Default false."}, @@ -164,6 +173,7 @@ fn find_schema() -> Value { "query": {"type": "string", "description": "The phrase to find, e.g. \"brown fox\"."}, "target": target_prop(), "model": model_prop(), + "device": device_prop(), "language": language_prop(), "hint": hint_prop(), "cut": { @@ -205,6 +215,7 @@ fn captions_schema() -> Value { "properties": { "target": target_prop(), "model": model_prop(), + "device": device_prop(), "language": language_prop(), "hint": hint_prop(), "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 { // ---- speech model ---------------------------------------------------------- -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."; +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."; /// A speech model download running in the background, and how it ended once it has. pub struct SpeechDownload { pub model: String, + pub device: Device, pub job: std::sync::Arc, pub handle: Option>>, pub outcome: Option, @@ -244,7 +256,8 @@ fn speech_model_schema() -> Value { "type": "object", "properties": { "download": {"type": "boolean", "description": "true starts downloading the model in the background."}, - "model": {"type": "string", "enum": ["tiny", "base", "small"], "description": "The model to download. Default base."}, + "model": {"type": "string", "enum": MODELS, "description": "The model to download. Default base."}, + "device": device_prop(), "cancel": {"type": "boolean", "description": "true stops the download running now."} }, "additionalProperties": false @@ -286,28 +299,41 @@ fn speech_model(srv: &mut Server, args: &Value) -> Reply { if !MODELS.contains(&model) { return Reply::err(format!("model `{model}` is not one of {}", MODELS.join(", "))); } - if engine::speech::installed_models().contains(&model) { - return Reply::ok(format!("the {model} speech model is already installed")); + let choice = match device_arg(args) { + Ok(c) => c.unwrap_or_else(|| project_choice(srv)), + Err(e) => return Reply::err(e), + }; + let device = download_device(choice); + if installed_models(device).contains(&model) { + return Reply::ok(format!("the {model} speech model ({}) is already installed", device.flag())); } - // The same call the GUI's Download model makes, on a thread of its own. let job = std::sync::Arc::new(engine::speech::Job::default()); let worker = job.clone(); let name = model.to_string(); let thread_name = name.clone(); - let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, &worker)); - srv.speech_download = Some(SpeechDownload { model: name, job, handle: Some(handle), outcome: None }); - return Reply::ok(format!("downloading the {model} speech model in the background; speech_model shows the progress")); - } - let installed = engine::speech::installed_models(); - let have = if installed.is_empty() { "none installed".to_string() } else { format!("installed: {}", installed.join(", ")) }; + let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, device, &worker)); + srv.speech_download = Some(SpeechDownload { model: name, device, job, handle: Some(handle), outcome: None }); + return Reply::ok(format!("downloading the {model} ({}) speech model in the background; speech_model shows the progress", device.flag())); + } + let cpu = installed_models(Device::Cpu); + let gpu = installed_models(Device::Gpu); + let list = |v: &[&str]| if v.is_empty() { "none".to_string() } else { v.join(", ") }; + let usable = gpu_available(); let state = match srv.speech_download.as_ref() { - Some(d) if running => format!("downloading {} {:.0}%", d.model, d.job.fraction() * 100.0), + Some(d) if running => format!("downloading {} ({}) {:.0}%", d.model, d.device.flag(), d.job.fraction() * 100.0), Some(d) => d.outcome.clone().unwrap_or_default(), None => "no download started".to_string(), }; - let text = format!("speech models: {have} (offered: {}); {state}", MODELS.join(", ")); + let text = format!( + "speech models: cpu: {}; gpu: {} (gpu {}); offered: {}; {state}", + list(&cpu), + list(&gpu), + if usable { "usable" } else { "not usable" }, + MODELS.join(", ") + ); Reply::ok(text).with(json!({ - "installed": installed, + "installed": {"cpu": cpu, "gpu": gpu}, + "gpu_available": usable, "offered": MODELS, "downloading": running, "progress": srv.speech_download.as_ref().filter(|_| running).map(|d| d.job.fraction()), @@ -659,20 +685,23 @@ fn fnv1a(bytes: &[u8]) -> u64 { /// The cache directory name of one source's transcription: file identity (path, mtime, length), /// the stream, and the model, language and prompt that heard it. `file` is (mtime in ns, length /// in bytes). The source range is not part of it: each range is an entry inside the directory. -fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, lang: &str, hint: &str) -> String { +fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> String { let (mtime_ns, len) = file; - let text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}"); + let mut text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}"); + if device == Device::Gpu { + text.push_str("|gpu"); + } format!("{:016x}", fnv1a(text.as_bytes())) } -fn source_key(path: &Path, stream: usize, model: &str, lang: &str, hint: &str) -> Option { +fn source_key(path: &Path, stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> Option { let meta = fs::metadata(path).ok()?; let mtime = meta .modified() .ok() .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) .map_or(0, |d| d.as_nanos()); - Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, lang, hint)) + Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, device, lang, hint)) } fn cache_dir() -> PathBuf { @@ -716,19 +745,40 @@ fn write_entry(dir: &Path, from: f64, to: f64, raw: &str) { } } -fn model_arg(args: &Value) -> Result { - match opt_str(args, "model") { - Some(m) => { - let m = m.trim().to_ascii_lowercase(); - check_model(&m)?; - Ok(m) - } - None => pick_model(|m| check_model(m).is_ok()) - .map(str::to_string) - .ok_or_else(|| "no whisper model is installed: install base (or small or tiny) under ~/.cache/edith/models".into()), +fn device_arg(args: &Value) -> Result, String> { + match opt_str(args, "device") { + None => Ok(None), + Some(d) => DeviceChoice::parse(d.trim()).map(Some).ok_or_else(|| format!("device `{d}` is not auto, cpu or gpu")), } } +/// The device a download fetches for when none is named: the GPU when edith-stt has one, else the CPU. +fn download_device(choice: DeviceChoice) -> Device { + match choice { + DeviceChoice::Auto if gpu_available() => Device::Gpu, + DeviceChoice::Auto | DeviceChoice::Cpu => Device::Cpu, + DeviceChoice::Gpu => Device::Gpu, + } +} + +fn project_choice(srv: &Server) -> DeviceChoice { + srv.session.as_ref().map_or(DeviceChoice::Auto, |s| s.speech_device()) +} + +/// The model and device a call runs on: the `model` and `device` args, else the project's +/// `speech_model` and `speech_device`, else the picked model and the auto device. +fn model_arg(args: &Value, s: &PlaybackSession) -> Result<(String, Device), String> { + let choice = device_arg(args)?.unwrap_or_else(|| s.speech_device()); + let named = match opt_str(args, "model") { + Some(m) => Some(m.trim().to_ascii_lowercase()), + None => s.speech_model().map(str::to_string), + }; + let (model, device) = plan(choice, named.as_deref()) + .ok_or_else(|| "no whisper model is installed for this device: install one with speech_model download".to_string())?; + check_model(&model, device)?; + Ok((model, device)) +} + /// `hint`: names and jargon as they should come out, handed to edith-stt as its prompt. fn hint_arg(args: &Value) -> Result { let h = opt_str(args, "hint").unwrap_or("").trim().to_string(); @@ -979,8 +1029,8 @@ impl Drop for TempFile { /// Runs edith-stt on one WAV (see [`engine::speech::run_stt`]); this server has no progress line /// and nobody to cancel it. -fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str) -> Result { - engine::speech::run_stt(bin, wav, model, lang, hint, offset, label, &engine::speech::Job::default()) +fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str) -> Result { + engine::speech::run_stt(bin, wav, model, device, lang, hint, offset, label, &engine::speech::Job::default()) } fn temp_path(tag: &str, ext: &str) -> PathBuf { @@ -1215,8 +1265,8 @@ fn review_text(segs: &[&Seg], fps: f64) -> String { /// Transcribes one piece, through the cache when it can: a cache entry for exactly this range /// serves it, and a new run is stored under that range. The output depends only on the piece. -fn run_piece(bin: &Path, p: &Piece, model: &str, lang: &str, hint: &str, fps: f64) -> Result, String> { - let known = if p.mix { None } else { source_key(&p.path, p.stream, model, lang, hint) }; +fn run_piece(bin: &Path, p: &Piece, model: &str, device: Device, lang: &str, hint: &str, fps: f64) -> Result, String> { + let known = if p.mix { None } else { source_key(&p.path, p.stream, model, device, lang, hint) }; let cached = |dir: &Path| read_exact(dir, p.from, p.to); if let Some(raw) = known.as_deref().and_then(|k| cached(&cache_dir().join(k))) { 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 } let key = known.unwrap_or_else(|| { let bytes = i16_bytes(&samples); - cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, lang, hint) + cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, device, lang, hint) }); let dir = cache_dir().join(&key); 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 let wav = TempFile(temp_path("stt", "wav")); // `wav` is removed when this function returns, on success and on every error path. fs::write(&wav.0, wav_bytes(&samples)).map_err(|e| temp_write_error(&wav.0, "writing", e))?; - let raw = run_stt(bin, &wav.0, model, lang, hint, p.from, &p.label)?; + let raw = run_stt(bin, &wav.0, model, device, lang, hint, p.from, &p.label)?; let segs = parse_raw(&raw)?.len(); write_entry(&dir, p.from, p.to, &raw); // 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> /// The transcript of source `n` in its own frames: what `transcribe` does for a source with no /// clip, whether or not the timeline plays it. +#[allow(clippy::too_many_arguments)] fn transcribe_source( s: &PlaybackSession, n: usize, range: Option<(u32, u32)>, model: &str, + device: Device, lang: &str, hint: &str, fps: f64, ) -> Result { let bin = stt_bin()?; - check_model(model)?; - let mut segs = source_segs(s, n, range, &bin, model, lang, hint, fps)?; + check_model(model, device)?; + let mut segs = source_segs(s, n, range, &bin, model, device, lang, hint, fps)?; segs.sort_by_key(|g| (g.start_f, g.end_f)); let mut segs = drop_overlap_repeats(segs); let corrections = correct_hints(&mut segs, hint); @@ -1337,10 +1389,10 @@ fn source_clips_note(n: usize, clips: &[(Lane, Clip)], fps: f64) -> String { format!("\nsrc:{n} times are the file's own clock; used by {}", used.join(", ")) } -fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, lang: &str, hint: &str) -> Result { +fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, device: Device, lang: &str, hint: &str) -> Result { let fps = parse::session_fps(s); let bin = stt_bin()?; - check_model(model)?; + check_model(model, device)?; let mut segs = Vec::new(); let mut gaps = Vec::new(); let pad = (WINDOW_SECS * fps).round() as u32; @@ -1360,7 +1412,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: map: Map::Mix, mix: true, }; - segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?); + segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?); // Audible sound the model returned no words for: reported, not hidden. if let Ok(Some(samples)) = decode_16k(&wav.0, 0, f64::from(lo) / fps, f64::from(hi) / fps) { gaps = coverage_gaps(&samples, lo, fps, &segs); @@ -1372,7 +1424,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: }; let clips = clips_of(s, want); if let (true, Some(n)) = (clips.is_empty(), source) { - segs.extend(source_segs(s, n, range, &bin, model, lang, hint, fps)?); + segs.extend(source_segs(s, n, range, &bin, model, device, lang, hint, fps)?); } for (lane, clip) in clips { let Some(src) = s.sources().get(clip.source) else { @@ -1396,7 +1448,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: map: Map::of(&clip), mix: false, }; - segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?); + segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?); } } segs.sort_by_key(|g| (g.start_f, g.end_f)); @@ -1424,6 +1476,7 @@ fn source_segs( range: Option<(u32, u32)>, bin: &Path, model: &str, + device: Device, lang: &str, hint: &str, fps: f64, @@ -1446,7 +1499,7 @@ fn source_segs( map: Map::Clip { start: 0, in_frame: 0, speed: Speed::NORMAL }, mix: false, }; - run_piece(bin, &piece, model, lang, hint, fps) + run_piece(bin, &piece, model, device, lang, hint, fps) } /// `mm:ss.mmm` for a timeline frame. @@ -1542,7 +1595,7 @@ fn transcript_run(srv: &Server, args: &Value) -> Result { }; let range = range_arg(args, fps, end)?; check_sources_online(s, &want)?; - let model = model_arg(args)?; + let (model, device) = model_arg(args, s)?; let lang = language_arg(args)?; let hint = with_fillers(&hint_arg(args)?, opt_bool(args, "fillers").unwrap_or(false)); 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 { _ => None, }; let t = match &want { - Want::Source(n) => transcribe_source(s, *n, range, &model, &lang, &hint, fps)?, - _ => transcribe(s, want, range, &model, &lang, &hint)?, + Want::Source(n) => transcribe_source(s, *n, range, &model, device, &lang, &hint, fps)?, + _ => transcribe(s, want, range, &model, device, &lang, &hint)?, }; let (body, shown, next) = page(&t, from, words); 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 { // gap beside a clip, which the ripple would close and shift the clip by. let clips = clip_intervals(s, &scope); check_sources_online(s, &want)?; - let model = model_arg(args)?; + let (model, device) = model_arg(args, s)?; let lang = language_arg(args)?; let fillers = is_filler_query(&qwords); let hint = with_fillers(&hint_arg(args)?, fillers); let label = want_label(s, &want); - let t = transcribe(s, want, None, &model, &lang, &hint)?; + let t = transcribe(s, want, None, &model, device, &lang, &hint)?; let mut flat: Vec<(&Seg, &Word)> = t.segs.iter().flat_map(|g| g.words.iter().map(move |w| (g, w))).collect(); flat.sort_by_key(|(_, w)| w.start_f); let norms: Vec = flat.iter().map(|(_, w)| norm(&w.w)).collect(); @@ -2826,12 +2879,12 @@ fn cue_names(cues: &[subtitle::Cue]) -> String { } fn captions_run(srv: &mut Server, args: &Value) -> Result { - let (fps, want, model, lang, hint, label, lane, max_chars, max_secs, out, speakers) = { + let (fps, want, model, device, lang, hint, label, lane, max_chars, max_secs, out, speakers) = { let s = session(srv)?; let fps = parse::session_fps(s); let want = want_arg(s, args)?; check_sources_online(s, &want)?; - let model = model_arg(args)?; + let (model, device) = model_arg(args, s)?; let lang = language_arg(args)?; let hint = hint_arg(args)?; let label = want_label(s, &want); @@ -2866,11 +2919,11 @@ fn captions_run(srv: &mut Server, args: &Value) -> Result { None => free_caption_path(s, std::env::temp_dir().join(format!("edith-captions-{}.srt", std::process::id()))), }, }; - (fps, want, model, lang, hint, label, lane_name, max_chars, max_secs, out, speakers) + (fps, want, model, device, lang, hint, label, lane_name, max_chars, max_secs, out, speakers) }; let is_mix = matches!(want, Want::Mix); let replace = opt_bool(args, "replace").unwrap_or(false); - let t = transcribe(session(srv)?, want.clone(), None, &model, &lang, &hint)?; + let t = transcribe(session(srv)?, want.clone(), None, &model, device, &lang, &hint)?; let s = session(srv)?; // Captions carry the words people say: disfluencies are left out, even when the // transcript kept them (a hint or the default model can still hear an "um"). @@ -3640,20 +3693,20 @@ mod tests { #[test] fn cache_key_follows_every_input() { - let base = cache_key("/a.mp4", (7, 100), 0, "small", "auto", ""); - assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", "")); - assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", "auto", "")); - assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", "auto", "")); - assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", "auto", "")); - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", "auto", "")); - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "en", "")); - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", "Edith, LUFS")); + let base = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", ""); + assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "")); + assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", Device::Cpu, "auto", "")); + assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", Device::Cpu, "auto", "")); + assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", Device::Cpu, "auto", "")); + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", Device::Cpu, "auto", "")); + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "en", "")); + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "Edith, LUFS")); assert_eq!(base.len(), 16); } #[test] fn cache_key_is_versioned_so_older_results_are_not_reused() { - let k = cache_key("/a.mp4", (7, 100), 0, "small", "auto", ""); + let k = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", ""); let v5 = format!("{:016x}", fnv1a(b"v5|/a.mp4|7|100|0|small|auto|")); assert_ne!(k, v5); assert_eq!(CACHE_VERSION, 9); @@ -4001,7 +4054,7 @@ mod tests { eprintln!("skipping speech_round_trip: {e}"); return; } - if check_model("tiny").is_err() { + if check_model("tiny", Device::Cpu).is_err() { eprintln!("skipping speech_round_trip: the tiny model is not installed"); return; } @@ -4099,7 +4152,7 @@ mod tests { #[test] fn find_cut_removes_the_matched_word_and_undo_restores_it() { - if stt_bin().is_err() || check_model("tiny").is_err() { + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { eprintln!("skipping find_cut_removes_the_matched_word_and_undo_restores_it: edith-stt or the tiny model is missing"); return; } @@ -4282,7 +4335,7 @@ mod tests { /// left in place. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing. #[test] fn find_cut_with_which_names_the_kept_match_and_the_lane_left_in_place() { - if stt_bin().is_err() || check_model("tiny").is_err() { + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { eprintln!("skipping find_cut_with_which_names_the_kept_match: edith-stt or the tiny model is missing"); return; } @@ -4357,7 +4410,7 @@ mod tests { /// silence. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing. #[test] fn unplaced_source_is_heard_as_its_own_file() { - if stt_bin().is_err() || check_model("tiny").is_err() { + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { eprintln!("skipping unplaced_source_is_heard_as_its_own_file: edith-stt or the tiny model is missing"); return; } @@ -4585,10 +4638,10 @@ mod tests { #[test] fn default_model_is_base_then_small_then_tiny() { - assert_eq!(pick_model(|_| true), Some("base")); - assert_eq!(pick_model(|m| m != "base"), Some("small")); - assert_eq!(pick_model(|m| m == "tiny"), Some("tiny")); - assert_eq!(pick_model(|_| false), None); + assert_eq!(engine::speech::pick_model(|_| true, Device::Cpu), Some("base")); + assert_eq!(engine::speech::pick_model(|m| m != "base", Device::Cpu), Some("small")); + assert_eq!(engine::speech::pick_model(|m| m == "tiny", Device::Cpu), Some("tiny")); + assert_eq!(engine::speech::pick_model(|_| false, Device::Cpu), None); } #[test] diff --git a/crates/mcp/src/tools/project.rs b/crates/mcp/src/tools/project.rs index 782ca81..3b8e1dd 100644 --- a/crates/mcp/src/tools/project.rs +++ b/crates/mcp/src/tools/project.rs @@ -12,6 +12,7 @@ use std::time::{Duration, SystemTime}; use engine::limiter::Limiter; use engine::project::{Lane, LaneKind, Rate, STILL_MAX_SECS, STILL_MIN_SECS}; +use engine::speech::{DeviceChoice, MODELS}; use engine::tonemap::Preset; use engine::export::EncoderSeat; use engine::PlaybackSession; @@ -160,6 +161,8 @@ pub fn tools() -> Vec { "tonemap": {"type": "string", "enum": ["reference", "standard", "vivid"], "description": "HDR to SDR rendition."}, "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."}, "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."}, + "speech_model": {"type": "string", "enum": MODELS.iter().copied().chain(["auto"]).collect::>(), "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."}, + "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."}, "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]}, "proxies": {"type": "boolean", "description": "Play and edit through proxy files."}, "auto_proxies": {"type": "boolean", "description": "Make proxies automatically for heavy sources."}, @@ -2294,11 +2297,12 @@ fn status_reply(server: &Server) -> Reply { false => format!("\nnotes: {}", s.notes()), }; let render_text = crate::tools::render::status_line(server).map_or_else(String::new, |l| format!("\n{l}")); + let speech_text = format!("{} on {}", s.speech_model().unwrap_or("auto"), s.speech_device().as_str()); let text = format!( "{path} · {state} · {w}x{h} @{} · {} ({end}f) · undo {undo} · redo {redo} · {running} export job(s) running\n\ lanes: {lane_text}{ducks_text}{voice_text}\n\ {recent_text}sources: {} {}{looks_text}\n\ - 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}", + 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}", fmt_fps(fps), parse::clock(end, fps), sources.len(), @@ -2347,6 +2351,8 @@ fn status_reply(server: &Server) -> Reply { "limiter": {"on": limiter.on, "ceiling_db": limiter.ceiling_db}, "sample_rate": s.sample_rate(), "still_secs": s.still_secs(), + "speech_model": s.speech_model(), + "speech_device": s.speech_device().as_str(), "notes": s.notes(), } }); @@ -2506,6 +2512,45 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { } } + if let Some(raw) = opt_str(args, "speech_model") { + asked += 1; + let v = raw.trim().to_ascii_lowercase(); + if v != "auto" && !MODELS.contains(&v.as_str()) { + refused += 1; + lines.push(format!("speech_model {raw}: refused; use one of {}, or auto", MODELS.join(", "))); + } else { + let cur = s.speech_model().unwrap_or("auto").to_string(); + let want = (v != "auto").then_some(v.as_str()); + if s.set_speech_model(want) { + changed += 1; + named.push(format!("speech_model {cur}→{v}")); + lines.push(format!("speech model {cur} -> {v}")); + } else { + lines.push(format!("speech model already {cur}")); + } + } + } + + if let Some(raw) = opt_str(args, "speech_device") { + asked += 1; + match DeviceChoice::parse(raw.trim()) { + Some(d) => { + let cur = s.speech_device(); + if s.set_speech_device(d) { + changed += 1; + named.push(format!("speech_device {}→{}", cur.as_str(), d.as_str())); + lines.push(format!("speech device {} -> {}", cur.as_str(), d.as_str())); + } else { + lines.push(format!("speech device already {}", d.as_str())); + } + } + None => { + refused += 1; + lines.push(format!("speech_device {raw}: refused; use auto, cpu or gpu")); + } + } + } + if let Some(v) = args.get("still_secs") { asked += 1; match v.as_f64() { @@ -2668,7 +2713,7 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { if asked == 0 { return Reply::err( - "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, proxies, auto_proxies, encoder, limiter, captions", + "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, proxies, auto_proxies, encoder, limiter, captions", ); } let mut out = Map::new(); diff --git a/tools/edith-stt/Cargo.lock b/tools/edith-stt/Cargo.lock index c527e1e..f628238 100644 --- a/tools/edith-stt/Cargo.lock +++ b/tools/edith-stt/Cargo.lock @@ -61,6 +61,26 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -185,7 +205,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", ] [[package]] @@ -194,6 +223,26 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "compact_str" version = "0.9.1" @@ -364,6 +413,7 @@ dependencies = [ "serde_json", "tracing", "ureq", + "whisper-rs", ] [[package]] @@ -473,6 +523,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "gemm" version = "0.19.0" @@ -626,6 +682,12 @@ dependencies = [ "r-efi 6.0.0", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "half" version = "2.7.1" @@ -798,6 +860,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -819,6 +890,16 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -1029,6 +1110,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1147,7 +1238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" dependencies = [ "either", - "itertools", + "itertools 0.14.0", "rayon", ] @@ -1210,6 +1301,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" version = "1.1.5" @@ -1292,6 +1389,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "seq-macro" version = "0.3.6" @@ -1350,6 +1453,12 @@ dependencies = [ "serde", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -1527,7 +1636,7 @@ dependencies = [ "derive_builder", "esaxx-rs", "getrandom 0.3.4", - "itertools", + "itertools 0.14.0", "log", "macro_rules_attribute", "monostate", @@ -1699,6 +1808,29 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "whisper-rs" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2088172d00f936c348d6a72f488dc2660ab3f507263a195df308a3c2383229f6" +dependencies = [ + "libc", + "whisper-rs-sys", +] + +[[package]] +name = "whisper-rs-sys" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6986c0fe081241d391f09b9a071fbcbb59720c3563628c3c829057cf69f2a56f" +dependencies = [ + "bindgen", + "cfg-if", + "cmake", + "fs_extra", + "semver", +] + [[package]] name = "winapi-util" version = "0.1.11" diff --git a/tools/edith-stt/Cargo.toml b/tools/edith-stt/Cargo.toml index 21f0de0..ce7329e 100644 --- a/tools/edith-stt/Cargo.toml +++ b/tools/edith-stt/Cargo.toml @@ -18,6 +18,11 @@ hound = "3.5" tracing = "0.1" serde_json = "1" ureq = { version = "2", default-features = false, features = ["tls"] } +whisper-rs = { version = "0.16.0", optional = true, features = ["vulkan"] } + +[features] +default = [] +vulkan = ["dep:whisper-rs"] [workspace] diff --git a/tools/edith-stt/src/gpu.rs b/tools/edith-stt/src/gpu.rs new file mode 100644 index 0000000..a1f931b --- /dev/null +++ b/tools/edith-stt/src/gpu.rs @@ -0,0 +1,301 @@ +#![forbid(unsafe_code)] + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{bail, Context, Result}; +use serde_json::json; +use whisper_rs::vulkan::list_devices; +use whisper_rs::{ + DtwMode, DtwModelPreset, DtwParameters, FullParams, SamplingStrategy, WhisperContext, + WhisperContextParameters, WhisperSegment, +}; + +use crate::{ + fit_words_to_audio, levels, r3, read_wav_16k_mono, silence_reason, span_rel_db, starts_past_end, + Cli, MAX_COMPRESSION_RATIO, MIN_AVG_LOGPROB, NO_SPEECH_PROB, SR, +}; + +const GPU_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; + +pub fn probe() -> Result<()> { + if list_devices().is_empty() { + bail!("no Vulkan device found"); + } + Ok(()) +} + +pub fn run(cli: &Cli) -> Result<()> { + let device = list_devices() + .into_iter() + .next() + .context("no Vulkan device found")?; + let (model, preset) = resolve_model(&cli.model)?; + let dtw = if cli.align { preset } else { None }; + + let mut cp = WhisperContextParameters::new(); + cp.use_gpu(true); + if let Some(model_preset) = dtw.clone() { + cp.dtw_parameters(DtwParameters { + mode: DtwMode::ModelPreset { model_preset }, + ..Default::default() + }); + } + let t_start = Instant::now(); + let ctx = WhisperContext::new_with_params(&model, cp) + .with_context(|| format!("failed to load whisper model {}", model.display()))?; + eprintln!( + "model loaded from {} on {} in {:.2}s", + model.display(), + device.name, + t_start.elapsed().as_secs_f64() + ); + + let pcm = read_wav_16k_mono(&cli.input)?; + let audio_s = pcm.len() as f64 / SR as f64; + let lv = levels(&pcm); + let eot = ctx.token_eot(); + + let language = if cli.language.eq_ignore_ascii_case("auto") { + None + } else { + Some(cli.language.to_ascii_lowercase()) + }; + let prompt = cli.prompt.as_deref().map(str::trim).filter(|t| !t.is_empty()); + let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); + + let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 }); + params.set_language(language.as_deref()); + params.set_translate(false); + params.set_no_context(true); + params.set_token_timestamps(dtw.is_some()); + params.set_temperature(0.0); + params.set_temperature_inc(0.2); + params.set_logprob_thold(MIN_AVG_LOGPROB as f32); + params.set_entropy_thold(MAX_COMPRESSION_RATIO as f32); + params.set_no_speech_thold(NO_SPEECH_PROB as f32); + if let Some(p) = prompt { + params.set_initial_prompt(p); + } + params.set_print_special(false); + params.set_print_progress(false); + params.set_print_realtime(false); + params.set_print_timestamps(false); + params.set_n_threads(threads as i32); + params.set_progress_callback_safe(|p: i32| eprintln!("progress {:.4}", p as f64 / 100.0)); + + let mut state = ctx.create_state().context("failed to create whisper state")?; + let t_decode = Instant::now(); + state.full(params, &pcm).context("whisper inference failed")?; + + let offset = cli.offset; + let mut n_segs = 0usize; + for seg in state.as_iter() { + let t0 = seg.start_timestamp() as f64 / 100.0; + let t1 = (seg.end_timestamp() as f64 / 100.0).min(audio_s).max(t0); + if starts_past_end(t0, audio_s) { + eprintln!("dropped segment at {:.2}s: starts at or past the audio end", t0 + offset); + continue; + } + let toks = text_tokens(&seg, eot)?; + let text = String::from_utf8_lossy(&toks.iter().flat_map(|t| t.bytes.iter().copied()).collect::>()) + .trim() + .to_string(); + if text.is_empty() { + continue; + } + let avg = toks.iter().map(|t| t.plog).sum::() / toks.len() as f64; + let no_speech = seg.no_speech_probability() as f64; + let span = span_rel_db(&lv, t0, t1); + if let Some(reason) = silence_reason(no_speech, avg, span) { + if !cli.keep_all { + eprintln!( + "skipped segment {:.2}-{:.2}s ({reason}, no_speech {no_speech:.2}, avg_logprob {avg:.2}): {text:?}", + t0 + offset, + t1 + offset + ); + continue; + } + } + + let groups = word_groups(&toks); + let use_dtw = dtw.is_some() && groups.iter().any(|g| g.start > 0.0); + let mut words = if use_dtw { + dtw_words(&groups, t0, t1, offset) + } else { + proportional_words(&groups, t0, t1, offset) + }; + + let n_words = words.len(); + let cut = fit_words_to_audio(&mut words, offset, audio_s); + if n_words > 0 && words.is_empty() { + eprintln!("dropped segment at {:.2}s: every word starts at or past the audio end: {text:?}", t0 + offset); + continue; + } + let text = if cut > 0 { + eprintln!("cut {cut} word(s) at {:.2}s that start at or past the audio end", t0 + offset); + words.iter().filter_map(|w| w["w"].as_str()).collect::>().join(" ") + } else { + text + }; + let (start, end) = match (words.first(), words.last()) { + (Some(f), Some(l)) => ( + f["start"].as_f64().unwrap_or(t0 + offset), + l["end"].as_f64().unwrap_or(t1 + offset), + ), + _ => (t0 + offset, t1 + offset), + }; + let line = json!({ + "start": r3(start), + "end": r3(end), + "text": text, + "words": words, + "approx": !use_dtw, + "no_speech": r3(no_speech), + "avg_logprob": r3(avg), + "span_db": span.map(r3), + }); + println!("{line}"); + n_segs += 1; + } + std::io::stdout().flush()?; + + let elapsed = t_decode.elapsed().as_secs_f64(); + eprintln!( + "done: {n_segs} segments, audio {audio_s:.2}s, decode {elapsed:.2}s, RTF {:.3}", + elapsed / audio_s.max(1e-9) + ); + Ok(()) +} + +fn resolve_model(arg: &str) -> Result<(PathBuf, Option)> { + let (path, name) = if arg.ends_with(".bin") || Path::new(arg).is_file() { + let path = PathBuf::from(arg); + let name = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or_default() + .trim_start_matches("ggml-") + .to_string(); + (path, name) + } else { + if !GPU_SIZES.contains(&arg) { + bail!("model '{arg}' is neither a .bin path nor one of {GPU_SIZES:?}"); + } + let home = std::env::var("HOME").context("HOME not set")?; + let path = PathBuf::from(home) + .join(".cache/edith/models") + .join(format!("ggml-{arg}.bin")); + (path, arg.to_string()) + }; + if !path.is_file() { + bail!("GPU model file not found: {} (--device gpu does not download models)", path.display()); + } + Ok((path, preset(&name))) +} + +fn preset(name: &str) -> Option { + Some(match name { + "tiny" => DtwModelPreset::Tiny, + "base" => DtwModelPreset::Base, + "small" => DtwModelPreset::Small, + "medium" => DtwModelPreset::Medium, + "large-v3" => DtwModelPreset::LargeV3, + "large-v3-turbo" => DtwModelPreset::LargeV3Turbo, + _ => return None, + }) +} + +struct Tok { + bytes: Vec, + plog: f64, + dtw: f64, +} + +fn text_tokens(seg: &WhisperSegment<'_>, eot: i32) -> Result> { + let mut out = Vec::new(); + for i in 0..seg.n_tokens() { + let Some(tok) = seg.get_token(i) else { + continue; + }; + if tok.token_id() >= eot { + continue; + } + let bytes = tok.to_bytes().context("failed to read token text")?.to_vec(); + if bytes.is_empty() { + continue; + } + let data = tok.token_data(); + out.push(Tok { bytes, plog: data.plog as f64, dtw: data.t_dtw as f64 / 100.0 }); + } + Ok(out) +} + +struct Group { + text: String, + p: f64, + start: f64, +} + +fn word_groups(toks: &[Tok]) -> Vec { + let mut words: Vec<(Vec, Vec, f64)> = Vec::new(); + for t in toks { + if words.is_empty() || t.bytes[0] == b' ' { + words.push((Vec::new(), Vec::new(), t.dtw)); + } + if let Some(w) = words.last_mut() { + w.0.extend_from_slice(&t.bytes); + w.1.push(t.plog); + } + } + words + .into_iter() + .filter_map(|(bytes, plogs, start)| { + let text = String::from_utf8_lossy(&bytes).trim().to_string(); + if text.is_empty() { + return None; + } + let p = (plogs.iter().sum::() / plogs.len().max(1) as f64).exp(); + Some(Group { text, p, start }) + }) + .collect() +} + +fn word_json(text: &str, start: f64, end: f64, p: f64, offset: f64) -> serde_json::Value { + json!({"w": text, "start": r3(start + offset), "end": r3(end + offset), "p": r3(p)}) +} + +fn dtw_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec { + let hi = t1.max(t0); + let mut starts: Vec = Vec::with_capacity(groups.len()); + for g in groups { + let s = if g.start > 0.0 { g.start } else { t0 }; + let prev = starts.last().copied().unwrap_or(t0); + starts.push(s.clamp(t0, hi).max(prev)); + } + groups + .iter() + .enumerate() + .map(|(i, g)| { + let start = starts[i]; + let end = starts.get(i + 1).copied().unwrap_or(hi).clamp(start, hi); + word_json(&g.text, start, end, g.p, offset) + }) + .collect() +} + +fn proportional_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec { + let total: usize = groups.iter().map(|g| g.text.chars().count()).sum(); + let span = (t1 - t0).max(0.0); + let mut t = t0; + groups + .iter() + .map(|g| { + let dur = if total > 0 { span * g.text.chars().count() as f64 / total as f64 } else { 0.0 }; + let (start, end) = (t, t + dur); + t = end; + word_json(&g.text, start, end, g.p, offset) + }) + .collect() +} diff --git a/tools/edith-stt/src/main.rs b/tools/edith-stt/src/main.rs index f30d546..b2de7f0 100644 --- a/tools/edith-stt/src/main.rs +++ b/tools/edith-stt/src/main.rs @@ -1,6 +1,7 @@ //! edith-stt: offline Whisper speech-to-text on CPU (candle), JSON-lines output. //! -//! usage: edith-stt --model base|small|tiny| [--language en|auto] [--offset SECS] [--no-align] [--keep-all] +//! usage: edith-stt --model base|small|tiny| [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] +//! edith-stt --has-gpu //! //! stdout: one JSON object per segment //! {"start":s,"end":s,"text":"...","words":[{"w":"Hello","start":s,"end":s,"p":prob}],"approx":false, @@ -15,6 +16,23 @@ //! stderr: progress lines `progress <0..1>` and diagnostics. mod whisper_model; +#[cfg(feature = "vulkan")] +mod gpu; +#[cfg(not(feature = "vulkan"))] +mod gpu { + use crate::Cli; + use anyhow::{bail, Result}; + + const NO_VULKAN: &str = "edith-stt was built without vulkan; rebuild with --features vulkan"; + + pub fn probe() -> Result<()> { + bail!(NO_VULKAN) + } + + pub fn run(_: &Cli) -> Result<()> { + bail!(NO_VULKAN) + } +} use anyhow::{anyhow, bail, Context, Result}; use candle_core::{DType, Device, IndexOp, Tensor}; @@ -54,7 +72,7 @@ const MAX_PREV_TOKENS: usize = 223; /// Silence filter thresholds (see `silence_reason`). const NO_SPEECH_PROB: f64 = 0.6; const NO_SPEECH_LOGPROB: f64 = -1.0; -const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3"]; +const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"]; const REQUIRED: &[&str] = &[ "config.json", "model.safetensors", @@ -81,11 +99,13 @@ struct Cli { /// `--prompt`: text Whisper sees before the audio, as OpenAI's `initial_prompt`. Names and /// jargon spelled the way they should come out ("Edith, LUFS") steer the decoder. prompt: Option, + gpu: bool, + has_gpu: bool, input: PathBuf, } fn usage() -> &'static str { - "usage: edith-stt --model base|small|tiny| [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] " + "usage: edith-stt --model base|small|tiny|| [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] \n edith-stt --has-gpu" } fn parse_cli() -> Result { @@ -95,11 +115,21 @@ fn parse_cli() -> Result { let mut align = true; let mut keep_all = false; let mut prompt: Option = None; + let mut gpu = false; + let mut has_gpu = false; let mut input: Option = None; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match a.as_str() { "--model" => model = args.next().context("--model needs a value")?, + "--device" => { + gpu = match args.next().context("--device needs a value")?.as_str() { + "cpu" => false, + "gpu" => true, + other => bail!("--device must be cpu or gpu, got {other}"), + } + } + "--has-gpu" => has_gpu = true, "--language" => language = args.next().context("--language needs a value")?, "--offset" => { offset = args @@ -124,12 +154,22 @@ fn parse_cli() -> Result { } } } - let input = input.with_context(|| usage().to_string())?; - Ok(Cli { model, language, offset, align, keep_all, prompt, input }) + let input = match (has_gpu, input) { + (true, Some(_)) => bail!("--has-gpu takes no input file\n{}", usage()), + (true, None) => PathBuf::new(), + (false, input) => input.with_context(|| usage().to_string())?, + }; + Ok(Cli { model, language, offset, align, keep_all, prompt, gpu, has_gpu, input }) } fn run() -> Result<()> { let cli = parse_cli()?; + if cli.has_gpu { + return gpu::probe(); + } + if cli.gpu { + return gpu::run(&cli); + } let dir = resolve_model(&cli.model)?; let t_start = Instant::now();