✨ Speech runs on the GPU too: edith-stt gains a Vulkan whisper.cpp backend (--features vulkan), medium and large-v3(-turbo) join the models, and the model and device are a project setting with a picker, project_settings and a per-call device
Browse files at this commitbcb4dc5db29b96be7e6ace4ff2f41d65016df705Parent: ef0571724 changed files +1171 -240
- MCP.md +5 -5
- crates/app/src/creator.rs +0 -12
- crates/app/src/menus.rs +4 -0
- crates/app/src/player/cards.rs +33 -0
- crates/app/src/player/tools.rs +8 -13
- crates/app/src/player/transcript.rs +35 -6
- crates/app/src/tests/caps.rs +1 -2
- crates/app/src/tests/creator.rs +3 -5
- crates/app/src/ui/cards/tools.rs +5 -11
- crates/app/src/ui/overlays.rs +2 -0
- crates/app/src/ui/settings_stance.rs +69 -6
- crates/app/src/ui/transcript_panel.rs +13 -6
- crates/engine/src/edith.rs +44 -12
- crates/engine/src/playback.rs +26 -2
- crates/engine/src/project.rs +43 -0
- crates/engine/src/speech.rs +217 -73
- crates/engine/tests/it/creator_tools.rs +3 -3
- crates/mcp/src/help.rs +2 -2
- crates/mcp/src/tools/listen.rs +125 -72
- crates/mcp/src/tools/project.rs +47 -2
- tools/edith-stt/Cargo.lock +135 -3
- tools/edith-stt/Cargo.toml +5 -0
- tools/edith-stt/src/gpu.rs +301 -0
- tools/edith-stt/src/main.rs +45 -5
MCP.mdmodified+5 -5
| @@ -229,7 +229,7 @@ in **bold**; optional ones follow the name. | ||
| 229 | 229 | | `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 | |
| 230 | 230 | | `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 | |
| 231 | 231 | | `project_status` | history (false) | path, saved or dirty, canvas size, fps, duration, lanes with clip counts, sources, the colour looks (a `looks:` line naming the built-in looks and the saved ones, the names the `look` op takes; `structuredContent` has them as `looks.builtin` and `looks.saved`), undo and redo depth, running exports, settings (and the notes, when there are any); an `OFFLINE: src:N <path>` line per offline source, and the fixes an open made to load (dirty until saved). `history: true` also lists every undo step and every redo step, newest first, each with the `steps` count that `undo` or `redo` needs to reach it (`undo {steps: 3}` takes back the three newest) | |
| 232 | -| `project_settings` | resolution, fps, tonemap, notes, still_secs, sample_rate, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. `sample_rate` is the sound mix's rate: `"source"` (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), `44100`, `48000` or `96000`, the same rows the GUI offers. Each is one undo step | | |
| 232 | +| `project_settings` | resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, sample_rate, proxies, auto_proxies, encoder, limiter, captions | the `ProjectSettings` knobs. `speech_model` is the Whisper model the listen tools run on (`auto` picks the first installed); `speech_device` is `auto`, `cpu` or `gpu` (auto is gpu when edith-stt has a usable GPU and that model is installed, else cpu). Both are saved with the project as format v57, and each call's `device` and `model` args override them. An fps change keeps clips, captions and titles at the same seconds; their frame numbers and addresses change. `notes` is free text (several lines; `""` clears it), saved with the project as format v52; `still_secs` is how long a still is placed for, 0.5 to 600 s, 5 s by default, and only stills placed after the change take it. `sample_rate` is the sound mix's rate: `"source"` (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), `44100`, `48000` or `96000`, the same rows the GUI offers. Each is one undo step | | |
| 233 | 233 | | `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 | |
| 234 | 234 | | `checkpoint` | **name** | save the whole project under a name (letters, digits, `-`, `_`), as a copy in `<project dir>/checkpoints/<stem>/` (the project's path, from `project_new {path}` or `project_save`; with no path at all, the temp dir, lost on reboot) | |
| 235 | 235 | | `restore` | **name** | replace the open project with a checkpoint, from this run or an earlier one; first saves the open project as `before-restore-<name>` (a suffix when that name is taken), so the state before the restore stays on disk; the project is dirty afterwards and its undo and redo history is cleared | |
| @@ -378,9 +378,9 @@ only when asked for (the first call that needs it says so and stops if it is abs | ||
| 378 | 378 | |
| 379 | 379 | | tool | args | does | |
| 380 | 380 | |---|---|---| |
| 381 | -| `transcript` | target, from, language, model=base\|tiny\|small, range, words, hint, fillers | what is said, as timeline frames; segment lines, or word times with `words:true`. Segment times are reliable; word times are DTW-aligned, and a segment whose words were only spread evenly is `approx:true` | | |
| 382 | -| `find_words` | **query**, target, language, model, hint, cut, keep (first\|last), which, pad, dry_run, lanes | a phrase, case-insensitive, punctuation ignored; returns the matching spans to cut or caption. `keep` with `cut` keeps one word of a repeat (`"I I"`). `cut` lanes default to the target's lane and its linked lanes (every lane for a mix or src target). Filler spellings (uh, um, and their variants) and hallucinated "Thank you"-type segments are handled. `cut:"lift"` removes the matches without ripple: a hole is left where each was and no other lane moves (use it on one speaker's lane, so the other speaker stays in step). With `cut`, each edge snaps to the quietest 10 ms within ±150 ms of Whisper's time (a pause, not a word's sound), never closer than 30 ms to the kept word on its side; `snap:false` cuts at Whisper's times. A match in an `approx:true` segment is a hint: pad it or check it with `frame` | | |
| 383 | -| `auto_captions` | target (default lane A1), lane (default S1), language, model, max_chars, max_secs, path, speakers, hint, replace | transcribes, cuts cues at pauses, sentence ends and the length limits, writes `<stem>.captions.srt` (`-2`, `-3` … when that name is taken; a temp file if the project is untitled), imports it as a subtitle track and places it on the caption lane at frame 0. One undo step. A re-run writes a new file and keeps the old one, so undo can bring the old track back. A lane that already holds captions takes the new run merged in, as one track in time order; a re-run on the same lane replaces the captions that lane made before. `replace:true` also removes overlapping captions that differ from what was heard now (hand edits included); undo brings them back. `speakers` (mix target) sets which audio lanes split the cues. `hint` also corrects near-miss spellings of its words after transcription, and the reply names each correction (`hint corrected: …`). An explicit `path` that a track already holds is refused | | |
| 381 | +| `transcript` | target, from, language, model=base (tiny, small, medium, large-v3, large-v3-turbo), device=auto\|cpu\|gpu, range, words, hint, fillers | what is said, as timeline frames; segment lines, or word times with `words:true`. Segment times are reliable; word times are DTW-aligned, and a segment whose words were only spread evenly is `approx:true` | | |
| 382 | +| `find_words` | **query**, target, language, model, device, hint, cut, keep (first\|last), which, pad, dry_run, lanes | a phrase, case-insensitive, punctuation ignored; returns the matching spans to cut or caption. `keep` with `cut` keeps one word of a repeat (`"I I"`). `cut` lanes default to the target's lane and its linked lanes (every lane for a mix or src target). Filler spellings (uh, um, and their variants) and hallucinated "Thank you"-type segments are handled. `cut:"lift"` removes the matches without ripple: a hole is left where each was and no other lane moves (use it on one speaker's lane, so the other speaker stays in step). With `cut`, each edge snaps to the quietest 10 ms within ±150 ms of Whisper's time (a pause, not a word's sound), never closer than 30 ms to the kept word on its side; `snap:false` cuts at Whisper's times. A match in an `approx:true` segment is a hint: pad it or check it with `frame` | | |
| 383 | +| `auto_captions` | target (default lane A1), lane (default S1), language, model, device, max_chars, max_secs, path, speakers, hint, replace | transcribes, cuts cues at pauses, sentence ends and the length limits, writes `<stem>.captions.srt` (`-2`, `-3` … when that name is taken; a temp file if the project is untitled), imports it as a subtitle track and places it on the caption lane at frame 0. One undo step. A re-run writes a new file and keeps the old one, so undo can bring the old track back. A lane that already holds captions takes the new run merged in, as one track in time order; a re-run on the same lane replaces the captions that lane made before. `replace:true` also removes overlapping captions that differ from what was heard now (hand edits included); undo brings them back. `speakers` (mix target) sets which audio lanes split the cues. `hint` also corrects near-miss spellings of its words after transcription, and the reply names each correction (`hint corrected: …`). An explicit `path` that a track already holds is refused | | |
| 384 | 384 | | `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 | |
| 385 | 385 | | `voiceover` | **text**, voice, speed=1, pause=0, name, place | speaks `text` into `<project>/voiceover/<name or slug>-<hash8>.wav` and imports it as a source (`src:N`), reporting its duration. Needs a project path (`project_new` or `project_open`): the WAV goes beside the `.edith` file even before `project_save`, and the reply says the source is unsaved until then. Renders are cached by (text, voice, speed, pause, model) in `voiceover/.renders/`: the same text with another `name` reuses the render and only copies it. Piper's duration noise is pinned off, so one text always renders to one length (the waveform keeps piper's usual small variation). `place {lane, at}` places it on a lane as one undo step; the lane must be an existing audio lane, and both are checked before anything is rendered. Text is capped at 5000 characters; `speed` 0.5–2; `pause` is seconds of silence after each sentence (max 10) | |
| 386 | 386 | | `record` | **action** (start\|stop\|status), lane, at=playhead, source | records a voice-over from the audio input into `<project stem>_media/voiceover-<n>.wav` beside the project (16-bit stereo WAV, 48 kHz; the folder `project_collect` uses). `start` begins a take at `at` (default the playhead) and needs a project path; `lane` is the audio lane it lands on, or a new one. `stop` ends the take, imports it as `src:N` and places it at the start point as one undo step. `status` reports the clock and the level in dBFS while recording, and the input list (`source` names, monitors marked) when idle. This is the microphone; `voiceover` is text-to-speech (Piper) and never records. Only one take runs at a time | |
| @@ -410,7 +410,7 @@ Piper's stderr is reported on failure. | ||
| 410 | 410 | | `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 | |
| 411 | 411 | | `export_captions` | format (`srt` or `vtt`, required unless chapters), path, overwrite, chapters | writes the timeline's captions (every cue on the subtitle lanes, in start order) as SRT or WebVTT; picture and empty cues are left out. Without `path`: `<first source> edit.<format>` in the Videos folder. Refuses an existing file unless `overwrite` is true, and writes nothing when there are no captions. `chapters: true` writes nothing and returns the chapter markers as the YouTube description listing (`00:00 Intro`, one line each), the text File > Copy chapters copies, as the reply text and as JSON (`chapters` lines, `text`, `warnings`) | |
| 412 | 412 | | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:<n>`, a list or `"all"`) | the editing copies (proxies) of sources. `status` shows each source's state (ready, making with its percent, off, not needed for a sound or still, or why a stand-in failed). `make` starts one in the background and turns that film's switch back on; a film that plays at speed on this machine needs none, and says so. `cancel` stops one being made and leaves the film off, as the Proxies switch on a library row does. `delete` removes the stand-in and keeps the film off. With `auto_proxies` on, each `media_import` starts its stand-ins the same way | |
| 413 | -| `speech_model` | download (false), model (`tiny`, `base` or `small`; default `base`), cancel (false) | the speech model that `transcript`, `find_words` and `auto_captions` run on: no argument shows which models are installed and the download in progress. `download: true` fetches a model in the background (the GUI's Download model fetches `base`); `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true | | |
| 413 | +| `speech_model` | download (false), model (default `base`), device (default: the one auto picks), cancel (false) | the speech model that `transcript`, `find_words` and `auto_captions` run on: no argument shows the models installed per device (cpu, gpu) and whether a GPU is usable. `download: true` fetches a model in the background: cpu is the Hugging Face folder `whisper-<model>`, gpu the single file `ggml-<model>.bin`. `cancel: true` stops it and keeps the files fetched so far. Nothing is downloaded unless `download` is true | | |
| 414 | 414 | | `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) | |
| 415 | 415 | | `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. | |
| 416 | 416 | | `export_queue` | action (`pause`, `start` or `status`, the default) | `pause` stops the queue after the running export: the running one finishes, and the queued exports (`export_start {queue:true}`) stay waiting. `start` lifts the pause and starts the next queued export now if nothing is running. `status` says whether the queue is paused, the running export and the queued ones in order. A pause holds only queued exports; a direct export (no `queue`) starts at once. `export_status` names a paused queue | |
crates/app/src/creator.rsmodified+0 -12
| @@ -56,18 +56,6 @@ pub(crate) fn model_label(model: &str) -> String { | ||
| 56 | 56 | } |
| 57 | 57 | } |
| 58 | 58 | |
| 59 | -/// What a model's tooltip says: what it trades off, and its name on disk so the plain word is | |
| 60 | -/// never a mystery. | |
| 61 | -pub(crate) fn model_tip(model: &str) -> String { | |
| 62 | - let what = match model { | |
| 63 | - "tiny" => "quickest, least accurate", | |
| 64 | - "base" => "a middle ground", | |
| 65 | - "small" => "slowest, most accurate", | |
| 66 | - _ => "a speech model", | |
| 67 | - }; | |
| 68 | - format!("{}: {what} ({model} model)", model_label(model)) | |
| 69 | -} | |
| 70 | - | |
| 71 | 59 | // ---- normalize ---------------------------------------------------------------------- |
| 72 | 60 | |
| 73 | 61 | /// A minus sign the way the cards print it: U+2212, never a hyphen. |
crates/app/src/menus.rsmodified+4 -0
| @@ -119,6 +119,8 @@ pub(crate) enum Pick { | ||
| 119 | 119 | /// ([`engine::PlaybackSession::set_sample_rate`]). Opened from the panel, |
| 120 | 120 | /// beside the resolution and rate it shares a row style with. |
| 121 | 121 | SampleRate, |
| 122 | + /// The speech model the project transcribes with, or Auto ([`Choice::SpeechModel`]). | |
| 123 | + SpeechModel, | |
| 122 | 124 | Fit(Lane, usize), |
| 123 | 125 | /// The colour label of the clip at (lane, index) ([`engine::project::LABELS`]). |
| 124 | 126 | Label(Lane, usize), |
| @@ -201,6 +203,8 @@ pub(crate) enum Choice { | ||
| 201 | 203 | Bin(u32), |
| 202 | 204 | /// The autosave period in seconds, `None` for Off ([`Pick::Autosave`]). |
| 203 | 205 | Autosave(Option<u64>), |
| 206 | + /// The speech model, `None` for Auto ([`engine::speech::MODELS`]). | |
| 207 | + SpeechModel(Option<&'static str>), | |
| 204 | 208 | } |
| 205 | 209 | |
| 206 | 210 | /// A status-bar item a shortcut-opened list hangs above. |
crates/app/src/player/cards.rsmodified+33 -0
| @@ -592,6 +592,30 @@ impl Player { | ||
| 592 | 592 | cx.notify(); |
| 593 | 593 | } |
| 594 | 594 | |
| 595 | + /// The project's speech model set (`None` for Auto). One undo step. | |
| 596 | + pub(crate) fn apply_speech_model(&mut self, model: Option<&str>, cx: &mut Context<Self>) { | |
| 597 | + if self.session.as_mut().is_some_and(|s| s.set_speech_model(model)) { | |
| 598 | + self.mark_dirty(); | |
| 599 | + } | |
| 600 | + cx.notify(); | |
| 601 | + } | |
| 602 | + | |
| 603 | + /// The project's speech device set. One undo step. | |
| 604 | + pub(crate) fn apply_speech_device(&mut self, device: engine::speech::DeviceChoice, cx: &mut Context<Self>) { | |
| 605 | + if self.session.as_mut().is_some_and(|s| s.set_speech_device(device)) { | |
| 606 | + self.mark_dirty(); | |
| 607 | + } | |
| 608 | + cx.notify(); | |
| 609 | + } | |
| 610 | + | |
| 611 | + /// Whether a speech model in the picker is not installed for the device the project resolves it to. | |
| 612 | + pub(crate) fn speech_model_missing(&self, choice: Choice) -> bool { | |
| 613 | + match (choice, self.session.as_ref()) { | |
| 614 | + (Choice::SpeechModel(Some(m)), Some(s)) => engine::speech::check_model(m, s.speech_device().resolve(m)).is_err(), | |
| 615 | + _ => false, | |
| 616 | + } | |
| 617 | + } | |
| 618 | + | |
| 595 | 619 | /// The project's still length set: stills placed from now on take it, and the ones already |
| 596 | 620 | /// on the timeline keep theirs. One undo step, and the project reads unsaved. |
| 597 | 621 | pub(crate) fn apply_still_secs(&mut self, secs: f64, cx: &mut Context<Self>) { |
| @@ -706,6 +730,7 @@ impl Player { | ||
| 706 | 730 | Choice::Size(w, h) => self.apply_resolution(w, h, cx), |
| 707 | 731 | Choice::Fps(fps) => self.apply_frame_rate(fps, cx), |
| 708 | 732 | Choice::SampleRate(rate) => self.apply_sample_rate(rate, cx), |
| 733 | + Choice::SpeechModel(model) => self.apply_speech_model(model, cx), | |
| 709 | 734 | Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), |
| 710 | 735 | Choice::Label(lane, idx, label) => self.apply_label(lane, idx, label, cx), |
| 711 | 736 | Choice::MarkerColor(idx, color) => self.set_marker_color(idx, color, cx), |
| @@ -880,6 +905,14 @@ impl Player { | ||
| 880 | 905 | } |
| 881 | 906 | Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()), |
| 882 | 907 | Pick::SampleRate => sample_rate_choices(session.sample_rate()), |
| 908 | + Pick::SpeechModel => { | |
| 909 | + let here = session.speech_model(); | |
| 910 | + std::iter::once((Choice::SpeechModel(None), "Auto".into(), "".into(), here.is_none())) | |
| 911 | + .chain(engine::speech::MODELS.iter().map(|&m| { | |
| 912 | + (Choice::SpeechModel(Some(m)), crate::creator::model_label(m).into(), "".into(), here == Some(m)) | |
| 913 | + })) | |
| 914 | + .collect() | |
| 915 | + } | |
| 883 | 916 | Pick::Fit(lane, idx) => { |
| 884 | 917 | fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) |
| 885 | 918 | } |
crates/app/src/player/tools.rsmodified+8 -13
| @@ -14,6 +14,7 @@ use engine::speech::{self, Filler, Hear, Job, Spoken}; | ||
| 14 | 14 | |
| 15 | 15 | use crate::creator::{self, LANGUAGES, LUFS_RANGE, LUFS_STEP, PEAK_RANGE, PEAK_STEP, Said}; |
| 16 | 16 | use crate::player::text_field::FieldKey; |
| 17 | +use crate::player::transcript; | |
| 17 | 18 | use crate::ui::kit::{NumberEdit, scrub_value}; |
| 18 | 19 | use crate::*; |
| 19 | 20 | |
| @@ -118,7 +119,6 @@ pub(crate) struct Tools { | ||
| 118 | 119 | pub(crate) each: bool, |
| 119 | 120 | // Captions and Fillers |
| 120 | 121 | pub(crate) lang: usize, |
| 121 | - pub(crate) model: usize, | |
| 122 | 122 | pub(crate) hear: usize, |
| 123 | 123 | /// Listen to the sound again even though a transcript is there to read from. |
| 124 | 124 | pub(crate) relisten: bool, |
| @@ -151,7 +151,6 @@ impl Tools { | ||
| 151 | 151 | ceiling: engine::normalize::TARGET_TRUE_PEAK, |
| 152 | 152 | each: false, |
| 153 | 153 | lang: 0, |
| 154 | - model: 0, | |
| 155 | 154 | hear: 0, |
| 156 | 155 | relisten: false, |
| 157 | 156 | found: Vec::new(), |
| @@ -428,10 +427,6 @@ impl Player { | ||
| 428 | 427 | self.session.as_ref().map_or_else(Vec::new, creator::hear_choices) |
| 429 | 428 | } |
| 430 | 429 | |
| 431 | - pub(crate) fn tools_models(&self) -> Vec<&'static str> { | |
| 432 | - speech::installed_models() | |
| 433 | - } | |
| 434 | - | |
| 435 | 430 | /// Opens a dropdown, or shuts it when it is the one open. |
| 436 | 431 | pub(crate) fn tools_toggle_drop(&mut self, what: Cycle, cx: &mut Context<Self>) { |
| 437 | 432 | if let Some(t) = self.tools_mut() { |
| @@ -445,7 +440,6 @@ impl Player { | ||
| 445 | 440 | if let Some(t) = self.tools_mut() { |
| 446 | 441 | match what { |
| 447 | 442 | Cycle::Language => t.lang = i, |
| 448 | - Cycle::Model => t.model = i, | |
| 449 | 443 | Cycle::Hear => t.hear = i, |
| 450 | 444 | Cycle::Voice => t.voice = i, |
| 451 | 445 | } |
| @@ -500,14 +494,16 @@ impl Player { | ||
| 500 | 494 | cx.notify(); |
| 501 | 495 | return; |
| 502 | 496 | } |
| 503 | - let (lang, model_at, hear_at) = (tools.lang, tools.model, tools.hear); | |
| 504 | - if let Err(why) = speech::available() { | |
| 497 | + let (lang, hear_at) = (tools.lang, tools.hear); | |
| 498 | + if let Err(why) = speech::stt_bin() { | |
| 505 | 499 | return self.listen_fail(fillers, &why, cx); |
| 506 | 500 | } |
| 507 | - let models = self.tools_models(); | |
| 508 | - let Some(&model) = models.get(model_at).or(models.first()) else { | |
| 501 | + let Some((model, device)) = transcript::speech_target(self.session.as_ref()) else { | |
| 509 | 502 | return self.listen_fail(fillers, "No speech model is installed", cx); |
| 510 | 503 | }; |
| 504 | + if let Err(why) = speech::available(device) { | |
| 505 | + return self.listen_fail(fillers, &why, cx); | |
| 506 | + } | |
| 511 | 507 | let hears = self.tools_hears(); |
| 512 | 508 | let hear = hears.get(hear_at).copied().unwrap_or(Hear::Mix); |
| 513 | 509 | let lang = LANGUAGES[lang.min(LANGUAGES.len() - 1)].0; |
| @@ -533,7 +529,7 @@ impl Player { | ||
| 533 | 529 | } |
| 534 | 530 | let work = cx.background_executor().spawn({ |
| 535 | 531 | let job = job.clone(); |
| 536 | - async move { speech::listen(heard, model, lang, fillers, &job) } | |
| 532 | + async move { speech::listen(heard, &model, device, lang, fillers, &job) } | |
| 537 | 533 | }); |
| 538 | 534 | cx.spawn(async move |this, cx| { |
| 539 | 535 | let heard = work.await; |
| @@ -895,7 +891,6 @@ impl Player { | ||
| 895 | 891 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 896 | 892 | pub(crate) enum Cycle { |
| 897 | 893 | Language, |
| 898 | - Model, | |
| 899 | 894 | Hear, |
| 900 | 895 | Voice, |
| 901 | 896 | } |
crates/app/src/player/transcript.rsmodified+35 -6
| @@ -28,6 +28,31 @@ const KEEP: usize = 64; | ||
| 28 | 28 | /// What identifies a state of the timeline well enough to tell whose words these are. |
| 29 | 29 | type Stamp = (usize, u32); |
| 30 | 30 | |
| 31 | +/// The model and device a run goes to: the project's pick, else the first one installed for the | |
| 32 | +/// device it allows. `None` when no model is installed there. | |
| 33 | +pub(crate) fn speech_target(session: Option<&PlaybackSession>) -> Option<(String, speech::Device)> { | |
| 34 | + let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device); | |
| 35 | + let model = session.and_then(PlaybackSession::speech_model); | |
| 36 | + speech::plan(choice, model).filter(|(m, d)| speech::check_model(m, *d).is_ok()) | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// The model the download button fetches and the device it goes to: the project's pick, else | |
| 40 | +/// large-v3-turbo on a GPU and base on the CPU. | |
| 41 | +pub(crate) fn speech_download(session: Option<&PlaybackSession>) -> (String, speech::Device) { | |
| 42 | + let choice = session.map_or(speech::DeviceChoice::Auto, PlaybackSession::speech_device); | |
| 43 | + let device = match choice { | |
| 44 | + speech::DeviceChoice::Cpu => speech::Device::Cpu, | |
| 45 | + speech::DeviceChoice::Gpu => speech::Device::Gpu, | |
| 46 | + speech::DeviceChoice::Auto if speech::gpu_available() => speech::Device::Gpu, | |
| 47 | + speech::DeviceChoice::Auto => speech::Device::Cpu, | |
| 48 | + }; | |
| 49 | + let model = session.and_then(PlaybackSession::speech_model).unwrap_or(match device { | |
| 50 | + speech::Device::Gpu => "large-v3-turbo", | |
| 51 | + speech::Device::Cpu => "base", | |
| 52 | + }); | |
| 53 | + (model.to_string(), device) | |
| 54 | +} | |
| 55 | + | |
| 31 | 56 | pub(crate) struct Transcript { |
| 32 | 57 | /// The words as the timeline stands (timeline frames), `None` before the first listen. |
| 33 | 58 | pub(crate) words: Option<Vec<Spoken>>, |
| @@ -199,12 +224,15 @@ impl Player { | ||
| 199 | 224 | this.notify_user(why.into()); |
| 200 | 225 | cx.notify(); |
| 201 | 226 | }; |
| 202 | - if let Err(why) = speech::available() { | |
| 227 | + if let Err(why) = speech::stt_bin() { | |
| 203 | 228 | return fail(self, why, cx); |
| 204 | 229 | } |
| 205 | - let Some(model) = speech::pick_model(|m| speech::check_model(m).is_ok()) else { | |
| 230 | + let Some((model, device)) = speech_target(self.session.as_ref()) else { | |
| 206 | 231 | return fail(self, "No speech model is installed".into(), cx); |
| 207 | 232 | }; |
| 233 | + if let Err(why) = speech::available(device) { | |
| 234 | + return fail(self, why, cx); | |
| 235 | + } | |
| 208 | 236 | let Some(session) = self.session.as_ref() else { |
| 209 | 237 | return; |
| 210 | 238 | }; |
| @@ -219,7 +247,7 @@ impl Player { | ||
| 219 | 247 | self.transcript.status.clear(); |
| 220 | 248 | let work = cx.background_executor().spawn({ |
| 221 | 249 | let job = job.clone(); |
| 222 | - async move { speech::listen(heard, model, "auto", true, &job) } | |
| 250 | + async move { speech::listen(heard, &model, device, "auto", true, &job) } | |
| 223 | 251 | }); |
| 224 | 252 | cx.spawn(async move |this, cx| { |
| 225 | 253 | let heard = work.await; |
| @@ -269,12 +297,13 @@ impl Player { | ||
| 269 | 297 | cx.notify(); |
| 270 | 298 | } |
| 271 | 299 | |
| 272 | - /// Fetches the speech model (the base one) with progress, off the UI thread. Nothing is | |
| 273 | - /// started while one is already coming. | |
| 300 | + /// Fetches the speech model the project chose (see [`speech_download`]) with progress, off the | |
| 301 | + /// UI thread. Nothing is started while one is already coming. | |
| 274 | 302 | pub(crate) fn start_model_download(&mut self, cx: &mut Context<Self>) { |
| 275 | 303 | if self.transcript.download.is_some() { |
| 276 | 304 | return; |
| 277 | 305 | } |
| 306 | + let (model, device) = speech_download(self.session.as_ref()); | |
| 278 | 307 | let job = Arc::new(Job::default()); |
| 279 | 308 | let id = self.transcript.runs.wrapping_add(1); |
| 280 | 309 | self.transcript.runs = id; |
| @@ -282,7 +311,7 @@ impl Player { | ||
| 282 | 311 | self.transcript.status.clear(); |
| 283 | 312 | let work = cx.background_executor().spawn({ |
| 284 | 313 | let job = job.clone(); |
| 285 | - async move { speech::download_model("base", &job) } | |
| 314 | + async move { speech::download_model(&model, device, &job) } | |
| 286 | 315 | }); |
| 287 | 316 | cx.spawn(async move |this, cx| { |
| 288 | 317 | let done = work.await; |
crates/app/src/tests/caps.rsmodified+1 -2
| @@ -13,12 +13,11 @@ fn a_caption_drag_stays_between_its_neighbours() { | ||
| 13 | 13 | } |
| 14 | 14 | |
| 15 | 15 | #[test] |
| 16 | -fn speech_models_have_plain_names_and_the_real_one_in_the_tooltip() { | |
| 16 | +fn speech_models_have_plain_names() { | |
| 17 | 17 | assert_eq!(crate::creator::model_label("tiny"), "Fast"); |
| 18 | 18 | assert_eq!(crate::creator::model_label("base"), "Balanced"); |
| 19 | 19 | assert_eq!(crate::creator::model_label("small"), "Accurate"); |
| 20 | 20 | assert_eq!(crate::creator::model_label("medium"), "Medium"); |
| 21 | - assert!(crate::creator::model_tip("tiny").contains("tiny")); | |
| 22 | 21 | } |
| 23 | 22 | |
| 24 | 23 | #[test] |
crates/app/src/tests/creator.rsmodified+3 -5
| @@ -206,7 +206,7 @@ fn speaking_text_makes_a_voiceover_the_timeline_takes() { | ||
| 206 | 206 | |
| 207 | 207 | #[test] |
| 208 | 208 | fn listening_for_captions_runs_end_to_end_when_speech_is_installed() { |
| 209 | - if speech::available().is_err() { | |
| 209 | + if speech::available(speech::Device::Cpu).is_err() { | |
| 210 | 210 | eprintln!("skipped: edith-stt or its model is not installed"); |
| 211 | 211 | return; |
| 212 | 212 | } |
| @@ -215,10 +215,10 @@ fn listening_for_captions_runs_end_to_end_when_speech_is_installed() { | ||
| 215 | 215 | assert!(hears.contains(&speech::Hear::Mix) && hears.contains(&speech::Hear::Lane(Lane::A1))); |
| 216 | 216 | let heard = speech::prepare(&s, speech::Hear::Mix).expect("the fixture has sound"); |
| 217 | 217 | let job = speech::Job::default(); |
| 218 | - let model = speech::installed_models()[0]; | |
| 218 | + let model = speech::installed_models(speech::Device::Cpu)[0]; | |
| 219 | 219 | // A tone is not speech: whatever comes back, it comes back (and cancel stops it early). |
| 220 | 220 | job.cancel.store(true, std::sync::atomic::Ordering::Relaxed); |
| 221 | - assert_eq!(speech::listen(heard, model, "en", false, &job).unwrap_err(), speech::CANCELLED); | |
| 221 | + assert_eq!(speech::listen(heard, model, speech::Device::Cpu, "en", false, &job).unwrap_err(), speech::CANCELLED); | |
| 222 | 222 | } |
| 223 | 223 | |
| 224 | 224 | #[test] |
| @@ -251,7 +251,6 @@ fn every_creator_tool_has_a_menu_row_a_palette_entry_and_a_card_control() { | ||
| 251 | 251 | "tools-target", |
| 252 | 252 | "tools-ceiling", |
| 253 | 253 | "tools-lang", |
| 254 | - "tools-model", | |
| 255 | 254 | "tools-tab-a", |
| 256 | 255 | "tools-tab-b", |
| 257 | 256 | "mix-normalize", |
| @@ -347,6 +346,5 @@ fn a_tool_error_or_a_clock_or_a_model_tip_reads_plainly() { | ||
| 347 | 346 | assert_eq!(creator::clock(0.0), "0:00"); |
| 348 | 347 | assert_eq!(creator::clock(75.0), "1:15"); |
| 349 | 348 | assert_eq!(creator::clock(3725.0), "1:02:05"); |
| 350 | - assert!(creator::model_tip("base").contains("a middle ground")); | |
| 351 | 349 | assert_eq!(creator::lufs_text(-20.0), "\u{2212}20.0"); |
| 352 | 350 | } |
crates/app/src/ui/cards/tools.rsmodified+5 -11
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | use super::common::*; |
| 7 | 7 | use crate::creator::{self, LANGUAGES, Said}; |
| 8 | 8 | use crate::player::tools::{Cycle, NumField, Tool, Tools}; |
| 9 | +use crate::player::transcript; | |
| 9 | 10 | use crate::ui::icons::Icon; |
| 10 | 11 | use crate::ui::kit::{self, Segment}; |
| 11 | 12 | use crate::*; |
| @@ -488,15 +489,14 @@ impl Player { | ||
| 488 | 489 | /// transcript to read from, "From the transcript" is the first and default choice (instant); |
| 489 | 490 | /// "Listen again" keeps the sound pickers under it. |
| 490 | 491 | fn listen_body(&self, t: &Tools, fillers: bool, list_w: f32, cx: &mut Context<Self>) -> Div { |
| 491 | - let models = self.tools_models(); | |
| 492 | + let no_model = transcript::speech_target(self.session.as_ref()).is_none(); | |
| 492 | 493 | let hears = self.tools_hears(); |
| 493 | 494 | let downloading = self.transcript.download.is_some(); |
| 494 | 495 | let from_transcript = self.transcript_words().is_some() && !t.relisten; |
| 495 | 496 | let hear_items: Vec<SharedString> = hears.iter().map(|h| creator::hear_label(*h).into()).collect(); |
| 496 | 497 | let lang_items: Vec<SharedString> = LANGUAGES.iter().map(|(_, name)| (*name).into()).collect(); |
| 497 | - let model_items: Vec<SharedString> = models.iter().map(|m| creator::model_label(m).into()).collect(); | |
| 498 | 498 | let _ = Hear::Mix; |
| 499 | - let why = match (models.is_empty() && !from_transcript, t.running.is_some()) { | |
| 499 | + let why = match (no_model && !from_transcript, t.running.is_some()) { | |
| 500 | 500 | (true, _) => Some("Install a speech model first"), |
| 501 | 501 | (false, true) => Some("Already listening"), |
| 502 | 502 | _ => None, |
| @@ -527,17 +527,11 @@ impl Player { | ||
| 527 | 527 | )); |
| 528 | 528 | } |
| 529 | 529 | if !from_transcript { |
| 530 | - let model_row = drop_row("tools-model", "Model", model_items, t.model, t.open == Some(Cycle::Model), Cycle::Model, list_w, busy, cx); | |
| 531 | - let model_tip = models.get(t.model).map(|m| creator::model_tip(m)); | |
| 532 | 530 | body = body |
| 533 | 531 | .child(drop_row("tools-hear", "Listen to", hear_items, t.hear, t.open == Some(Cycle::Hear), Cycle::Hear, list_w, busy, cx)) |
| 534 | - .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx)) | |
| 535 | - .child(match model_tip { | |
| 536 | - Some(tip) => model_row.id("tools-model-row").tooltip(crate::ui::widgets::overlay_tip_hover("Model", "", Some(&tip))).into_any_element(), | |
| 537 | - None => model_row.into_any_element(), | |
| 538 | - }); | |
| 532 | + .child(drop_row("tools-lang", "Language", lang_items, t.lang, t.open == Some(Cycle::Language), Cycle::Language, list_w, busy, cx)); | |
| 539 | 533 | } |
| 540 | - if models.is_empty() && !from_transcript { | |
| 534 | + if no_model && !from_transcript { | |
| 541 | 535 | body = body.child(missing( |
| 542 | 536 | "No speech model is installed yet. Download one, or put one in the models folder.", |
| 543 | 537 | vec![ |
crates/app/src/ui/overlays.rsmodified+2 -0
| @@ -788,7 +788,9 @@ impl Player { | ||
| 788 | 788 | // A refused row (a format this timeline cannot be written in) is |
| 789 | 789 | // dimmed and says why on hover; it takes no click. |
| 790 | 790 | let why = self.export_choice_refusal(choice); |
| 791 | + let missing = self.speech_model_missing(choice); | |
| 791 | 792 | crate::ui::popup::popup_row(("picker-row", n), label, detail, Some(picked), why.as_deref()) |
| 793 | + .when(missing, |d| d.opacity(0.45)) | |
| 792 | 794 | .when(n == picker.sel, |d| d.bg(rgb(DARK_RAISED()))) |
| 793 | 795 | .when(why.is_none(), |d| { |
| 794 | 796 | d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx))) |
crates/app/src/ui/settings_stance.rsmodified+69 -6
| @@ -54,6 +54,7 @@ use crate::ui::choice; | ||
| 54 | 54 | use crate::ui::hitmap; |
| 55 | 55 | use crate::ui::type_scale; |
| 56 | 56 | use crate::*; |
| 57 | +use engine::speech::{self, DeviceChoice}; | |
| 57 | 58 | use gpui::{AnyElement, KeyDownEvent, SharedString}; |
| 58 | 59 | |
| 59 | 60 | /// Which of the page's four sections is showing. Kept on [`Player`] beside |
| @@ -293,6 +294,24 @@ pub(crate) enum ChoiceRow { | ||
| 293 | 294 | /// The two stand-in switches, Off/On. |
| 294 | 295 | Proxies, |
| 295 | 296 | AutoProxies, |
| 297 | + /// What the speech model runs on ([`device_choices`]). | |
| 298 | + Device, | |
| 299 | +} | |
| 300 | + | |
| 301 | +/// The devices the picker offers: the GPU only when edith-stt has one. | |
| 302 | +pub(crate) fn device_choices() -> Vec<DeviceChoice> { | |
| 303 | + match speech::gpu_available() { | |
| 304 | + true => vec![DeviceChoice::Auto, DeviceChoice::Cpu, DeviceChoice::Gpu], | |
| 305 | + false => vec![DeviceChoice::Auto, DeviceChoice::Cpu], | |
| 306 | + } | |
| 307 | +} | |
| 308 | + | |
| 309 | +fn device_label(device: DeviceChoice) -> &'static str { | |
| 310 | + match device { | |
| 311 | + DeviceChoice::Auto => "Auto", | |
| 312 | + DeviceChoice::Cpu => "CPU", | |
| 313 | + DeviceChoice::Gpu => "GPU", | |
| 314 | + } | |
| 296 | 315 | } |
| 297 | 316 | |
| 298 | 317 | /// The two words a switch answers with, and the index each one sits at. |
| @@ -316,10 +335,11 @@ pub(crate) fn index_of<T: PartialEq>(all: &[T], value: T) -> Option<usize> { | ||
| 316 | 335 | impl ChoiceRow { |
| 317 | 336 | /// Every choice row there is, for the guards below. |
| 318 | 337 | #[cfg(test)] |
| 319 | - pub(crate) const ALL: [ChoiceRow; 3] = [ | |
| 338 | + pub(crate) const ALL: [ChoiceRow; 4] = [ | |
| 320 | 339 | ChoiceRow::Tone, |
| 321 | 340 | ChoiceRow::Proxies, |
| 322 | 341 | ChoiceRow::AutoProxies, |
| 342 | + ChoiceRow::Device, | |
| 323 | 343 | ]; |
| 324 | 344 | |
| 325 | 345 | /// The row's chips, in order, each a word read off the same table the |
| @@ -334,6 +354,7 @@ impl ChoiceRow { | ||
| 334 | 354 | ChoiceRow::Proxies | ChoiceRow::AutoProxies => { |
| 335 | 355 | SWITCH.iter().map(|w| w.to_string()).collect() |
| 336 | 356 | } |
| 357 | + ChoiceRow::Device => device_choices().into_iter().map(|d| device_label(d).to_string()).collect(), | |
| 337 | 358 | } |
| 338 | 359 | } |
| 339 | 360 | |
| @@ -343,6 +364,7 @@ impl ChoiceRow { | ||
| 343 | 364 | match self { |
| 344 | 365 | ChoiceRow::Tone => player.session.is_some(), |
| 345 | 366 | ChoiceRow::Proxies | ChoiceRow::AutoProxies => true, |
| 367 | + ChoiceRow::Device => player.session.is_some(), | |
| 346 | 368 | } |
| 347 | 369 | } |
| 348 | 370 | } |
| @@ -352,7 +374,7 @@ impl ChoiceRow { | ||
| 352 | 374 | /// and a song has no Encoder row ([`export_section`]'s own two gates). |
| 353 | 375 | pub(crate) fn choice_rows(tab: SettingsTab, _format: Format) -> Vec<ChoiceRow> { |
| 354 | 376 | match tab { |
| 355 | - SettingsTab::Project => vec![ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies], | |
| 377 | + SettingsTab::Project => vec![ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies], | |
| 356 | 378 | SettingsTab::Editor | SettingsTab::Keys => Vec::new(), |
| 357 | 379 | } |
| 358 | 380 | } |
| @@ -364,6 +386,10 @@ pub(crate) fn current_choice(player: &Player, row: ChoiceRow) -> Option<usize> { | ||
| 364 | 386 | .session |
| 365 | 387 | .as_ref() |
| 366 | 388 | .and_then(|session| index_of(&Preset::ALL, session.tone())), |
| 389 | + ChoiceRow::Device => player | |
| 390 | + .session | |
| 391 | + .as_ref() | |
| 392 | + .and_then(|session| index_of(&device_choices(), session.speech_device())), | |
| 367 | 393 | ChoiceRow::Proxies => Some(switch_index(player.proxies_on)), |
| 368 | 394 | // The import switch waits on editing copies: while they are off it shows off, and its own |
| 369 | 395 | // value is kept, so it comes back on when they are turned on again. |
| @@ -616,6 +642,18 @@ fn project_section(player: &Player, cx: &mut Context<Player>) -> impl IntoElemen | ||
| 616 | 642 | INK1(), |
| 617 | 643 | )) |
| 618 | 644 | .child(still_row(player, cx)) |
| 645 | + .child(speech_model_row(player, cx)) | |
| 646 | + .child(choice_row( | |
| 647 | + "settings-speech-device", | |
| 648 | + "Speech device", | |
| 649 | + "where the speech model runs; Auto takes the GPU when this computer has one", | |
| 650 | + None, | |
| 651 | + None, | |
| 652 | + false, | |
| 653 | + ChoiceRow::Device, | |
| 654 | + player, | |
| 655 | + cx, | |
| 656 | + )) | |
| 619 | 657 | // Only a project with HDR in it has anything to choose here. |
| 620 | 658 | .children(has_hdr.then(|| { |
| 621 | 659 | choice_row( |
| @@ -706,6 +744,25 @@ fn still_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement { | ||
| 706 | 744 | .child(field) |
| 707 | 745 | } |
| 708 | 746 | |
| 747 | +/// The speech model the project transcribes with: Auto, or one of [`speech::MODELS`] from a list. | |
| 748 | +/// Models not installed for the device are dimmed in the list. | |
| 749 | +fn speech_model_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement { | |
| 750 | + let value = match player.session.as_ref().and_then(|s| s.speech_model()) { | |
| 751 | + Some(model) => crate::creator::model_label(model), | |
| 752 | + None => "Auto".to_string(), | |
| 753 | + }; | |
| 754 | + list_row( | |
| 755 | + "settings-speech-model", | |
| 756 | + "Speech model", | |
| 757 | + value, | |
| 758 | + "the model that hears the timeline for captions, fillers and the transcript; Auto takes the best one installed", | |
| 759 | + None, | |
| 760 | + player, | |
| 761 | + cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::SpeechModel, event.position(), cx)), | |
| 762 | + INK1(), | |
| 763 | + ) | |
| 764 | +} | |
| 765 | + | |
| 709 | 766 | /// A chip of `row` was picked (by a click, or by an arrow through |
| 710 | 767 | /// [`settings_arrow`]): the value at `at`, through the same door the row's |
| 711 | 768 | /// 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< | ||
| 729 | 786 | player.toggle_auto_proxies(cx); |
| 730 | 787 | } |
| 731 | 788 | } |
| 789 | + ChoiceRow::Device => { | |
| 790 | + if let Some(&device) = device_choices().get(at) { | |
| 791 | + player.apply_speech_device(device, cx); | |
| 792 | + } | |
| 793 | + } | |
| 732 | 794 | } |
| 733 | 795 | } |
| 734 | 796 | |
| @@ -1785,7 +1847,7 @@ const SETTINGS_GAP: f32 = 8.; | ||
| 1785 | 1847 | /// under the hand (user 2026-09-20: "switching between them feels weird"). A |
| 1786 | 1848 | /// shorter section leaves air below its last row; a short window still |
| 1787 | 1849 | /// scrolls, the plate's `max_h` cap shrinking this from `min_h(0)`. |
| 1788 | -pub(crate) const SETTINGS_ROWS_H: f32 = 7. * CONTROL_H + 36. + 7. * 2.; | |
| 1850 | +pub(crate) const SETTINGS_ROWS_H: f32 = 9. * CONTROL_H + 36. + 9. * 2.; | |
| 1789 | 1851 | |
| 1790 | 1852 | /// The plate's height that is not its rows: the dialog's padding and gaps, the title and the tab |
| 1791 | 1853 | /// 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 { | ||
| 2019 | 2081 | fn the_choice_rows_sit_in_the_tabs_they_belong_to() { |
| 2020 | 2082 | assert_eq!( |
| 2021 | 2083 | choice_rows(SettingsTab::Project, Format::Mp4), |
| 2022 | - [ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies] | |
| 2084 | + [ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies] | |
| 2023 | 2085 | ); |
| 2024 | 2086 | assert!(choice_rows(SettingsTab::Editor, Format::Mp4).is_empty()); |
| 2025 | 2087 | assert!(choice_rows(SettingsTab::Keys, Format::Mp4).is_empty()); |
| @@ -2035,7 +2097,7 @@ mod tests { | ||
| 2035 | 2097 | fn the_panel_and_its_chip_rows_fit_at_1280_by_720() { |
| 2036 | 2098 | // PROJECT at its tallest (HDR row and its hint, both switches, the |
| 2037 | 2099 | // storage line) still fits the rows area. |
| 2038 | - let project_tallest = 7. * CONTROL_H + 36. + 7. * 2.; | |
| 2100 | + let project_tallest = 9. * CONTROL_H + 36. + 9. * 2.; | |
| 2039 | 2101 | assert!(project_tallest <= SETTINGS_ROWS_H); |
| 2040 | 2102 | // Width: a generous measure per glyph, so a real font only has room |
| 2041 | 2103 | // to spare. (label, chord, tail, row) |
| @@ -2044,7 +2106,8 @@ mod tests { | ||
| 2044 | 2106 | let mono_w = |text: &str| text.chars().count() as f32 * 8.; |
| 2045 | 2107 | let _ = keys; |
| 2046 | 2108 | // (label, tail, row); the key lives in the tooltip, the column is empty. |
| 2047 | - let rows: [(&str, &str, ChoiceRow); 3] = [ | |
| 2109 | + let rows: [(&str, &str, ChoiceRow); 4] = [ | |
| 2110 | + ("Speech device", "", ChoiceRow::Device), | |
| 2048 | 2111 | ("When HDR plays on a normal screen", "", ChoiceRow::Tone), |
| 2049 | 2112 | ("Editing copies (proxies)", "100%", ChoiceRow::Proxies), |
| 2050 | 2113 | (" Make them on import", "", ChoiceRow::AutoProxies), |
crates/app/src/ui/transcript_panel.rsmodified+13 -6
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | //! lit. Every state is a background on a word whose box never changes, so nothing moves. |
| 5 | 5 | |
| 6 | 6 | use crate::layout::redesign as r; |
| 7 | +use crate::player::transcript; | |
| 7 | 8 | use crate::ui::hitmap; |
| 8 | 9 | use crate::ui::icons::{Icon, IconSize}; |
| 9 | 10 | use crate::ui::kit::{Button, ButtonSize, ButtonStyle}; |
| @@ -299,11 +300,15 @@ fn paragraph( | ||
| 299 | 300 | /// model on the computer it says so plainly and offers to download one. |
| 300 | 301 | fn empty_view(player: &Player, cx: &mut Context<Player>) -> impl IntoElement { |
| 301 | 302 | let t = tokens(); |
| 302 | - let ready = speech::available(); | |
| 303 | - let no_model = speech::stt_bin().is_ok() && speech::installed_models().is_empty(); | |
| 303 | + let target = transcript::speech_target(player.session.as_ref()); | |
| 304 | + let ready = match &target { | |
| 305 | + Some((_, device)) => speech::available(*device), | |
| 306 | + None => speech::available(transcript::speech_download(player.session.as_ref()).1), | |
| 307 | + }; | |
| 308 | + let no_model = speech::stt_bin().is_ok() && target.is_none(); | |
| 304 | 309 | let not_built = speech::stt_bin().is_err(); |
| 305 | 310 | if let Some((job, _)) = &player.transcript.download { |
| 306 | - return download_view(job.fraction(), cx).into_any_element(); | |
| 311 | + return download_view(player.session.as_ref(), job.fraction(), cx).into_any_element(); | |
| 307 | 312 | } |
| 308 | 313 | let note = match (&ready, player.transcript.status.as_str()) { |
| 309 | 314 | (Err(_), status) if no_model && !status.is_empty() => format!("{status}. You can also put a model in the models folder yourself."), |
| @@ -360,9 +365,11 @@ fn empty_view(player: &Player, cx: &mut Context<Player>) -> impl IntoElement { | ||
| 360 | 365 | } |
| 361 | 366 | |
| 362 | 367 | /// While the speech model downloads: how far, and Cancel. |
| 363 | -fn download_view(fraction: f32, cx: &mut Context<Player>) -> impl IntoElement { | |
| 368 | +fn download_view(session: Option<&PlaybackSession>, fraction: f32, cx: &mut Context<Player>) -> impl IntoElement { | |
| 364 | 369 | let t = tokens(); |
| 365 | - let mb = speech::model_bytes("base") as f32 * fraction / 1_000_000.; | |
| 370 | + let (model, device) = transcript::speech_download(session); | |
| 371 | + let total = speech::model_bytes(&model, device) as f32; | |
| 372 | + let mb = total * fraction / 1_000_000.; | |
| 366 | 373 | div() |
| 367 | 374 | .id("transcript-downloading") |
| 368 | 375 | .flex_1() |
| @@ -381,7 +388,7 @@ fn download_view(fraction: f32, cx: &mut Context<Player>) -> impl IntoElement { | ||
| 381 | 388 | .type_style(type_scale::body()) |
| 382 | 389 | .text_color(rgb(t.ink2)) |
| 383 | 390 | .child("Downloading the speech model") |
| 384 | - .child(format!("{mb:.0} of {:.0} MB", speech::model_bytes("base") as f32 / 1_000_000.)), | |
| 391 | + .child(format!("{mb:.0} of {:.0} MB", total / 1_000_000.)), | |
| 385 | 392 | ) |
| 386 | 393 | .child( |
| 387 | 394 | div() |
crates/engine/src/edith.rsmodified+44 -12
| @@ -444,11 +444,12 @@ use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, Tr | ||
| 444 | 444 | /// The newest project format version: the `N` in the `edith N` first line that |
| 445 | 445 | /// [`save`] writes for a project that uses the newest features. A reader refuses any |
| 446 | 446 | /// higher version by name. |
| 447 | -pub const NEWEST_VERSION: u32 = 56; | |
| 447 | +pub const NEWEST_VERSION: u32 = 57; | |
| 448 | 448 | |
| 449 | 449 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module |
| 450 | 450 | /// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`]. |
| 451 | -const MAGIC: &[u8] = b"edith 56"; | |
| 451 | +const MAGIC: &[u8] = b"edith 57"; | |
| 452 | +const MAGIC_V56: &[u8] = b"edith 56"; | |
| 452 | 453 | const MAGIC_V55: &[u8] = b"edith 55"; |
| 453 | 454 | const MAGIC_V54: &[u8] = b"edith 54"; |
| 454 | 455 | const MAGIC_V53: &[u8] = b"edith 53"; |
| @@ -650,6 +651,11 @@ pub struct Document { | ||
| 650 | 651 | /// The length a still is placed at, from the `still` line (v52). `None` for a file that |
| 651 | 652 | /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s. |
| 652 | 653 | pub still_secs: Option<f64>, |
| 654 | + /// The speech model, from the `speech` line (v57). `None` for a file that names none, which | |
| 655 | + /// means the model is picked. | |
| 656 | + pub speech_model: Option<String>, | |
| 657 | + /// The device the speech model runs on, from the `speech` line (v57). Auto for a file without one. | |
| 658 | + pub speech_device: crate::speech::DeviceChoice, | |
| 653 | 659 | } |
| 654 | 660 | |
| 655 | 661 | /// A parked sequence read off a v45 file. |
| @@ -831,7 +837,7 @@ pub fn encode_flagged( | ||
| 831 | 837 | 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() { |
| 832 | 838 | let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len()); |
| 833 | 839 | let header = if curved { |
| 834 | - MAGIC | |
| 840 | + MAGIC_V56 | |
| 835 | 841 | } else if pitched { |
| 836 | 842 | MAGIC_V55 |
| 837 | 843 | } else if titled { |
| @@ -939,10 +945,11 @@ pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin | ||
| 939 | 945 | main |
| 940 | 946 | } |
| 941 | 947 | |
| 942 | -/// `main` with the project notes and the still length after it (v52): a `notes` line when there | |
| 943 | -/// are notes, a `still` line when the length is not the default. A project with neither is `main` | |
| 944 | -/// untouched, so it keeps the bytes it had before v52. | |
| 945 | -pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> { | |
| 948 | +/// `main` with the project notes, the still length and the speech choices after it (v52, v57): a | |
| 949 | +/// `notes` line when there are notes, a `still` line when the length is not the default, a | |
| 950 | +/// `speech` line when a model or a device is picked. A project with none is `main` untouched, so | |
| 951 | +/// it keeps the bytes it had before v52. | |
| 952 | +pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64, speech_model: Option<&str>, speech_device: crate::speech::DeviceChoice) -> Vec<u8> { | |
| 946 | 953 | let mut lines = Vec::new(); |
| 947 | 954 | if !notes.is_empty() { |
| 948 | 955 | lines.extend_from_slice(b"notes "); |
| @@ -952,11 +959,19 @@ pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64) -> Vec<u8> { | ||
| 952 | 959 | if still_secs != STILL_DEFAULT_SECS { |
| 953 | 960 | lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes()); |
| 954 | 961 | } |
| 962 | + let speech = speech_model.is_some() || speech_device != crate::speech::DeviceChoice::Auto; | |
| 963 | + if speech { | |
| 964 | + lines.extend_from_slice(format!("speech {}", speech_device.as_str()).as_bytes()); | |
| 965 | + if let Some(m) = speech_model { | |
| 966 | + lines.extend_from_slice(format!(" {m}").as_bytes()); | |
| 967 | + } | |
| 968 | + lines.push(b'\n'); | |
| 969 | + } | |
| 955 | 970 | if lines.is_empty() { |
| 956 | 971 | return main; |
| 957 | 972 | } |
| 958 | 973 | let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len()); |
| 959 | - let header = raise_header(&main[..first_end], MAGIC_V52); | |
| 974 | + let header = raise_header(&main[..first_end], if speech { MAGIC } else { MAGIC_V52 }); | |
| 960 | 975 | main.splice(..first_end, header); |
| 961 | 976 | if main.last() != Some(&b'\n') { |
| 962 | 977 | main.push(b'\n'); |
| @@ -1049,7 +1064,8 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se | ||
| 1049 | 1064 | // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46 |
| 1050 | 1065 | // when a part is v46; a newer-only line under an older header is refused. |
| 1051 | 1066 | let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n'); |
| 1052 | - let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); | |
| 1067 | + let v57 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); | |
| 1068 | + let v56 = v57 || is(&bytes, MAGIC_V56) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V56)); | |
| 1053 | 1069 | let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55)); |
| 1054 | 1070 | let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54)); |
| 1055 | 1071 | let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53)); |
| @@ -1060,7 +1076,7 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se | ||
| 1060 | 1076 | let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48)); |
| 1061 | 1077 | let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47)); |
| 1062 | 1078 | let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46)); |
| 1063 | - let header = if v56 { MAGIC } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 }; | |
| 1079 | + let header = if v57 { MAGIC } else if v56 { MAGIC_V56 } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 }; | |
| 1064 | 1080 | bytes.splice(..first_end, header.iter().copied()); |
| 1065 | 1081 | bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes()); |
| 1066 | 1082 | escape_text(active.1, &mut bytes); |
| @@ -2297,7 +2313,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | ||
| 2297 | 2313 | // The one that carries a clip's placement animation, as `tkeys` lines... |
| 2298 | 2314 | // The one that carries a clip's stabilisation, as `stab` lines... |
| 2299 | 2315 | // The one that carries a clip's pitch shift, as `pitch` lines... |
| 2300 | - let v56 = first == MAGIC; | |
| 2316 | + let v57 = first == MAGIC; | |
| 2317 | + let v56 = v57 || first == MAGIC_V56; | |
| 2301 | 2318 | let v55 = v56 || first == MAGIC_V55; |
| 2302 | 2319 | let v54 = v55 || first == MAGIC_V54; |
| 2303 | 2320 | let v53 = v54 || first == MAGIC_V53; |
| @@ -2454,6 +2471,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | ||
| 2454 | 2471 | bins: Vec::new(), |
| 2455 | 2472 | notes: String::new(), |
| 2456 | 2473 | still_secs: None, |
| 2474 | + speech_model: None, | |
| 2475 | + speech_device: crate::speech::DeviceChoice::Auto, | |
| 2457 | 2476 | }; |
| 2458 | 2477 | // The block of a parked sequence being read: its id, name and the lines so far. |
| 2459 | 2478 | let mut block: Option<(u32, String, Vec<u8>)> = None; |
| @@ -3588,6 +3607,19 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | ||
| 3588 | 3607 | } |
| 3589 | 3608 | doc.still_secs = Some(secs); |
| 3590 | 3609 | } |
| 3610 | + b"speech" if v57 => { | |
| 3611 | + let text = std::str::from_utf8(rest).map_err(|_| format!("line {n}: speech is not text"))?; | |
| 3612 | + let f: Vec<&str> = text.split(' ').collect(); | |
| 3613 | + doc.speech_device = f | |
| 3614 | + .first() | |
| 3615 | + .and_then(|d| crate::speech::DeviceChoice::parse(d)) | |
| 3616 | + .ok_or_else(|| format!("line {n}: speech wants a device, auto, cpu or gpu"))?; | |
| 3617 | + doc.speech_model = match f.get(1) { | |
| 3618 | + None => None, | |
| 3619 | + Some(m) if crate::speech::MODELS.contains(m) && f.len() == 2 => Some(m.to_string()), | |
| 3620 | + Some(m) => return Err(format!("line {n}: speech model `{m}` is not one of {}", crate::speech::MODELS.join(", ")).into()), | |
| 3621 | + }; | |
| 3622 | + } | |
| 3591 | 3623 | b"bin" if v51 => { |
| 3592 | 3624 | let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect(); |
| 3593 | 3625 | if f.len() != 3 { |
| @@ -7199,7 +7231,7 @@ mod tests { | ||
| 7199 | 7231 | crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(), |
| 7200 | 7232 | Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[], |
| 7201 | 7233 | ); |
| 7202 | - let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS); | |
| 7234 | + let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS, None, crate::speech::DeviceChoice::Auto); | |
| 7203 | 7235 | std::fs::write(&path, &bytes).unwrap(); |
| 7204 | 7236 | String::from_utf8(bytes).unwrap() |
| 7205 | 7237 | }; |
crates/engine/src/playback.rsmodified+26 -2
| @@ -1436,7 +1436,8 @@ impl PlaybackSession { | ||
| 1436 | 1436 | .with_lane_flags(&doc.flags) |
| 1437 | 1437 | .with_tone(doc.tone) |
| 1438 | 1438 | .with_notes(doc.notes) |
| 1439 | - .with_still_secs(doc.still_secs); | |
| 1439 | + .with_still_secs(doc.still_secs) | |
| 1440 | + .with_speech(doc.speech_model, doc.speech_device); | |
| 1440 | 1441 | session.counts = counts; |
| 1441 | 1442 | session.rates = rates; |
| 1442 | 1443 | Ok(session) |
| @@ -2296,7 +2297,7 @@ impl PlaybackSession { | ||
| 2296 | 2297 | .min(main.timeline_frames().saturating_sub(1)); |
| 2297 | 2298 | let main_bytes = self.encode_sequence(&dir, main, playhead); |
| 2298 | 2299 | let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins()); |
| 2299 | - let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs()); | |
| 2300 | + let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs(), self.project.speech_model(), self.project.speech_device()); | |
| 2300 | 2301 | if !self.project.uses_sequences() { |
| 2301 | 2302 | return crate::edith::write_atomic(path, &main_bytes); |
| 2302 | 2303 | } |
| @@ -5251,6 +5252,26 @@ impl PlaybackSession { | ||
| 5251 | 5252 | self.project.set_still_secs(secs) |
| 5252 | 5253 | } |
| 5253 | 5254 | |
| 5255 | + /// The speech model the project names, or `None` for the one picked ([`Project::speech_model`]). | |
| 5256 | + pub fn speech_model(&self) -> Option<&str> { | |
| 5257 | + self.project.speech_model() | |
| 5258 | + } | |
| 5259 | + | |
| 5260 | + /// Sets it ([`Project::set_speech_model`]). | |
| 5261 | + pub fn set_speech_model(&mut self, model: Option<&str>) -> bool { | |
| 5262 | + self.project.set_speech_model(model) | |
| 5263 | + } | |
| 5264 | + | |
| 5265 | + /// The device the speech model runs on ([`Project::speech_device`]). | |
| 5266 | + pub fn speech_device(&self) -> crate::speech::DeviceChoice { | |
| 5267 | + self.project.speech_device() | |
| 5268 | + } | |
| 5269 | + | |
| 5270 | + /// Sets it ([`Project::set_speech_device`]). | |
| 5271 | + pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool { | |
| 5272 | + self.project.set_speech_device(device) | |
| 5273 | + } | |
| 5274 | + | |
| 5254 | 5275 | /// What source 0's own file declared about how bright it gets |
| 5255 | 5276 | /// ([`ContentLight`]): a property of the film, read once at open, and |
| 5256 | 5277 | /// entirely absent (every field `None`) for an SDR file, a song or a |
| @@ -6883,6 +6904,8 @@ impl PlaybackSession { | ||
| 6883 | 6904 | caption_style: self.project.caption_style(), |
| 6884 | 6905 | notes: self.project.notes().to_string(), |
| 6885 | 6906 | still_secs: self.project.still_secs(), |
| 6907 | + speech_model: self.project.speech_model().map(str::to_string), | |
| 6908 | + speech_device: self.project.speech_device(), | |
| 6886 | 6909 | } |
| 6887 | 6910 | } |
| 6888 | 6911 | |
| @@ -7959,6 +7982,7 @@ Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? | ||
| 7959 | 7982 | .with_tone(doc.tone) |
| 7960 | 7983 | .with_notes(doc.notes) |
| 7961 | 7984 | .with_still_secs(doc.still_secs) |
| 7985 | + .with_speech(doc.speech_model, doc.speech_device) | |
| 7962 | 7986 | // The palette before what is placed on it: a caption names a row of |
| 7963 | 7987 | // it, and [`Project::with_subs`] refuses one naming a row that is |
| 7964 | 7988 | // not there. |
crates/engine/src/project.rsmodified+43 -0
| @@ -2365,6 +2365,10 @@ pub(crate) struct ProjectSettings { | ||
| 2365 | 2365 | pub(crate) notes: String, |
| 2366 | 2366 | /// How long a still image is placed for, in seconds (v52). |
| 2367 | 2367 | pub(crate) still_secs: f64, |
| 2368 | + /// The speech model the transcript and captions run on; `None` picks one (v57). | |
| 2369 | + pub(crate) speech_model: Option<String>, | |
| 2370 | + /// The device the speech model runs on (v57). | |
| 2371 | + pub(crate) speech_device: crate::speech::DeviceChoice, | |
| 2368 | 2372 | } |
| 2369 | 2373 | |
| 2370 | 2374 | impl ProjectSettings { |
| @@ -2387,6 +2391,8 @@ impl ProjectSettings { | ||
| 2387 | 2391 | caption_style: crate::captionanim::CaptionStyle::default(), |
| 2388 | 2392 | notes: String::new(), |
| 2389 | 2393 | still_secs: STILL_DEFAULT_SECS, |
| 2394 | + speech_model: None, | |
| 2395 | + speech_device: crate::speech::DeviceChoice::Auto, | |
| 2390 | 2396 | } |
| 2391 | 2397 | } |
| 2392 | 2398 | } |
| @@ -4342,6 +4348,43 @@ impl Project { | ||
| 4342 | 4348 | self |
| 4343 | 4349 | } |
| 4344 | 4350 | |
| 4351 | + /// The speech model the project names, or `None` for the one picked. | |
| 4352 | + pub fn speech_model(&self) -> Option<&str> { | |
| 4353 | + self.settings.speech_model.as_deref() | |
| 4354 | + } | |
| 4355 | + | |
| 4356 | + /// Sets it (`None` picks one). `false` for the one already in force; otherwise one undo step. | |
| 4357 | + pub fn set_speech_model(&mut self, model: Option<&str>) -> bool { | |
| 4358 | + if self.settings.speech_model.as_deref() == model { | |
| 4359 | + return false; | |
| 4360 | + } | |
| 4361 | + self.snapshot(); | |
| 4362 | + self.settings.speech_model = model.map(str::to_string); | |
| 4363 | + true | |
| 4364 | + } | |
| 4365 | + | |
| 4366 | + /// The device the speech model runs on. | |
| 4367 | + pub fn speech_device(&self) -> crate::speech::DeviceChoice { | |
| 4368 | + self.settings.speech_device | |
| 4369 | + } | |
| 4370 | + | |
| 4371 | + /// Sets it. `false` for the one already in force; otherwise one undo step. | |
| 4372 | + pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool { | |
| 4373 | + if self.settings.speech_device == device { | |
| 4374 | + return false; | |
| 4375 | + } | |
| 4376 | + self.snapshot(); | |
| 4377 | + self.settings.speech_device = device; | |
| 4378 | + true | |
| 4379 | + } | |
| 4380 | + | |
| 4381 | + /// The speech choices a *load* puts back: no undo step, as [`with_still_secs`](Project::with_still_secs). | |
| 4382 | + pub(crate) fn with_speech(mut self, model: Option<String>, device: crate::speech::DeviceChoice) -> Self { | |
| 4383 | + self.settings.speech_model = model; | |
| 4384 | + self.settings.speech_device = device; | |
| 4385 | + self | |
| 4386 | + } | |
| 4387 | + | |
| 4345 | 4388 | /// Sets it. `false` for the one already in force, which is what keeps a |
| 4346 | 4389 | /// re-pick of the current rendition from costing a reseek. One undo step |
| 4347 | 4390 | /// like every other project-setting pick. |
crates/engine/src/speech.rsmodified+217 -73
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | use std::io::{BufRead, BufReader, Read}; |
| 10 | 10 | use std::path::{Path, PathBuf}; |
| 11 | 11 | use std::process::{Command, Stdio}; |
| 12 | +use std::sync::OnceLock; | |
| 12 | 13 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 13 | 14 | |
| 14 | 15 | use crate::project::Lane; |
| @@ -17,7 +18,7 @@ use crate::{AudioSession, PlaybackSession, subtitle}; | ||
| 17 | 18 | /// The sample rate edith-stt is fed. |
| 18 | 19 | pub const RATE: u32 = 16_000; |
| 19 | 20 | /// The Whisper model sizes edith-stt knows. |
| 20 | -pub const MODELS: &[&str] = &["tiny", "base", "small"]; | |
| 21 | +pub const MODELS: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; | |
| 21 | 22 | /// Silence longer than this (seconds) between two words ends a caption cue. |
| 22 | 23 | pub const CAPTION_GAP_SECS: f64 = 0.7; |
| 23 | 24 | /// Whisper drops disfluencies unless its prompt shows them: this prompt, put before the |
| @@ -46,7 +47,7 @@ pub fn home() -> PathBuf { | ||
| 46 | 47 | /// The edith-stt binary: `EDITH_STT_BIN`, else the first |
| 47 | 48 | /// `tools/edith-stt/target/release/edith-stt` above the running executable. |
| 48 | 49 | pub fn stt_bin() -> Result<PathBuf, String> { |
| 49 | - const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` in the edith repo, or set EDITH_STT_BIN to the binary"; | |
| 50 | + const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` (`--features vulkan` for the GPU) in the edith repo, or set EDITH_STT_BIN to the binary"; | |
| 50 | 51 | if let Some(p) = std::env::var_os("EDITH_STT_BIN") { |
| 51 | 52 | let p = PathBuf::from(p); |
| 52 | 53 | return if p.is_file() { Ok(p) } else { Err(format!("EDITH_STT_BIN is set to {}, which is not a file. {NOT_BUILT}", p.display())) }; |
| @@ -62,13 +63,99 @@ pub fn stt_bin() -> Result<PathBuf, String> { | ||
| 62 | 63 | Err(NOT_BUILT.into()) |
| 63 | 64 | } |
| 64 | 65 | |
| 65 | -pub fn check_model(model: &str) -> Result<(), String> { | |
| 66 | +/// What edith-stt runs the model on. | |
| 67 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 68 | +pub enum Device { | |
| 69 | + Cpu, | |
| 70 | + Gpu, | |
| 71 | +} | |
| 72 | + | |
| 73 | +impl Device { | |
| 74 | + /// The name edith-stt takes for `--device`. | |
| 75 | + pub fn flag(self) -> &'static str { | |
| 76 | + match self { | |
| 77 | + Self::Cpu => "cpu", | |
| 78 | + Self::Gpu => "gpu", | |
| 79 | + } | |
| 80 | + } | |
| 81 | +} | |
| 82 | + | |
| 83 | +/// The device a user picks: auto leaves it to [`DeviceChoice::resolve`]. | |
| 84 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 85 | +pub enum DeviceChoice { | |
| 86 | + #[default] | |
| 87 | + Auto, | |
| 88 | + Cpu, | |
| 89 | + Gpu, | |
| 90 | +} | |
| 91 | + | |
| 92 | +impl DeviceChoice { | |
| 93 | + pub fn parse(s: &str) -> Option<Self> { | |
| 94 | + match s { | |
| 95 | + "auto" => Some(Self::Auto), | |
| 96 | + "cpu" => Some(Self::Cpu), | |
| 97 | + "gpu" => Some(Self::Gpu), | |
| 98 | + _ => None, | |
| 99 | + } | |
| 100 | + } | |
| 101 | + | |
| 102 | + pub fn as_str(self) -> &'static str { | |
| 103 | + match self { | |
| 104 | + Self::Auto => "auto", | |
| 105 | + Self::Cpu => "cpu", | |
| 106 | + Self::Gpu => "gpu", | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 110 | + /// The device this choice runs `model` on: auto is the GPU when edith-stt has one and the | |
| 111 | + /// GPU file of `model` is installed, else the CPU. | |
| 112 | + pub fn resolve(self, model: &str) -> Device { | |
| 113 | + match self { | |
| 114 | + Self::Cpu => Device::Cpu, | |
| 115 | + Self::Gpu => Device::Gpu, | |
| 116 | + Self::Auto if gpu_available() && check_model(model, Device::Gpu).is_ok() => Device::Gpu, | |
| 117 | + Self::Auto => Device::Cpu, | |
| 118 | + } | |
| 119 | + } | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// Whether edith-stt reports a usable GPU (`--has-gpu` exits 0). An old binary without the flag | |
| 123 | +/// counts as no GPU. | |
| 124 | +pub fn gpu_available() -> bool { | |
| 125 | + static GPU: OnceLock<bool> = OnceLock::new(); | |
| 126 | + *GPU.get_or_init(|| { | |
| 127 | + stt_bin().is_ok_and(|bin| { | |
| 128 | + Command::new(bin) | |
| 129 | + .arg("--has-gpu") | |
| 130 | + .stdin(Stdio::null()) | |
| 131 | + .stdout(Stdio::null()) | |
| 132 | + .stderr(Stdio::null()) | |
| 133 | + .status() | |
| 134 | + .is_ok_and(|st| st.success()) | |
| 135 | + }) | |
| 136 | + }) | |
| 137 | +} | |
| 138 | + | |
| 139 | +/// Where a model lives for `device`: the folder `whisper-<model>` for the CPU, the file | |
| 140 | +/// `ggml-<model>.bin` for the GPU. | |
| 141 | +pub fn model_path(model: &str, device: Device) -> PathBuf { | |
| 142 | + match device { | |
| 143 | + Device::Cpu => models_dir().join(format!("whisper-{model}")), | |
| 144 | + Device::Gpu => models_dir().join(format!("ggml-{model}.bin")), | |
| 145 | + } | |
| 146 | +} | |
| 147 | + | |
| 148 | +pub fn check_model(model: &str, device: Device) -> Result<(), String> { | |
| 66 | 149 | if !MODELS.contains(&model) { |
| 67 | 150 | return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); |
| 68 | 151 | } |
| 69 | - let dir = home().join(".cache/edith/models").join(format!("whisper-{model}")); | |
| 70 | - if !dir.is_dir() { | |
| 71 | - return Err(format!("the {model} model is not installed at {}; edith-stt downloads it only when asked to", dir.display())); | |
| 152 | + let at = model_path(model, device); | |
| 153 | + let there = match device { | |
| 154 | + Device::Cpu => at.is_dir(), | |
| 155 | + Device::Gpu => at.is_file(), | |
| 156 | + }; | |
| 157 | + if !there { | |
| 158 | + return Err(format!("the {model} model ({}) is not installed at {}; edith-stt downloads it only when asked to", device.flag(), at.display())); | |
| 72 | 159 | } |
| 73 | 160 | Ok(()) |
| 74 | 161 | } |
| @@ -78,9 +165,30 @@ pub fn check_lang(lang: &str) -> Result<(), String> { | ||
| 78 | 165 | if ok { Ok(()) } else { Err(format!("language `{lang}` must be auto or a language code such as en")) } |
| 79 | 166 | } |
| 80 | 167 | |
| 81 | -/// The model when none is named: the first installed of base, small, tiny. | |
| 82 | -pub fn pick_model(installed: impl Fn(&str) -> bool) -> Option<&'static str> { | |
| 83 | - ["base", "small", "tiny"].into_iter().find(|m| installed(m)) | |
| 168 | +/// The model when none is named: the first installed in the device's order. | |
| 169 | +pub fn pick_model(installed: impl Fn(&str) -> bool, device: Device) -> Option<&'static str> { | |
| 170 | + let order: [&'static str; 6] = match device { | |
| 171 | + Device::Gpu => ["large-v3-turbo", "large-v3", "medium", "small", "base", "tiny"], | |
| 172 | + Device::Cpu => ["base", "small", "tiny", "medium", "large-v3-turbo", "large-v3"], | |
| 173 | + }; | |
| 174 | + order.into_iter().find(|m| installed(m)) | |
| 175 | +} | |
| 176 | + | |
| 177 | +/// The model and device a request runs on: the named model (its device from `choice`), or with no | |
| 178 | +/// model named the first one installed for the device `choice` allows (auto tries the GPU first). | |
| 179 | +pub fn plan(choice: DeviceChoice, model: Option<&str>) -> Option<(String, Device)> { | |
| 180 | + if let Some(m) = model { | |
| 181 | + return Some((m.to_string(), choice.resolve(m))); | |
| 182 | + } | |
| 183 | + let on = |d: Device| move |m: &str| check_model(m, d).is_ok(); | |
| 184 | + let gpu = || pick_model(on(Device::Gpu), Device::Gpu).map(|m| (m.to_string(), Device::Gpu)); | |
| 185 | + let cpu = || pick_model(on(Device::Cpu), Device::Cpu).map(|m| (m.to_string(), Device::Cpu)); | |
| 186 | + match choice { | |
| 187 | + DeviceChoice::Cpu => cpu(), | |
| 188 | + DeviceChoice::Gpu => gpu(), | |
| 189 | + DeviceChoice::Auto if gpu_available() => gpu().or_else(cpu), | |
| 190 | + DeviceChoice::Auto => cpu(), | |
| 191 | + } | |
| 84 | 192 | } |
| 85 | 193 | |
| 86 | 194 | #[derive(Clone, Debug)] |
| @@ -548,10 +656,10 @@ pub const CANCELLED: &str = "cancelled"; | ||
| 548 | 656 | /// lines feed `job`; setting `job.cancel` kills it. The last few other stderr lines are kept |
| 549 | 657 | /// for the error if the binary fails. |
| 550 | 658 | #[allow(clippy::too_many_arguments)] |
| 551 | -pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> { | |
| 659 | +pub fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> { | |
| 552 | 660 | let hint_args: Vec<&str> = if hint.is_empty() { Vec::new() } else { vec!["--prompt", hint] }; |
| 553 | 661 | let mut child = Command::new(bin) |
| 554 | - .args(["--model", model, "--language", lang, "--offset"]) | |
| 662 | + .args(["--model", model, "--device", device.flag(), "--language", lang, "--offset"]) | |
| 555 | 663 | .arg(format!("{offset:.3}")) |
| 556 | 664 | .args(&hint_args) |
| 557 | 665 | .arg(wav) |
| @@ -608,9 +716,9 @@ pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offs | ||
| 608 | 716 | Ok(out) |
| 609 | 717 | } |
| 610 | 718 | |
| 611 | -/// The models installed, smallest first. | |
| 612 | -pub fn installed_models() -> Vec<&'static str> { | |
| 613 | - MODELS.iter().copied().filter(|m| check_model(m).is_ok()).collect() | |
| 719 | +/// The models installed for `device`, smallest first. | |
| 720 | +pub fn installed_models(device: Device) -> Vec<&'static str> { | |
| 721 | + MODELS.iter().copied().filter(|m| check_model(m, device).is_ok()).collect() | |
| 614 | 722 | } |
| 615 | 723 | |
| 616 | 724 | /// Where the speech models live: one folder per model, `whisper-<name>`, here. |
| @@ -628,80 +736,116 @@ const MODEL_FILES: [(&str, bool); 4] = [ | ||
| 628 | 736 | const MODEL_OPTIONAL: &str = "generation_config.json"; |
| 629 | 737 | |
| 630 | 738 | /// About how many bytes a model's files add up to, for a progress bar before the sizes are known. |
| 631 | -pub fn model_bytes(model: &str) -> u64 { | |
| 632 | - match model { | |
| 633 | - "tiny" => 152_000_000, | |
| 634 | - "small" => 970_000_000, | |
| 739 | +pub fn model_bytes(model: &str, device: Device) -> u64 { | |
| 740 | + match (device, model) { | |
| 741 | + (Device::Gpu, "tiny") => 78_000_000, | |
| 742 | + (Device::Gpu, "base") => 148_000_000, | |
| 743 | + (Device::Gpu, "small") => 488_000_000, | |
| 744 | + (Device::Gpu, "medium") => 1_530_000_000, | |
| 745 | + (Device::Gpu, "large-v3") => 3_100_000_000, | |
| 746 | + (Device::Gpu, "large-v3-turbo") => 1_620_000_000, | |
| 747 | + (Device::Cpu, "tiny") => 152_000_000, | |
| 748 | + (Device::Cpu, "small") => 970_000_000, | |
| 749 | + (Device::Cpu, "medium") => 3_060_000_000, | |
| 750 | + (Device::Cpu, "large-v3") => 3_090_000_000, | |
| 751 | + (Device::Cpu, "large-v3-turbo") => 1_620_000_000, | |
| 635 | 752 | _ => 293_000_000, |
| 636 | 753 | } |
| 637 | 754 | } |
| 638 | 755 | |
| 639 | -/// Downloads the `model` (one of [`MODELS`]) into [`models_dir`] with `curl`, from the same place | |
| 640 | -/// `edith-stt` fetches it (huggingface.co/openai/whisper-<model>). The folder appears only when | |
| 756 | +/// Fetches `url` into `tmp` with curl, reporting the bytes `have` counts against `total` as | |
| 757 | +/// progress. `Ok(false)` when curl fails (`tmp` is removed); a cancel kills it. | |
| 758 | +fn fetch(url: &str, tmp: &Path, job: &Job, total: f64, have: &dyn Fn() -> u64) -> Result<bool, String> { | |
| 759 | + let mut child = Command::new("curl") | |
| 760 | + .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"]) | |
| 761 | + .arg(tmp) | |
| 762 | + .arg(url) | |
| 763 | + .stdin(Stdio::null()) | |
| 764 | + .stdout(Stdio::null()) | |
| 765 | + .stderr(Stdio::null()) | |
| 766 | + .spawn() | |
| 767 | + .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", models_dir().display()))?; | |
| 768 | + let status = loop { | |
| 769 | + if job.cancelled() { | |
| 770 | + let _ = child.kill(); | |
| 771 | + let _ = child.wait(); | |
| 772 | + let _ = std::fs::remove_file(tmp); | |
| 773 | + return Err(CANCELLED.into()); | |
| 774 | + } | |
| 775 | + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { | |
| 776 | + break status; | |
| 777 | + } | |
| 778 | + job.set((have() as f64 / total).min(0.99)); | |
| 779 | + std::thread::sleep(std::time::Duration::from_millis(150)); | |
| 780 | + }; | |
| 781 | + if !status.success() { | |
| 782 | + let _ = std::fs::remove_file(tmp); | |
| 783 | + } | |
| 784 | + Ok(status.success()) | |
| 785 | +} | |
| 786 | + | |
| 787 | +/// Downloads the `model` (one of [`MODELS`]) for `device` into [`models_dir`], from the same place | |
| 788 | +/// `edith-stt` fetches it: huggingface.co/openai/whisper-<model> for the CPU folder, and the | |
| 789 | +/// ggerganov/whisper.cpp `ggml-<model>.bin` file for the GPU. The CPU folder appears only when | |
| 641 | 790 | /// every file is in, so a half-finished download is never taken for an installed model; the files |
| 642 | 791 | /// already fetched are kept for the next try. `job` carries the progress and the cancel. |
| 643 | -pub fn download_model(model: &str, job: &Job) -> Result<(), String> { | |
| 792 | +pub fn download_model(model: &str, device: Device, job: &Job) -> Result<(), String> { | |
| 644 | 793 | if !MODELS.contains(&model) { |
| 645 | 794 | return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); |
| 646 | 795 | } |
| 647 | 796 | let root = models_dir(); |
| 648 | - let part = root.join(format!("whisper-{model}.part")); | |
| 649 | - let done = root.join(format!("whisper-{model}")); | |
| 650 | - std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?; | |
| 651 | - let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main"); | |
| 652 | - let total = model_bytes(model) as f64; | |
| 653 | - let have = |dir: &Path| -> u64 { | |
| 654 | - std::fs::read_dir(dir) | |
| 655 | - .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()) | |
| 656 | - .unwrap_or(0) | |
| 657 | - }; | |
| 658 | - let files = MODEL_FILES.iter().map(|&(f, need)| (f, need)).chain([(MODEL_OPTIONAL, false)]); | |
| 659 | - for (file, needed) in files { | |
| 660 | - let target = part.join(file); | |
| 661 | - if target.exists() { | |
| 662 | - continue; | |
| 663 | - } | |
| 664 | - let tmp = part.join(format!("{file}.tmp")); | |
| 665 | - let mut child = Command::new("curl") | |
| 666 | - .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"]) | |
| 667 | - .arg(&tmp) | |
| 668 | - .arg(format!("{base}/{file}")) | |
| 669 | - .stdin(Stdio::null()) | |
| 670 | - .stdout(Stdio::null()) | |
| 671 | - .stderr(Stdio::null()) | |
| 672 | - .spawn() | |
| 673 | - .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", done.display()))?; | |
| 674 | - let status = loop { | |
| 675 | - if job.cancelled() { | |
| 676 | - let _ = child.kill(); | |
| 677 | - let _ = child.wait(); | |
| 678 | - let _ = std::fs::remove_file(&tmp); | |
| 679 | - return Err(CANCELLED.into()); | |
| 680 | - } | |
| 681 | - if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { | |
| 682 | - break status; | |
| 797 | + std::fs::create_dir_all(&root).map_err(|e| format!("cannot create {}: {e}", root.display()))?; | |
| 798 | + let total = model_bytes(model, device) as f64; | |
| 799 | + match device { | |
| 800 | + Device::Gpu => { | |
| 801 | + let file = format!("ggml-{model}.bin"); | |
| 802 | + let target = root.join(&file); | |
| 803 | + let tmp = root.join(format!("{file}.part")); | |
| 804 | + let url = format!("https://huggingface.co/ggerganov/whisper.cpp/resolve/main/{file}"); | |
| 805 | + let len = || std::fs::metadata(&tmp).map(|m| m.len()).unwrap_or(0); | |
| 806 | + if !fetch(&url, &tmp, job, total, &len)? { | |
| 807 | + return Err(format!("could not download {file}: check the internet connection and try again")); | |
| 683 | 808 | } |
| 684 | - job.set((have(&part) as f64 / total).min(0.99)); | |
| 685 | - std::thread::sleep(std::time::Duration::from_millis(150)); | |
| 686 | - }; | |
| 687 | - if status.success() { | |
| 688 | 809 | std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; |
| 689 | - } else { | |
| 690 | - let _ = std::fs::remove_file(&tmp); | |
| 691 | - if needed { | |
| 692 | - return Err(format!("could not download {file}: check the internet connection and try again")); | |
| 810 | + } | |
| 811 | + Device::Cpu => { | |
| 812 | + let part = root.join(format!("whisper-{model}.part")); | |
| 813 | + let done = model_path(model, device); | |
| 814 | + std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?; | |
| 815 | + let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main"); | |
| 816 | + let have = || -> u64 { | |
| 817 | + std::fs::read_dir(&part) | |
| 818 | + .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()) | |
| 819 | + .unwrap_or(0) | |
| 820 | + }; | |
| 821 | + let files = MODEL_FILES.iter().copied().chain([(MODEL_OPTIONAL, false)]); | |
| 822 | + for (file, needed) in files { | |
| 823 | + let target = part.join(file); | |
| 824 | + if target.exists() { | |
| 825 | + continue; | |
| 826 | + } | |
| 827 | + let tmp = part.join(format!("{file}.tmp")); | |
| 828 | + if fetch(&format!("{base}/{file}"), &tmp, job, total, &have)? { | |
| 829 | + std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; | |
| 830 | + } else if needed { | |
| 831 | + return Err(format!("could not download {file}: check the internet connection and try again")); | |
| 832 | + } | |
| 693 | 833 | } |
| 834 | + std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?; | |
| 694 | 835 | } |
| 695 | 836 | } |
| 696 | - std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?; | |
| 697 | 837 | job.set(1.0); |
| 698 | 838 | Ok(()) |
| 699 | 839 | } |
| 700 | 840 | |
| 701 | -/// Whether speech can run at all here: the edith-stt binary is built and a model is installed. | |
| 702 | -pub fn available() -> Result<(), String> { | |
| 841 | +/// Whether speech can run at all here on `device`: the edith-stt binary is built, the GPU is | |
| 842 | +/// usable for the GPU device, and a model is installed for it. | |
| 843 | +pub fn available(device: Device) -> Result<(), String> { | |
| 703 | 844 | stt_bin()?; |
| 704 | - if installed_models().is_empty() { | |
| 845 | + if device == Device::Gpu && !gpu_available() { | |
| 846 | + return Err("edith-stt finds no usable GPU".into()); | |
| 847 | + } | |
| 848 | + if installed_models(device).is_empty() { | |
| 705 | 849 | return Err("The speech model is not installed yet.".into()); |
| 706 | 850 | } |
| 707 | 851 | Ok(()) |
| @@ -771,8 +915,8 @@ fn silence_hallucination(text: &str, no_speech: Option<f64>, avg_logprob: Option | ||
| 771 | 915 | /// What is said in `hear`, word by word, in timeline frames. `fillers` asks Whisper to keep its |
| 772 | 916 | /// disfluencies ([`FILLER_PROMPT`]); without it the model tends to drop them. The model runs on |
| 773 | 917 | /// a worker thread of the caller's choosing: this blocks until it is done or `job` is cancelled. |
| 774 | -pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { | |
| 775 | - listen(prepare(s, hear)?, model, lang, fillers, job) | |
| 918 | +pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { | |
| 919 | + listen(prepare(s, hear)?, model, device, lang, fillers, job) | |
| 776 | 920 | } |
| 777 | 921 | |
| 778 | 922 | /// The sound of `hear` as the speech model takes it, read off the session. Split from |
| @@ -797,9 +941,9 @@ pub fn prepare(s: &PlaybackSession, hear: Hear) -> Result<Heard, String> { | ||
| 797 | 941 | } |
| 798 | 942 | |
| 799 | 943 | /// Runs the speech model over what [`prepare`] read. Needs no session, so it can run anywhere. |
| 800 | -pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { | |
| 944 | +pub fn listen(heard: Heard, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { | |
| 801 | 945 | let bin = stt_bin()?; |
| 802 | - check_model(model)?; | |
| 946 | + check_model(model, device)?; | |
| 803 | 947 | check_lang(lang)?; |
| 804 | 948 | let fps = heard.fps; |
| 805 | 949 | if job.cancelled() { |
| @@ -810,7 +954,7 @@ pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) - | ||
| 810 | 954 | std::fs::write(&wav, wav_bytes(&heard.samples)).map_err(|e| format!("writing {}: {e}", wav.display()))?; |
| 811 | 955 | let guard = TempFile(wav.clone()); |
| 812 | 956 | let hint = if fillers { FILLER_PROMPT } else { "" }; |
| 813 | - let raw = run_stt(&bin, &wav, model, lang, hint, 0.0, &heard.label, job); | |
| 957 | + let raw = run_stt(&bin, &wav, model, device, lang, hint, 0.0, &heard.label, job); | |
| 814 | 958 | drop(guard); |
| 815 | 959 | let mut words = Vec::new(); |
| 816 | 960 | for seg in parse_raw(&raw?)? { |
crates/engine/tests/it/creator_tools.rsmodified+3 -3
| @@ -116,7 +116,7 @@ fn a_voiceover_refuses_empty_text_and_out_of_range_speed() { | ||
| 116 | 116 | |
| 117 | 117 | #[test] |
| 118 | 118 | fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() { |
| 119 | - if speech::available().is_err() { | |
| 119 | + if speech::available(speech::Device::Cpu).is_err() { | |
| 120 | 120 | eprintln!("skipped: edith-stt or its model is not installed"); |
| 121 | 121 | return; |
| 122 | 122 | } |
| @@ -124,8 +124,8 @@ fn listening_to_the_timeline_finds_the_words_when_speech_is_installed() { | ||
| 124 | 124 | // words (or a silent mix), never crash or hang. |
| 125 | 125 | let s = PlaybackSession::open(asset("test_av.mp4")).expect("open"); |
| 126 | 126 | let job = speech::Job::default(); |
| 127 | - let model = speech::installed_models()[0]; | |
| 128 | - match speech::transcribe(&s, speech::Hear::Mix, model, "en", false, &job) { | |
| 127 | + let model = speech::installed_models(speech::Device::Cpu)[0]; | |
| 128 | + match speech::transcribe(&s, speech::Hear::Mix, model, speech::Device::Cpu, "en", false, &job) { | |
| 129 | 129 | Ok(words) => assert!(words.len() < 20, "a tone is not a speech: {words:?}"), |
| 130 | 130 | Err(e) => assert!(!e.is_empty()), |
| 131 | 131 | } |
crates/mcp/src/help.rsmodified+2 -2
| @@ -360,12 +360,12 @@ PROJECT | ||
| 360 | 360 | 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. |
| 361 | 361 | 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. |
| 362 | 362 | proxies {action:status|make|cancel|delete, source} manages editing copies: make starts one in the background (its progress shows in status), cancel stops it and leaves the film off, delete removes it and keeps the film off. With auto_proxies on, each media_import starts its stand-ins. |
| 363 | - speech_model {download?, model?, cancel?} shows the speech models installed and any download in progress; download:true fetches one in the background (base by default). | |
| 363 | + speech_model {download?, model?, device?, cancel?} shows the speech models installed per device (cpu, gpu) and any download in progress; download:true fetches one in the background (base by default). | |
| 364 | 364 | 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. |
| 365 | 365 | render_preview {clear:true} deletes every render file in the cache (refused while a render runs). |
| 366 | 366 | project_status reports the open project. project_settings sets resolution, fps, tonemap, proxies, |
| 367 | 367 | auto_proxies, encoder, the master limiter, the notes (free text, several lines, shown by project_status when set) and the still length |
| 368 | - (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it). Each change and each refusal is reported. | |
| 368 | + (still_secs, 0.5 to 600 s, 5 by default: stills placed after the change take it), the speech model and device (speech_model, speech_device auto|cpu|gpu). Each change and each refusal is reported. | |
| 369 | 369 | 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. |
| 370 | 370 | 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). |
| 371 | 371 | templates {save:{name, with_clips?}} saves the open project as a template (settings, and the clips too with with_clips:true); a built-in's name is refused. |
crates/mcp/src/tools/listen.rsmodified+125 -72
| @@ -19,7 +19,7 @@ use std::time::{Duration, UNIX_EPOCH}; | ||
| 19 | 19 | |
| 20 | 20 | use engine::export::{ExportSettings, Format}; |
| 21 | 21 | use engine::project::{Lane, LaneKind, Speed, SpeedRamp}; |
| 22 | -use engine::speech::{CAPTION_FILLERS, CAPTION_GAP_SECS, CUE_LOW_P, CUE_MIN_SECS, FILLER_PROMPT, MODELS, RATE, RawWord, attach_word_times, caption_cues, capitalise_sentence_starts, check_lang, check_model, home, i16_bytes, norm, parse_raw, pick_model, resample_linear, speaker_changes, stt_bin, wav_bytes}; | |
| 22 | +use engine::speech::{CAPTION_FILLERS, CAPTION_GAP_SECS, CUE_LOW_P, CUE_MIN_SECS, Device, DeviceChoice, FILLER_PROMPT, MODELS, RATE, RawWord, attach_word_times, caption_cues, capitalise_sentence_starts, check_lang, check_model, gpu_available, home, i16_bytes, installed_models, norm, parse_raw, plan, resample_linear, speaker_changes, stt_bin, wav_bytes}; | |
| 23 | 23 | use engine::{AudioSession, Clip, PlaybackSession, subtitle}; |
| 24 | 24 | use serde_json::{Value, json}; |
| 25 | 25 | |
| @@ -78,8 +78,8 @@ Silent and hallucinated windows are dropped by edith-stt before they reach this | ||
| 78 | 78 | 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 \ |
| 79 | 79 | 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 \ |
| 80 | 80 | cached per source file, model, language and prompt (the hint and any filler prompt); a range an earlier run covered is served from that run, so a repeat, or a call after cuts, is instant. A first run on long audio takes minutes (progress goes to stderr). \ |
| 81 | -Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, or EDITH_STT_BIN) and the model under \ | |
| 82 | -~/.cache/edith/models/whisper-<size>."; | |
| 81 | +Needs edith-stt built (`cd tools/edith-stt && cargo build --release`, `--features vulkan` for the GPU, or EDITH_STT_BIN) and the model under \ | |
| 82 | +~/.cache/edith/models (whisper-<size> for device cpu, ggml-<size>.bin for gpu)."; | |
| 83 | 83 | |
| 84 | 84 | const FIND_DOC: &str = "Find a phrase (case-insensitive, punctuation ignored) in the transcript of a target. Each match is numbered \ |
| 85 | 85 | (#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 { | ||
| 129 | 129 | json!({ |
| 130 | 130 | "type": "string", |
| 131 | 131 | "enum": MODELS, |
| 132 | - "description": "Whisper model size. Default base, or the first installed of base, small, tiny; tiny is fastest and roughest." | |
| 132 | + "description": "Whisper model size: tiny, base, small, medium, large-v3, large-v3-turbo. Default: the project's speech_model, else the first installed one for the device." | |
| 133 | + }) | |
| 134 | +} | |
| 135 | + | |
| 136 | +fn device_prop() -> Value { | |
| 137 | + json!({ | |
| 138 | + "type": "string", | |
| 139 | + "enum": ["auto", "cpu", "gpu"], | |
| 140 | + "description": "Where the model runs: cpu, gpu (needs a usable GPU and the ggml model file), or auto (gpu when usable and that model is installed, else cpu). Default: the project's speech_device, else auto." | |
| 133 | 141 | }) |
| 134 | 142 | } |
| 135 | 143 | |
| @@ -147,6 +155,7 @@ fn transcript_schema() -> Value { | ||
| 147 | 155 | "target": target_prop(), |
| 148 | 156 | "range": range_prop(), |
| 149 | 157 | "model": model_prop(), |
| 158 | + "device": device_prop(), | |
| 150 | 159 | "language": language_prop(), |
| 151 | 160 | "hint": hint_prop(), |
| 152 | 161 | "words": {"type": "boolean", "description": "List the words of each segment too. Default false."}, |
| @@ -164,6 +173,7 @@ fn find_schema() -> Value { | ||
| 164 | 173 | "query": {"type": "string", "description": "The phrase to find, e.g. \"brown fox\"."}, |
| 165 | 174 | "target": target_prop(), |
| 166 | 175 | "model": model_prop(), |
| 176 | + "device": device_prop(), | |
| 167 | 177 | "language": language_prop(), |
| 168 | 178 | "hint": hint_prop(), |
| 169 | 179 | "cut": { |
| @@ -205,6 +215,7 @@ fn captions_schema() -> Value { | ||
| 205 | 215 | "properties": { |
| 206 | 216 | "target": target_prop(), |
| 207 | 217 | "model": model_prop(), |
| 218 | + "device": device_prop(), | |
| 208 | 219 | "language": language_prop(), |
| 209 | 220 | "hint": hint_prop(), |
| 210 | 221 | "lane": {"type": "string", "description": "Caption lane (S1, S2 ...) to place the track on. Default S1. A media lane such as A1 is refused: captions go on a caption lane."}, |
| @@ -229,11 +240,12 @@ pub fn tools() -> Vec<Tool> { | ||
| 229 | 240 | |
| 230 | 241 | // ---- speech model ---------------------------------------------------------- |
| 231 | 242 | |
| 232 | -const SPEECH_MODEL_DOC: &str = "The speech model that transcript, find_words and auto_captions run on: which are installed, and the download in progress. With no argument it is the status. download:true fetches a model in the background (model is tiny, base or small; default base, the one the GUI's Download model fetches from huggingface.co); the status shows its percent until it is installed, and a download that fails says why. cancel:true stops the download running now and keeps the files already fetched for the next try. Nothing is downloaded unless download is true."; | |
| 243 | +const SPEECH_MODEL_DOC: &str = "The speech models that transcript, find_words and auto_captions run on, per device (cpu, or gpu when edith-stt has a usable GPU): which are installed, and the download in progress. With no argument it is the status. download:true fetches a model in the background (model default base; device default the one auto picks: gpu when usable, else cpu); the status shows its percent until it is installed, and a download that fails says why. cancel:true stops the download running now and keeps the files already fetched for the next try. Nothing is downloaded unless download is true."; | |
| 233 | 244 | |
| 234 | 245 | /// A speech model download running in the background, and how it ended once it has. |
| 235 | 246 | pub struct SpeechDownload { |
| 236 | 247 | pub model: String, |
| 248 | + pub device: Device, | |
| 237 | 249 | pub job: std::sync::Arc<engine::speech::Job>, |
| 238 | 250 | pub handle: Option<std::thread::JoinHandle<Result<(), String>>>, |
| 239 | 251 | pub outcome: Option<String>, |
| @@ -244,7 +256,8 @@ fn speech_model_schema() -> Value { | ||
| 244 | 256 | "type": "object", |
| 245 | 257 | "properties": { |
| 246 | 258 | "download": {"type": "boolean", "description": "true starts downloading the model in the background."}, |
| 247 | - "model": {"type": "string", "enum": ["tiny", "base", "small"], "description": "The model to download. Default base."}, | |
| 259 | + "model": {"type": "string", "enum": MODELS, "description": "The model to download. Default base."}, | |
| 260 | + "device": device_prop(), | |
| 248 | 261 | "cancel": {"type": "boolean", "description": "true stops the download running now."} |
| 249 | 262 | }, |
| 250 | 263 | "additionalProperties": false |
| @@ -286,28 +299,41 @@ fn speech_model(srv: &mut Server, args: &Value) -> Reply { | ||
| 286 | 299 | if !MODELS.contains(&model) { |
| 287 | 300 | return Reply::err(format!("model `{model}` is not one of {}", MODELS.join(", "))); |
| 288 | 301 | } |
| 289 | - if engine::speech::installed_models().contains(&model) { | |
| 290 | - return Reply::ok(format!("the {model} speech model is already installed")); | |
| 302 | + let choice = match device_arg(args) { | |
| 303 | + Ok(c) => c.unwrap_or_else(|| project_choice(srv)), | |
| 304 | + Err(e) => return Reply::err(e), | |
| 305 | + }; | |
| 306 | + let device = download_device(choice); | |
| 307 | + if installed_models(device).contains(&model) { | |
| 308 | + return Reply::ok(format!("the {model} speech model ({}) is already installed", device.flag())); | |
| 291 | 309 | } |
| 292 | - // The same call the GUI's Download model makes, on a thread of its own. | |
| 293 | 310 | let job = std::sync::Arc::new(engine::speech::Job::default()); |
| 294 | 311 | let worker = job.clone(); |
| 295 | 312 | let name = model.to_string(); |
| 296 | 313 | let thread_name = name.clone(); |
| 297 | - let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, &worker)); | |
| 298 | - srv.speech_download = Some(SpeechDownload { model: name, job, handle: Some(handle), outcome: None }); | |
| 299 | - return Reply::ok(format!("downloading the {model} speech model in the background; speech_model shows the progress")); | |
| 300 | - } | |
| 301 | - let installed = engine::speech::installed_models(); | |
| 302 | - let have = if installed.is_empty() { "none installed".to_string() } else { format!("installed: {}", installed.join(", ")) }; | |
| 314 | + let handle = std::thread::spawn(move || engine::speech::download_model(&thread_name, device, &worker)); | |
| 315 | + srv.speech_download = Some(SpeechDownload { model: name, device, job, handle: Some(handle), outcome: None }); | |
| 316 | + return Reply::ok(format!("downloading the {model} ({}) speech model in the background; speech_model shows the progress", device.flag())); | |
| 317 | + } | |
| 318 | + let cpu = installed_models(Device::Cpu); | |
| 319 | + let gpu = installed_models(Device::Gpu); | |
| 320 | + let list = |v: &[&str]| if v.is_empty() { "none".to_string() } else { v.join(", ") }; | |
| 321 | + let usable = gpu_available(); | |
| 303 | 322 | let state = match srv.speech_download.as_ref() { |
| 304 | - Some(d) if running => format!("downloading {} {:.0}%", d.model, d.job.fraction() * 100.0), | |
| 323 | + Some(d) if running => format!("downloading {} ({}) {:.0}%", d.model, d.device.flag(), d.job.fraction() * 100.0), | |
| 305 | 324 | Some(d) => d.outcome.clone().unwrap_or_default(), |
| 306 | 325 | None => "no download started".to_string(), |
| 307 | 326 | }; |
| 308 | - let text = format!("speech models: {have} (offered: {}); {state}", MODELS.join(", ")); | |
| 327 | + let text = format!( | |
| 328 | + "speech models: cpu: {}; gpu: {} (gpu {}); offered: {}; {state}", | |
| 329 | + list(&cpu), | |
| 330 | + list(&gpu), | |
| 331 | + if usable { "usable" } else { "not usable" }, | |
| 332 | + MODELS.join(", ") | |
| 333 | + ); | |
| 309 | 334 | Reply::ok(text).with(json!({ |
| 310 | - "installed": installed, | |
| 335 | + "installed": {"cpu": cpu, "gpu": gpu}, | |
| 336 | + "gpu_available": usable, | |
| 311 | 337 | "offered": MODELS, |
| 312 | 338 | "downloading": running, |
| 313 | 339 | "progress": srv.speech_download.as_ref().filter(|_| running).map(|d| d.job.fraction()), |
| @@ -659,20 +685,23 @@ fn fnv1a(bytes: &[u8]) -> u64 { | ||
| 659 | 685 | /// The cache directory name of one source's transcription: file identity (path, mtime, length), |
| 660 | 686 | /// the stream, and the model, language and prompt that heard it. `file` is (mtime in ns, length |
| 661 | 687 | /// in bytes). The source range is not part of it: each range is an entry inside the directory. |
| 662 | -fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, lang: &str, hint: &str) -> String { | |
| 688 | +fn cache_key(path: &str, file: (u128, u64), stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> String { | |
| 663 | 689 | let (mtime_ns, len) = file; |
| 664 | - let text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}"); | |
| 690 | + let mut text = format!("v{CACHE_VERSION}|{path}|{mtime_ns}|{len}|{stream}|{model}|{lang}|{hint}"); | |
| 691 | + if device == Device::Gpu { | |
| 692 | + text.push_str("|gpu"); | |
| 693 | + } | |
| 665 | 694 | format!("{:016x}", fnv1a(text.as_bytes())) |
| 666 | 695 | } |
| 667 | 696 | |
| 668 | -fn source_key(path: &Path, stream: usize, model: &str, lang: &str, hint: &str) -> Option<String> { | |
| 697 | +fn source_key(path: &Path, stream: usize, model: &str, device: Device, lang: &str, hint: &str) -> Option<String> { | |
| 669 | 698 | let meta = fs::metadata(path).ok()?; |
| 670 | 699 | let mtime = meta |
| 671 | 700 | .modified() |
| 672 | 701 | .ok() |
| 673 | 702 | .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) |
| 674 | 703 | .map_or(0, |d| d.as_nanos()); |
| 675 | - Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, lang, hint)) | |
| 704 | + Some(cache_key(&path.display().to_string(), (mtime, meta.len()), stream, model, device, lang, hint)) | |
| 676 | 705 | } |
| 677 | 706 | |
| 678 | 707 | fn cache_dir() -> PathBuf { |
| @@ -716,19 +745,40 @@ fn write_entry(dir: &Path, from: f64, to: f64, raw: &str) { | ||
| 716 | 745 | } |
| 717 | 746 | } |
| 718 | 747 | |
| 719 | -fn model_arg(args: &Value) -> Result<String, String> { | |
| 720 | - match opt_str(args, "model") { | |
| 721 | - Some(m) => { | |
| 722 | - let m = m.trim().to_ascii_lowercase(); | |
| 723 | - check_model(&m)?; | |
| 724 | - Ok(m) | |
| 725 | - } | |
| 726 | - None => pick_model(|m| check_model(m).is_ok()) | |
| 727 | - .map(str::to_string) | |
| 728 | - .ok_or_else(|| "no whisper model is installed: install base (or small or tiny) under ~/.cache/edith/models".into()), | |
| 748 | +fn device_arg(args: &Value) -> Result<Option<DeviceChoice>, String> { | |
| 749 | + match opt_str(args, "device") { | |
| 750 | + None => Ok(None), | |
| 751 | + Some(d) => DeviceChoice::parse(d.trim()).map(Some).ok_or_else(|| format!("device `{d}` is not auto, cpu or gpu")), | |
| 729 | 752 | } |
| 730 | 753 | } |
| 731 | 754 | |
| 755 | +/// The device a download fetches for when none is named: the GPU when edith-stt has one, else the CPU. | |
| 756 | +fn download_device(choice: DeviceChoice) -> Device { | |
| 757 | + match choice { | |
| 758 | + DeviceChoice::Auto if gpu_available() => Device::Gpu, | |
| 759 | + DeviceChoice::Auto | DeviceChoice::Cpu => Device::Cpu, | |
| 760 | + DeviceChoice::Gpu => Device::Gpu, | |
| 761 | + } | |
| 762 | +} | |
| 763 | + | |
| 764 | +fn project_choice(srv: &Server) -> DeviceChoice { | |
| 765 | + srv.session.as_ref().map_or(DeviceChoice::Auto, |s| s.speech_device()) | |
| 766 | +} | |
| 767 | + | |
| 768 | +/// The model and device a call runs on: the `model` and `device` args, else the project's | |
| 769 | +/// `speech_model` and `speech_device`, else the picked model and the auto device. | |
| 770 | +fn model_arg(args: &Value, s: &PlaybackSession) -> Result<(String, Device), String> { | |
| 771 | + let choice = device_arg(args)?.unwrap_or_else(|| s.speech_device()); | |
| 772 | + let named = match opt_str(args, "model") { | |
| 773 | + Some(m) => Some(m.trim().to_ascii_lowercase()), | |
| 774 | + None => s.speech_model().map(str::to_string), | |
| 775 | + }; | |
| 776 | + let (model, device) = plan(choice, named.as_deref()) | |
| 777 | + .ok_or_else(|| "no whisper model is installed for this device: install one with speech_model download".to_string())?; | |
| 778 | + check_model(&model, device)?; | |
| 779 | + Ok((model, device)) | |
| 780 | +} | |
| 781 | + | |
| 732 | 782 | /// `hint`: names and jargon as they should come out, handed to edith-stt as its prompt. |
| 733 | 783 | fn hint_arg(args: &Value) -> Result<String, String> { |
| 734 | 784 | let h = opt_str(args, "hint").unwrap_or("").trim().to_string(); |
| @@ -979,8 +1029,8 @@ impl Drop for TempFile { | ||
| 979 | 1029 | |
| 980 | 1030 | /// Runs edith-stt on one WAV (see [`engine::speech::run_stt`]); this server has no progress line |
| 981 | 1031 | /// and nobody to cancel it. |
| 982 | -fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str) -> Result<String, String> { | |
| 983 | - engine::speech::run_stt(bin, wav, model, lang, hint, offset, label, &engine::speech::Job::default()) | |
| 1032 | +fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str) -> Result<String, String> { | |
| 1033 | + engine::speech::run_stt(bin, wav, model, device, lang, hint, offset, label, &engine::speech::Job::default()) | |
| 984 | 1034 | } |
| 985 | 1035 | |
| 986 | 1036 | fn temp_path(tag: &str, ext: &str) -> PathBuf { |
| @@ -1215,8 +1265,8 @@ fn review_text(segs: &[&Seg], fps: f64) -> String { | ||
| 1215 | 1265 | |
| 1216 | 1266 | /// Transcribes one piece, through the cache when it can: a cache entry for exactly this range |
| 1217 | 1267 | /// serves it, and a new run is stored under that range. The output depends only on the piece. |
| 1218 | -fn run_piece(bin: &Path, p: &Piece, model: &str, lang: &str, hint: &str, fps: f64) -> Result<Vec<Seg>, String> { | |
| 1219 | - let known = if p.mix { None } else { source_key(&p.path, p.stream, model, lang, hint) }; | |
| 1268 | +fn run_piece(bin: &Path, p: &Piece, model: &str, device: Device, lang: &str, hint: &str, fps: f64) -> Result<Vec<Seg>, String> { | |
| 1269 | + let known = if p.mix { None } else { source_key(&p.path, p.stream, model, device, lang, hint) }; | |
| 1220 | 1270 | let cached = |dir: &Path| read_exact(dir, p.from, p.to); |
| 1221 | 1271 | if let Some(raw) = known.as_deref().and_then(|k| cached(&cache_dir().join(k))) { |
| 1222 | 1272 | 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 | ||
| 1230 | 1280 | } |
| 1231 | 1281 | let key = known.unwrap_or_else(|| { |
| 1232 | 1282 | let bytes = i16_bytes(&samples); |
| 1233 | - cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, lang, hint) | |
| 1283 | + cache_key(&format!("content:{:016x}", fnv1a(&bytes)), (0, bytes.len() as u64), 0, model, device, lang, hint) | |
| 1234 | 1284 | }); |
| 1235 | 1285 | let dir = cache_dir().join(&key); |
| 1236 | 1286 | 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 | ||
| 1240 | 1290 | let wav = TempFile(temp_path("stt", "wav")); |
| 1241 | 1291 | // `wav` is removed when this function returns, on success and on every error path. |
| 1242 | 1292 | fs::write(&wav.0, wav_bytes(&samples)).map_err(|e| temp_write_error(&wav.0, "writing", e))?; |
| 1243 | - let raw = run_stt(bin, &wav.0, model, lang, hint, p.from, &p.label)?; | |
| 1293 | + let raw = run_stt(bin, &wav.0, model, device, lang, hint, p.from, &p.label)?; | |
| 1244 | 1294 | let segs = parse_raw(&raw)?.len(); |
| 1245 | 1295 | write_entry(&dir, p.from, p.to, &raw); |
| 1246 | 1296 | // 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> | ||
| 1306 | 1356 | |
| 1307 | 1357 | /// The transcript of source `n` in its own frames: what `transcribe` does for a source with no |
| 1308 | 1358 | /// clip, whether or not the timeline plays it. |
| 1359 | +#[allow(clippy::too_many_arguments)] | |
| 1309 | 1360 | fn transcribe_source( |
| 1310 | 1361 | s: &PlaybackSession, |
| 1311 | 1362 | n: usize, |
| 1312 | 1363 | range: Option<(u32, u32)>, |
| 1313 | 1364 | model: &str, |
| 1365 | + device: Device, | |
| 1314 | 1366 | lang: &str, |
| 1315 | 1367 | hint: &str, |
| 1316 | 1368 | fps: f64, |
| 1317 | 1369 | ) -> Result<Transcript, String> { |
| 1318 | 1370 | let bin = stt_bin()?; |
| 1319 | - check_model(model)?; | |
| 1320 | - let mut segs = source_segs(s, n, range, &bin, model, lang, hint, fps)?; | |
| 1371 | + check_model(model, device)?; | |
| 1372 | + let mut segs = source_segs(s, n, range, &bin, model, device, lang, hint, fps)?; | |
| 1321 | 1373 | segs.sort_by_key(|g| (g.start_f, g.end_f)); |
| 1322 | 1374 | let mut segs = drop_overlap_repeats(segs); |
| 1323 | 1375 | let corrections = correct_hints(&mut segs, hint); |
| @@ -1337,10 +1389,10 @@ fn source_clips_note(n: usize, clips: &[(Lane, Clip)], fps: f64) -> String { | ||
| 1337 | 1389 | format!("\nsrc:{n} times are the file's own clock; used by {}", used.join(", ")) |
| 1338 | 1390 | } |
| 1339 | 1391 | |
| 1340 | -fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, lang: &str, hint: &str) -> Result<Transcript, String> { | |
| 1392 | +fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: &str, device: Device, lang: &str, hint: &str) -> Result<Transcript, String> { | |
| 1341 | 1393 | let fps = parse::session_fps(s); |
| 1342 | 1394 | let bin = stt_bin()?; |
| 1343 | - check_model(model)?; | |
| 1395 | + check_model(model, device)?; | |
| 1344 | 1396 | let mut segs = Vec::new(); |
| 1345 | 1397 | let mut gaps = Vec::new(); |
| 1346 | 1398 | let pad = (WINDOW_SECS * fps).round() as u32; |
| @@ -1360,7 +1412,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: | ||
| 1360 | 1412 | map: Map::Mix, |
| 1361 | 1413 | mix: true, |
| 1362 | 1414 | }; |
| 1363 | - segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?); | |
| 1415 | + segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?); | |
| 1364 | 1416 | // Audible sound the model returned no words for: reported, not hidden. |
| 1365 | 1417 | if let Ok(Some(samples)) = decode_16k(&wav.0, 0, f64::from(lo) / fps, f64::from(hi) / fps) { |
| 1366 | 1418 | gaps = coverage_gaps(&samples, lo, fps, &segs); |
| @@ -1372,7 +1424,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: | ||
| 1372 | 1424 | }; |
| 1373 | 1425 | let clips = clips_of(s, want); |
| 1374 | 1426 | if let (true, Some(n)) = (clips.is_empty(), source) { |
| 1375 | - segs.extend(source_segs(s, n, range, &bin, model, lang, hint, fps)?); | |
| 1427 | + segs.extend(source_segs(s, n, range, &bin, model, device, lang, hint, fps)?); | |
| 1376 | 1428 | } |
| 1377 | 1429 | for (lane, clip) in clips { |
| 1378 | 1430 | let Some(src) = s.sources().get(clip.source) else { |
| @@ -1396,7 +1448,7 @@ fn transcribe(s: &PlaybackSession, want: Want, range: Option<(u32, u32)>, model: | ||
| 1396 | 1448 | map: Map::of(&clip), |
| 1397 | 1449 | mix: false, |
| 1398 | 1450 | }; |
| 1399 | - segs.extend(run_piece(&bin, &piece, model, lang, hint, fps)?); | |
| 1451 | + segs.extend(run_piece(&bin, &piece, model, device, lang, hint, fps)?); | |
| 1400 | 1452 | } |
| 1401 | 1453 | } |
| 1402 | 1454 | segs.sort_by_key(|g| (g.start_f, g.end_f)); |
| @@ -1424,6 +1476,7 @@ fn source_segs( | ||
| 1424 | 1476 | range: Option<(u32, u32)>, |
| 1425 | 1477 | bin: &Path, |
| 1426 | 1478 | model: &str, |
| 1479 | + device: Device, | |
| 1427 | 1480 | lang: &str, |
| 1428 | 1481 | hint: &str, |
| 1429 | 1482 | fps: f64, |
| @@ -1446,7 +1499,7 @@ fn source_segs( | ||
| 1446 | 1499 | map: Map::Clip { start: 0, in_frame: 0, speed: Speed::NORMAL }, |
| 1447 | 1500 | mix: false, |
| 1448 | 1501 | }; |
| 1449 | - run_piece(bin, &piece, model, lang, hint, fps) | |
| 1502 | + run_piece(bin, &piece, model, device, lang, hint, fps) | |
| 1450 | 1503 | } |
| 1451 | 1504 | |
| 1452 | 1505 | /// `mm:ss.mmm` for a timeline frame. |
| @@ -1542,7 +1595,7 @@ fn transcript_run(srv: &Server, args: &Value) -> Result<Reply, String> { | ||
| 1542 | 1595 | }; |
| 1543 | 1596 | let range = range_arg(args, fps, end)?; |
| 1544 | 1597 | check_sources_online(s, &want)?; |
| 1545 | - let model = model_arg(args)?; | |
| 1598 | + let (model, device) = model_arg(args, s)?; | |
| 1546 | 1599 | let lang = language_arg(args)?; |
| 1547 | 1600 | let hint = with_fillers(&hint_arg(args)?, opt_bool(args, "fillers").unwrap_or(false)); |
| 1548 | 1601 | let from = parse::opt_frame_arg(args, "from", fps, end).map_err(|r| r.text)?.unwrap_or(0); |
| @@ -1555,8 +1608,8 @@ fn transcript_run(srv: &Server, args: &Value) -> Result<Reply, String> { | ||
| 1555 | 1608 | _ => None, |
| 1556 | 1609 | }; |
| 1557 | 1610 | let t = match &want { |
| 1558 | - Want::Source(n) => transcribe_source(s, *n, range, &model, &lang, &hint, fps)?, | |
| 1559 | - _ => transcribe(s, want, range, &model, &lang, &hint)?, | |
| 1611 | + Want::Source(n) => transcribe_source(s, *n, range, &model, device, &lang, &hint, fps)?, | |
| 1612 | + _ => transcribe(s, want, range, &model, device, &lang, &hint)?, | |
| 1560 | 1613 | }; |
| 1561 | 1614 | let (body, shown, next) = page(&t, from, words); |
| 1562 | 1615 | let mut text = transcript_text(&label, &model, &lang, from, &body, &shown, next); |
| @@ -2130,12 +2183,12 @@ fn find_run(srv: &mut Server, args: &Value) -> Result<Reply, String> { | ||
| 2130 | 2183 | // gap beside a clip, which the ripple would close and shift the clip by. |
| 2131 | 2184 | let clips = clip_intervals(s, &scope); |
| 2132 | 2185 | check_sources_online(s, &want)?; |
| 2133 | - let model = model_arg(args)?; | |
| 2186 | + let (model, device) = model_arg(args, s)?; | |
| 2134 | 2187 | let lang = language_arg(args)?; |
| 2135 | 2188 | let fillers = is_filler_query(&qwords); |
| 2136 | 2189 | let hint = with_fillers(&hint_arg(args)?, fillers); |
| 2137 | 2190 | let label = want_label(s, &want); |
| 2138 | - let t = transcribe(s, want, None, &model, &lang, &hint)?; | |
| 2191 | + let t = transcribe(s, want, None, &model, device, &lang, &hint)?; | |
| 2139 | 2192 | let mut flat: Vec<(&Seg, &Word)> = t.segs.iter().flat_map(|g| g.words.iter().map(move |w| (g, w))).collect(); |
| 2140 | 2193 | flat.sort_by_key(|(_, w)| w.start_f); |
| 2141 | 2194 | let norms: Vec<String> = flat.iter().map(|(_, w)| norm(&w.w)).collect(); |
| @@ -2826,12 +2879,12 @@ fn cue_names(cues: &[subtitle::Cue]) -> String { | ||
| 2826 | 2879 | } |
| 2827 | 2880 | |
| 2828 | 2881 | fn captions_run(srv: &mut Server, args: &Value) -> Result<Reply, String> { |
| 2829 | - let (fps, want, model, lang, hint, label, lane, max_chars, max_secs, out, speakers) = { | |
| 2882 | + let (fps, want, model, device, lang, hint, label, lane, max_chars, max_secs, out, speakers) = { | |
| 2830 | 2883 | let s = session(srv)?; |
| 2831 | 2884 | let fps = parse::session_fps(s); |
| 2832 | 2885 | let want = want_arg(s, args)?; |
| 2833 | 2886 | check_sources_online(s, &want)?; |
| 2834 | - let model = model_arg(args)?; | |
| 2887 | + let (model, device) = model_arg(args, s)?; | |
| 2835 | 2888 | let lang = language_arg(args)?; |
| 2836 | 2889 | let hint = hint_arg(args)?; |
| 2837 | 2890 | let label = want_label(s, &want); |
| @@ -2866,11 +2919,11 @@ fn captions_run(srv: &mut Server, args: &Value) -> Result<Reply, String> { | ||
| 2866 | 2919 | None => free_caption_path(s, std::env::temp_dir().join(format!("edith-captions-{}.srt", std::process::id()))), |
| 2867 | 2920 | }, |
| 2868 | 2921 | }; |
| 2869 | - (fps, want, model, lang, hint, label, lane_name, max_chars, max_secs, out, speakers) | |
| 2922 | + (fps, want, model, device, lang, hint, label, lane_name, max_chars, max_secs, out, speakers) | |
| 2870 | 2923 | }; |
| 2871 | 2924 | let is_mix = matches!(want, Want::Mix); |
| 2872 | 2925 | let replace = opt_bool(args, "replace").unwrap_or(false); |
| 2873 | - let t = transcribe(session(srv)?, want.clone(), None, &model, &lang, &hint)?; | |
| 2926 | + let t = transcribe(session(srv)?, want.clone(), None, &model, device, &lang, &hint)?; | |
| 2874 | 2927 | let s = session(srv)?; |
| 2875 | 2928 | // Captions carry the words people say: disfluencies are left out, even when the |
| 2876 | 2929 | // transcript kept them (a hint or the default model can still hear an "um"). |
| @@ -3640,20 +3693,20 @@ mod tests { | ||
| 3640 | 3693 | |
| 3641 | 3694 | #[test] |
| 3642 | 3695 | fn cache_key_follows_every_input() { |
| 3643 | - let base = cache_key("/a.mp4", (7, 100), 0, "small", "auto", ""); | |
| 3644 | - assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", "")); | |
| 3645 | - assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", "auto", "")); | |
| 3646 | - assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", "auto", "")); | |
| 3647 | - assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", "auto", "")); | |
| 3648 | - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", "auto", "")); | |
| 3649 | - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "en", "")); | |
| 3650 | - assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", "auto", "Edith, LUFS")); | |
| 3696 | + let base = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", ""); | |
| 3697 | + assert_eq!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "")); | |
| 3698 | + assert_ne!(base, cache_key("/a.mp4", (8, 100), 0, "small", Device::Cpu, "auto", "")); | |
| 3699 | + assert_ne!(base, cache_key("/a.mp4", (7, 101), 0, "small", Device::Cpu, "auto", "")); | |
| 3700 | + assert_ne!(base, cache_key("/a.mp4", (7, 100), 1, "small", Device::Cpu, "auto", "")); | |
| 3701 | + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "tiny", Device::Cpu, "auto", "")); | |
| 3702 | + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "en", "")); | |
| 3703 | + assert_ne!(base, cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", "Edith, LUFS")); | |
| 3651 | 3704 | assert_eq!(base.len(), 16); |
| 3652 | 3705 | } |
| 3653 | 3706 | |
| 3654 | 3707 | #[test] |
| 3655 | 3708 | fn cache_key_is_versioned_so_older_results_are_not_reused() { |
| 3656 | - let k = cache_key("/a.mp4", (7, 100), 0, "small", "auto", ""); | |
| 3709 | + let k = cache_key("/a.mp4", (7, 100), 0, "small", Device::Cpu, "auto", ""); | |
| 3657 | 3710 | let v5 = format!("{:016x}", fnv1a(b"v5|/a.mp4|7|100|0|small|auto|")); |
| 3658 | 3711 | assert_ne!(k, v5); |
| 3659 | 3712 | assert_eq!(CACHE_VERSION, 9); |
| @@ -4001,7 +4054,7 @@ mod tests { | ||
| 4001 | 4054 | eprintln!("skipping speech_round_trip: {e}"); |
| 4002 | 4055 | return; |
| 4003 | 4056 | } |
| 4004 | - if check_model("tiny").is_err() { | |
| 4057 | + if check_model("tiny", Device::Cpu).is_err() { | |
| 4005 | 4058 | eprintln!("skipping speech_round_trip: the tiny model is not installed"); |
| 4006 | 4059 | return; |
| 4007 | 4060 | } |
| @@ -4099,7 +4152,7 @@ mod tests { | ||
| 4099 | 4152 | |
| 4100 | 4153 | #[test] |
| 4101 | 4154 | fn find_cut_removes_the_matched_word_and_undo_restores_it() { |
| 4102 | - if stt_bin().is_err() || check_model("tiny").is_err() { | |
| 4155 | + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { | |
| 4103 | 4156 | eprintln!("skipping find_cut_removes_the_matched_word_and_undo_restores_it: edith-stt or the tiny model is missing"); |
| 4104 | 4157 | return; |
| 4105 | 4158 | } |
| @@ -4282,7 +4335,7 @@ mod tests { | ||
| 4282 | 4335 | /// left in place. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing. |
| 4283 | 4336 | #[test] |
| 4284 | 4337 | fn find_cut_with_which_names_the_kept_match_and_the_lane_left_in_place() { |
| 4285 | - if stt_bin().is_err() || check_model("tiny").is_err() { | |
| 4338 | + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { | |
| 4286 | 4339 | eprintln!("skipping find_cut_with_which_names_the_kept_match: edith-stt or the tiny model is missing"); |
| 4287 | 4340 | return; |
| 4288 | 4341 | } |
| @@ -4357,7 +4410,7 @@ mod tests { | ||
| 4357 | 4410 | /// silence. Skipped, with the reason printed, when edith-stt, the tiny model or espeak-ng is missing. |
| 4358 | 4411 | #[test] |
| 4359 | 4412 | fn unplaced_source_is_heard_as_its_own_file() { |
| 4360 | - if stt_bin().is_err() || check_model("tiny").is_err() { | |
| 4413 | + if stt_bin().is_err() || check_model("tiny", Device::Cpu).is_err() { | |
| 4361 | 4414 | eprintln!("skipping unplaced_source_is_heard_as_its_own_file: edith-stt or the tiny model is missing"); |
| 4362 | 4415 | return; |
| 4363 | 4416 | } |
| @@ -4585,10 +4638,10 @@ mod tests { | ||
| 4585 | 4638 | |
| 4586 | 4639 | #[test] |
| 4587 | 4640 | fn default_model_is_base_then_small_then_tiny() { |
| 4588 | - assert_eq!(pick_model(|_| true), Some("base")); | |
| 4589 | - assert_eq!(pick_model(|m| m != "base"), Some("small")); | |
| 4590 | - assert_eq!(pick_model(|m| m == "tiny"), Some("tiny")); | |
| 4591 | - assert_eq!(pick_model(|_| false), None); | |
| 4641 | + assert_eq!(engine::speech::pick_model(|_| true, Device::Cpu), Some("base")); | |
| 4642 | + assert_eq!(engine::speech::pick_model(|m| m != "base", Device::Cpu), Some("small")); | |
| 4643 | + assert_eq!(engine::speech::pick_model(|m| m == "tiny", Device::Cpu), Some("tiny")); | |
| 4644 | + assert_eq!(engine::speech::pick_model(|_| false, Device::Cpu), None); | |
| 4592 | 4645 | } |
| 4593 | 4646 | |
| 4594 | 4647 | #[test] |
crates/mcp/src/tools/project.rsmodified+47 -2
| @@ -12,6 +12,7 @@ use std::time::{Duration, SystemTime}; | ||
| 12 | 12 | |
| 13 | 13 | use engine::limiter::Limiter; |
| 14 | 14 | use engine::project::{Lane, LaneKind, Rate, STILL_MAX_SECS, STILL_MIN_SECS}; |
| 15 | +use engine::speech::{DeviceChoice, MODELS}; | |
| 15 | 16 | use engine::tonemap::Preset; |
| 16 | 17 | use engine::export::EncoderSeat; |
| 17 | 18 | use engine::PlaybackSession; |
| @@ -160,6 +161,8 @@ pub fn tools() -> Vec<Tool> { | ||
| 160 | 161 | "tonemap": {"type": "string", "enum": ["reference", "standard", "vivid"], "description": "HDR to SDR rendition."}, |
| 161 | 162 | "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."}, |
| 162 | 163 | "still_secs": {"type": "number", "description": "How long a still image is placed for, in seconds: 0.5 to 600 (default 5). Stills placed after this change take it; clips already placed keep theirs. Saved with the project; one undo step."}, |
| 164 | + "speech_model": {"type": "string", "enum": MODELS.iter().copied().chain(["auto"]).collect::<Vec<_>>(), "description": "The Whisper model transcript, find_words and auto_captions run on; auto (default) picks the first installed. Saved with the project; one undo step."}, | |
| 165 | + "speech_device": {"type": "string", "enum": ["auto", "cpu", "gpu"], "description": "Where that model runs: auto (gpu when usable and that model is installed, else cpu), cpu or gpu. Saved with the project; one undo step."}, | |
| 163 | 166 | "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]}, |
| 164 | 167 | "proxies": {"type": "boolean", "description": "Play and edit through proxy files."}, |
| 165 | 168 | "auto_proxies": {"type": "boolean", "description": "Make proxies automatically for heavy sources."}, |
| @@ -2294,11 +2297,12 @@ fn status_reply(server: &Server) -> Reply { | ||
| 2294 | 2297 | false => format!("\nnotes: {}", s.notes()), |
| 2295 | 2298 | }; |
| 2296 | 2299 | let render_text = crate::tools::render::status_line(server).map_or_else(String::new, |l| format!("\n{l}")); |
| 2300 | + let speech_text = format!("{} on {}", s.speech_model().unwrap_or("auto"), s.speech_device().as_str()); | |
| 2297 | 2301 | let text = format!( |
| 2298 | 2302 | "{path} · {state} · {w}x{h} @{} · {} ({end}f) · undo {undo} · redo {redo} · {running} export job(s) running\n\ |
| 2299 | 2303 | lanes: {lane_text}{ducks_text}{voice_text}\n\ |
| 2300 | 2304 | {recent_text}sources: {} {}{looks_text}\n\ |
| 2301 | - settings: tonemap {tone} · proxies {} · auto proxies {} · encoder {encoder} · limiter {limiter_text} · sample rate {sample_rate} · still {:.1} s{offline_text}{fix_text}{notes_text}{render_text}", | |
| 2305 | + settings: tonemap {tone} · proxies {} · auto proxies {} · encoder {encoder} · limiter {limiter_text} · sample rate {sample_rate} · still {:.1} s · speech {speech_text}{offline_text}{fix_text}{notes_text}{render_text}", | |
| 2302 | 2306 | fmt_fps(fps), |
| 2303 | 2307 | parse::clock(end, fps), |
| 2304 | 2308 | sources.len(), |
| @@ -2347,6 +2351,8 @@ fn status_reply(server: &Server) -> Reply { | ||
| 2347 | 2351 | "limiter": {"on": limiter.on, "ceiling_db": limiter.ceiling_db}, |
| 2348 | 2352 | "sample_rate": s.sample_rate(), |
| 2349 | 2353 | "still_secs": s.still_secs(), |
| 2354 | + "speech_model": s.speech_model(), | |
| 2355 | + "speech_device": s.speech_device().as_str(), | |
| 2350 | 2356 | "notes": s.notes(), |
| 2351 | 2357 | } |
| 2352 | 2358 | }); |
| @@ -2506,6 +2512,45 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { | ||
| 2506 | 2512 | } |
| 2507 | 2513 | } |
| 2508 | 2514 | |
| 2515 | + if let Some(raw) = opt_str(args, "speech_model") { | |
| 2516 | + asked += 1; | |
| 2517 | + let v = raw.trim().to_ascii_lowercase(); | |
| 2518 | + if v != "auto" && !MODELS.contains(&v.as_str()) { | |
| 2519 | + refused += 1; | |
| 2520 | + lines.push(format!("speech_model {raw}: refused; use one of {}, or auto", MODELS.join(", "))); | |
| 2521 | + } else { | |
| 2522 | + let cur = s.speech_model().unwrap_or("auto").to_string(); | |
| 2523 | + let want = (v != "auto").then_some(v.as_str()); | |
| 2524 | + if s.set_speech_model(want) { | |
| 2525 | + changed += 1; | |
| 2526 | + named.push(format!("speech_model {cur}→{v}")); | |
| 2527 | + lines.push(format!("speech model {cur} -> {v}")); | |
| 2528 | + } else { | |
| 2529 | + lines.push(format!("speech model already {cur}")); | |
| 2530 | + } | |
| 2531 | + } | |
| 2532 | + } | |
| 2533 | + | |
| 2534 | + if let Some(raw) = opt_str(args, "speech_device") { | |
| 2535 | + asked += 1; | |
| 2536 | + match DeviceChoice::parse(raw.trim()) { | |
| 2537 | + Some(d) => { | |
| 2538 | + let cur = s.speech_device(); | |
| 2539 | + if s.set_speech_device(d) { | |
| 2540 | + changed += 1; | |
| 2541 | + named.push(format!("speech_device {}→{}", cur.as_str(), d.as_str())); | |
| 2542 | + lines.push(format!("speech device {} -> {}", cur.as_str(), d.as_str())); | |
| 2543 | + } else { | |
| 2544 | + lines.push(format!("speech device already {}", d.as_str())); | |
| 2545 | + } | |
| 2546 | + } | |
| 2547 | + None => { | |
| 2548 | + refused += 1; | |
| 2549 | + lines.push(format!("speech_device {raw}: refused; use auto, cpu or gpu")); | |
| 2550 | + } | |
| 2551 | + } | |
| 2552 | + } | |
| 2553 | + | |
| 2509 | 2554 | if let Some(v) = args.get("still_secs") { |
| 2510 | 2555 | asked += 1; |
| 2511 | 2556 | match v.as_f64() { |
| @@ -2668,7 +2713,7 @@ pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { | ||
| 2668 | 2713 | |
| 2669 | 2714 | if asked == 0 { |
| 2670 | 2715 | return Reply::err( |
| 2671 | - "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, proxies, auto_proxies, encoder, limiter, captions", | |
| 2716 | + "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, proxies, auto_proxies, encoder, limiter, captions", | |
| 2672 | 2717 | ); |
| 2673 | 2718 | } |
| 2674 | 2719 | let mut out = Map::new(); |
tools/edith-stt/Cargo.lockmodified+135 -3
| @@ -61,6 +61,26 @@ version = "0.22.1" | ||
| 61 | 61 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 62 | 62 | checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" |
| 63 | 63 | |
| 64 | +[[package]] | |
| 65 | +name = "bindgen" | |
| 66 | +version = "0.72.1" | |
| 67 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 68 | +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" | |
| 69 | +dependencies = [ | |
| 70 | + "bitflags", | |
| 71 | + "cexpr", | |
| 72 | + "clang-sys", | |
| 73 | + "itertools 0.13.0", | |
| 74 | + "log", | |
| 75 | + "prettyplease", | |
| 76 | + "proc-macro2", | |
| 77 | + "quote", | |
| 78 | + "regex", | |
| 79 | + "rustc-hash", | |
| 80 | + "shlex 1.3.0", | |
| 81 | + "syn 2.0.119", | |
| 82 | +] | |
| 83 | + | |
| 64 | 84 | [[package]] |
| 65 | 85 | name = "bit-set" |
| 66 | 86 | version = "0.8.0" |
| @@ -185,7 +205,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 185 | 205 | checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" |
| 186 | 206 | dependencies = [ |
| 187 | 207 | "find-msvc-tools", |
| 188 | - "shlex", | |
| 208 | + "shlex 2.0.1", | |
| 209 | +] | |
| 210 | + | |
| 211 | +[[package]] | |
| 212 | +name = "cexpr" | |
| 213 | +version = "0.6.0" | |
| 214 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 215 | +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" | |
| 216 | +dependencies = [ | |
| 217 | + "nom", | |
| 189 | 218 | ] |
| 190 | 219 | |
| 191 | 220 | [[package]] |
| @@ -194,6 +223,26 @@ version = "1.0.5" | ||
| 194 | 223 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 195 | 224 | checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" |
| 196 | 225 | |
| 226 | +[[package]] | |
| 227 | +name = "clang-sys" | |
| 228 | +version = "1.9.1" | |
| 229 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 230 | +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" | |
| 231 | +dependencies = [ | |
| 232 | + "glob", | |
| 233 | + "libc", | |
| 234 | + "libloading", | |
| 235 | +] | |
| 236 | + | |
| 237 | +[[package]] | |
| 238 | +name = "cmake" | |
| 239 | +version = "0.1.58" | |
| 240 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 241 | +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" | |
| 242 | +dependencies = [ | |
| 243 | + "cc", | |
| 244 | +] | |
| 245 | + | |
| 197 | 246 | [[package]] |
| 198 | 247 | name = "compact_str" |
| 199 | 248 | version = "0.9.1" |
| @@ -364,6 +413,7 @@ dependencies = [ | ||
| 364 | 413 | "serde_json", |
| 365 | 414 | "tracing", |
| 366 | 415 | "ureq", |
| 416 | + "whisper-rs", | |
| 367 | 417 | ] |
| 368 | 418 | |
| 369 | 419 | [[package]] |
| @@ -473,6 +523,12 @@ dependencies = [ | ||
| 473 | 523 | "percent-encoding", |
| 474 | 524 | ] |
| 475 | 525 | |
| 526 | +[[package]] | |
| 527 | +name = "fs_extra" | |
| 528 | +version = "1.3.0" | |
| 529 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 530 | +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" | |
| 531 | + | |
| 476 | 532 | [[package]] |
| 477 | 533 | name = "gemm" |
| 478 | 534 | version = "0.19.0" |
| @@ -626,6 +682,12 @@ dependencies = [ | ||
| 626 | 682 | "r-efi 6.0.0", |
| 627 | 683 | ] |
| 628 | 684 | |
| 685 | +[[package]] | |
| 686 | +name = "glob" | |
| 687 | +version = "0.3.4" | |
| 688 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 689 | +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" | |
| 690 | + | |
| 629 | 691 | [[package]] |
| 630 | 692 | name = "half" |
| 631 | 693 | version = "2.7.1" |
| @@ -798,6 +860,15 @@ dependencies = [ | ||
| 798 | 860 | "hashbrown 0.17.1", |
| 799 | 861 | ] |
| 800 | 862 | |
| 863 | +[[package]] | |
| 864 | +name = "itertools" | |
| 865 | +version = "0.13.0" | |
| 866 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 867 | +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" | |
| 868 | +dependencies = [ | |
| 869 | + "either", | |
| 870 | +] | |
| 871 | + | |
| 801 | 872 | [[package]] |
| 802 | 873 | name = "itertools" |
| 803 | 874 | version = "0.14.0" |
| @@ -819,6 +890,16 @@ version = "0.2.190" | ||
| 819 | 890 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 820 | 891 | checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" |
| 821 | 892 | |
| 893 | +[[package]] | |
| 894 | +name = "libloading" | |
| 895 | +version = "0.8.9" | |
| 896 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 897 | +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" | |
| 898 | +dependencies = [ | |
| 899 | + "cfg-if", | |
| 900 | + "windows-link", | |
| 901 | +] | |
| 902 | + | |
| 822 | 903 | [[package]] |
| 823 | 904 | name = "libm" |
| 824 | 905 | version = "0.2.16" |
| @@ -1029,6 +1110,16 @@ dependencies = [ | ||
| 1029 | 1110 | "zerocopy", |
| 1030 | 1111 | ] |
| 1031 | 1112 | |
| 1113 | +[[package]] | |
| 1114 | +name = "prettyplease" | |
| 1115 | +version = "0.2.37" | |
| 1116 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1117 | +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" | |
| 1118 | +dependencies = [ | |
| 1119 | + "proc-macro2", | |
| 1120 | + "syn 2.0.119", | |
| 1121 | +] | |
| 1122 | + | |
| 1032 | 1123 | [[package]] |
| 1033 | 1124 | name = "proc-macro2" |
| 1034 | 1125 | version = "1.0.107" |
| @@ -1147,7 +1238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1147 | 1238 | checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" |
| 1148 | 1239 | dependencies = [ |
| 1149 | 1240 | "either", |
| 1150 | - "itertools", | |
| 1241 | + "itertools 0.14.0", | |
| 1151 | 1242 | "rayon", |
| 1152 | 1243 | ] |
| 1153 | 1244 | |
| @@ -1210,6 +1301,12 @@ dependencies = [ | ||
| 1210 | 1301 | "windows-sys 0.52.0", |
| 1211 | 1302 | ] |
| 1212 | 1303 | |
| 1304 | +[[package]] | |
| 1305 | +name = "rustc-hash" | |
| 1306 | +version = "2.1.3" | |
| 1307 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1308 | +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" | |
| 1309 | + | |
| 1213 | 1310 | [[package]] |
| 1214 | 1311 | name = "rustix" |
| 1215 | 1312 | version = "1.1.5" |
| @@ -1292,6 +1389,12 @@ dependencies = [ | ||
| 1292 | 1389 | "winapi-util", |
| 1293 | 1390 | ] |
| 1294 | 1391 | |
| 1392 | +[[package]] | |
| 1393 | +name = "semver" | |
| 1394 | +version = "1.0.28" | |
| 1395 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1396 | +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" | |
| 1397 | + | |
| 1295 | 1398 | [[package]] |
| 1296 | 1399 | name = "seq-macro" |
| 1297 | 1400 | version = "0.3.6" |
| @@ -1350,6 +1453,12 @@ dependencies = [ | ||
| 1350 | 1453 | "serde", |
| 1351 | 1454 | ] |
| 1352 | 1455 | |
| 1456 | +[[package]] | |
| 1457 | +name = "shlex" | |
| 1458 | +version = "1.3.0" | |
| 1459 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1460 | +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" | |
| 1461 | + | |
| 1353 | 1462 | [[package]] |
| 1354 | 1463 | name = "shlex" |
| 1355 | 1464 | version = "2.0.1" |
| @@ -1527,7 +1636,7 @@ dependencies = [ | ||
| 1527 | 1636 | "derive_builder", |
| 1528 | 1637 | "esaxx-rs", |
| 1529 | 1638 | "getrandom 0.3.4", |
| 1530 | - "itertools", | |
| 1639 | + "itertools 0.14.0", | |
| 1531 | 1640 | "log", |
| 1532 | 1641 | "macro_rules_attribute", |
| 1533 | 1642 | "monostate", |
| @@ -1699,6 +1808,29 @@ dependencies = [ | ||
| 1699 | 1808 | "rustls-pki-types", |
| 1700 | 1809 | ] |
| 1701 | 1810 | |
| 1811 | +[[package]] | |
| 1812 | +name = "whisper-rs" | |
| 1813 | +version = "0.16.0" | |
| 1814 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1815 | +checksum = "2088172d00f936c348d6a72f488dc2660ab3f507263a195df308a3c2383229f6" | |
| 1816 | +dependencies = [ | |
| 1817 | + "libc", | |
| 1818 | + "whisper-rs-sys", | |
| 1819 | +] | |
| 1820 | + | |
| 1821 | +[[package]] | |
| 1822 | +name = "whisper-rs-sys" | |
| 1823 | +version = "0.15.0" | |
| 1824 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1825 | +checksum = "6986c0fe081241d391f09b9a071fbcbb59720c3563628c3c829057cf69f2a56f" | |
| 1826 | +dependencies = [ | |
| 1827 | + "bindgen", | |
| 1828 | + "cfg-if", | |
| 1829 | + "cmake", | |
| 1830 | + "fs_extra", | |
| 1831 | + "semver", | |
| 1832 | +] | |
| 1833 | + | |
| 1702 | 1834 | [[package]] |
| 1703 | 1835 | name = "winapi-util" |
| 1704 | 1836 | version = "0.1.11" |
tools/edith-stt/Cargo.tomlmodified+5 -0
| @@ -18,6 +18,11 @@ hound = "3.5" | ||
| 18 | 18 | tracing = "0.1" |
| 19 | 19 | serde_json = "1" |
| 20 | 20 | ureq = { version = "2", default-features = false, features = ["tls"] } |
| 21 | +whisper-rs = { version = "0.16.0", optional = true, features = ["vulkan"] } | |
| 22 | + | |
| 23 | +[features] | |
| 24 | +default = [] | |
| 25 | +vulkan = ["dep:whisper-rs"] | |
| 21 | 26 | |
| 22 | 27 | [workspace] |
| 23 | 28 |
tools/edith-stt/src/gpu.rsadded+301 -0
| @@ -0,0 +1,301 @@ | ||
| 1 | +#![forbid(unsafe_code)] | |
| 2 | + | |
| 3 | +use std::io::Write; | |
| 4 | +use std::path::{Path, PathBuf}; | |
| 5 | +use std::time::Instant; | |
| 6 | + | |
| 7 | +use anyhow::{bail, Context, Result}; | |
| 8 | +use serde_json::json; | |
| 9 | +use whisper_rs::vulkan::list_devices; | |
| 10 | +use whisper_rs::{ | |
| 11 | + DtwMode, DtwModelPreset, DtwParameters, FullParams, SamplingStrategy, WhisperContext, | |
| 12 | + WhisperContextParameters, WhisperSegment, | |
| 13 | +}; | |
| 14 | + | |
| 15 | +use crate::{ | |
| 16 | + fit_words_to_audio, levels, r3, read_wav_16k_mono, silence_reason, span_rel_db, starts_past_end, | |
| 17 | + Cli, MAX_COMPRESSION_RATIO, MIN_AVG_LOGPROB, NO_SPEECH_PROB, SR, | |
| 18 | +}; | |
| 19 | + | |
| 20 | +const GPU_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; | |
| 21 | + | |
| 22 | +pub fn probe() -> Result<()> { | |
| 23 | + if list_devices().is_empty() { | |
| 24 | + bail!("no Vulkan device found"); | |
| 25 | + } | |
| 26 | + Ok(()) | |
| 27 | +} | |
| 28 | + | |
| 29 | +pub fn run(cli: &Cli) -> Result<()> { | |
| 30 | + let device = list_devices() | |
| 31 | + .into_iter() | |
| 32 | + .next() | |
| 33 | + .context("no Vulkan device found")?; | |
| 34 | + let (model, preset) = resolve_model(&cli.model)?; | |
| 35 | + let dtw = if cli.align { preset } else { None }; | |
| 36 | + | |
| 37 | + let mut cp = WhisperContextParameters::new(); | |
| 38 | + cp.use_gpu(true); | |
| 39 | + if let Some(model_preset) = dtw.clone() { | |
| 40 | + cp.dtw_parameters(DtwParameters { | |
| 41 | + mode: DtwMode::ModelPreset { model_preset }, | |
| 42 | + ..Default::default() | |
| 43 | + }); | |
| 44 | + } | |
| 45 | + let t_start = Instant::now(); | |
| 46 | + let ctx = WhisperContext::new_with_params(&model, cp) | |
| 47 | + .with_context(|| format!("failed to load whisper model {}", model.display()))?; | |
| 48 | + eprintln!( | |
| 49 | + "model loaded from {} on {} in {:.2}s", | |
| 50 | + model.display(), | |
| 51 | + device.name, | |
| 52 | + t_start.elapsed().as_secs_f64() | |
| 53 | + ); | |
| 54 | + | |
| 55 | + let pcm = read_wav_16k_mono(&cli.input)?; | |
| 56 | + let audio_s = pcm.len() as f64 / SR as f64; | |
| 57 | + let lv = levels(&pcm); | |
| 58 | + let eot = ctx.token_eot(); | |
| 59 | + | |
| 60 | + let language = if cli.language.eq_ignore_ascii_case("auto") { | |
| 61 | + None | |
| 62 | + } else { | |
| 63 | + Some(cli.language.to_ascii_lowercase()) | |
| 64 | + }; | |
| 65 | + let prompt = cli.prompt.as_deref().map(str::trim).filter(|t| !t.is_empty()); | |
| 66 | + let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); | |
| 67 | + | |
| 68 | + let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 }); | |
| 69 | + params.set_language(language.as_deref()); | |
| 70 | + params.set_translate(false); | |
| 71 | + params.set_no_context(true); | |
| 72 | + params.set_token_timestamps(dtw.is_some()); | |
| 73 | + params.set_temperature(0.0); | |
| 74 | + params.set_temperature_inc(0.2); | |
| 75 | + params.set_logprob_thold(MIN_AVG_LOGPROB as f32); | |
| 76 | + params.set_entropy_thold(MAX_COMPRESSION_RATIO as f32); | |
| 77 | + params.set_no_speech_thold(NO_SPEECH_PROB as f32); | |
| 78 | + if let Some(p) = prompt { | |
| 79 | + params.set_initial_prompt(p); | |
| 80 | + } | |
| 81 | + params.set_print_special(false); | |
| 82 | + params.set_print_progress(false); | |
| 83 | + params.set_print_realtime(false); | |
| 84 | + params.set_print_timestamps(false); | |
| 85 | + params.set_n_threads(threads as i32); | |
| 86 | + params.set_progress_callback_safe(|p: i32| eprintln!("progress {:.4}", p as f64 / 100.0)); | |
| 87 | + | |
| 88 | + let mut state = ctx.create_state().context("failed to create whisper state")?; | |
| 89 | + let t_decode = Instant::now(); | |
| 90 | + state.full(params, &pcm).context("whisper inference failed")?; | |
| 91 | + | |
| 92 | + let offset = cli.offset; | |
| 93 | + let mut n_segs = 0usize; | |
| 94 | + for seg in state.as_iter() { | |
| 95 | + let t0 = seg.start_timestamp() as f64 / 100.0; | |
| 96 | + let t1 = (seg.end_timestamp() as f64 / 100.0).min(audio_s).max(t0); | |
| 97 | + if starts_past_end(t0, audio_s) { | |
| 98 | + eprintln!("dropped segment at {:.2}s: starts at or past the audio end", t0 + offset); | |
| 99 | + continue; | |
| 100 | + } | |
| 101 | + let toks = text_tokens(&seg, eot)?; | |
| 102 | + let text = String::from_utf8_lossy(&toks.iter().flat_map(|t| t.bytes.iter().copied()).collect::<Vec<u8>>()) | |
| 103 | + .trim() | |
| 104 | + .to_string(); | |
| 105 | + if text.is_empty() { | |
| 106 | + continue; | |
| 107 | + } | |
| 108 | + let avg = toks.iter().map(|t| t.plog).sum::<f64>() / toks.len() as f64; | |
| 109 | + let no_speech = seg.no_speech_probability() as f64; | |
| 110 | + let span = span_rel_db(&lv, t0, t1); | |
| 111 | + if let Some(reason) = silence_reason(no_speech, avg, span) { | |
| 112 | + if !cli.keep_all { | |
| 113 | + eprintln!( | |
| 114 | + "skipped segment {:.2}-{:.2}s ({reason}, no_speech {no_speech:.2}, avg_logprob {avg:.2}): {text:?}", | |
| 115 | + t0 + offset, | |
| 116 | + t1 + offset | |
| 117 | + ); | |
| 118 | + continue; | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + let groups = word_groups(&toks); | |
| 123 | + let use_dtw = dtw.is_some() && groups.iter().any(|g| g.start > 0.0); | |
| 124 | + let mut words = if use_dtw { | |
| 125 | + dtw_words(&groups, t0, t1, offset) | |
| 126 | + } else { | |
| 127 | + proportional_words(&groups, t0, t1, offset) | |
| 128 | + }; | |
| 129 | + | |
| 130 | + let n_words = words.len(); | |
| 131 | + let cut = fit_words_to_audio(&mut words, offset, audio_s); | |
| 132 | + if n_words > 0 && words.is_empty() { | |
| 133 | + eprintln!("dropped segment at {:.2}s: every word starts at or past the audio end: {text:?}", t0 + offset); | |
| 134 | + continue; | |
| 135 | + } | |
| 136 | + let text = if cut > 0 { | |
| 137 | + eprintln!("cut {cut} word(s) at {:.2}s that start at or past the audio end", t0 + offset); | |
| 138 | + words.iter().filter_map(|w| w["w"].as_str()).collect::<Vec<_>>().join(" ") | |
| 139 | + } else { | |
| 140 | + text | |
| 141 | + }; | |
| 142 | + let (start, end) = match (words.first(), words.last()) { | |
| 143 | + (Some(f), Some(l)) => ( | |
| 144 | + f["start"].as_f64().unwrap_or(t0 + offset), | |
| 145 | + l["end"].as_f64().unwrap_or(t1 + offset), | |
| 146 | + ), | |
| 147 | + _ => (t0 + offset, t1 + offset), | |
| 148 | + }; | |
| 149 | + let line = json!({ | |
| 150 | + "start": r3(start), | |
| 151 | + "end": r3(end), | |
| 152 | + "text": text, | |
| 153 | + "words": words, | |
| 154 | + "approx": !use_dtw, | |
| 155 | + "no_speech": r3(no_speech), | |
| 156 | + "avg_logprob": r3(avg), | |
| 157 | + "span_db": span.map(r3), | |
| 158 | + }); | |
| 159 | + println!("{line}"); | |
| 160 | + n_segs += 1; | |
| 161 | + } | |
| 162 | + std::io::stdout().flush()?; | |
| 163 | + | |
| 164 | + let elapsed = t_decode.elapsed().as_secs_f64(); | |
| 165 | + eprintln!( | |
| 166 | + "done: {n_segs} segments, audio {audio_s:.2}s, decode {elapsed:.2}s, RTF {:.3}", | |
| 167 | + elapsed / audio_s.max(1e-9) | |
| 168 | + ); | |
| 169 | + Ok(()) | |
| 170 | +} | |
| 171 | + | |
| 172 | +fn resolve_model(arg: &str) -> Result<(PathBuf, Option<DtwModelPreset>)> { | |
| 173 | + let (path, name) = if arg.ends_with(".bin") || Path::new(arg).is_file() { | |
| 174 | + let path = PathBuf::from(arg); | |
| 175 | + let name = path | |
| 176 | + .file_stem() | |
| 177 | + .and_then(|s| s.to_str()) | |
| 178 | + .unwrap_or_default() | |
| 179 | + .trim_start_matches("ggml-") | |
| 180 | + .to_string(); | |
| 181 | + (path, name) | |
| 182 | + } else { | |
| 183 | + if !GPU_SIZES.contains(&arg) { | |
| 184 | + bail!("model '{arg}' is neither a .bin path nor one of {GPU_SIZES:?}"); | |
| 185 | + } | |
| 186 | + let home = std::env::var("HOME").context("HOME not set")?; | |
| 187 | + let path = PathBuf::from(home) | |
| 188 | + .join(".cache/edith/models") | |
| 189 | + .join(format!("ggml-{arg}.bin")); | |
| 190 | + (path, arg.to_string()) | |
| 191 | + }; | |
| 192 | + if !path.is_file() { | |
| 193 | + bail!("GPU model file not found: {} (--device gpu does not download models)", path.display()); | |
| 194 | + } | |
| 195 | + Ok((path, preset(&name))) | |
| 196 | +} | |
| 197 | + | |
| 198 | +fn preset(name: &str) -> Option<DtwModelPreset> { | |
| 199 | + Some(match name { | |
| 200 | + "tiny" => DtwModelPreset::Tiny, | |
| 201 | + "base" => DtwModelPreset::Base, | |
| 202 | + "small" => DtwModelPreset::Small, | |
| 203 | + "medium" => DtwModelPreset::Medium, | |
| 204 | + "large-v3" => DtwModelPreset::LargeV3, | |
| 205 | + "large-v3-turbo" => DtwModelPreset::LargeV3Turbo, | |
| 206 | + _ => return None, | |
| 207 | + }) | |
| 208 | +} | |
| 209 | + | |
| 210 | +struct Tok { | |
| 211 | + bytes: Vec<u8>, | |
| 212 | + plog: f64, | |
| 213 | + dtw: f64, | |
| 214 | +} | |
| 215 | + | |
| 216 | +fn text_tokens(seg: &WhisperSegment<'_>, eot: i32) -> Result<Vec<Tok>> { | |
| 217 | + let mut out = Vec::new(); | |
| 218 | + for i in 0..seg.n_tokens() { | |
| 219 | + let Some(tok) = seg.get_token(i) else { | |
| 220 | + continue; | |
| 221 | + }; | |
| 222 | + if tok.token_id() >= eot { | |
| 223 | + continue; | |
| 224 | + } | |
| 225 | + let bytes = tok.to_bytes().context("failed to read token text")?.to_vec(); | |
| 226 | + if bytes.is_empty() { | |
| 227 | + continue; | |
| 228 | + } | |
| 229 | + let data = tok.token_data(); | |
| 230 | + out.push(Tok { bytes, plog: data.plog as f64, dtw: data.t_dtw as f64 / 100.0 }); | |
| 231 | + } | |
| 232 | + Ok(out) | |
| 233 | +} | |
| 234 | + | |
| 235 | +struct Group { | |
| 236 | + text: String, | |
| 237 | + p: f64, | |
| 238 | + start: f64, | |
| 239 | +} | |
| 240 | + | |
| 241 | +fn word_groups(toks: &[Tok]) -> Vec<Group> { | |
| 242 | + let mut words: Vec<(Vec<u8>, Vec<f64>, f64)> = Vec::new(); | |
| 243 | + for t in toks { | |
| 244 | + if words.is_empty() || t.bytes[0] == b' ' { | |
| 245 | + words.push((Vec::new(), Vec::new(), t.dtw)); | |
| 246 | + } | |
| 247 | + if let Some(w) = words.last_mut() { | |
| 248 | + w.0.extend_from_slice(&t.bytes); | |
| 249 | + w.1.push(t.plog); | |
| 250 | + } | |
| 251 | + } | |
| 252 | + words | |
| 253 | + .into_iter() | |
| 254 | + .filter_map(|(bytes, plogs, start)| { | |
| 255 | + let text = String::from_utf8_lossy(&bytes).trim().to_string(); | |
| 256 | + if text.is_empty() { | |
| 257 | + return None; | |
| 258 | + } | |
| 259 | + let p = (plogs.iter().sum::<f64>() / plogs.len().max(1) as f64).exp(); | |
| 260 | + Some(Group { text, p, start }) | |
| 261 | + }) | |
| 262 | + .collect() | |
| 263 | +} | |
| 264 | + | |
| 265 | +fn word_json(text: &str, start: f64, end: f64, p: f64, offset: f64) -> serde_json::Value { | |
| 266 | + json!({"w": text, "start": r3(start + offset), "end": r3(end + offset), "p": r3(p)}) | |
| 267 | +} | |
| 268 | + | |
| 269 | +fn dtw_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> { | |
| 270 | + let hi = t1.max(t0); | |
| 271 | + let mut starts: Vec<f64> = Vec::with_capacity(groups.len()); | |
| 272 | + for g in groups { | |
| 273 | + let s = if g.start > 0.0 { g.start } else { t0 }; | |
| 274 | + let prev = starts.last().copied().unwrap_or(t0); | |
| 275 | + starts.push(s.clamp(t0, hi).max(prev)); | |
| 276 | + } | |
| 277 | + groups | |
| 278 | + .iter() | |
| 279 | + .enumerate() | |
| 280 | + .map(|(i, g)| { | |
| 281 | + let start = starts[i]; | |
| 282 | + let end = starts.get(i + 1).copied().unwrap_or(hi).clamp(start, hi); | |
| 283 | + word_json(&g.text, start, end, g.p, offset) | |
| 284 | + }) | |
| 285 | + .collect() | |
| 286 | +} | |
| 287 | + | |
| 288 | +fn proportional_words(groups: &[Group], t0: f64, t1: f64, offset: f64) -> Vec<serde_json::Value> { | |
| 289 | + let total: usize = groups.iter().map(|g| g.text.chars().count()).sum(); | |
| 290 | + let span = (t1 - t0).max(0.0); | |
| 291 | + let mut t = t0; | |
| 292 | + groups | |
| 293 | + .iter() | |
| 294 | + .map(|g| { | |
| 295 | + let dur = if total > 0 { span * g.text.chars().count() as f64 / total as f64 } else { 0.0 }; | |
| 296 | + let (start, end) = (t, t + dur); | |
| 297 | + t = end; | |
| 298 | + word_json(&g.text, start, end, g.p, offset) | |
| 299 | + }) | |
| 300 | + .collect() | |
| 301 | +} |
tools/edith-stt/src/main.rsmodified+45 -5
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | //! edith-stt: offline Whisper speech-to-text on CPU (candle), JSON-lines output. |
| 2 | 2 | //! |
| 3 | -//! usage: edith-stt --model base|small|tiny|<dir> [--language en|auto] [--offset SECS] [--no-align] [--keep-all] <input.wav> | |
| 3 | +//! usage: edith-stt --model base|small|tiny|<dir> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] <input.wav> | |
| 4 | +//! edith-stt --has-gpu | |
| 4 | 5 | //! |
| 5 | 6 | //! stdout: one JSON object per segment |
| 6 | 7 | //! {"start":s,"end":s,"text":"...","words":[{"w":"Hello","start":s,"end":s,"p":prob}],"approx":false, |
| @@ -15,6 +16,23 @@ | ||
| 15 | 16 | //! stderr: progress lines `progress <0..1>` and diagnostics. |
| 16 | 17 | |
| 17 | 18 | mod whisper_model; |
| 19 | +#[cfg(feature = "vulkan")] | |
| 20 | +mod gpu; | |
| 21 | +#[cfg(not(feature = "vulkan"))] | |
| 22 | +mod gpu { | |
| 23 | + use crate::Cli; | |
| 24 | + use anyhow::{bail, Result}; | |
| 25 | + | |
| 26 | + const NO_VULKAN: &str = "edith-stt was built without vulkan; rebuild with --features vulkan"; | |
| 27 | + | |
| 28 | + pub fn probe() -> Result<()> { | |
| 29 | + bail!(NO_VULKAN) | |
| 30 | + } | |
| 31 | + | |
| 32 | + pub fn run(_: &Cli) -> Result<()> { | |
| 33 | + bail!(NO_VULKAN) | |
| 34 | + } | |
| 35 | +} | |
| 18 | 36 | |
| 19 | 37 | use anyhow::{anyhow, bail, Context, Result}; |
| 20 | 38 | use candle_core::{DType, Device, IndexOp, Tensor}; |
| @@ -54,7 +72,7 @@ const MAX_PREV_TOKENS: usize = 223; | ||
| 54 | 72 | /// Silence filter thresholds (see `silence_reason`). |
| 55 | 73 | const NO_SPEECH_PROB: f64 = 0.6; |
| 56 | 74 | const NO_SPEECH_LOGPROB: f64 = -1.0; |
| 57 | -const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3"]; | |
| 75 | +const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"]; | |
| 58 | 76 | const REQUIRED: &[&str] = &[ |
| 59 | 77 | "config.json", |
| 60 | 78 | "model.safetensors", |
| @@ -81,11 +99,13 @@ struct Cli { | ||
| 81 | 99 | /// `--prompt`: text Whisper sees before the audio, as OpenAI's `initial_prompt`. Names and |
| 82 | 100 | /// jargon spelled the way they should come out ("Edith, LUFS") steer the decoder. |
| 83 | 101 | prompt: Option<String>, |
| 102 | + gpu: bool, | |
| 103 | + has_gpu: bool, | |
| 84 | 104 | input: PathBuf, |
| 85 | 105 | } |
| 86 | 106 | |
| 87 | 107 | fn usage() -> &'static str { |
| 88 | - "usage: edith-stt --model base|small|tiny|<dir> [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] <input.wav>" | |
| 108 | + "usage: edith-stt --model base|small|tiny|<dir>|<file.bin> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] <input.wav>\n edith-stt --has-gpu" | |
| 89 | 109 | } |
| 90 | 110 | |
| 91 | 111 | fn parse_cli() -> Result<Cli> { |
| @@ -95,11 +115,21 @@ fn parse_cli() -> Result<Cli> { | ||
| 95 | 115 | let mut align = true; |
| 96 | 116 | let mut keep_all = false; |
| 97 | 117 | let mut prompt: Option<String> = None; |
| 118 | + let mut gpu = false; | |
| 119 | + let mut has_gpu = false; | |
| 98 | 120 | let mut input: Option<PathBuf> = None; |
| 99 | 121 | let mut args = std::env::args().skip(1); |
| 100 | 122 | while let Some(a) = args.next() { |
| 101 | 123 | match a.as_str() { |
| 102 | 124 | "--model" => model = args.next().context("--model needs a value")?, |
| 125 | + "--device" => { | |
| 126 | + gpu = match args.next().context("--device needs a value")?.as_str() { | |
| 127 | + "cpu" => false, | |
| 128 | + "gpu" => true, | |
| 129 | + other => bail!("--device must be cpu or gpu, got {other}"), | |
| 130 | + } | |
| 131 | + } | |
| 132 | + "--has-gpu" => has_gpu = true, | |
| 103 | 133 | "--language" => language = args.next().context("--language needs a value")?, |
| 104 | 134 | "--offset" => { |
| 105 | 135 | offset = args |
| @@ -124,12 +154,22 @@ fn parse_cli() -> Result<Cli> { | ||
| 124 | 154 | } |
| 125 | 155 | } |
| 126 | 156 | } |
| 127 | - let input = input.with_context(|| usage().to_string())?; | |
| 128 | - Ok(Cli { model, language, offset, align, keep_all, prompt, input }) | |
| 157 | + let input = match (has_gpu, input) { | |
| 158 | + (true, Some(_)) => bail!("--has-gpu takes no input file\n{}", usage()), | |
| 159 | + (true, None) => PathBuf::new(), | |
| 160 | + (false, input) => input.with_context(|| usage().to_string())?, | |
| 161 | + }; | |
| 162 | + Ok(Cli { model, language, offset, align, keep_all, prompt, gpu, has_gpu, input }) | |
| 129 | 163 | } |
| 130 | 164 | |
| 131 | 165 | fn run() -> Result<()> { |
| 132 | 166 | let cli = parse_cli()?; |
| 167 | + if cli.has_gpu { | |
| 168 | + return gpu::probe(); | |
| 169 | + } | |
| 170 | + if cli.gpu { | |
| 171 | + return gpu::run(&cli); | |
| 172 | + } | |
| 133 | 173 | let dir = resolve_model(&cli.model)?; |
| 134 | 174 | let t_start = Instant::now(); |
| 135 | 175 |