Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.
Rust chatterboxdesktopdubbingmobilemultilingualofflineomnivoicerustrvcspeech-synthesisspeech-to-textstttext-to-speechttsvoice-cloningvoxcpm2whisper
feat: save subtitles as SRT, WebVTT or SBV files (#174)
Taras Hevlich0967abe95568
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 072188b..f6c5cdf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,10 @@* **The MCP server reads books in character voices:** `start_book` takes `men_voice`, `women_voice` and `cast`, andthe new `find_speakers` tool says who speaks each line (the narrator, the characters, the lines per voice and adescription for a voice of each role) before the book is read.+* **Subtitles as files:** **Save subtitles…** above Redub's transcript (in every mode, and above the translation in+ Translate & dub's review) and the **Subtitles** formats of **Export as…** save the timed text as SRT, WebVTT or SBV,+ to upload to YouTube or open in a player instead of burning it into a video. For programs: `subtitles.export`, and+ the MCP tool `export_subtitles`.## 0.9.0diff --git a/contract/engine-protocol.md b/contract/engine-protocol.mdindex c31e760..4e42818 100644--- a/contract/engine-protocol.md+++ b/contract/engine-protocol.md@@ -1327,6 +1327,24 @@ anything needing ffmpeg answers `not_ready`.`video.cancel {"job"?}` -> `{"cancelled":bool}`: stops that export (without `job`: the one running); it ends with`video.error` `cancelled`. `cancelled` is false when no such export runs.+### `subtitles.export` (a subtitle file)+`{"format":"srt|vtt|sbv","dest","segments"?:[{"start","end","text","words"?}],"segments_path"?,"path"?,"sidecar"?}`+-> `{"path","cues","source":"given|recorded|estimated","size_bytes"}`+- Writes timed lines as a subtitle file, the alternative to burning them into a video: SubRip (`srt`), WebVTT (`vtt`)+ or SubViewer (`sbv`, YouTube's own). `dest` is an absolute file path ending in `.<format>`; an existing file is+ replaced (written to `<dest>.part-<pid>` first). UTF-8 without a BOM.+- The lines come from, the first that is given: `segments` (with Whisper's `words`, as `redub.render` takes them,+ cues are timed by the words), `segments_path`, or the result file `path` and its sidecar (or `sidecar`), exactly as+ the subtitles of [`video.export`](#videoexport--videocancel) (`source` as there; an `estimated` result is decoded,+ so it needs ffmpeg for a file soundfile cannot read).+- Cues as burned subtitles have them ([Video output](#video-output-output-keep_background) step 5): a sentence per+ cue, a long one split at its clauses, at most two lines of 42 characters, never overlapping. Times in+ milliseconds (`00:00:01,500` in SRT, `00:00:01.500` in WebVTT, `0:00:01.500` in SBV), hours past 99 as they are.+ WebVTT text has `&`, `<` and `>` escaped; SRT and SBV have no escapes (an SRT backslash is followed by a zero-width+ space, so players do not read `\N` or `{\...}` as tags). Runs of whitespace become one space.+- Errors: `bad_request` (`format`, `dest`, `segments`, `segments_path`, `sidecar`, none of them with `path`, a file+ with no saved text, no line with a text and a length), `not_found` (`path`, `segments_path` or `sidecar` missing).+## Audiobooks (`text.import`, `book.*`)Speak has two modes: **Text** (`tts.generate`, above) and **Book**, which reads a whole document in the active voice@@ -2119,6 +2137,7 @@ mimvox mcp [the same arguments]| `wait_job` | `job`, `timeout_s`? | waits for the job's end event (300 s by default, at most 3600; then `running` with `timed_out`) || `export_video` | `path` or `parts` (`[{path, segments?, segments_path?, image?}]`), `segments`?, `segments_path`?, `format`?, `subtitles`?, `subtitle_position`?, `images`?, `transitions`?, `dest`?, `timeout_s`? | `video.export` (`format` default `mp4`; `subtitles` default true when any `segments` or `segments_path` is given, sent as `{position}`); waits for `video.done` (1800 s by default, then `running` with the job) and returns `dest`, a `mimvox://file/` link, `duration_s`, `parts` (where each part starts) and `subtitles`. Without `dest`: next to `path` when it lies in an `outputs` folder, else `<data>/outputs/videos/` (the data folder read from the first source's path: `outputs`, `api/uploads` or `design`; `bad_request` when it is none of them), named after the source, or for parts sharing a folder after that folder (a book's title), with `_2`, `_3`, ... when a file of that name exists (checked through `GET /files`). Cancelling the call sends `video.cancel` || `subtitle_video` | `path`, `language`?, `subtitle_position`?, `segments`?, `images`?, `transitions`?, `picture`?, `timeout_s`? | without `segments`: `redub.transcribe` (`language` default `auto`) and its segments' `{start, end, text}`; then `redub.render` `mode:"subtitles"` with the transcript's `language` (and `images` as given, `[{path, start?}]` as for `export_video`, with `transitions`; `picture: "black"` for a video without images); returns `video_path`, a link, `subtitles_burned`, `subtitle_lines`, `subtitle_note`?, `transcribed` and the `segments` used. Progress: the transcription 0-50, the render 50-100. One timeout (1800 s) for both; cancelling sends `redub.cancel` |+| `export_subtitles` | `segments`?, `path`?, `format`?, `language`?, `dest`?, `timeout_s`? | without `segments`: `redub.transcribe` of `path` (`language` default `auto`) and its segments' `{start, end, text, words}`; then `subtitles.export` with them (`format` default `srt`). Without `dest`: named after `path`, placed as `export_video` places a video (`bad_request` with neither `path` nor `dest`). Returns `path`, a `mimvox://file/` link, `format`, `cues`, `size_bytes`, `transcribed` and, when transcribed, `language` and the `segments`. One timeout (1800 s) for the transcription; cancelling sends `redub.cancel` || `dub_video` | `path`, `voice`?, `target_language`?, `source_language`?, `subtitles`?, `subtitle_position`?, `timeout_s`? | `redub.dub` with `output:"video"` in the voice (as for `speak`); waits for `redub.done` (1800 s) and returns `video_path` and the audio `path` with links, the languages, the subtitle and background fields and the whole `result`. Cancelling sends `redub.cancel` || `create_voice` | `paths` (recordings of one speaker), `name`?, `language`?, `remove_music`?; or `bundle`, `name`? | Record's "Use recordings you already have": `voices.create` (`name` default the first file's name, `language` default `en` until heard), `media.combine` of the files (`language:"auto"` and the voice unless `language` is given, `remove_music` as given), then `dataset.add` of the result as part 1000 (or one past the highest part); answers the voice from `voices.list`, `part`, `recordings` (the summary), `files`, `skipped`, `unused`, the `music_*` fields and `language_heard`. A failed `media.combine` or `dataset.add` deletes the new voice again. With `bundle`: `voices.import {bundle, name?}` || `manage_voice` | `voice`, `action` (`rename`, `delete`, `export`), `name`?, `language`?, `dest`? | `voices.rename` (`name` and/or `language`), `voices.delete` or `voices.export` (the bundle's path with a `mimvox://file/` link). `voice` is an id or name and never defaults |@@ -2133,8 +2152,8 @@ mimvox mcp [the same arguments]| `upload_file` | `local_path` | `POST /files` (streamed): the path on the API's machine || `download_file` | `path`, `dest`?, `overwrite`? | `GET /files` (streamed) to `dest` (a file or folder; default the Downloads folder) |-- **Progress.** When a `speak`, `export_video`, `subtitle_video`, `dub_video`, `transcribe`, `respeak`,- `convert_voice` or `wait_job` call carries a `progressToken`, each progress event of its job becomes a+- **Progress.** When a `speak`, `export_video`, `subtitle_video`, `export_subtitles`, `dub_video`, `transcribe`,+ `respeak`, `convert_voice` or `wait_job` call carries a `progressToken`, each progress event of its job becomes a`notifications/progress`: `pct` / `percent` out of 100 (`train.progress`, `book.progress`, `redub.progress`,`video.progress`, `voices.media.progress`), or the chunk count out of `segments` (`tts.chunk`), with the event nameand stage as the message. Values only increase.@@ -2151,6 +2170,6 @@ mimvox mcp [the same arguments]- `resources/list`: the latest 100 saved results (`outputs.list`), one resource per audio file and per video,`mimvox://file/<absolute path, percent-encoded>` with the MIME type and a description (kind, voice, length, text).- Template `mimvox://file/{path}`: any file `GET /files` serves. `resources/read` returns it (base64 `blob`; text for- `.txt`, `.srt`, `.vtt`, `.json`) up to 32 MB; larger files are refused with a hint to use `download_file`.+ `.txt`, `.srt`, `.vtt`, `.sbv`, `.json`) up to 32 MB; larger files are refused with a hint to use `download_file`.The consent and licence rules of the API apply unchanged.diff --git a/crates/api/openapi/methods.json b/crates/api/openapi/methods.jsonindex 69eff79..59bb220 100644--- a/crates/api/openapi/methods.json+++ b/crates/api/openapi/methods.json@@ -5043,6 +5043,125 @@]}},+ {+ "name": "subtitles.export",+ "summary": "Save timed lines as a subtitle file",+ "description": "Writes SRT, WebVTT or SBV (YouTube's own format) to dest, in UTF-8, with the cues of a burned video: sentences of at most two lines of 42 characters, never overlapping. The lines come from segments, segments_path, or a result file's sidecar (its segments, else its text laid over the speech, as video.export does); an existing dest is replaced. Errors: bad_request (format, dest, segments, no lines or none with a length), not_found (path, segments_path or sidecar missing).",+ "job": false,+ "params": {+ "type": "object",+ "properties": {+ "format": {+ "type": "string",+ "description": "Subtitle format; dest ends in .<format>",+ "enum": [+ "srt",+ "vtt",+ "sbv"+ ]+ },+ "dest": {+ "type": "string",+ "description": "Absolute path of the file to write, ending in .<format>"+ },+ "segments": {+ "type": "array",+ "description": "Timed lines, such as a redub.transcribe transcript; win over segments_path and path",+ "items": {+ "type": "object",+ "description": "A subtitle line",+ "properties": {+ "start": {+ "type": "number",+ "description": "Seconds"+ },+ "end": {+ "type": "number",+ "description": "Seconds"+ },+ "text": {+ "type": "string",+ "description": "The words"+ },+ "words": {+ "type": "array",+ "description": "Whisper's words of the line, [start, end, word] in seconds (from redub.transcript): subtitles are timed by them, also after the text was edited",+ "items": {+ "type": "array",+ "prefixItems": [+ {+ "type": "number"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ }+ ],+ "minItems": 3,+ "maxItems": 3+ }+ }+ },+ "required": [+ "start",+ "end",+ "text"+ ]+ }+ },+ "segments_path": {+ "type": "string",+ "description": "A book's segment file or any JSON object with a segments list, such as a .result.json"+ },+ "path": {+ "type": "string",+ "description": "A result file (a Speak take, a Redub result, a book chapter): the lines of its sidecar"+ },+ "sidecar": {+ "type": "string",+ "description": "With path: the sidecar to read instead of <name>.result.json (a Design take's take.json)"+ }+ },+ "required": [+ "format",+ "dest"+ ]+ },+ "result": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Absolute path of the written file"+ },+ "cues": {+ "type": "integer",+ "description": "Subtitles written"+ },+ "source": {+ "type": "string",+ "description": "Where the lines came from",+ "enum": [+ "given",+ "recorded",+ "estimated"+ ]+ },+ "size_bytes": {+ "type": "integer",+ "description": "Size of the written file in bytes"+ }+ },+ "required": [+ "path",+ "cues",+ "source",+ "size_bytes"+ ]+ }+ },{"name": "voices.add_reference","summary": "Add a reference clip for another language",diff --git a/crates/api/src/files.rs b/crates/api/src/files.rsindex dab617f..28ab0d9 100644--- a/crates/api/src/files.rs+++ b/crates/api/src/files.rs@@ -120,6 +120,7 @@ pub fn content_type(path: &Path) -> &'static str {"txt" => "text/plain; charset=utf-8","srt" => "application/x-subrip","vtt" => "text/vtt",+ "sbv" => "text/plain; charset=utf-8","png" => "image/png","jpg" | "jpeg" => "image/jpeg",_ => "application/octet-stream",diff --git a/crates/desktop/examples/fake_engine.py b/crates/desktop/examples/fake_engine.pyindex 4556deb..6fadf45 100644--- a/crates/desktop/examples/fake_engine.py+++ b/crates/desktop/examples/fake_engine.py@@ -459,6 +459,29 @@ def audio_export(params):return {"path": str(dest), "size_bytes": dest.stat().st_size}+def srt_time(t):+ return f"{int(t // 3600):02d}:{int(t // 60 % 60):02d}:{t % 60:06.3f}".replace(".", ",")+++def subtitles_export(data_dir, params):+ """One cue per line, written as SRT whatever the format."""+ recorded(data_dir, "subtitles.export", params)+ fmt, dest = params.get("format"), Path(params.get("dest") or "")+ if fmt not in ("srt", "vtt", "sbv") or not dest.is_absolute() or dest.suffix != f".{fmt}":+ raise BadRequest("'format' must be srt, vtt or sbv and 'dest' an absolute path ending in it")+ segs, source = params.get("segments"), "given"+ if segs is None and params.get("segments_path"):+ segs, source = json.loads(Path(params["segments_path"]).read_text(encoding="utf-8"))["segments"], "recorded"+ if segs is None and params.get("path"):+ segs, source = [{"start": 0.0, "end": wav_seconds(params["path"]), "text": "Recorded."}], "recorded"+ if not segs:+ raise BadRequest("give 'segments', 'segments_path' or 'path'")+ cues = [f"{k}\n{srt_time(s['start'])} --> {srt_time(s['end'])}\n{s['text']}\n" for k, s in enumerate(segs, 1)]+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.write_text("\n".join(cues), encoding="utf-8")+ return {"path": str(dest), "cues": len(cues), "source": source, "size_bytes": dest.stat().st_size}++def outputs_delete(data_dir, params):path = Path(params["path"])out = (data_dir / "outputs").absolute()@@ -645,6 +668,8 @@ def handle(data_dir, req):result = train_control(params, method)elif method == "audio.export":result = audio_export(params)+ elif method == "subtitles.export":+ result = subtitles_export(data_dir, params)elif method == "outputs.delete":result = outputs_delete(data_dir, params)elif method == "presets.list":diff --git a/crates/desktop/src/ui/design.rs b/crates/desktop/src/ui/design.rsindex 15b6a92..fa1c5ba 100644--- a/crates/desktop/src/ui/design.rs+++ b/crates/desktop/src/ui/design.rs@@ -925,6 +925,7 @@ fn take_row(s: &AppState, p: &Palette, t: &Take) -> El {video: None,duration_s: t.duration,sidecar: t.path.parent().map(|d| d.join("take.json")),+ lines: None,};r = r.child(super::formats::export_button(*p, menu, false)).child(super::components::icon_button(*p,diff --git a/crates/desktop/src/ui/formats.rs b/crates/desktop/src/ui/formats.rsindex e8eb0db..4f59263 100644--- a/crates/desktop/src/ui/formats.rs+++ b/crates/desktop/src/ui/formats.rs@@ -5,7 +5,8 @@ use super::theme::{Palette, motion, radius, ty};use super::voices::kit;use crate::engine::EngineMsg;use crate::engine::protocol::{- self, EngineError, EngineEvent, JobStarted, SubtitlePosition, VideoDone, VideoExportParams, VideoImage,+ self, EngineError, EngineEvent, JobStarted, RedubSegmentIn, SubtitlePosition, VideoDone, VideoExportParams,+ VideoImage,};use crate::state::{AppState, Screen};use rune::{Align, Color, El, Icon, ScrollSpec, Side, col, el, row, text};@@ -25,6 +26,8 @@ pub const EXPORT_ALL: [(&str, &str); 7] = [pub const EXPORT_VIDEO: [(&str, &str); 4] = [("mp4", "MP4"), ("mkv", "MKV"), ("webm", "WebM"), ("mov", "MOV")];+pub const EXPORT_SUBTITLES: [(&str, &str); 3] = [("srt", "SRT"), ("vtt", "WebVTT"), ("sbv", "SBV")];+/// Used until the engine answers `formats.list`.const DEFAULT_IMPORT: &[&str] = &["wav", "mp3", "flac", "ogg", "oga", "opus", "m4a", "aac", "wma", "aiff", "aif", "mp4", "mkv", "mov", "avi", "webm",@@ -89,6 +92,8 @@ pub struct Menu {pub duration_s: f32,/// A Design take's take.json; other results keep their sidecar next to `src`.pub sidecar: Option<PathBuf>,+ /// Timed lines to save as subtitles, the only formats then offered; `src` names the file.+ pub lines: Option<Vec<RedubSegmentIn>>,}#[derive(Clone, Debug)]@@ -123,7 +128,7 @@ struct VideoRun {enum Phase {#[default]Idle,- Picking(Job),+ Picking(Box<Job>),Exporting {req: u64,dest: PathBuf,@@ -195,12 +200,21 @@ fn is_video(ext: &str) -> bool {EXPORT_VIDEO.iter().any(|(e, _)| *e == ext)}+fn is_subtitles(ext: &str) -> bool {+ EXPORT_SUBTITLES.iter().any(|(e, _)| *e == ext)+}+fn known(ext: &str) -> bool {- EXPORT_ALL.iter().any(|(e, _)| *e == ext) || is_video(ext)+ EXPORT_ALL.iter().any(|(e, _)| *e == ext) || is_video(ext) || is_subtitles(ext)}fn label_of(ext: &str) -> &'static str {- EXPORT_ALL.iter().chain(EXPORT_VIDEO.iter()).find(|(e, _)| *e == ext).map_or("", |(_, l)| l)+ EXPORT_ALL.iter().chain(&EXPORT_VIDEO).chain(&EXPORT_SUBTITLES).find(|(e, _)| *e == ext).map_or("", |(_, l)| l)+}++/// The format the menu saves in: a menu of lines offers subtitle formats only.+fn chosen<'a>(f: &'a FormatsState, m: &Menu) -> &'a str {+ if m.lines.is_some() && !is_subtitles(&f.format) { EXPORT_SUBTITLES[0].0 } else { &f.format }}fn position(f: &FormatsState) -> SubtitlePosition {@@ -220,6 +234,9 @@ fn blurb(ext: &str) -> &'static str {"mkv" => "An open container, for players like VLC.","webm" => "An open format for the web.","mov" => "For Apple devices and video editors.",+ "srt" => "Subtitles for YouTube, players and video editors.",+ "vtt" => "Subtitles for YouTube and web players.",+ "sbv" => "YouTube's own subtitle format.",_ => "",}}@@ -326,7 +343,7 @@ pub fn on_engine(s: &mut AppState, msg: &EngineMsg) {}let f = &mut s.formats;f.export_video = ext_list(v.get("export_video"));- if !f.export.contains(&f.format) && !f.export_video.contains(&f.format) {+ if !f.export.contains(&f.format) && !f.export_video.contains(&f.format) && !is_subtitles(&f.format) {f.format = f.export.first().cloned().unwrap_or_else(|| "wav".into());}}@@ -462,7 +479,7 @@ fn on_picked(s: &mut AppState, choice: Option<PathBuf>) {if let Phase::Picking(job) = std::mem::take(&mut s.formats.phase)&& let Some(dest) = choice{- finish_pick(s, job, dest);+ finish_pick(s, *job, dest);}}@@ -487,7 +504,7 @@ pub fn export_button(p: Palette, menu: Menu, grow: bool) -> El {b.build(p)}-fn toggle_menu(s: &mut AppState, menu: Menu) {+pub fn toggle_menu(s: &mut AppState, menu: Menu) {let f = &mut s.formats;if f.menu.as_ref().is_some_and(|m| m.anchor == menu.anchor) {f.menu = None;@@ -554,7 +571,7 @@ fn start_export(s: &mut AppState) {if s.shell.scripted() {return;}- let format = s.formats.format.clone();+ let format = chosen(&s.formats, &menu).to_owned();let video = if is_video(&format) {match video_job(&s.formats, &menu) {Ok(v) => Some(v),@@ -572,9 +589,13 @@ fn start_export(s: &mut AppState) {menu.src.file_stem().map_or_else(|| "audio".into(), |n| n.to_string_lossy().into_owned()));let (ext, label) = (format.clone(), label_of(&format).to_owned());- let title = if video.is_some() { "Export video" } else { "Export audio" };+ let title = match () {+ _ if is_subtitles(&format) => "Save subtitles",+ _ if video.is_some() => "Export video",+ _ => "Export audio",+ };let dir = menu.src.parent().map(Path::to_path_buf).filter(|d| d.is_dir());- s.formats.phase = Phase::Picking(Job { menu, format, quality: s.formats.quality, video });+ s.formats.phase = Phase::Picking(Box::new(Job { menu, format, quality: s.formats.quality, video }));std::thread::spawn(move || {let mut dialog = rfd::FileDialog::new().set_title(title).set_file_name(name).add_filter(label, &[ext]);if let Some(d) = dir {@@ -596,6 +617,14 @@ fn finish_pick(s: &mut AppState, job: Job, mut dest: PathBuf) {start_video(s, job.menu.clone(), &job.format, v, dest);return;}+ if is_subtitles(&job.format) {+ let params = subtitles_params(&job.menu, &job.format, &dest);+ match shell::request(s, "subtitles.export", params) {+ Some(req) => s.formats.phase = Phase::Exporting { req, dest },+ None => shell::toast(s, Tone::Danger, "The engine is not running, so the subtitles cannot be saved yet."),+ }+ return;+ }// tmp is emptied when the engine starts, so the playback WAV may be gone.let audio = if job.menu.audio.is_file() { job.menu.audio } else { job.menu.src };let audio_is_wav = audio.extension().is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("wav"));@@ -617,6 +646,20 @@ fn finish_pick(s: &mut AppState, job: Job, mut dest: PathBuf) {}}+fn subtitles_params(m: &Menu, format: &str, dest: &Path) -> Value {+ let mut params = json!({ "format": format, "dest": dest });+ match &m.lines {+ Some(lines) => params["segments"] = json!(lines),+ None => {+ params["path"] = json!(m.src);+ if let Some(side) = &m.sidecar {+ params["sidecar"] = json!(side);+ }+ }+ }+ params+}+fn start_video(s: &mut AppState, menu: Menu, format: &str, v: &VideoJob, dest: PathBuf) {if same_file(&v.path, &dest) {if v.subtitles.is_some() {@@ -644,12 +687,12 @@ fn same_file(a: &Path, b: &Path) -> bool {}}-fn chip_grid(s: &AppState, p: Palette, formats: &[&(&str, &str)]) -> El {+fn chip_grid(p: Palette, cur: &str, formats: &[&(&str, &str)]) -> El {let mut grid = col().w_full().gap(6.0);for chunk in formats.chunks(4) {let mut r = row().w_full().gap(6.0);for (ext, label) in chunk {- let on = s.formats.format == *ext;+ let on = cur == *ext;let ext_owned = (*ext).to_owned();r = r.child(row()@@ -679,20 +722,20 @@ fn chip_grid(s: &AppState, p: Palette, formats: &[&(&str, &str)]) -> El {grid}-fn format_chips(s: &AppState, p: Palette) -> El {+fn format_chips(s: &AppState, p: Palette, m: &Menu) -> El {+ let cur = chosen(&s.formats, m);+ let subtitles: Vec<_> = EXPORT_SUBTITLES.iter().collect();+ if m.lines.is_some() {+ return chip_grid(p, cur, &subtitles);+ }let audio = writable(s);let video: Vec<_> = EXPORT_VIDEO.iter().filter(|(e, _)| s.formats.export_video.iter().any(|x| x == e)).collect();- if video.is_empty() {- return chip_grid(s, p, &audio);- }let group = |label: &str| text(label.to_owned()).font(ty::CAPTION).color(p.text_faint);- col()- .w_full()- .gap(6.0)- .child(group("Audio"))- .child(chip_grid(s, p, &audio))- .child(group("Video").mt(4.0))- .child(chip_grid(s, p, &video))+ let mut c = col().w_full().gap(6.0).child(group("Audio")).child(chip_grid(p, cur, &audio));+ if !video.is_empty() {+ c = c.child(group("Video").mt(4.0)).child(chip_grid(p, cur, &video));+ }+ c.child(group("Subtitles").mt(4.0)).child(chip_grid(p, cur, &subtitles))}fn quality_block(s: &AppState, p: Palette) -> El {@@ -767,26 +810,33 @@ fn progress_body(p: Palette, run: &VideoRun) -> Vec<El> {}fn menu_body(s: &AppState, p: Palette, m: &Menu) -> Vec<El> {- let blurb_text = if lossless(&s.formats.format) {+ let format = chosen(&s.formats, m);+ let blurb_text = if lossless(format) {"Lossless: every detail is kept, so quality does not apply.".to_owned()} else {- blurb(&s.formats.format).to_owned()+ blurb(format).to_owned()};- let options = if is_video(&s.formats.format) {+ let options = if is_video(format) {Some(video_block(s, p, m))} else {- (!lossless(&s.formats.format)).then(|| quality_block(s, p))+ (!lossless(format) && !is_subtitles(format)).then(|| quality_block(s, p))};- let go = Button::new("Export…").primary().small().icon(&DOWNLOAD).key("export-go").on_press(start_export).build(p);+ let go = Button::new(if m.lines.is_some() { "Save…" } else { "Export…" })+ .primary()+ .small()+ .icon(&DOWNLOAD)+ .key("export-go")+ .on_press(start_export)+ .build(p);let cancel =Button::new("Cancel").ghost().small().key("export-cancel").on_press(|s| s.formats.menu = None).build(p);let mut body = vec![col().w_full().gap(1.0)- .child(text("Export as").font(ty::TITLE).color(p.text))+ .child(text(if m.lines.is_some() { "Save subtitles" } else { "Export as" }).font(ty::TITLE).color(p.text)).child(text(file_name(&m.src)).font(ty::CAPTION).color(p.text_faint).truncate()),- format_chips(s, p),+ format_chips(s, p, m),text(blurb_text).font(ty::CAPTION).color(p.text_dim).wrap(),];body.extend(options);@@ -806,7 +856,7 @@ pub fn overlay(s: &AppState, p: Palette) -> Option<El> {_ => menu_body(s, p, m),};// The photo rows need room for their names next to a preview, a folder button, a time and a remove button.- let wide = is_video(&s.formats.format) && s.formats.photos.on;+ let wide = is_video(chosen(&s.formats, m)) && s.formats.photos.on;let panel = col().key("export-menu").w(if wide { 420.0 } else { 318.0 })@@ -1014,9 +1064,33 @@ mod tests {video: video.map(PathBuf::from),duration_s: 60.0,sidecar: sidecar.map(PathBuf::from),+ lines: None,}}+ #[test]+ fn subtitles_come_from_the_lines_or_the_result() {+ let mut m = menu(None, Some("/d/design/1/take.json"));+ let dest = Path::new("/out/take.srt");+ assert_eq!(+ subtitles_params(&m, "srt", dest),+ json!({"format": "srt", "dest": "/out/take.srt", "path": "/o/take.wav", "sidecar": "/d/design/1/take.json"})+ );+ let f = FormatsState { format: "mp3".into(), ..Default::default() };+ assert_eq!(chosen(&f, &m), "mp3");+ let words = vec![(1.0, 1.5, "Hi.".to_owned())];+ m.lines = Some(vec![RedubSegmentIn { start: 1.0, end: 2.5, text: "Hi.".into(), words }]);+ assert_eq!(chosen(&f, &m), "srt");+ assert_eq!(+ subtitles_params(&m, "vtt", Path::new("/out/take.vtt")),+ json!({+ "format": "vtt",+ "dest": "/out/take.vtt",+ "segments": [{"start": 1.0, "end": 2.5, "text": "Hi.", "words": [[1.0, 1.5, "Hi."]]}],+ })+ );+ }+fn sent(f: &FormatsState, m: &Menu) -> (&'static str, Value) {video_request(&video_job(f, m).unwrap(), Path::new("/out/take.webm"), "webm")}diff --git a/crates/desktop/src/ui/redub.rs b/crates/desktop/src/ui/redub.rsindex da3115a..6e5f932 100644--- a/crates/desktop/src/ui/redub.rs+++ b/crates/desktop/src/ui/redub.rs@@ -1438,6 +1438,7 @@ fn export_menu(r: &Redub, anchor: String) -> formats::Menu {video: r.video.clone(),duration_s: r.duration_s,sidecar: None,+ lines: None,}}@@ -2272,11 +2273,14 @@ fn review_table(s: &AppState, p: Palette) -> El {if let Some(l) = r.lang_label() {head = head.child(badge(p, &l, Tone::Neutral));}- head = head.child(el().grow(1.0)).child(- text(format!("{n} line{} · {} of speech", if n == 1 { "" } else { "s" }, fmt_time(total)))- .font(ty::CAPTION)- .color(p.text_faint),- );+ head = head+ .child(el().grow(1.0))+ .child(+ text(format!("{n} line{} · {} of speech", if n == 1 { "" } else { "s" }, fmt_time(total)))+ .font(ty::CAPTION)+ .color(p.text_faint),+ )+ .child(subtitles_file_button(s, p));let cols = row().w_full().gap(10.0)@@ -2512,6 +2516,25 @@ fn transcribe_row(s: &AppState, p: Palette) -> El {.child(el().grow(1.0).min_w(0.0).child(hint.wrap()))}+const SUBTITLES_FILE: &str = "redub-subtitles-file";++fn subtitles_file_button(s: &AppState, p: Palette) -> El {+ Button::new("Save subtitles…")+ .small()+ .icon(&formats::DOWNLOAD)+ .key(SUBTITLES_FILE)+ .disabled(s.redub.file.is_none() || s.redub.kept_segments().next().is_none())+ .on_press(open_subtitles_file)+ .build(p)+}++fn open_subtitles_file(s: &mut AppState) {+ let Some(src) = s.redub.file.as_ref().map(|f| f.path.clone()) else { return };+ let menu =+ formats::Menu { anchor: SUBTITLES_FILE.into(), src, lines: Some(segments_in(&s.redub)), ..Default::default() };+ formats::toggle_menu(s, menu);+}+fn transcript_list(s: &AppState, p: Palette) -> El {let r = &s.redub;let total: f32 = r.kept_segments().map(|g| (g.end - g.start).max(0.0)).sum();@@ -2537,6 +2560,7 @@ fn transcript_list(s: &AppState, p: Palette) -> El {.font(ty::CAPTION).color(p.text_faint),);+ head = head.child(subtitles_file_button(s, p));let busy = r.busy();let rows =r.segments.iter().enumerate().map(|(i, g)| segment_row(p, i, g, busy, false, r.mode == RedubMode::Subtitles));@@ -3558,6 +3582,11 @@ fn scene_subtitles_transcript(s: &mut AppState) {s.redub.mode = RedubMode::Subtitles;}+fn scene_subtitles_file(s: &mut AppState) {+ scene_subtitles_transcript(s);+ open_subtitles_file(s);+}+fn scene_subtitles_photos(s: &mut AppState) {scene_transcript(s);s.redub.mode = RedubMode::Subtitles;@@ -3656,6 +3685,7 @@ pub fn scenes() -> &'static [super::Scene] {("redub_subtitles_transcript", scene_subtitles_transcript),("redub_subtitles_done", scene_subtitles_done),("redub_subtitles_photos", scene_subtitles_photos),+ ("redub_subtitles_file", scene_subtitles_file),]}@@ -3809,6 +3839,21 @@ mod tests {assert!(p.get("images").is_none());}+ #[test]+ fn a_transcript_saves_its_kept_lines_as_subtitles() {+ let mut s = AppState::default();+ scene_subtitles_transcript(&mut s);+ s.redub.segments[2].edit = TextEdit::new(" ");+ open_subtitles_file(&mut s);+ let m = s.formats.menu.clone().unwrap();+ assert_eq!((m.anchor.as_str(), m.src.clone()), (SUBTITLES_FILE, s.redub.file.as_ref().unwrap().path.clone()));+ let texts: Vec<_> = m.lines.unwrap().into_iter().map(|g| g.text).collect();+ assert_eq!(texts, segments_in(&s.redub).into_iter().map(|g| g.text).collect::<Vec<_>>());+ assert_eq!(texts.len(), 3);+ open_subtitles_file(&mut s);+ assert!(s.formats.menu.is_none());+ }+#[test]fn subtitles_send_the_photos_over_a_sound_or_a_video() {let mut s = AppState::default();diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rsindex f965141..83e05a9 100644--- a/crates/mcp/src/server.rs+++ b/crates/mcp/src/server.rs@@ -48,7 +48,7 @@ voice from recordings of the speaker (voice_recordings adds more, train_voice trmanage_voice renames, deletes or exports it); design_voice makes a new voice from a description instead. \export_video turns results into a video (one result, or book chapters joined into one episode with a picture and \subtitles per chapter), transcribe turns speech into timed lines, subtitle_video burns subtitles into a video, \-dub_video translates a video and dubs it in a voice, respeak speaks a file's (edited) lines again in a voice and \+export_subtitles saves them as a subtitle file (SRT, WebVTT, SBV), dub_video translates a video and dubs it in a voice, respeak speaks a file's (edited) lines again in a voice and \convert_voice turns its speech into a trained voice. list_results, export_audio and delete_result handle the saved \results. This server is a client of the Mimvox local HTTP API (on in Mimvox Settings, API, or `mimvox serve`). \Paths in requests and answers are on the API's machine: with a remote API, upload_file a local file first and \@@ -59,7 +59,7 @@ const ENGINE_CALL: &str = "Call any Mimvox engine method through the API's /rpceverything the app can do. Method families: hello, components.set; voices.* (list, create, rename, delete, import, \export, warm, reference_candidates, set_reference, add_reference, remove_reference, reference_from_media, \media_cancel, clear_media, design, design_cancel, design_takes, design_delete); media.combine; video.export, \-video.cancel; presets.list; text.analyze, text.import, text.stress; recording.check; dataset.add, dataset.remove, \+video.cancel, subtitles.export; presets.list; text.analyze, text.import, text.stress; recording.check; dataset.add, dataset.remove, \dataset.summary; train.start, train.pause, train.resume, train.cancel; tts.generate, tts.cancel, tts.languages; \outputs.list, outputs.play, outputs.delete; formats.list, audio.export; book.start, book.resume, book.pause, \book.cancel, book.list, book.get, book.delete, book.reread, book.play; redub.probe, redub.prepare, redub.transcribe, \@@ -341,6 +341,25 @@ impl VideoFormat {}}+#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum SubtitleFormat {+ #[default]+ Srt,+ Vtt,+ Sbv,+}++impl SubtitleFormat {+ fn as_str(self) -> &'static str {+ match self {+ Self::Srt => "srt",+ Self::Vtt => "vtt",+ Self::Sbv => "sbv",+ }+ }+}+#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]#[serde(rename_all = "lowercase")]pub enum Position {@@ -462,6 +481,30 @@ pub struct SubtitleVideoArgs {pub timeout_s: Option<u64>,}+#[derive(Debug, Deserialize, JsonSchema)]+pub struct ExportSubtitlesArgs {+ /// The lines to save (seconds), such as transcribe's segments; given, nothing is transcribed.+ #[serde(default)]+ pub segments: Option<Vec<Line>>,+ /// An audio or video file on the API's machine: transcribed when no segments are given, and where the+ /// subtitle file goes by default.+ #[serde(default)]+ pub path: Option<String>,+ /// srt (default), vtt (WebVTT) or sbv (YouTube's SubViewer).+ #[serde(default)]+ pub format: Option<SubtitleFormat>,+ /// ISO 639-1 code of the speech to transcribe, or "auto" (default) to detect it.+ #[serde(default)]+ pub language: Option<String>,+ /// Absolute path of the subtitle file on the API's machine (replaced when it exists); default: named after path,+ /// placed as export_video places a video.+ #[serde(default)]+ pub dest: Option<String>,+ /// Seconds to wait for the transcription (default 1800); after that it goes on and wait_job follows it.+ #[serde(default)]+ pub timeout_s: Option<u64>,+}+#[derive(Debug, Deserialize, JsonSchema)]pub struct DubVideoArgs {/// A video on the API's machine.@@ -805,7 +848,7 @@ pub fn mime_for(path: &str) -> &'static str {"avi" => "video/x-msvideo","json" => "application/json","mimvoice" | "zip" => "application/zip",- "txt" | "srt" | "vtt" => "text/plain",+ "txt" | "srt" | "vtt" | "sbv" => "text/plain","png" => "image/png","jpg" | "jpeg" => "image/jpeg","gif" => "image/gif",@@ -1373,6 +1416,84 @@ impl Mimvox {Ok(with_links(summary, &[&dest]))}+ /// The file's lines as redub.transcribe hears them, `{start, end, text, words?}`, and their language; Err: the+ /// transcription still runs, with `then` the tool to give its segments to.+ async fn heard(+ &self,+ path: &str,+ language: &str,+ timeout: Duration,+ progress: Option<&mut Progress>,+ cancel: &CancellationToken,+ then: &str,+ ) -> Result<Result<(Vec<Value>, Option<String>), CallToolResult>, ApiError> {+ let params = json!({ "path": path, "language": language });+ let (job, ran) = self.run_job("redub.transcribe", params, "redub.cancel", timeout, progress, cancel).await?;+ let Ran::Done(t) = ran else {+ let hint = format!("still transcribing: follow it with wait_job, then give its segments to {then}");+ return Ok(Err(still_running(&job, &hint)));+ };+ let lines = t["segments"].as_array().cloned().unwrap_or_default();+ let lines = lines+ .iter()+ .map(|s| {+ let mut line = json!({ "start": s["start"], "end": s["end"], "text": s["text"] });+ if s["words"].is_array() {+ line["words"] = s["words"].clone();+ }+ line+ })+ .collect();+ Ok(Ok((lines, t["language"].as_str().map(str::to_string))))+ }++ async fn export_subtitles_inner(+ &self,+ args: ExportSubtitlesArgs,+ progress: Option<&mut Progress>,+ cancel: &CancellationToken,+ ) -> Result<CallToolResult, ApiError> {+ let format = args.format.unwrap_or_default().as_str();+ let dest = match (args.dest, &args.path) {+ (Some(dest), _) => dest,+ (None, Some(path)) => self.video_dest(&[path.as_str()], true, format).await?,+ (None, None) => return Err(ApiError::new("bad_request", "give path, or segments and dest")),+ };+ let mut summary = json!({ "transcribed": args.segments.is_none() });+ let segments: Vec<Value> = match (args.segments, &args.path) {+ (Some(given), _) => given.iter().map(|s| json!(s)).collect(),+ (None, Some(path)) => {+ let language = args.language.unwrap_or_else(|| "auto".into());+ let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);+ match self.heard(path, &language, timeout, progress, cancel, "export_subtitles").await? {+ Ok((lines, lang)) => {+ summary["language"] = json!(lang.unwrap_or(language));+ summary["segments"] = json!(lines);+ lines+ }+ Err(running) => return Ok(running),+ }+ }+ (None, None) => return Err(ApiError::new("bad_request", "give segments or path")),+ };+ if segments.is_empty() {+ return Err(ApiError::new("bad_request", "no speech was found in this file: no subtitles to save"));+ }+ let params = json!({ "format": format, "dest": dest, "segments": segments });+ let r = self.api.rpc("subtitles.export", params).await?;+ let path = r["path"].as_str().unwrap_or(&dest).to_string();+ for (key, value) in [+ ("path", json!(path)),+ ("uri", json!(file_uri(&path))),+ ("format", json!(format)),+ ("cues", r["cues"].clone()),+ ("size_bytes", r["size_bytes"].clone()),+ ] {+ summary[key] = value;+ }+ Ok(with_links(summary, &[&path]))+ }+async fn subtitle_inner(&self,args: SubtitleVideoArgs,@@ -1389,30 +1510,14 @@ impl Mimvox {if let Some(p) = progress.as_deref_mut() {p.span = (0.0, 50.0);}- let params = json!({ "path": args.path, "language": language });- let (job, ran) = self- .run_job("redub.transcribe", params, "redub.cancel", left(), progress.as_deref_mut(), cancel)- .await?;- let Ran::Done(t) = ran else {- return Ok(still_running(- &job,- "still transcribing: follow it with wait_job, then give its segments to subtitle_video",- ));- };- if let Some(lang) = t["language"].as_str() {- language = lang.to_string();+ let then = "subtitle_video";+ match self.heard(&args.path, &language, left(), progress.as_deref_mut(), cancel, then).await? {+ Ok((lines, lang)) => {+ language = lang.unwrap_or(language);+ lines+ }+ Err(running) => return Ok(running),}- let lines = t["segments"].as_array().cloned().unwrap_or_default();- lines- .iter()- .map(|s| {- let mut line = json!({ "start": s["start"], "end": s["end"], "text": s["text"] });- if s["words"].is_array() {- line["words"] = s["words"].clone();- }- line- })- .collect()}};if segments.is_empty() {@@ -2316,6 +2421,23 @@ impl Mimvox {Ok(self.subtitle_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))}+ #[tool(description = "Save timed lines as a subtitle file to upload to YouTube or open in a player, instead of \+ burning them in: SRT (default), WebVTT or SBV, cut into cues as subtitle_video draws them. \+ The lines are the given segments (such as transcribe's, with their words), or path \+ transcribed first (redub.transcribe); then subtitles.export. Returns the file's path, a \+ mimvox://file/ link, the number of cues and, when transcribed, the segments. Cancelling \+ the call stops the transcription.")]+ async fn export_subtitles(+ &self,+ Parameters(args): Parameters<ExportSubtitlesArgs>,+ meta: RequestMetaObject,+ peer: Peer<RoleServer>,+ cancel: CancellationToken,+ ) -> Result<CallToolResult, ErrorData> {+ let mut progress = Progress::new(&meta, peer);+ Ok(self.export_subtitles_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))+ }+#[tool(description = "Translate a video's speech and dub it in a voice (Redub's Translate & dub, redub.dub with \output video): the new voice over the original music and sounds, optionally with the \translated text drawn in. Waits for redub.done (minutes) and returns the paths of the \diff --git a/crates/mcp/tests/mcp.rs b/crates/mcp/tests/mcp.rsindex 8961cb7..50f72a6 100644--- a/crates/mcp/tests/mcp.rs+++ b/crates/mcp/tests/mcp.rs@@ -17,7 +17,7 @@ use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;const WAIT: Duration = Duration::from_secs(30);-const TOOLS: [&str; 30] = [+const TOOLS: [&str; 31] = ["engine_call","list_voices","speak",@@ -35,6 +35,7 @@ const TOOLS: [&str; 30] = ["wait_job","export_video","subtitle_video",+ "export_subtitles","dub_video","create_voice","manage_voice",@@ -601,6 +602,42 @@ async fn videos() {assert_eq!(res["structuredContent"]["error"]["code"], "not_found");}+#[tokio::test]+async fn subtitle_files() {+ let api = api(None).await;+ let home = tempfile::tempdir().unwrap();+ let mut mcp = Mcp::start(&api.url, home.path(), &[], &[]).await;+ let clip = api.data.join("outputs").join("clip.wav");+ write_wav(&clip, 2.0);++ let args = json!({ "path": clip, "format": "vtt" });+ let req = json!({ "name": "export_subtitles", "arguments": args, "_meta": { "progressToken": "p-file" } });+ let res = mcp.request("tools/call", req).await;+ let done = &res["result"]["structuredContent"];+ let dest = clip.with_extension("vtt");+ assert_eq!(Path::new(done["path"].as_str().unwrap()), dest, "{res}");+ assert!(dest.is_file());+ assert_eq!((&done["transcribed"], &done["language"], &done["cues"]), (&json!(true), &json!("en"), &json!(2)));+ let link = res["result"]["content"].as_array().unwrap().iter().find(|c| c["type"] == "resource_link").cloned();+ assert_eq!(link.expect("a link")["mimeType"], "text/plain");+ assert!(!mcp.progress("p-file").is_empty());+ let params = sent(&api.data, "subtitles.export");+ assert_eq!((¶ms["format"], ¶ms["dest"]), (&json!("vtt"), &json!(dest)));+ assert_eq!(params["segments"], done["segments"]);+ assert!(done["segments"][0]["words"].is_array());+ let again = mcp.ok("export_subtitles", json!({ "path": clip, "format": "vtt" })).await;+ assert_eq!(Path::new(again["path"].as_str().unwrap()), dest.with_file_name("clip_2.vtt"));++ let given = json!([{ "start": 3700.0, "end": 3702.5, "text": "Over an hour." }]);+ let mine = home.path().join("mine.srt");+ let done = mcp.ok("export_subtitles", json!({ "segments": given, "dest": mine })).await;+ assert_eq!((&done["transcribed"], done.get("segments")), (&json!(false), None));+ let params = sent(&api.data, "subtitles.export");+ assert_eq!((¶ms["format"], ¶ms["segments"]), (&json!("srt"), &given));+ assert!(std::fs::read_to_string(&mine).unwrap().contains("01:01:40,000 --> 01:01:42,500"));+ assert_eq!(code(&mcp.err("export_subtitles", json!({ "segments": given })).await), "bad_request");+}+fn code(res: &Value) -> &Value {&res["structuredContent"]["error"]["code"]}diff --git a/docs/usage.md b/docs/usage.mdindex a0e4d62..b15daef 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -405,6 +405,7 @@ The tools:| `import_text`, `find_speakers`, `start_book`, `book_status`, `pause_book`, `resume_book` | a document read as an audiobook, in one voice or with the men and women in their own voices || `transcribe` | the speech of a file as timed lines, optionally translated || `respeak`, `convert_voice`, `dub_video`, `subtitle_video` | Redub's Re-speak, Convert voice, Translate & dub (the video as the result) and Subtitle video (photos over the sound, optionally fading), each in one call |+| `export_subtitles` | timed lines (given, or a file transcribed first) saved as an SRT, WebVTT or SBV subtitle file, to upload to YouTube or open in a player || `export_video` | a video of a result, or of book chapters joined into one episode with a picture and subtitles per chapter; it answers where each chapter starts, for chapter marks || `list_results`, `export_audio`, `delete_result` | your saved results: list them, save one in another format, delete one || `job_status`, `wait_job` | long jobs (books, training), with progress |@@ -855,6 +856,10 @@ for the lossy formats (for example MP3 at 320, 192 or 128 kbps). Your last choicThe same menu also makes a **video** of any result (Speak, Redub, Design): MP4, MKV, WebM or MOV.+Its **Subtitles** formats save the result's spoken text as a subtitle file instead: **SRT** (YouTube, players and+video editors), **WebVTT** (YouTube and web players) or **SBV** (YouTube's own format). The text and its times are+those a video's subtitles would get (below), cut into the same lines of at most two rows.+- **Subtitles** (off by default) draw the spoken text at the **Bottom** or the **Top**. Results made since this@@ -1252,12 +1257,16 @@ it.**Photos**. Photos show over the sound in the same box as in [Export as…](#results-and-export): **Add photos…**,previews, drag to reorder, the folder button to replace one, start times, **Even starts** and **Fade in andbetween**.-6. Press **Make video**.+6. Press **Make video**, or **Save subtitles…** above the lines to save them as a subtitle file (SRT, WebVTT or+ SBV) to upload with the video to YouTube or open in a player, with nothing burned in.A video keeps its picture (unless Black or photos replace it), encoded again with the words drawn in, and its original sound,in its own container. An audio file, or a video with photos, gets a 1920x1080 picture with the words on it, on black orover your photos.+**Save subtitles…** is above the transcript in every mode, and above the translation in Translate & dub's review, so+a translation can be saved as subtitles too. The file is named after the source file and saved where you choose.+Redub remembers what you were working on: the file, each mode's transcript with your edits (switching modes keepsthem apart), its language and the photos come back after the app restarts (unless the file has been moved or deleted). The sound is also saved as the result's audio, in the**Save as** format, so **Result** plays it in the app. In this mode **Results** lists only subtitled videos (*No@@ -1272,8 +1281,8 @@ subtitled videos yet* before the first one); each row says *Subtitled* and has *`outputs/redub_<date>_<time>.wav`, or in the format chosen with **Save as** in the Results header (shared withSpeak, see [Results and export](#results-and-export)). For a video with **Output: Video with new voice**, also`outputs/redub_<date>_<time>.mp4` (or the source's container) next to it.-- **Export as…** on a result converts its audio to WAV, MP3, FLAC, OGG, Opus, M4A or AIFF, or makes a video (MP4,- MKV, WebM, MOV), as on Speak. A result with a video exports that video, in another container when asked.+- **Export as…** on a result converts its audio to WAV, MP3, FLAC, OGG, Opus, M4A or AIFF, makes a video (MP4,+ MKV, WebM, MOV) or saves its text as subtitles (SRT, WebVTT, SBV), as on Speak. A result with a video exports that video, in another container when asked.- The **trash** button on a result in the Results list deletes it, after asking, exactly as on Speak: the saved filein `outputs` and its playback copy are removed and the row leaves the list. The original file you dropped is nevertouched.diff --git a/engine/src/mimvox_engine/redub/subtitles.py b/engine/src/mimvox_engine/redub/subtitles.pyindex b600eca..4787545 100644--- a/engine/src/mimvox_engine/redub/subtitles.py+++ b/engine/src/mimvox_engine/redub/subtitles.py@@ -633,20 +633,56 @@ def ass(items: list[Cue], width_px: int, height_px: int, position: str = "bottomreturn "\n".join([*head, *events]) + "\n"-def _srt_time(t: float) -> str:+def _ms(t: float) -> tuple[int, int, int, int]:ms = max(round(t * 1000), 0)- return f"{ms // 3600000:02d}:{ms // 60000 % 60:02d}:{ms // 1000 % 60:02d},{ms % 1000:03d}"+ return ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000+++def _srt_time(t: float) -> str:+ h, m, s, ms = _ms(t)+ return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"+++def _vtt_time(t: float) -> str:+ h, m, s, ms = _ms(t)+ return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"+++def _sbv_time(t: float) -> str:+ h, m, s, ms = _ms(t)+ return f"{h}:{m:02d}:{s:02d}.{ms:03d}"+++def _plain(line: str) -> str:+ return re.sub(r"\s+", " ", line).strip()def srt(items: list[Cue]) -> str:"""For MP4 and WebM tracks: ffmpeg keeps an escaped ASS brace escaped in them, while an SRT brace stays a brace."""blocks = []for k, c in enumerate(items, 1):- text = "\n".join(re.sub(r"\s+", " ", ln.replace("\\", "\\\u200b")).strip() for ln in c.lines)+ text = "\n".join(_plain(ln.replace("\\", "\\\u200b")) for ln in c.lines)blocks.append(f"{k}\n{_srt_time(c.start)} --> {_srt_time(c.end)}\n{text}\n")return "\n".join(blocks)+def vtt(items: list[Cue]) -> str:+ blocks = ["WEBVTT\n"]+ for c in items:+ lines = (_plain(ln).replace("&", "&").replace("<", "<").replace(">", ">") for ln in c.lines)+ blocks.append(f"{_vtt_time(c.start)} --> {_vtt_time(c.end)}\n" + "\n".join(lines) + "\n")+ return "\n".join(blocks)+++def sbv(items: list[Cue]) -> str:+ return "\n".join(+ f"{_sbv_time(c.start)},{_sbv_time(c.end)}\n" + "\n".join(_plain(ln) for ln in c.lines) + "\n" for c in items+ )+++WRITERS: dict[str, Callable[[list[Cue]], str]] = {"srt": srt, "vtt": vtt, "sbv": sbv}++def write(plan: Plan, items: list[Cue], width_px: int, height_px: int) -> tuple[Path, Path]:"""(the ASS file, the SRT next to it)."""plan.path.parent.mkdir(parents=True, exist_ok=True)diff --git a/engine/src/mimvox_engine/videoexport.py b/engine/src/mimvox_engine/videoexport.pyindex 2a54c59..32ece6b 100644--- a/engine/src/mimvox_engine/videoexport.py+++ b/engine/src/mimvox_engine/videoexport.py@@ -676,6 +676,17 @@ def _dest(params: dict[str, Any], fmt: str) -> Path:return out+def _sidecar(params: dict[str, Any]) -> Path | None:+ side = params.get("sidecar")+ if side in (None, ""):+ return None+ if not isinstance(side, str):+ raise EngineError("bad_request", "'sidecar' must be a file path")+ if not Path(side).is_file():+ raise EngineError("not_found", f"file not found: {side}")+ return Path(side)++def request(params: dict[str, Any]) -> Request:"""Blocking (probes the files)."""fmt = params.get("format")@@ -723,14 +734,7 @@ def request(params: dict[str, Any]) -> Request:if out.resolve() == path.resolve():raise EngineError("bad_request", "'dest' must differ from the source file")lines, source = given_lines(params)- side = params.get("sidecar")- sidecar = None- if side not in (None, ""):- if not isinstance(side, str):- raise EngineError("bad_request", "'sidecar' must be a file path")- sidecar = Path(side)- if not sidecar.is_file():- raise EngineError("not_found", f"file not found: {sidecar}")+ sidecar = _sidecar(params)media.require_ffmpeg()if fmt not in containers(media._ffmpeg_lists()[2]):raise EngineError("not_ready", f"This ffmpeg build has no encoder for {fmt.upper()} video.")@@ -1005,3 +1009,44 @@ async def video_cancel(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:for j in hit:ctx.cancel(j)return {"cancelled": bool(hit)}+++def _heard(segments: Any) -> list[subtitles.Words]:+ out: list[subtitles.Words] = []+ for s in segments:+ words = s.get("words") if isinstance(s.get("words"), list) else []+ ok = (w for w in words if isinstance(w, list | tuple) and len(w) == 3)+ out.append([(float(a), float(b), w) for a, b, w in ok if _num(a) and _num(b) and isinstance(w, str)])+ return out+++def save_subtitles(params: dict[str, Any]) -> dict[str, Any]:+ """Blocking (probes the file, and decodes it when its lines are estimated)."""+ fmt = params.get("format")+ if fmt not in subtitles.WRITERS:+ raise EngineError("bad_request", f"'format' must be one of {', '.join(subtitles.WRITERS)}")+ dest = _dest(params, fmt)+ lines, source = given_lines(params)+ words = _heard(params["segments"]) if lines is not None and source == "given" else None+ if lines is None:+ if params.get("path") in (None, ""):+ raise EngineError("bad_request", "give 'segments', 'segments_path' or 'path'")+ path = media._check_file(params.get("path"))+ sidecar = _sidecar(params)+ duration = float(media.probe(path)["duration_s"])+ lines, source, _ = part_lines(Part(path, 0.0, duration), sidecar)+ if not lines:+ raise EngineError("bad_request", "This file has no saved text, so it has no subtitles.")+ items = subtitles.cues(lines, words)+ if not items:+ raise EngineError("bad_request", "No line has a text and a length, so there are no subtitles.")+ dest.parent.mkdir(parents=True, exist_ok=True)+ part = dest.with_name(f"{dest.name}.part-{os.getpid()}")+ part.write_text(subtitles.WRITERS[fmt](items), encoding="utf-8")+ part.replace(dest)+ return {"path": str(dest), "cues": len(items), "source": source, "size_bytes": dest.stat().st_size}+++@method("subtitles.export")+async def subtitles_export(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ return await aio.run_io(save_subtitles, params)diff --git a/engine/tests/test_redub_subtitles.py b/engine/tests/test_redub_subtitles.pyindex 216e014..75d7975 100644--- a/engine/tests/test_redub_subtitles.py+++ b/engine/tests/test_redub_subtitles.py@@ -193,6 +193,25 @@ def test_srt_keeps_braces_and_breaks_lines():assert doc == "1\n00:00:00,500 --> 00:00:02,000\nHi {there}\nline two\n"+def test_subtitle_files_time_each_cue_past_an_hour():+ cues = [subtitles.Cue(0.5, 2.0, ("Hi",)), subtitles.Cue(3599.9996, 3725.0424, ("Over", "an hour"))]+ assert subtitles.srt(cues).splitlines()[5] == "01:00:00,000 --> 01:02:05,042"+ assert subtitles.vtt(cues) == (+ "WEBVTT\n\n00:00:00.500 --> 00:00:02.000\nHi\n\n01:00:00.000 --> 01:02:05.042\nOver\nan hour\n"+ )+ assert subtitles.sbv(cues) == "0:00:00.500,0:00:02.000\nHi\n\n1:00:00.000,1:02:05.042\nOver\nan hour\n"+ assert subtitles.vtt([subtitles.Cue(-0.2, 100 * 3600.0, ("x",))]).splitlines()[2] == (+ "00:00:00.000 --> 100:00:00.000"+ )+++def test_subtitle_files_escape_what_their_format_reads_as_markup():+ cue = subtitles.Cue(1.0, 2.0, ("a <b> & c --> d", " tabs\tand\nbreaks "))+ assert subtitles.vtt([cue]).splitlines()[3:5] == ["a <b> & c --> d", "tabs and breaks"]+ assert subtitles.srt([subtitles.Cue(1.0, 2.0, ("C:\\N {x}",))]).splitlines()[2] == "C:\\\u200bN {x}"+ assert subtitles.sbv([cue]).splitlines()[1:3] == ["a <b> & c --> d", "tabs and breaks"]++def test_fonts_by_script_and_platform():assert subtitles.font_name("zh", "win32") == "Microsoft YaHei"assert subtitles.font_name("ja", "darwin") == "Hiragino Sans"diff --git a/engine/tests/test_video_export.py b/engine/tests/test_video_export.pyindex 07dedd6..5c23efb 100644--- a/engine/tests/test_video_export.py+++ b/engine/tests/test_video_export.py@@ -764,3 +764,57 @@ def test_a_failing_encoder_falls_back_to_the_next(tmp_path, clip, monkeypatch):event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", subtitles=None)assert event == "video.done", dataassert picture_and_length(dest) == (True, pytest.approx(1.5, abs=0.1))+++def save(**params):+ return videoexport.save_subtitles(params)+++def test_subtitle_file_of_given_lines_uses_their_words(tmp_path):+ words = [[0.5, 0.9, "Hello"], [1.0, 1.4, "there."], [5.0, 5.5, "Bye."]]+ lines = [{"start": 0.5, "end": 5.5, "text": "Hello there. Bye.", "words": words}]+ r = save(dest=str(tmp_path / "a.vtt"), format="vtt", segments=lines)+ assert (r["cues"], r["source"]) == (2, "given")+ doc = (tmp_path / "a.vtt").read_text(encoding="utf-8")+ assert doc.startswith("WEBVTT\n\n00:00:00.500 --> 00:00:01.700\nHello there.\n")+ assert "00:00:05.000 --> " in doc+ assert r["size_bytes"] == (tmp_path / "a.vtt").stat().st_size+ assert not list(tmp_path.glob("*.part*"))+++def test_subtitle_file_of_a_result_reads_its_sidecar_or_estimates(tmp_path):+ path = tmp_path / "take.wav"+ sf.write(path, bursts((0.1, False), (0.5, True), (0.4, False), (0.4, True), (0.1, False)), SR)+ side = tmp_path / "take.result.json"+ side.write_text(json.dumps({"segments": [{"start": 0.1, "end": 0.6, "text": "Recorded."}]}), encoding="utf-8")+ r = save(path=str(path), dest=str(tmp_path / "take.srt"), format="srt")+ assert (r["cues"], r["source"]) == (1, "recorded")+ assert (tmp_path / "take.srt").read_text(encoding="utf-8").startswith("1\n00:00:00,100 --> ")+ if media.ffmpeg_path() is None:+ return+ side.write_text(json.dumps({"text": "Hello there. Second line."}), encoding="utf-8")+ r = save(path=str(path), dest=str(tmp_path / "take.sbv"), format="sbv")+ assert (r["cues"], r["source"]) == (2, "estimated")+++def test_subtitle_file_refuses_bad_requests(tmp_path):+ path = tmp_path / "take.wav"+ sf.write(path, np.zeros(SR, np.float32), SR)+ lines = [{"start": 0, "end": 1, "text": "Hi."}]+ cases = [+ ({"format": "ass", "dest": str(tmp_path / "a.ass"), "segments": lines}, "bad_request"),+ ({"format": "srt", "dest": "a.srt", "segments": lines}, "bad_request"),+ ({"format": "srt", "dest": str(tmp_path / "a.vtt"), "segments": lines}, "bad_request"),+ ({"format": "srt", "dest": str(tmp_path / "a.srt")}, "bad_request"),+ (+ {"format": "srt", "dest": str(tmp_path / "a.srt"), "segments": [{"start": 1, "end": 1, "text": "x"}]},+ "bad_request",+ ),+ ({"format": "srt", "dest": str(tmp_path / "a.srt"), "path": str(path)}, "bad_request"),+ ({"format": "srt", "dest": str(tmp_path / "a.srt"), "path": str(tmp_path / "gone.wav")}, "not_found"),+ ]+ for params, code in cases:+ with pytest.raises(EngineError) as e:+ save(**params)+ assert e.value.code == code, params+ assert not (tmp_path / "a.srt").exists()