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
fix(app): Record over a voice in another language, or a new one named My voice (Language) #N (#166)
Taras Hevlich8ded03ab5917
diff --git a/contract/engine-protocol.md b/contract/engine-protocol.mdindex 5522488..ff10b1c 100644--- a/contract/engine-protocol.md+++ b/contract/engine-protocol.md@@ -642,7 +642,9 @@ coverage:speech model speaks, remembered as `record_language` in `settings.json`); "Use my own text" offers "Detect" or oneof them (`text.analyze` `language`). A new voice is madein the language that is read; an empty active voice in another language is switched to it (`voices.rename`- `language`); one with recordings in another language is kept and a new voice "<name> (<Language>)" is made.+ `language`); one with recordings in another language is kept ("This is for" defaults to a new voice, named as+ typed or "My voice (French) #1"), or, when picked and confirmed, recorded over: the first part is saved with+ `dataset.add` `start_over`.### `presets.list``{"language"?}` -> `{"language":"uk","languages":[{"code":"en","name":"English","native":"English"},@@ -686,7 +688,9 @@ in the order quick, standard, pro.Errors: `not_found` (no such file), `bad_request` (unreadable or empty audio).### `dataset.add` / `dataset.remove` / `dataset.summary`-- `dataset.add {"voice_id","part_index","path","expected_s"?}`: reads any audio file (also the audio track of a+- `dataset.add {"voice_id","part_index","path","expected_s"?,"start_over"?,"language"?}`: with `start_over` the voice+ first loses everything but its id, name and creation time (recordings, reference clips, media pool, trained model)+ and takes `language`; then the part is added as usual. Otherwise it reads any audio file (also the audio track of avideo; so a user can import an existing file as a dataset part instead of recording), trims leading/trailing silence(0.25 s kept), normalises loudness (about -20 dBFS active speech, peak at most 0.9), stores mono 16-bit`dataset/part<N>.wav` (resampled to 44.1 kHz only above 48 kHz), replaces an older take of that part, refreshesdiff --git a/crates/api/openapi/methods.json b/crates/api/openapi/methods.jsonindex 248f9bb..1c4158c 100644--- a/crates/api/openapi/methods.json+++ b/crates/api/openapi/methods.json@@ -1392,6 +1392,14 @@"expected_s": {"type": "number","description": "Estimated reading time, seconds"+ },+ "start_over": {+ "type": "boolean",+ "description": "First remove the voice's recordings, reference clips, media pool and trained model"+ },+ "language": {+ "type": "string",+ "description": "With start_over: the voice's new language code"}},"required": [diff --git a/crates/desktop/src/ui/components.rs b/crates/desktop/src/ui/components.rsindex 8f47979..58cf662 100644--- a/crates/desktop/src/ui/components.rs+++ b/crates/desktop/src/ui/components.rs@@ -809,11 +809,38 @@ pub fn segmented_help(selected: usize,on_pick: impl Fn(&mut AppState, usize) + Clone + 'static,) -> El {- let mut strip = row().key(key.to_owned()).padding(3.0).gap(2.0).radius(17.0).fill(p.well).border_gradient(- 1.0,- Color::BLACK.alpha(0.35),- p.well_rim,- );+ segmented_sized(p, key, options, helps, selected, 28.0, 3.0, on_pick)+}++/// [`segmented`] as tall as a text field beside it (34 points), its options filling it.+pub fn segmented_tall(+ p: Palette,+ key: &str,+ options: &[&str],+ selected: usize,+ on_pick: impl Fn(&mut AppState, usize) + Clone + 'static,+) -> El {+ segmented_sized(p, key, options, &[], selected, 32.0, 1.0, on_pick)+}++/// [`segmented`] with options `height` points tall in a well `inset` points wide.+#[allow(clippy::too_many_arguments)]+fn segmented_sized(+ p: Palette,+ key: &str,+ options: &[&str],+ helps: &[&str],+ selected: usize,+ height: f32,+ inset: f32,+ on_pick: impl Fn(&mut AppState, usize) + Clone + 'static,+) -> El {+ let mut strip =+ row().key(key.to_owned()).center_y().padding(inset).gap(2.0).radius(17.0).fill(p.well).border_gradient(+ 1.0,+ Color::BLACK.alpha(0.35),+ p.well_rim,+ );for (i, name) in options.iter().enumerate() {let on = i == selected;let pick = on_pick.clone();@@ -823,10 +850,10 @@ pub fn segmented_help(.label(*name).checked(on).focusable(true)- .h(28.0)+ .h(height).px(14.0).center()- .radius(14.0)+ .radius(height / 2.0).fill(if on { p.accent.alpha(0.22) } else { Color::TRANSPARENT }).border(1.0, if on { p.accent.alpha(0.5) } else { Color::TRANSPARENT }).hover(if on { p.accent.alpha(0.28) } else { p.glass_hover })@@ -852,11 +879,12 @@ pub fn segmented_fill(enabled: bool,on_pick: impl Fn(&mut AppState, usize) + Clone + 'static,) -> El {- let mut strip = row().key(key.to_owned()).w_full().padding(3.0).gap(2.0).radius(17.0).fill(p.well).border_gradient(- 1.0,- Color::BLACK.alpha(0.35),- p.well_rim,- );+ let mut strip =+ row().key(key.to_owned()).w_full().center_y().padding(3.0).gap(2.0).radius(17.0).fill(p.well).border_gradient(+ 1.0,+ Color::BLACK.alpha(0.35),+ p.well_rim,+ );for (i, name) in options.iter().enumerate() {let on = i == selected;let mut opt = row()diff --git a/crates/desktop/src/ui/lang.rs b/crates/desktop/src/ui/lang.rsindex 55e9e43..9c24b65 100644--- a/crates/desktop/src/ui/lang.rs+++ b/crates/desktop/src/ui/lang.rs@@ -309,7 +309,8 @@ pub fn overlay(s: &AppState, p: &Palette) -> Option<El> {let q = s.langpick.search.text.trim().to_lowercase();let cur = current(s, target);let opts = options(s, target);- let mut list = col().w_full().gap(1.0);+ // Room for a focused row's ring, which the scrolling list would clip.+ let mut list = col().w_full().gap(1.0).padding(3.0);if q.is_empty() {list = list.child(text("Common").font(ty::OVERLINE).color(p.text_faint).px(12.0).pt(4.0).pb(2.0));for l in opts.iter().filter(|l| l.common) {diff --git a/crates/desktop/src/ui/mod.rs b/crates/desktop/src/ui/mod.rsindex c9fcbdd..3742ae5 100644--- a/crates/desktop/src/ui/mod.rs+++ b/crates/desktop/src/ui/mod.rs@@ -53,6 +53,7 @@ pub const SCENES: &[Scene] = &[("record_own_text", record::scene_own_text),("record_language_uk", record::scene_language_uk),("record_language_menu", record::scene_language_menu),+ ("record_other_language", record::scene_other_language),("record_session_uk", record::scene_session_uk),("record_own_text_uk", record::scene_own_text_uk),("record_recording", record::scene_recording),diff --git a/crates/desktop/src/ui/record.rs b/crates/desktop/src/ui/record.rsindex ca677bb..07a797f 100644--- a/crates/desktop/src/ui/record.rs+++ b/crates/desktop/src/ui/record.rs@@ -5,6 +5,8 @@ mod pick;mod session;mod widgets;+pub use pick::over_dialog;+use super::events::{self, Latest};use super::shell;use super::theme;@@ -21,8 +23,8 @@ use widgets::Tone;pub use fixtures::{scene_files_ask, scene_files_done, scene_files_hover, scene_files_working, scene_import_checking,scene_import_drop, scene_import_saved, scene_language_menu, scene_language_uk, scene_mic_open, scene_mic_picker,- scene_mic_warning, scene_new_voice, scene_notice_saved, scene_own_text, scene_own_text_uk, scene_picker,- scene_quick_ready, scene_recording, scene_recording_loud, scene_rejected, scene_saved_with_issues,+ scene_mic_warning, scene_new_voice, scene_notice_saved, scene_other_language, scene_own_text, scene_own_text_uk,+ scene_picker, scene_quick_ready, scene_recording, scene_recording_loud, scene_rejected, scene_saved_with_issues,scene_session_uk, scene_summary_ready,};@@ -287,6 +289,12 @@ pub struct RecordState {pub creating_voice: bool,new_voice_name: Option<String>,pub for_new: bool,+ /// The active voice was picked although it has recordings in another language: they are replaced.+ pub replace: bool,+ /// A reading plan waiting for "Record over" in the dialog.+ pub confirm_over: Option<Plan>,+ /// Recording over the voice: the first saved part replaces its recordings, references and trained model.+ pub over: bool,pub new_name: TextEdit,pub files: FilesFlow,pub import_over: bool,@@ -729,6 +737,9 @@ impl RecordState {}fn apply_summary(&mut self, sum: Summary) {+ if self.over {+ return;+ }let stored = |this: &Self, n: u32| {this.voice_id.as_ref()@@ -922,13 +933,21 @@ impl RecordState {};let dest = self.data_dir.join("voices").join(&voice).join("dataset").join(format!("part{}.wav", part + 1));let expected = self.plan.as_ref().and_then(|pl| pl.parts.get(part)).map(|x| x.est_seconds).filter(|e| *e > 0.0);- let params = json!({"voice_id": voice, "part_index": part + 1, "path": path, "expected_s": expected});+ let mut params = json!({"voice_id": voice, "part_index": part + 1, "path": path, "expected_s": expected});+ params["language"] = json!(self.plan.as_ref().map_or_else(|| self.lang().to_owned(), |p| p.language.clone()));+ if self.over {+ params["start_over"] = json!(true);+ }if !self.request("dataset.add", params, Pending::Add { part, dest }) {self.set_take_failed(part, "The engine is not running");}}fn on_added(&mut self, part: usize, dest: PathBuf, v: &Value) {+ if self.over {+ self.over = false;+ self.voices_dirty = true;+ }let verdict = v.pointer("/part/verdict").and_then(Value::as_str).map(Verdict::parse);let dur = v.pointer("/part/duration_s").and_then(Value::as_f64).map(|d| d as f32);let issues = v.pointer("/part").map(|p| str_list(p, "issues"));@@ -1169,54 +1188,90 @@ pub fn set_language(s: &mut AppState, code: &str) {}s.record.language = code.to_owned();s.record.presets_stale = true;+ s.record.replace = false;if !s.shell.scripted() {super::onboarding::save_setting("record_language", json!(code));}}+/// The active voice when it already has recordings in another language than the one read: those go to a new voice.+pub fn kept_voice(s: &AppState) -> Option<&shell::VoiceInfo> {+ shell::active_voice(s).filter(|v| v.lang() != s.record.lang() && (v.parts > 0 || v.trained))+}++/// "My voice (French) #2": the name of a new voice nobody typed a name for.+pub fn plain_name(s: &AppState, lang: &str) -> String {+ let base = format!("My voice ({})", super::lang::name(lang));+ let n = s.shell.voices.iter().filter(|v| v.name.starts_with(&base)).count() + 1;+ format!("{base} #{n}")+}+fn begin_in_language(s: &mut AppState, plan: Plan) {let lang = plan.language.clone();let active = shell::active_voice(s).cloned();- if s.record.for_new || active.is_none() {+ let kept = active.as_ref().filter(|v| v.lang() != lang && (v.parts > 0 || v.trained)).cloned();+ let new = active.is_none() || if kept.is_some() { !s.record.replace } else { s.record.for_new };+ if new {+ s.record.for_new = false;+ s.record.replace = false;let typed = s.record.new_name.text.trim().to_owned();- let name = if !typed.is_empty() {- typed- } else if s.shell.voices.is_empty() {- "My voice".to_owned()- } else {- format!("Voice {}", s.shell.voices.len() + 1)- };+ let name = if typed.is_empty() { plain_name(s, &lang) } else { typed };+ let notice = kept.map(|v| {+ let text = format!("“{}” stays in {}; this goes into “{name}”.", v.name, super::lang::name(v.lang()));+ (text, Tone::Neutral)+ });s.record.voice_id = None;s.record.new_voice_name = Some(name);- s.record.for_new = false;s.record.new_name = TextEdit::default();s.record.begin(plan);+ if notice.is_some() {+ s.record.notice = notice;+ }return;}- match active {- Some(v) if v.lang() != lang && v.parts == 0 => {- shell::request(s, "voices.rename", json!({ "id": v.id, "language": lang }));- if let Some(info) = s.shell.voices.iter_mut().find(|x| x.id == v.id) {- info.language = lang.clone();- }- s.record.begin(plan);- }- Some(v) if v.lang() != lang => {- s.record.voice_id = None;- s.record.new_voice_name = Some(format!("{} ({})", v.name, super::lang::name(&lang)));- s.record.begin(plan);- s.record.notice = Some((- format!(- "Recording into a new voice for {}: “{}” keeps its {} recordings.",- super::lang::name(&lang),- v.name,- super::lang::name(v.lang())- ),- Tone::Neutral,- ));- }- _ => s.record.begin(plan),+ if kept.is_some() || active.as_ref().is_some_and(|v| v.parts > 0 || v.trained) {+ s.record.confirm_over = Some(plan);+ return;}+ // An empty voice takes the reading language with its first saved part (`dataset.add` `language`).+ s.record.begin(plan);+}++/// "Record over" in the dialog: nothing changes until the first part is saved.+pub fn record_over(s: &mut AppState) {+ let Some(plan) = s.record.confirm_over.take() else { return };+ let Some(v) = shell::active_voice(s).cloned() else { return };+ s.record.replace = false;+ s.record.voice_id = Some(v.id.clone());+ s.record.over = true;+ s.record.begin(plan);+ let text = format!(+ "Recording over “{}”: its {} recordings and trained model are replaced when you save the first part.",+ v.name,+ super::lang::name(v.lang())+ );+ s.record.notice = Some((text, Tone::Warning));+}++/// "Add to it" in the dialog (same language only): the new parts join the voice's recordings.+pub fn add_to_voice(s: &mut AppState) {+ let Some(plan) = s.record.confirm_over.take() else { return };+ s.record.replace = false;+ s.record.begin(plan);+}++pub fn cancel_over(s: &mut AppState) {+ s.record.confirm_over = None;+}++/// The × on "Continue": the unfinished reading is dropped; parts already saved stay in the voice.+pub fn drop_plan(s: &mut AppState) {+ s.record.cancel_recording();+ s.record.plan = None;+ s.record.takes.clear();+ s.record.over = false;+ s.record.notice = None;+ s.record.phase = Phase::Pick;}pub fn choose_preset(s: &mut AppState, id: &str) {@@ -1328,3 +1383,110 @@ pub fn settle(s: &mut AppState) -> bool {}changed}++#[cfg(test)]+mod language_tests {+ use super::*;++ fn state(parts: u32) -> AppState {+ let mut s = AppState::default();+ s.shell.active_voice = Some("huyang".into());+ s.record.voice_id = Some("huyang".into());+ s.shell.voices = vec![shell::VoiceInfo {+ id: "huyang".into(),+ name: "HUYANG".into(),+ language: "en".into(),+ parts,+ ..Default::default()+ }];+ s.record.language = "es".into();+ s+ }++ fn plan() -> Plan {+ Plan {+ id: "quick".into(),+ language: "es".into(),+ title: "Quick".into(),+ target_minutes: 1.0,+ trains_rvc: false,+ parts: vec![PartText { index: 1, title: "Uno".into(), text: "Hola.".into(), est_seconds: 60.0 }],+ }+ }++ #[test]+ fn recordings_in_another_language_start_a_voice_with_a_plain_name() {+ let mut s = state(3);+ assert!(kept_voice(&s).is_some());+ begin_in_language(&mut s, plan());+ let (method, params, _) = s.record.outbox.last().expect("a voice is created");+ assert_eq!(+ (method.as_str(), ¶ms["name"], ¶ms["language"]),+ ("voices.create", &json!("My voice (Spanish) #1"), &json!("es"))+ );+ assert_eq!(s.record.voice_id, None);+ assert!(s.record.notice.as_ref().is_some_and(|(t, _)| t.contains("“HUYANG” stays in English")));+ }++ #[test]+ fn recording_over_asks_first_and_changes_nothing_before_the_first_part() {+ let mut s = state(3);+ s.record.replace = true;+ begin_in_language(&mut s, plan());+ assert!(s.record.confirm_over.is_some());+ assert!(s.record.outbox.is_empty());+ cancel_over(&mut s);+ assert!(s.record.confirm_over.is_none() && s.record.plan.is_none());+ assert_eq!(s.shell.voices[0].language, "en");++ begin_in_language(&mut s, plan());+ assert!(s.record.confirm_over.is_some(), "a cancelled dialog asks again");+ record_over(&mut s);+ assert!(s.record.outbox.iter().all(|(m, ..)| m != "voices.rename" && m != "voices.create"));+ assert_eq!(s.shell.voices[0].language, "en");+ s.record.on_check(0, PathBuf::from("/t/take.wav"), &json!({"verdict": "ok", "duration_s": 5.0}));+ let (m, p, _) = s.record.outbox.last().unwrap();+ assert_eq!((m.as_str(), &p["start_over"], &p["language"]), ("dataset.add", &json!(true), &json!("es")));+ drop_plan(&mut s);+ assert!(!s.record.over && s.record.plan.is_none());+ }++ #[test]+ fn an_empty_voice_takes_the_reading_language_with_its_first_part() {+ let mut s = state(0);+ assert!(kept_voice(&s).is_none());+ begin_in_language(&mut s, plan());+ assert!(s.record.outbox.iter().all(|(m, ..)| m != "voices.create" && m != "voices.rename"));+ assert_eq!(s.shell.voices[0].language, "en");+ s.record.on_check(0, PathBuf::from("/t/take.wav"), &json!({"verdict": "ok", "duration_s": 5.0}));+ let (m, p, _) = s.record.outbox.last().unwrap();+ assert_eq!((m.as_str(), &p["language"], p.get("start_over")), ("dataset.add", &json!("es"), None));+ }++ #[test]+ fn a_voice_with_recordings_in_the_same_language_asks_add_or_over() {+ let mut s = state(3);+ s.shell.voices[0].language = "es".into();+ s.record.for_new = false;+ begin_in_language(&mut s, plan());+ assert!(s.record.confirm_over.is_some() && s.record.plan.is_none());+ add_to_voice(&mut s);+ assert!(s.record.plan.is_some() && !s.record.over);+ assert!(s.record.outbox.iter().all(|(m, ..)| m != "voices.create"));+ }++ #[test]+ fn a_trained_voice_without_recordings_is_kept_too() {+ let mut s = state(0);+ s.shell.voices[0].trained = true;+ assert!(kept_voice(&s).is_some());+ }++ #[test]+ fn plain_names_count_up() {+ let mut s = state(0);+ assert_eq!(plain_name(&s, "fr"), "My voice (French) #1");+ s.shell.voices[0].name = "My voice (French) #1".into();+ assert_eq!(plain_name(&s, "fr"), "My voice (French) #2");+ }+}diff --git a/crates/desktop/src/ui/record/fixtures.rs b/crates/desktop/src/ui/record/fixtures.rsindex 84eacd4..d7fe68b 100644--- a/crates/desktop/src/ui/record/fixtures.rs+++ b/crates/desktop/src/ui/record/fixtures.rs@@ -117,6 +117,14 @@ pub fn scene_language_menu(s: &mut AppState) {s.langpick.open = Some((crate::ui::lang::Target::Record, "record-lang-pick".into()));}+pub fn scene_other_language(s: &mut AppState) {+ base(s);+ s.shell.voices[0].name = "HUYANG".into();+ s.shell.voices[0].language = "zh".into();+ s.shell.voices[0].parts = 13;+ s.record.language = "fr".into();+}+pub fn scene_new_voice(s: &mut AppState) {base(s);s.record.for_new = true;diff --git a/crates/desktop/src/ui/record/pick.rs b/crates/desktop/src/ui/record/pick.rsindex 8c1f34f..b6ef671 100644--- a/crates/desktop/src/ui/record/pick.rs+++ b/crates/desktop/src/ui/record/pick.rs@@ -3,7 +3,7 @@use super::widgets::*;use super::{Analysis, Level, Load, Phase, Preset, RecordState};use crate::state::AppState;-use crate::ui::components::{TextArea, segmented};+use crate::ui::components::TextArea;use crate::ui::lang;use crate::ui::theme::ty;use rune::{El, ScrollSpec, col, el, row};@@ -46,12 +46,39 @@ fn own_language_strip(r: &RecordState, p: Pal) -> El {.child(lang::chip(&p, "own-lang-pick", &label, lang::Target::RecordText, true))}+/// The new voice's name, built like the voice switch beside it: a 1-point well around a 32-point line.+fn name_field(p: Pal, edit: &rune::TextEdit, hint: &str) -> El {+ // Focus shows on the inner line, as the switch shows its choice, so both keep the same dark rim.+ let line = row().w_full().h(32.0).px(13.0).center_y().radius(16.0);+ let line = if edit.focused { line.fill(p.accent.alpha(0.12)).border(1.0, p.accent.alpha(0.5)) } else { line };+ row()+ .key("record-name")+ .w(260.0)+ .padding(1.0)+ .radius(17.0)+ .fill(p.well)+ .border_gradient(1.0, rune::Color::BLACK.alpha(0.35), p.well_rim)+ .child(+ line.child(+ rune::text_input(edit, ty::LABEL)+ .key("record-name-input")+ .single_line()+ .w_full()+ .color(p.text)+ .placeholder(hint.to_owned(), p.text_faint)+ .caret(p.accent, p.accent.alpha(0.35))+ .on_edit(|s: &mut AppState| &mut s.record.new_name),+ ),+ )+}+fn target_strip(s: &AppState, p: Pal) -> El {let r = &s.record;let active = crate::ui::shell::active_voice(s);- let new = r.for_new || active.is_none();+ let kept = super::kept_voice(s);+ let new = active.is_none() || if kept.is_some() { !r.replace } else { r.for_new };// As tall as the name field, so the field appearing does not push the page down.- let mut line = row().key("record-for").w_full().min_h(42.0).gap(12.0).center_y().flex_wrap().child(txt(+ let mut line = row().key("record-for").w_full().min_h(34.0).gap(12.0).center_y().flex_wrap().child(txt("This is for",13.0,600.0,@@ -59,21 +86,31 @@ fn target_strip(s: &AppState, p: Pal) -> El {));if let Some(v) = active {let labels = [v.name.as_str(), "A new voice"];- line = line.child(segmented(p, "record-for-pick", &labels, usize::from(new), |s: &mut AppState, i| {- s.record.for_new = i == 1- }));+ line = line.child(crate::ui::components::segmented_tall(+ p,+ "record-for-pick",+ &labels,+ usize::from(new),+ |s: &mut AppState, i| {+ s.record.for_new = i == 1;+ s.record.replace = i == 0;+ },+ ));} else {line = line.child(txt("a new voice", 13.0, 600.0, p.text));}if new {- line = line.child(el().w(260.0).child(crate::ui::voices::kit::field(- &p,- &r.new_name,- "Its name, for example \"My voice\"",- |s: &mut AppState| &mut s.record.new_name,- )));+ let hint = super::plain_name(s, r.lang());+ line = line.child(name_field(p, &r.new_name, &hint));}- line+ let Some(v) = kept else { return line };+ let (old, read) = (crate::ui::lang::name(v.lang()), crate::ui::lang::name(r.lang()));+ let (note, color) = if new {+ (format!("“{}” stays in {}.", v.name, old), p.text_faint)+ } else {+ (format!("“{}” switches to {}: its {} recordings and trained model are replaced.", v.name, read, old), p.warn)+ };+ col().w_full().gap(6.0).child(line).child(txt(note, 13.0, 400.0, color))}pub fn presets(s: &AppState, p: Pal) -> El {@@ -116,21 +153,30 @@ pub fn presets(s: &AppState, p: Pal) -> El {.wrap(),),);- c = c.child(target_strip(s, p)).child(language_strip(r, p));+ c = c.child(language_strip(r, p)).child(target_strip(s, p));if let Some(plan) = &r.plan {let done = r.saved_count();let whose = crate::ui::shell::active_voice(s).map_or(String::new(), |v| format!(" of “{}”", v.name));let label = format!("Continue: {}{whose} ({}/{} parts)", plan.title, done, plan.parts.len());- c = c.child(glass(p).w_full().px(20.0).py(14.0).child(- row().w_full().center_y().justify_between().child(txt(label, 15.0, 600.0, p.text)).child(button(- p,- "continue",- "Continue recording",- BtnKind::Primary,- true,- |s: &mut AppState| s.record.phase = Phase::Session,- )),- ));+ c = c.child(+ glass(p).w_full().px(22.0).py(18.0).child(+ row()+ .w_full()+ .gap(12.0)+ .center_y()+ .child(txt(label, 15.0, 600.0, p.text).grow(1.0).min_w(0.0))+ .child(button(p, "continue", "Continue recording", BtnKind::Primary, true, |s: &mut AppState| {+ s.record.phase = Phase::Session+ }))+ .child(crate::ui::components::icon_button(+ p,+ "continue-drop",+ &crate::ui::components::icons::CLOSE,+ "Stop this reading; saved parts stay in the voice",+ super::drop_plan,+ )),+ ),+ );}c = c.child(cards).child(glass(p).w_full().px(22.0).py(18.0).child(@@ -313,3 +359,55 @@ fn analysis_card(p: Pal, a: &Analysis) -> El {super::record_own,)))}++pub fn over_dialog(s: &AppState, p: &crate::ui::theme::Palette) -> Option<El> {+ use crate::ui::voices::kit::{BtnKind as K, button as kbutton};+ let plan = s.record.confirm_over.as_ref()?;+ let v = crate::ui::shell::active_voice(s)?;+ let same = v.lang() == plan.language;+ let (old, read) = (lang::name(v.lang()), lang::name(&plan.language));+ let (title, body) = if same {+ (+ format!("Record into “{}”?", v.name),+ format!(+ "It already has {old} recordings or a trained model. Add to it: the new parts join them, and a part \+ read again replaces its old take. Record over it: its recordings, reference clips and trained model \+ are replaced. Nothing changes until you save the first part."+ ),+ )+ } else {+ (+ format!("Record over “{}”?", v.name),+ format!(+ "Its {old} recordings, reference clips and trained model are replaced by the {read} ones you record. \+ Nothing changes until you save the first part."+ ),+ )+ };+ let mut buttons =+ row().w_full().justify_end().gap(10.0).child(kbutton(p, "Cancel", K::Glass, true, super::cancel_over));+ if same {+ buttons = buttons.child(kbutton(p, "Add to it", K::Primary, true, super::add_to_voice));+ }+ buttons = buttons.child(kbutton(p, "Record over", K::Danger, true, super::record_over));+ let card = col()+ .key("over-dialog")+ .w(500.0)+ .padding(22.0)+ .gap(14.0)+ .radius(crate::ui::theme::radius::PANEL)+ .fill(rune::oklcha(0.2, 0.03, 255.0, 0.96))+ .border_gradient(1.0, p.rim_top, p.rim_bottom)+ .shadow(18.0, 50.0, p.shadow)+ .child(rune::text(title).font(ty::TITLE).color(p.text))+ .child(rune::text(body).font(ty::BODY).color(p.text_dim).wrap())+ .child(buttons);+ Some(+ el().key("over-layer")+ .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))+ .center()+ .fill(rune::Color::BLACK.alpha(0.55))+ .on_press(super::cancel_over)+ .child(card.on_press(|_: &mut AppState| {})),+ )+}diff --git a/crates/desktop/src/ui/shell.rs b/crates/desktop/src/ui/shell.rsindex ae52e45..fb2970e 100644--- a/crates/desktop/src/ui/shell.rs+++ b/crates/desktop/src/ui/shell.rs@@ -668,6 +668,7 @@ pub fn view(s: &AppState, cx: &mut Cx<AppState>) -> El {overlays.extend(super::update::overlay(s, &p));overlays.extend(super::settings::overlay(s, &p));overlays.extend(super::relocate::overlay(s, &p));+ overlays.extend(super::record::over_dialog(s, &p));overlays.extend(super::train::close_overlay(s, &p));overlays.extend(super::formats::overlay(s, p));overlays.extend(super::book::voice_overlay(s, p));diff --git a/docs/usage.md b/docs/usage.mdindex aa80a1d..2b58c6e 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -457,7 +457,12 @@ empty active voice set its language the same way; a voice that already has recor### Pick a preset and a reading languageReading aloud goes into the voice chosen under **This is for**: the active voice, or **A new voice** (type its name;-left empty it is "My voice", then "Voice 2", ...). If you have no voice yet, a new one is made.+left empty it is "My voice", then "Voice 2", ...). If you have no voice yet, a new one is made. If the active voice+already has recordings in another language than the **Reading language**, **A new voice** is chosen (left unnamed it+is "My voice (French) #1"), and the active voice keeps its recordings; pick the active voice instead to record over+it: after you confirm, saving the first part replaces its recordings, reference clips and trained model, and it takes+the new language. Reading into a voice that already has recordings or a model in the same language asks too: **Add to+it** keeps them (a part read again replaces its old take), **Record over** replaces them. Until then nothing changes; the × on **Continue** drops an unfinished reading.At the top, choose the **Reading language** (the menu has a search field): every language an installed speech modelspeaks, 67 in all. Each language has its own texts, written for that language, in `presets/<lang>/` (`quick.md`,diff --git a/engine/src/mimvox_engine/dataset/store.py b/engine/src/mimvox_engine/dataset/store.pyindex bf1ae81..d444c7c 100644--- a/engine/src/mimvox_engine/dataset/store.py+++ b/engine/src/mimvox_engine/dataset/store.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport re+import shutilimport threadingfrom pathlib import Pathfrom typing import Any@@ -343,6 +344,38 @@ def _summary(vdir: str | Path, meta: dict[str, Any]) -> dict[str, Any]:return out+def _write_voice_meta(vdir: Path, meta: dict[str, Any]) -> None:+ path = vdir / "voice.json"+ tmp = path.with_name(path.name + ".tmp")+ with tmp.open("w", encoding="utf-8") as f:+ json.dump(meta, f, indent=1)+ tmp.replace(path)+++def _set_language(vdir: Path, language: str) -> None:+ """The first part read into an empty voice gives it the reading language."""+ with (vdir / "voice.json").open(encoding="utf-8") as f:+ meta = json.load(f)+ if language and meta.get("language") != language and not _existing_parts(vdir):+ meta["language"] = language+ _write_voice_meta(vdir, meta)+++def _start_over(vdir: Path, language: Any) -> None:+ """Recording over a voice: it keeps its id and name; recordings, references and the trained model go."""+ meta_path = vdir / "voice.json"+ with meta_path.open(encoding="utf-8") as f:+ old = json.load(f)+ for p in vdir.iterdir():+ if p.is_dir():+ shutil.rmtree(p)+ elif p != meta_path:+ p.unlink()+ meta = {k: old[k] for k in ("id", "name", "created") if k in old}+ meta["language"] = language if isinstance(language, str) and language else old.get("language")+ _write_voice_meta(vdir, meta)++@method("dataset.add")def dataset_add(ctx: Any, params: dict[str, Any]) -> dict[str, Any]:vdir = _voice_dir(ctx, params)@@ -362,6 +395,10 @@ def dataset_add(ctx: Any, params: dict[str, Any]) -> dict[str, Any]:verdict, issues = quality.assess(m1, float(expected) if isinstance(expected, (int, float)) else None)y = normalise(y, m1)with _LOCK:+ if params.get("start_over") is True:+ _start_over(vdir, params.get("language"))+ elif isinstance(params.get("language"), str):+ _set_language(vdir, params["language"])_ddir(vdir).mkdir(parents=True, exist_ok=True)write_wav(_part_path(vdir, n), y, sr)meta = _load_meta(vdir)diff --git a/engine/tests/test_dataset_start_over.py b/engine/tests/test_dataset_start_over.pynew file mode 100644index 0000000..b1b8cd1--- /dev/null+++ b/engine/tests/test_dataset_start_over.py@@ -0,0 +1,60 @@+import json++import numpy as np+from mimvox_engine import voices+from mimvox_engine.audio_util import write_wav+from mimvox_engine.dataset import store+++class Ctx:+ def __init__(self, path):+ self.data_dir = str(path)+++def tone(path, seconds=2.0):+ t = np.linspace(0, seconds, int(48000 * seconds), endpoint=False)+ write_wav(path, (0.2 * np.sin(2 * np.pi * 220 * t)).astype(np.float32), 48000)+ return path+++def test_recording_over_a_voice_keeps_only_its_name(tmp_path):+ ctx = Ctx(tmp_path / "data")+ vid = voices.voices_create(ctx, {"name": "Huyang", "language": "zh"})["voice"]["id"]+ vdir = store._voice_dir(ctx, {"voice_id": vid})+ for n in (1, 2, 1000123):+ tone(store._part_path(vdir, n))+ (vdir / "rvc").mkdir()+ (vdir / "rvc" / "model.pth").write_bytes(b"model")+ tone(vdir / "reference.wav")+ meta = json.loads((vdir / "voice.json").read_text(encoding="utf-8"))+ meta.update(trained=True, trained_epochs=450)+ (vdir / "voice.json").write_text(json.dumps(meta), encoding="utf-8")++ take = tone(tmp_path / "take.wav", 3.0)+ store.dataset_add(ctx, {"voice_id": vid, "part_index": 1, "path": str(take), "start_over": True, "language": "fr"})++ assert store._existing_parts(vdir) == [1]+ assert not (vdir / "rvc").exists()+ after = json.loads((vdir / "voice.json").read_text(encoding="utf-8"))+ assert (after["name"], after["language"]) == ("Huyang", "fr")+ assert "trained" not in after+ assert voices.describe(voices.config.data_dir(ctx), vid)["trained"] is False+++def test_a_plain_take_keeps_the_others(tmp_path):+ ctx = Ctx(tmp_path / "data")+ vid = voices.voices_create(ctx, {"name": "Anna", "language": "en"})["voice"]["id"]+ vdir = store._voice_dir(ctx, {"voice_id": vid})+ tone(store._part_path(vdir, 2))+ store.dataset_add(ctx, {"voice_id": vid, "part_index": 1, "path": str(tone(tmp_path / "t.wav", 3.0))})+ assert store._existing_parts(vdir) == [1, 2]+++def test_an_empty_voice_takes_the_language_of_its_first_part_only(tmp_path):+ ctx = Ctx(tmp_path / "data")+ vid = voices.voices_create(ctx, {"name": "Nova", "language": "zh"})["voice"]["id"]+ vdir = store._voice_dir(ctx, {"voice_id": vid})+ take = tone(tmp_path / "t.wav", 3.0)+ store.dataset_add(ctx, {"voice_id": vid, "part_index": 1, "path": str(take), "language": "fr"})+ store.dataset_add(ctx, {"voice_id": vid, "part_index": 2, "path": str(take), "language": "de"})+ assert json.loads((vdir / "voice.json").read_text(encoding="utf-8"))["language"] == "fr"