Skip to content

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.

feat(mcp): books in character voices and a find_speakers tool (#173)

Taras Hevlichf8d090210bcc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9665005..072188b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## Unreleased
+
+* **The MCP server reads books in character voices:** `start_book` takes `men_voice`, `women_voice` and `cast`, and
+ the new `find_speakers` tool says who speaks each line (the narrator, the characters, the lines per voice and a
+ description for a voice of each role) before the book is read.
+
## 0.9.0
* **Books read in one, two or three voices:** with **Three voices**, the narrator, the men and the women each have
diff --git a/crates/desktop/examples/fake_engine.py b/crates/desktop/examples/fake_engine.py
index a0b84bd..4556deb 100644
--- a/crates/desktop/examples/fake_engine.py
+++ b/crates/desktop/examples/fake_engine.py
@@ -22,6 +22,8 @@ CANCELLED = set()
JOB_COUNTER = [0]
DESIGN_CANCEL = threading.Event()
BOOKS = {}
+CASTS = set()
+CASTING = [None]
VOICES = [
{
"id": "fake-voice",
@@ -551,6 +553,39 @@ def book_job(book, job):
send({"event": "book.done", "job": job, "data": {"id": book["id"], "folder": book["folder"], "chapters": n}})
+CAST_SUMMARY = {
+ "mode": "fast",
+ "narrator": {"first_person": False, "name": ""},
+ "characters": [{"name": "Anna", "gender": "f", "lines": 2}, {"name": "Tom", "gender": "m", "lines": 1}],
+ "lines": {"men": 1, "women": 2, "narrator": 0},
+ "voices": {"narrator": "male, middle-aged", "men": "male, young adult", "women": "female, young adult"},
+}
+
+
+def book_cast(params):
+ """Finds the speakers once per chapters, language and mode; asking again answers at once with job null."""
+ key = json.dumps([[c["text"] for c in params["chapters"]], params.get("language"), params.get("cast", "fast")])
+ if key in CASTS and not params.get("again"):
+ return {"key": "cast1", "job": None, **CAST_SUMMARY}
+ job = next_job()
+ CASTING[0] = job
+
+ def run():
+ time.sleep(0.3) # after the answer with the job, as the engine sends them
+ send({"event": "book.cast_progress", "job": job, "data": {"key": "cast1", "pct": 50.0}})
+ time.sleep(0.3)
+ CASTING[0] = None
+ if job in CANCELLED:
+ data = {"key": "cast1", "code": "cancelled", "message": "finding the speakers was cancelled"}
+ send({"event": "book.cast_error", "job": job, "data": data})
+ return
+ CASTS.add(key)
+ send({"event": "book.cast_done", "job": job, "data": {"key": "cast1", **CAST_SUMMARY}})
+
+ threading.Thread(target=run, daemon=True).start()
+ return {"key": "cast1", "job": job}
+
+
def start_book(data_dir, book):
job = next_job()
book["status"], book["job"] = "running", job
@@ -706,8 +741,15 @@ def handle(data_dir, req):
}
elif method == "text.import":
result = import_text(params["path"])
+ elif method == "book.cast":
+ recorded(data_dir, method, params)
+ result = book_cast(params)
+ elif method == "book.cast_cancel":
+ result = {"cancelled": CASTING[0] is not None}
+ CANCELLED.add(CASTING[0])
elif method == "book.start":
- if not any(v["id"] == params.get("voice_id") for v in VOICES):
+ ids = [params.get("voice_id"), *(params.get("voices") or {}).values()]
+ if not all(any(v["id"] == i for v in VOICES) for i in ids):
raise KeyError("voice")
book_id = f"book{len(BOOKS) + 1}"
book = {
diff --git a/crates/mcp/src/events.rs b/crates/mcp/src/events.rs
index d9d0163..7287c0c 100644
--- a/crates/mcp/src/events.rs
+++ b/crates/mcp/src/events.rs
@@ -58,14 +58,14 @@ impl JobState {
/// How an event ends its job, if it does.
pub fn end_state(event: &str) -> Option<State> {
- if event == "redub.transcript" || event.ends_with(".done") {
- Some(State::Done)
- } else if event.ends_with(".paused") {
- Some(State::Paused)
- } else if event.ends_with(".error") {
- Some(State::Error)
- } else {
- None
+ if event == "redub.transcript" {
+ return Some(State::Done);
+ }
+ match event.rsplit(['.', '_']).next() {
+ Some("done") => Some(State::Done),
+ Some("paused") => Some(State::Paused),
+ Some("error") => Some(State::Error),
+ _ => None,
}
}
@@ -305,6 +305,9 @@ mod tests {
("train.paused", Some(State::Paused)),
("book.error", Some(State::Error)),
("job.error", Some(State::Error)),
+ ("book.cast_done", Some(State::Done)),
+ ("book.cast_error", Some(State::Error)),
+ ("book.cast_progress", None),
("tts.chunk", None),
("book.chapter", None),
] {
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index 9ae6e6a..f965141 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -101,6 +101,22 @@ pub enum Quality {
Fast,
}
+#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum Cast {
+ Fast,
+ Careful,
+}
+
+impl Cast {
+ fn as_str(self) -> &'static str {
+ match self {
+ Cast::Fast => "fast",
+ Cast::Careful => "careful",
+ }
+ }
+}
+
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EngineCallArgs {
/// Engine method, e.g. "voices.list" or "audio.export".
@@ -239,6 +255,42 @@ pub struct StartBookArgs {
/// Voice-cloning model: omnivoice, voxcpm or chatterbox when installed; default: the engine's choice.
#[serde(default)]
pub model: Option<String>,
+ /// Voice id or name that reads every male character's lines; voice then reads the narration. Needs the
+ /// Character voices component.
+ #[serde(default)]
+ pub men_voice: Option<String>,
+ /// Voice id or name that reads every female character's lines, as men_voice.
+ #[serde(default)]
+ pub women_voice: Option<String>,
+ /// How the speakers are found with men_voice or women_voice: "fast" (default) or "careful" (reads the book
+ /// twice and leaves the lines the two readings disagree on to the narrator).
+ #[serde(default)]
+ pub cast: Option<Cast>,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct FindSpeakersArgs {
+ /// A document on the API's machine (imported as import_text does). Give this or chapters.
+ #[serde(default)]
+ pub path: Option<String>,
+ /// The chapters, instead of a document.
+ #[serde(default)]
+ pub chapters: Option<Vec<Chapter>>,
+ /// Only these chapters of the document (0-based indexes, as import_text lists them).
+ #[serde(default)]
+ pub chapter_indexes: Option<Vec<usize>>,
+ /// Language code of the text; default: the document's detected language. Use the same as start_book.
+ #[serde(default)]
+ pub language: Option<String>,
+ /// "fast" (default) or "careful", as start_book's cast.
+ #[serde(default)]
+ pub cast: Option<Cast>,
+ /// Search every chapter again, even one searched before (default false).
+ #[serde(default)]
+ pub again: Option<bool>,
+ /// Seconds to wait for the result (default 1800); after that the job goes on and wait_job follows it.
+ #[serde(default)]
+ pub timeout_s: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -855,6 +907,15 @@ impl Progress {
}
}
+#[derive(Default)]
+struct BookText {
+ chapters: Vec<Value>,
+ title: Option<String>,
+ language: Option<String>,
+ /// The document's path and format.
+ source: Option<(Value, Value)>,
+}
+
enum Ran {
Done(Value),
Running,
@@ -1197,7 +1258,20 @@ impl Mimvox {
self.events_ready().await?;
let started = self.api.rpc(method, params).await?;
let job = started["job"].as_str().unwrap_or_default().to_string();
- let ran = match self.wait(&job, timeout, progress, None, cancel).await {
+ let ran = self.follow(&job, cancel_method, timeout, progress, cancel).await?;
+ Ok((job, ran))
+ }
+
+ /// Waits for a started job's end; a cancelled call cancels the job with `cancel_method`.
+ async fn follow(
+ &self,
+ job: &str,
+ cancel_method: &str,
+ timeout: Duration,
+ progress: Option<&mut Progress>,
+ cancel: &CancellationToken,
+ ) -> Result<Ran, ApiError> {
+ Ok(match self.wait(job, timeout, progress, None, cancel).await {
Waited::Ended(st) => {
let result = st.result.unwrap_or(Value::Null);
if st.state != State::Done {
@@ -1211,8 +1285,7 @@ impl Mimvox {
let _ = self.api.rpc(cancel_method, json!({ "job": job })).await;
return Err(ApiError::new("cancelled", "the request was cancelled, and so was the job"));
}
- };
- Ok((job, ran))
+ })
}
/// A video path that no file has yet, as `video_place` picks it (`_2`, `_3`, ... on a clash).
@@ -1824,20 +1897,22 @@ impl Mimvox {
Ok(Fetched::Bytes(bytes))
}
- async fn start_book_inner(&self, args: StartBookArgs) -> Result<Value, ApiError> {
- let mut params = Map::new();
- let mut detected = None;
- let mut title = args.title;
- let chapters: Vec<Value> = match (args.path, args.chapters) {
+ async fn book_text(
+ &self,
+ path: Option<String>,
+ chapters: Option<Vec<Chapter>>,
+ indexes: Option<&[usize]>,
+ ) -> Result<BookText, ApiError> {
+ let mut text = BookText::default();
+ text.chapters = match (path, chapters) {
(Some(path), None) => {
let doc = self.api.rpc("text.import", json!({ "path": path, "language": "auto" })).await?;
- detected = doc["language"].as_str().map(str::to_string);
- title = title.or_else(|| doc["title"].as_str().filter(|t| !t.is_empty()).map(str::to_string));
- title = title.or_else(|| doc["name"].as_str().map(str::to_string));
- params.insert("source".into(), doc["path"].clone());
- params.insert("format".into(), doc["format"].clone());
+ text.language = doc["language"].as_str().map(str::to_string);
+ text.title = doc["title"].as_str().filter(|t| !t.is_empty()).map(str::to_string);
+ text.title = text.title.or_else(|| doc["name"].as_str().map(str::to_string));
+ text.source = Some((doc["path"].clone(), doc["format"].clone()));
let all = doc["chapters"].as_array().cloned().unwrap_or_default();
- let picked = match &args.chapter_indexes {
+ let picked = match indexes {
Some(idx) => idx.iter().filter_map(|i| all.get(*i).cloned()).collect(),
None => all,
};
@@ -1848,14 +1923,30 @@ impl Mimvox {
}
_ => return Err(ApiError::new("bad_request", "give either path or chapters")),
};
- if chapters.is_empty() {
+ if text.chapters.is_empty() {
return Err(ApiError::new("bad_request", "no chapters to read"));
}
+ Ok(text)
+ }
+
+ async fn start_book_inner(&self, args: StartBookArgs) -> Result<Value, ApiError> {
+ let mut params = Map::new();
+ let text = self.book_text(args.path, args.chapters, args.chapter_indexes.as_deref()).await?;
+ if let Some((source, format)) = text.source {
+ params.insert("source".into(), source);
+ params.insert("format".into(), format);
+ }
let voice = self.voice(args.voice.as_deref()).await?;
- params.insert("title".into(), json!(title.unwrap_or_else(|| "Untitled".into())));
- params.insert("chapters".into(), json!(chapters));
+ let mut voices = Map::new();
+ for (role, wanted) in [("men", args.men_voice), ("women", args.women_voice)] {
+ if let Some(w) = wanted.filter(|w| !w.trim().is_empty()) {
+ voices.insert(role.into(), self.voice(Some(&w)).await?["id"].clone());
+ }
+ }
+ params.insert("title".into(), json!(args.title.or(text.title).unwrap_or_else(|| "Untitled".into())));
+ params.insert("chapters".into(), json!(text.chapters));
params.insert("voice_id".into(), voice["id"].clone());
- if let Some(lang) = args.language.or(detected).or_else(|| voice["language"].as_str().map(str::to_string)) {
+ if let Some(lang) = args.language.or(text.language).or_else(|| voice["language"].as_str().map(str::to_string)) {
params.insert("language".into(), json!(lang));
}
let optional = [
@@ -1866,6 +1957,8 @@ impl Mimvox {
("expressiveness", args.expressiveness.map(Value::from)),
("quality", args.quality.map(|q| json!(if matches!(q, Quality::Fast) { "fast" } else { "best" }))),
("model", args.model.map(Value::from)),
+ ("voices", Some(Value::Object(voices)).filter(|v| v.as_object().is_some_and(|m| !m.is_empty()))),
+ ("cast", args.cast.map(|c| json!(c.as_str()))),
];
for (key, value) in optional {
if let Some(v) = value {
@@ -1877,6 +1970,37 @@ impl Mimvox {
Ok(started)
}
+ async fn find_speakers_inner(
+ &self,
+ args: FindSpeakersArgs,
+ progress: Option<&mut Progress>,
+ cancel: &CancellationToken,
+ ) -> Result<CallToolResult, ApiError> {
+ let text = self.book_text(args.path, args.chapters, args.chapter_indexes.as_deref()).await?;
+ let mut params = json!({ "chapters": text.chapters });
+ put(
+ &mut params,
+ [
+ ("language", args.language.or(text.language).map(Value::from)),
+ ("cast", args.cast.map(|c| json!(c.as_str()))),
+ ("again", args.again.map(Value::from)),
+ ],
+ );
+ self.events_ready().await?;
+ let mut found = self.api.rpc("book.cast", params).await?;
+ let Some(job) = found["job"].as_str().map(str::to_string) else {
+ found["state"] = json!("done");
+ return Ok(ok(found));
+ };
+ let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
+ let Ran::Done(mut found) = self.follow(&job, "book.cast_cancel", timeout, progress, cancel).await? else {
+ return Ok(still_running(&job, "still finding the speakers: follow it with wait_job"));
+ };
+ found["job"] = json!(job);
+ found["state"] = json!("done");
+ Ok(ok(found))
+ }
+
async fn download_inner(&self, args: DownloadArgs) -> Result<Value, ApiError> {
let name = file_name(&args.path);
if name.is_empty() {
@@ -2016,13 +2140,30 @@ impl Mimvox {
}
#[tool(description = "Start reading an audiobook: a document (path) or given chapters, one audio file per \
- chapter in <data>/outputs/books/<title>/. Returns the book id and its job; follow it with \
+ chapter in <data>/outputs/books/<title>/, in one voice or with men_voice and women_voice \
+ reading the characters' lines. Returns the book id and its job; follow it with \
wait_job (progress in percent) or book_status. Only one generation runs at a time: while \
a book is read, speak answers busy until it is paused.")]
async fn start_book(&self, Parameters(args): Parameters<StartBookArgs>) -> Result<CallToolResult, ErrorData> {
Ok(reply(self.start_book_inner(args).await))
}
+ #[tool(description = "Find who speaks each line of a book before it is read (Character voices component, a \
+ local model): the narrator, the speaking characters with gender and lines, how many lines \
+ the men's, the women's voice and the narrator read, and a design_voice description for a \
+ voice of each role. Waits with progress; the result is kept, so start_book of the same \
+ chapters, language and cast uses it at once. Cancelling the call stops the search.")]
+ async fn find_speakers(
+ &self,
+ Parameters(args): Parameters<FindSpeakersArgs>,
+ meta: RequestMetaObject,
+ peer: Peer<RoleServer>,
+ cancel: CancellationToken,
+ ) -> Result<CallToolResult, ErrorData> {
+ let mut progress = Progress::new(&meta, peer);
+ Ok(self.find_speakers_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
+ }
+
#[tool(
description = "One book's status (percent, chapters done, time left, chapter files) or, without id, every \
book.",
diff --git a/crates/mcp/tests/mcp.rs b/crates/mcp/tests/mcp.rs
index da486e8..8961cb7 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; 29] = [
+const TOOLS: [&str; 30] = [
"engine_call",
"list_voices",
"speak",
@@ -27,6 +27,7 @@ const TOOLS: [&str; 29] = [
"delete_design_take",
"import_text",
"start_book",
+ "find_speakers",
"book_status",
"pause_book",
"resume_book",
@@ -439,6 +440,53 @@ async fn books_and_jobs_with_progress() {
assert_eq!(res["structuredContent"]["error"]["code"], "bad_request");
}
+#[tokio::test]
+async fn books_in_character_voices() {
+ let api = api(None).await;
+ let home = tempfile::tempdir().unwrap();
+ let mut mcp = Mcp::start(&api.url, home.path(), &[], &[]).await;
+ let doc = api.data.join("book.txt");
+ std::fs::write(&doc, "A Talk\nChapter 1\n\"Hi,\" said Anna.\nChapter 2\n\"Hello,\" said Tom.\n").unwrap();
+
+ let args = json!({ "path": doc, "chapter_indexes": [1], "cast": "careful" });
+ let req = json!({ "name": "find_speakers", "arguments": args, "_meta": { "progressToken": "p-cast" } });
+ let res = mcp.request("tools/call", req).await;
+ let found = &res["result"]["structuredContent"];
+ assert_eq!(found["state"], "done", "{res}");
+ assert!(found["job"].is_string(), "{found}");
+ assert_eq!(found["characters"][0]["name"], "Anna");
+ assert_eq!(found["voices"]["women"], "female, young adult");
+ let sent_cast = sent(&api.data, "book.cast");
+ assert_eq!(sent_cast["chapters"], json!([{ "title": "Chapter 2", "text": "\"Hello,\" said Tom." }]));
+ assert_eq!((&sent_cast["language"], &sent_cast["cast"]), (&json!("en"), &json!("careful")));
+ let progress = mcp.progress("p-cast");
+ assert!(progress[0]["params"]["message"].as_str().unwrap().starts_with("book.cast_progress"), "{progress:?}");
+
+ let again = mcp.ok("find_speakers", args.clone()).await;
+ assert_eq!((&again["job"], &again["state"]), (&Value::Null, &json!("done")));
+
+ let started = mcp
+ .ok(
+ "start_book",
+ json!({ "path": doc, "men_voice": "fake voice", "women_voice": "fake-voice", "cast": "careful" }),
+ )
+ .await;
+ let status = mcp.ok("book_status", json!({ "id": started["id"] })).await;
+ assert_eq!(status["settings"]["voices"], json!({ "men": "fake-voice", "women": "fake-voice" }));
+ assert_eq!(status["settings"]["cast"], "careful");
+ mcp.ok("wait_job", json!({ "job": started["job"] })).await;
+
+ let one = mcp.ok("start_book", json!({ "path": doc })).await;
+ let status = mcp.ok("book_status", json!({ "id": one["id"] })).await;
+ assert!(status["settings"].get("voices").is_none() && status["settings"].get("cast").is_none(), "{status}");
+ mcp.ok("wait_job", json!({ "job": one["job"] })).await;
+
+ let res = mcp.err("start_book", json!({ "path": doc, "women_voice": "Nobody" })).await;
+ assert_eq!(res["structuredContent"]["error"]["code"], "not_found");
+ let res = mcp.err("find_speakers", json!({ "title": "Nothing" })).await;
+ assert_eq!(res["structuredContent"]["error"]["code"], "bad_request");
+}
+
#[tokio::test]
async fn videos() {
let api = api(None).await;
diff --git a/docs/usage.md b/docs/usage.md
index 9a4966a..a0e4d62 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -402,7 +402,7 @@ The tools:
| `manage_voice` | rename a voice, delete it, or export it as a voice bundle |
| `train_voice` | train a voice (start, pause, resume, cancel, status) for a closer likeness |
| `design_voice`, `list_design_takes`, `keep_design_take`, `delete_design_take` | a new voice from a description, as the Design tab makes it |
-| `import_text`, `start_book`, `book_status`, `pause_book`, `resume_book` | a document read as an audiobook |
+| `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_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 |