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: books read in one to three voices, with the speakers found by a local model (#171)
Taras Hevlich069121219719
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9140d03..8bc5adf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,31 @@* **A video made with photos is no longer squeezed:** a tall picture gave the video its own pixel shape, and playersthat honour it drew the whole frame narrow. Videos now have square pixels. The first photo's start, always 0:00, lookslike the other start fields, dimmed.+* **Books read in one, two or three voices:** with **Three voices**, the narrator, the men and the women each have+ their own voice; **Two voices** gives the second one to the men or the women. **Find who speaks** has a local+ language model (Gemma 4 12B through llama.cpp, the new *Character voices* part in **Settings** > **Modules**, 7.4 GB)+ read the ticked chapters and say who says each line, in any language the speech models speak. **Fast** reads them+ once (96% of 384 English lines right); **Careful** reads them twice and leaves the lines the two disagree on to the+ narrator. Lines it cannot place go to the narrator. For programs: `book.cast`, `book.cast_status`, and `voices`+ and `cast` in `book.start`.+* **A voice for each role:** pick one of yours, or **Generate** one from Gemma's description of the book's narrator,+ men and women (a plain one when no chapter picked has dialogue), as **Auto**, **Male** or **Female**. It is added to+ Your voices as "Book · role" at once and made anew by the next Generate. Voices tells which role a book voice reads+ and changes it; Book warns when a role's voice was made for another role.+* **Chapters analysed once stay analysed:** each line is known by its text, so chapters merged or split again need+ no new search; a brain marks the chapters Gemma has read (yellow: no dialogue, nothing to read), only the ones not+ read yet are searched, and **Search again** reads the ticked ones anew.+* **Every book has its own draft in the Book workspace:** Your books lists each book once as *Draft*, *In progress* or+ *Finished*; chapters read are marked with ✓, ▶ and ↻ (read again), more chapters can be read into the same book,+ chapters and drafts can be removed, and **Open folder** shows the files. Voices, accuracy and chapters are locked+ while a book is read; Resume and ↻ take the settings set now; an M4B ticked during reading is made when it ends.+ While a book is read, Redub and training wait, and Subtitle video works beside it.+* **HolosTTS is picked in Speak's Model menu** for Ukrainian, in place of the *Exact stress* checkbox, and reads+ without the zero-shot converter; *Closer voice* is gone, it made the Ukrainian r burr. Style shows only what+ applies to the model reading.+* **Fixes:** opening a book no longer gives its language to the draft left open; a new book no longer starts with the+ last book's speakers and voices; the language and model menus stay in step in Book; the player plays a voice's new+ clip after Generate, not the old one.## 0.8.0diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 73a1000..c381369 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -120,6 +120,17 @@ chosen; none of it is part of this repository or of the app's installers.(its record on Zenodo; part of it is CC BY-NC-SA 4.0). Treat the weights as **non-commercial**, which matches therest of this project (**verify** before any other use).+### Character voices: llama.cpp and Gemma 4 (the optional "Character voices" component)++- **llama.cpp** release b12818 (MIT, Copyright (c) 2023-2026 The ggml authors; the `LICENSE` in the archive and in+ <https://github.com/ggml-org/llama.cpp>): the prebuilt `llama-server` from its GitHub release (the CUDA 12 build for+ an NVIDIA GPU, Metal on a Mac, Vulkan otherwise), which setup downloads into `<data>/runtime/llama` (checked by+ SHA-256). The CUDA build loads the CUDA runtime and cuBLAS that come with the engine's PyTorch (NVIDIA's licence for+ the CUDA redistributables).+- **Gemma 4 12B instruct** (Google, **Apache-2.0**, the licence field of `google/gemma-4-12B-it` on Hugging Face):+ its Q4_K_M GGUF quantization from `unsloth/gemma-4-12b-it-GGUF` (Apache-2.0, weights unchanged apart from the+ quantization), 7.1 GB, which setup downloads into `<data>/runtime/models/llm` (checked by SHA-256).+### IndexTTS and IndexTTS-2.5 (legacy: used by earlier versions, no longer installed)Earlier versions of this app spoke through IndexTTS-2.5; it was replaced by OmniVoice. Setup no longer downloads it anddiff --git a/contract/engine-protocol.md b/contract/engine-protocol.mdindex ff10b1c..c31e760 100644--- a/contract/engine-protocol.md+++ b/contract/engine-protocol.md@@ -328,13 +328,17 @@ continues (see [Pause and resume](#pause-and-resume)).`{"name","preset"?,"language"?}` -> `{"voice":{...as in list...}}` (a new voice has no dataset and no reference;`language` defaults to `"en"`, `"auto"` also means `"en"`, an unsupported code is `bad_request`; a voice made frommedia files may get another language the speech model speaks from `media.combine`) ·-`voices.rename {"id","name"?,"language"?}` -> `{"voice":{...}}` (`name` renames; `language` changes the recording+`voices.rename {"id","name"?,"language"?,"book_role"?}` (`book_role`: `narrator`, `men` or `women`, the lines a book voice reads) -> `{"voice":{...}}` (`name` renames; `language` changes the recordinglanguage, e.g. when the first texts read into a still empty voice are in another language; at least one of the two) ·`{"id"}` -> `{}` (removes the whole folder). Names are trimmed to 80 characters.`not_found` for an unknown id.### `voices.import` (existing recordings and model; no retraining)-`{"name","reference_path"?,"dataset_dir"?,"rvc_model"?,"rvc_index"?,"preset"?,"language"?}` -> `{"voice":{...as in list...}}`+`{"name","reference_path"?,"dataset_dir"?,"rvc_model"?,"rvc_index"?,"preset"?,"language"?,"book"?,"book_role"?,"into"?}` (`into`: the id+of a voice whose reference is replaced by `reference_path`, keeping its id) ->+`{"voice":{...as in list...}}`+- `book` and `book_role` (`narrator`, `men`, `women`) mark a voice Book made for a book; they are stored in+ `voice.json` and returned by `voices.list` (`null` for other voices), so the app lists such voices apart.- Creates a voice, then: every `part<N>.<ext>` in `dataset_dir` (any importable extension, `wav` by default) goes through `dataset.add` (trim, normalise, verdict;the reference is chosen by it); `reference_path` (any importable format), when given, replaces `reference.wav` as it is (converted to mono 16-bit WAV, notrimming; a later `dataset.add`/`dataset.remove` picks the reference again); `rvc_model` (and `rvc_index`) are copied@@ -944,12 +948,8 @@ the clip's language does not matter (only timbre and manner are taken, never thefor OmniVoice. Measured on an RTX 4070: about 0.1 s per second of speech (10x OmniVoice), 2.3 GB of VRAM.- **Timbre.** HolosTTS's voice encoder keeps little of a voice: speaker similarity to the reference clip (ECAPA) was- 0.76, against 0.94 for OmniVoice from the same clip. A trained voice goes through RVC as always; for a voice that is- not trained, every HolosTTS segment goes through the zero-shot converter (Seed-VC, the `native_accent` component)- toward the reference clip, which brings it to 0.88. `quality` sets the converter's steps (12 Best, 8 Fast). Without- the converter the segment is used as HolosTTS made it. The conversion costs about as much time as OmniVoice itself- (about 4-5x real time instead of about 20x), so it depends on `keep_voice`: default `true` in `tts.generate`,- `false` in `book.start` (a book stores it with its settings).+ 0.76, against 0.94 for OmniVoice from the same clip. A trained voice goes through RVC as always; a voice that is not+ trained is used as HolosTTS made it (the zero-shot converter made the Ukrainian "р" burr, so it is not used here).- **`exact_stress`** (`tts.generate`, `book.start`; default `true`): `false` speaks Ukrainian with OmniVoice even whenHolosTTS is installed. A book keeps the value it started with.@@ -965,8 +965,8 @@ environment (`backends/voxcpm_worker.py`, `backends/chatterbox_worker.py`, shari`load`, `synth`, `release`, `status`).- **`model`** (`tts.generate`, `book.start`; default `"auto"`): `"auto"` is the first installed model that speaks the- language, OmniVoice first (HolosTTS for Ukrainian with `exact_stress`); `"omnivoice"`, `"voxcpm"`- or `"chatterbox"` names one. A named model that is not installed is `not_ready`, one that does not speak+ language, OmniVoice first (HolosTTS for Ukrainian with `exact_stress`, for `"omnivoice"` too); `"omnivoice"`,+ `"voxcpm"` or `"chatterbox"` names one. A named model that is not installed is `not_ready`, one that does not speak`language` is `bad_request`, any other value is `bad_request`. A book keeps the value it started with. The replyof `tts.generate` and `tts.done` say which model spoke (`model`). Redub always speaks with `"auto"`.- **Languages.** VoxCPM2: ar da de el en es fi fr he hi id it ja km ko lo ms my nl no pl pt ru sv sw th tl tr vi zh.@@ -1397,8 +1397,8 @@ only shows it.### `book.start``{"title","source"?,"format"?,"chapters":[{"title","text"}],"voice_id","language"?,"expressiveness"?:0.6,"voice_match"?:1.0,"quality"?:"best","speed"?:1.0,"accent"?,"native_voice"?,"output_format"?:"wav","m4b"?:false,-"read_titles"?:true,"ref"?,"model"?:"auto"}` -> `{"id","job","folder","chapters","words","ref","existing","status", ...accent and reference-fields as tts.generate}`+"read_titles"?:true,"ref"?,"model"?:"auto","voices"?:{"men"?,"women"?},"cast"?:"fast"}` -> `{"id","job","folder","chapters","words","ref",+"existing","status", ...accent and reference fields as tts.generate}`- Creates a book project and starts reading it at once. The voice settings mean what they mean for `tts.generate` andare checked the same way (`not_found`, `not_ready`, `bad_request`), before anything is written. `expressiveness`defaults to **0.6** for a book (a steadier narrator than Speak's 0.8); a given value is used as is. Empty chapters@@ -1417,12 +1417,51 @@ fields as tts.generate}``error`, `cancelled`) is resumed as by `book.resume`, with the accent and reference fields. `existing` is then`true` (`false` for a new project); `status` is `running` or `done`. A second `book.start` with the same`ref` while the first is still answering gets `busy`.+- `voices` (Character voices): `{"men": voice id, "women": voice id}`, either may be left out or null. The engine finds+ who speaks each line (as `book.cast`, with `cast` `fast` or `careful`; a result `book.cast` found for the same+ chapters, language and mode is used, else this is the job's first stage, `book.progress` `stage: "cast"` with+ `stage_pct`), then reads a man's line in the `men` voice and a woman's in the `women` voice; the narrator (`voice_id`)+ reads the rest, the author's words between the speech too. `not_ready` without the component; `not_found` for a+ voice without a reference. See [Character voices](#character-voices).- `busy` while any generation runs (only one at a time). **While a book is read it holds the generation slot**:`tts.generate`, Redub, `voices.warm` and reference changes answer `busy` with the message "a book is being read;pause it (Speak, Book) to use speech, Redub or training" (training answers `busy` too). Nothing pre-empts a book.+### `book.cast` / `book.cast_cancel` (who speaks each line)+`{"chapters":[{"title","text"}],"language"?,"cast"?:"fast","again"?:false}` -> `{"key","job", ...summary}`; `again`+ reads every chapter with speech again, kept results or not+- Finds who speaks each line of a book before it is read (the optional **Character voices** component, `cast`:+ llama.cpp's `llama-server` and Gemma 4 12B, started only for this). The speech models leave the GPU while it runs and+ load again after. It holds the generation slot like a book (`busy` for others, the message "the speakers of a book+ are being found; wait for it or cancel it").+- The result is kept in `<data>/cast/<key>.json` (`key`: the chapters' texts, the language and the mode), and each+ speech line's in `<data>/cast/lines-<language>-<mode>.json`, found again by its text and its neighbours, so chapters+ joined or split differently keep it. Asking again about chapters whose lines were all searched before (a chapter+ without speech needs no search) answers at once with `job: null` and the summary, and `book.start` of them uses it;+ otherwise only the chapters with a line never searched are read, and the summary covers all asked (characters summed+ over the searches).+- `book.cast_status {"chapters":[{"title","text"}],"language","cast"}` -> `{"searched":[bool, ...]}`: one per chapter+ given, whether it needs no new search.+- Summary: `{"mode","narrator":{"first_person","name"},"characters":[{"name","gender":"m|f","lines"}],"lines":{"men",+ "women","narrator"},"voices":{"narrator","men","women"}}`: the first 30 characters by lines; `voices` are OmniVoice+ design terms for a voice of each role (`voices.design` `description`).+- Events: `book.cast_progress {"key","pct"}` (0-100), then `book.cast_done {"key", ...summary}` or+ `book.cast_error {"key","code","message"}` (`cancelled` after `book.cast_cancel`, `internal` when the model failed).+- `book.cast_cancel {}` -> `{"cancelled"}`.+- `not_ready` without the component, `bad_request` for a `cast` other than `fast` or `careful`.++### `book.add` (more chapters for a book)+`{"id","chapters":[{"title","text","number"?}],"voice_id"?,"voices"?,"cast"?,"m4b"?,"read_titles"?,"exact_stress"?}` -> as `book.get`: adds the chapters the book lacks (one with the same text is skipped;+`bad_request` when none is new), numbered in the files by `number` (the chapter's place in the source, also accepted by+`book.start`), and leaves the book `paused`. `voice_id`, `voices`, `cast` and the flags replace the book's from now on,+as in `book.start`; `book.resume` reads the new chapters into its folder (the speakers of their lines are found first+when it is read with several voices). `busy` while it is read.+### `book.resume` / `book.pause` / `book.cancel`-- `book.resume {"id"}` -> as `book.start` (`id`, `job`, ...). Continues a `paused`, `error`, `cancelled` or `new` book+`book.resume`, `book.reread`, `book.add` and `book.settings {"id", ...}` (also while the book is read; an M4B ticked+then is made when the reading ends) take the settings to read on with: `voice_id`, `voices` (the roles given),+`cast`, `m4b`, `read_titles` and `exact_stress` replace the book's for the chapters read from then on.+- `book.resume {"id", ...}` -> as `book.start` (`id`, `job`, ...). Continues a `paused`, `error`, `cancelled` or `new` bookwith the settings it was started with, from the next unfinished segment (see Resume); a chapter whose segments wereall made before the stop but whose file was not written is finished first (`book.chapter`). `bad_request` for afinished book, `busy` as above.@@ -1435,7 +1474,7 @@ fields as tts.generate}`### `book.list` / `book.get` / `book.delete` / `book.reread` / `book.play`- `book.list {}` -> `{"books":[summary, ...]}`, the most recently changed first. A summary: `{"id","title","source",- "format","language","voice_id","status":"new|running|paused|done|error|cancelled","interrupted","job","chapters",+ "format","language","voice_id","voices","status":"new|running|paused|done|error|cancelled","interrupted","job","chapters","chapters_done","current","folder","m4b","output_format","words","ref","created","updated","error":{"code","message"}|null,"percent","audio_s","elapsed_s","rtf","eta_s","est_audio_s","chars","chars_done"}`. A book recorded as running whosejob is not running in this engine (the app or engine closed mid-book) is reported `paused` with `interrupted: true`.@@ -1445,7 +1484,8 @@ fields as tts.generate}`and for chapters finished before the engine wrote one).- `book.delete {"id"}` -> `{}`: forgets the project (its texts, progress and segment timing); the files in`outputs/books` stay. `busy` while it is being read.-- `book.reread {"id","voice_id"?,"chapters"?:[index, ...]}` -> like `book.get`: reads the listed chapters again (all of+- `book.reread {"id","voice_id"?,"voices"?:{"men"?,"women"?},"chapters"?:[index, ...], ...}` -> like `book.get`+ (`voices` changes the voice of men's or women's lines as `voice_id` changes the narrator): reads the listed chapters again (all ofthem when `chapters` is left out; `[]` for none), with `voice_id` from now on when given (`not_found` for a voicewithout a reference). Each listed chapter's file, segment timing, progress and audio are dropped, and so is the M4B.The book is then `paused` (`new` when nothing is made), or stays `done` when every chapter is still made;@@ -1494,6 +1534,32 @@ The pipeline is `tts.generate`'s (backend, native accent and its converter, RVC)finished chapter is normalized as a whole to **-18 LUFS** with sample peaks under **-1 dBFS** (two streamed passes).Per-segment measures are kept in `<data>/books/<id>/stats/<NNN>.json`.+### Character voices+How a book with `voices` is read (`cast.py`):+- **Who speaks.** A chapter is read in requests of about 8,000 characters of text whose paragraphs with speech (one+ starting with a dash, or with `"`, `“`, `«` or `„` in it) are numbered, with about 3,000 characters before and 2,000+ after as context. A llama.cpp grammar makes the model answer one line per number, `[12] f Ruth`: `m`/`f` a man's or a+ woman's speech, `i` the first-person narrator's, `t` a thought, `l` a letter or note with its writer, `x` none of+ these. A number left out is asked again in two smaller requests. The characters named so far go with every request,+ so one person keeps one name. `careful` reads every chapter twice, with other request bounds and wording; a line+ the two readings disagree on is the narrator's.+- **Roles.** The model is asked once whether the book is told in the first person and by whom; that character's lines+ are the narrator's. A letter whose writer speaks elsewhere in the book is read in the writer's voice; thoughts and+ other letters by the narrator, more expressively (`narration.EXPRESSIVE_NARRATOR`, 1.2; OmniVoice only).+- **Remarks.** For every dash line spoken by a man, a woman or a thought, the model is then asked, 40 lines a request+ with no other task, to copy out the narrator's words in it (`[3] | dijo Carlos`); a grammar keeps it from copying+ speech (a remark never starts with a capital, a dash or a quote) or looping (at most three, 120 characters each).+- **Pieces.** A dash line is cut at those remarks, found in it however the model spaced them. Where the model gave none,+ or one that is not in the line, and in the speech it left between them, rules for Spanish, Italian and Portuguese+ (a remark after a dash opens with a small letter and a verb of saying, or is closed by a dash before punctuation or+ a new sentence) and French (a remark between commas, `, s’écria-t-il,`, or after `»`) cut the line, else any dash+ after punctuation does (`— Wait,— he said.— Then…`). Quoted speech (`"…"`, `“…”`, `«…»`, `»…«`, `„…“`, `「…」`) is+ cut at the first quotation and every quotation of three words or more (a word quoted in narration stays narration).+ Pieces of one paragraph are separated by 260 ms. Character voices speak at `narration.CHARACTER_EXPRESSIVENESS` (0.85) or the book's, whichever+ is higher.+- Each voice has its own reference, voice conversion and outlier check; segment stats record the `voice`+ (`narrator`, `expressive`, `men`, `women`).+### Resume (what is on disk)- After every segment its audio (44.1 kHz, 16-bit, mono) is appended to `work/<NNN>.pcm` and fsynced, then`state.json` records the next segment and the PCM length that goes with it (written atomically). A resume cuts thediff --git a/crates/api/openapi/methods.json b/crates/api/openapi/methods.jsonindex 1c4158c..69eff79 100644--- a/crates/api/openapi/methods.json+++ b/crates/api/openapi/methods.json@@ -88,6 +88,232 @@"properties": {}}},+ {+ "name": "book.cast",+ "summary": "Find who speaks each line of a book",+ "description": "Finds who speaks each line before a book is read (Character voices component): the cast, the lines per voice and design terms for the voices. The result is kept: book.start of the same chapters, language and mode uses it, and asking again answers at once with job null. Holds the generation slot while it runs. Errors: not_ready without the component, busy while any generation runs.",+ "job": true,+ "events": [+ "book.cast_progress",+ "book.cast_done",+ "book.cast_error"+ ],+ "params": {+ "type": "object",+ "properties": {+ "chapters": {+ "type": "array",+ "description": "Chapters to read; empty ones are skipped",+ "items": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "description": "Chapter title"+ },+ "text": {+ "type": "string",+ "description": "Chapter text"+ }+ },+ "required": [+ "title",+ "text"+ ]+ }+ },+ "language": {+ "type": "string",+ "description": "Language code of the text"+ },+ "cast": {+ "type": "string",+ "enum": [+ "fast",+ "careful"+ ],+ "default": "fast",+ "description": "How the speakers are found: careful reads the book twice and leaves lines the two readings disagree on to the narrator"+ },+ "again": {+ "type": "boolean",+ "description": "Read every chapter with speech again, kept results or not"+ }+ },+ "required": [+ "chapters"+ ]+ },+ "result": {+ "type": "object",+ "properties": {+ "job": {+ "type": [+ "string",+ "null"+ ],+ "description": "Null when the cast was found before"+ },+ "key": {+ "type": "string",+ "description": "The cast's key: the chapters, language and mode"+ },+ "mode": {+ "type": "string",+ "description": "fast or careful"+ },+ "narrator": {+ "type": "object",+ "properties": {+ "first_person": {+ "type": "boolean",+ "description": "The book is told by an I who is a character"+ },+ "name": {+ "type": "string",+ "description": "That narrator's name"+ }+ }+ },+ "characters": {+ "type": "array",+ "description": "The speaking characters, most lines first (at most 30)",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Name"+ },+ "gender": {+ "type": "string",+ "enum": [+ "m",+ "f"+ ],+ "description": "m or f"+ },+ "lines": {+ "type": "integer",+ "description": "Lines"+ }+ }+ }+ },+ "lines": {+ "type": "object",+ "properties": {+ "men": {+ "type": "integer",+ "description": "Lines read by the men's voice"+ },+ "women": {+ "type": "integer",+ "description": "Lines read by the women's voice"+ },+ "narrator": {+ "type": "integer",+ "description": "Speech lines left to the narrator"+ }+ }+ },+ "voices": {+ "type": "object",+ "description": "OmniVoice design terms for a voice of each role (voices.design description)",+ "properties": {+ "narrator": {+ "type": "string",+ "description": "The narrator's voice"+ },+ "men": {+ "type": "string",+ "description": "The men's voice"+ },+ "women": {+ "type": "string",+ "description": "The women's voice"+ }+ }+ }+ },+ "required": [+ "key",+ "job"+ ]+ }+ },+ {+ "name": "book.cast_status",+ "summary": "Which chapters need no new search",+ "description": "One answer per chapter given: whether every speech line in it was searched before (in any grouping of the chapters), so book.cast and book.start use the result at once.",+ "job": false,+ "events": [],+ "params": {+ "type": "object",+ "required": [+ "chapters"+ ],+ "properties": {+ "chapters": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "text": {+ "type": "string"+ }+ }+ }+ },+ "language": {+ "type": "string"+ },+ "cast": {+ "type": "string",+ "enum": [+ "fast",+ "careful"+ ]+ }+ }+ },+ "result": {+ "type": "object",+ "properties": {+ "searched": {+ "type": "array",+ "items": {+ "type": "boolean"+ }+ }+ }+ }+ },+ {+ "name": "book.cast_cancel",+ "summary": "Stop finding who speaks",+ "description": "Stops a running book.cast; book.cast_error with code cancelled follows.",+ "job": false,+ "events": [+ "book.cast_error"+ ],+ "params": {+ "type": "object",+ "properties": {}+ },+ "result": {+ "type": "object",+ "properties": {+ "cancelled": {+ "type": "boolean",+ "description": "A book.cast was running"+ }+ }+ }+ },{"name": "book.delete","summary": "Forget a book project",@@ -637,31 +863,331 @@},"required": ["id",- "index"- ]- },- "result": {- "type": "object",- "properties": {- "path": {- "type": "string",- "description": "The chapter file"- },- "path_play": {- "type": "string",- "description": "A WAV of the chapter to play"- }- },- "required": [- "path",- "path_play"+ "index"+ ]+ },+ "result": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "The chapter file"+ },+ "path_play": {+ "type": "string",+ "description": "A WAV of the chapter to play"+ }+ },+ "required": [+ "path",+ "path_play"+ ]+ }+ },+ {+ "name": "book.reread",+ "summary": "Mark book chapters to be read again",+ "description": "Drops the listed chapters' files, timing, progress and the M4B so book.resume reads them again, optionally with another voice. not_found for a voice without a reference, busy while it is read or reread.",+ "job": false,+ "params": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": "Book id"+ },+ "voice_id": {+ "type": "string",+ "description": "Voice to use from now on"+ },+ "chapters": {+ "type": "array",+ "items": {+ "type": "integer"+ },+ "description": "Chapter indexes to read again; all when omitted, [] for none"+ },+ "voices": {+ "type": "object",+ "description": "The voice of men's or women's lines from now on",+ "properties": {+ "men": {+ "type": "string"+ },+ "women": {+ "type": "string"+ }+ }+ }+ },+ "required": [+ "id"+ ]+ },+ "result": {+ "type": "object",+ "description": "A book summary plus its settings and chapter list",+ "properties": {+ "id": {+ "type": "string",+ "description": "Book id"+ },+ "title": {+ "type": "string",+ "description": "Book title"+ },+ "source": {+ "type": [+ "string",+ "null"+ ],+ "description": "Source file the text came from"+ },+ "format": {+ "type": [+ "string",+ "null"+ ],+ "description": "Source format"+ },+ "language": {+ "type": "string",+ "description": "Language code"+ },+ "voice_id": {+ "type": "string",+ "description": "Voice that reads the book"+ },+ "status": {+ "type": "string",+ "description": "Book status",+ "enum": [+ "new",+ "running",+ "paused",+ "done",+ "error",+ "cancelled"+ ]+ },+ "interrupted": {+ "type": "boolean",+ "description": "True for a book recorded as running whose job is not running in this engine (reported paused)"+ },+ "job": {+ "type": [+ "string",+ "null"+ ],+ "description": "Job id while it is read, else null"+ },+ "chapters": {+ "type": "integer",+ "description": "Number of chapters"+ },+ "chapters_done": {+ "type": "integer",+ "description": "Chapters finished"+ },+ "current": {+ "type": [+ "integer",+ "null"+ ],+ "description": "Index of the current chapter"+ },+ "folder": {+ "type": "string",+ "description": "Output folder of the chapter files"+ },+ "m4b": {+ "type": [+ "string",+ "null"+ ],+ "description": "Path of the M4B audiobook, when made"+ },+ "output_format": {+ "type": "string",+ "description": "Format of the chapter files",+ "enum": [+ "wav",+ "mp3",+ "flac",+ "ogg",+ "opus",+ "m4a",+ "aiff"+ ]+ },+ "words": {+ "type": "integer",+ "description": "Words in the book"+ },+ "ref": {+ "type": [+ "string",+ "null"+ ],+ "description": "The client's own name for the project"+ },+ "created": {+ "type": "number",+ "description": "Creation time (unix seconds)"+ },+ "updated": {+ "type": "number",+ "description": "Last change (unix seconds)"+ },+ "error": {+ "type": [+ "object",+ "null"+ ],+ "description": "Last error, or null",+ "properties": {+ "code": {+ "type": "string",+ "description": "Error code"+ },+ "message": {+ "type": "string",+ "description": "Message"+ }+ }+ },+ "percent": {+ "type": "number",+ "description": "Progress by characters (0-100)"+ },+ "audio_s": {+ "type": "number",+ "description": "Audio made so far, seconds"+ },+ "elapsed_s": {+ "type": "number",+ "description": "Generation time over all sessions, seconds"+ },+ "rtf": {+ "type": [+ "number",+ "null"+ ],+ "description": "elapsed_s / audio_s"+ },+ "eta_s": {+ "type": [+ "number",+ "null"+ ],+ "description": "Time left at the measured pace; null until the first segment"+ },+ "est_audio_s": {+ "type": [+ "number",+ "null"+ ],+ "description": "The whole book's length extrapolated, seconds"+ },+ "chars": {+ "type": "integer",+ "description": "Characters in the book"+ },+ "chars_done": {+ "type": "integer",+ "description": "Characters read so far"+ },+ "settings": {+ "type": "object",+ "description": "The voice and output settings the book was started with"+ },+ "chapter_list": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "index": {+ "type": "integer",+ "description": "Chapter index"+ },+ "title": {+ "type": "string",+ "description": "Chapter title"+ },+ "words": {+ "type": "integer",+ "description": "Words"+ },+ "chars": {+ "type": "integer",+ "description": "Characters"+ },+ "status": {+ "type": "string",+ "description": "Chapter status",+ "enum": [+ "waiting",+ "partial",+ "done"+ ]+ },+ "segment": {+ "type": "integer",+ "description": "Segments done"+ },+ "segments": {+ "type": "integer",+ "description": "Segments in the chapter"+ },+ "audio_s": {+ "type": "number",+ "description": "Audio made, seconds"+ },+ "elapsed_s": {+ "type": "number",+ "description": "Generation time, seconds"+ },+ "rtf": {+ "type": [+ "number",+ "null"+ ],+ "description": "Real-time factor"+ },+ "path": {+ "type": [+ "string",+ "null"+ ],+ "description": "Chapter file"+ },+ "segments_path": {+ "type": [+ "string",+ "null"+ ],+ "description": "Segment timing file; null until done and for chapters finished before the engine wrote one"+ },+ "text": {+ "type": "string",+ "description": "Chapter text (only with text: true)"+ }+ }+ }+ }+ },+ "required": [+ "id",+ "title",+ "status",+ "chapter_list"]}},{- "name": "book.reread",- "summary": "Mark book chapters to be read again",- "description": "Drops the listed chapters' files, timing, progress and the M4B so book.resume reads them again, optionally with another voice. not_found for a voice without a reference, busy while it is read or reread.",+ "name": "book.add",+ "summary": "Add chapters to a book",+ "description": "Adds the chapters the book lacks (by text), numbered in the files by number, and leaves it paused; book.resume reads them into its folder with its settings. bad_request when none is new, busy while it is read.","job": false,"params": {"type": "object",@@ -670,20 +1196,35 @@"type": "string","description": "Book id"},- "voice_id": {- "type": "string",- "description": "Voice to use from now on"- },"chapters": {"type": "array",+ "description": "Chapters to read; empty ones are skipped","items": {- "type": "integer"- },- "description": "Chapter indexes to read again; all when omitted, [] for none"+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "description": "Chapter title"+ },+ "text": {+ "type": "string",+ "description": "Chapter text"+ },+ "number": {+ "type": "integer",+ "description": "The chapter's place in the source, for its file name"+ }+ },+ "required": [+ "title",+ "text"+ ]+ }}},"required": [- "id"+ "id",+ "chapters"]},"result": {@@ -946,6 +1487,59 @@]}},+ {+ "name": "book.settings",+ "summary": "Change a book's settings",+ "description": "Sets voice_id, voices, cast, m4b, read_titles or exact_stress for what the book reads from now on, also while it is read; an M4B ticked then is made when the reading ends.",+ "job": false,+ "events": [],+ "params": {+ "type": "object",+ "required": [+ "id"+ ],+ "properties": {+ "id": {+ "type": "string",+ "description": "Book id"+ },+ "voice_id": {+ "type": "string"+ },+ "voices": {+ "type": "object",+ "properties": {+ "men": {+ "type": "string"+ },+ "women": {+ "type": "string"+ }+ }+ },+ "cast": {+ "type": "string",+ "enum": [+ "fast",+ "careful"+ ]+ },+ "m4b": {+ "type": "boolean"+ },+ "read_titles": {+ "type": "boolean"+ },+ "exact_stress": {+ "type": "boolean"+ }+ }+ },+ "result": {+ "type": "object",+ "properties": {}+ }+ },{"name": "book.resume","summary": "Resume a paused, failed or cancelled book",@@ -1108,6 +1702,10 @@"text": {"type": "string","description": "Chapter text"+ },+ "number": {+ "type": "integer",+ "description": "The chapter's place in the source, for its file name"}},"required": [@@ -1208,6 +1806,35 @@"type": "string","description": "Voice-cloning model: auto (OmniVoice, or an installed model for a language OmniVoice does not speak), or the id of an installed one in hello speech_models (omnivoice, voxcpm, chatterbox)","default": "auto"+ },+ "voices": {+ "type": "object",+ "description": "Character voices: the voice ids that read the men's and the women's lines (the narrator reads the rest); needs the Character voices component",+ "properties": {+ "men": {+ "type": [+ "string",+ "null"+ ],+ "description": "Voice id for every male character"+ },+ "women": {+ "type": [+ "string",+ "null"+ ],+ "description": "Voice id for every female character"+ }+ }+ },+ "cast": {+ "type": "string",+ "enum": [+ "fast",+ "careful"+ ],+ "default": "fast",+ "description": "How the speakers are found: careful reads the book twice and leaves lines the two readings disagree on to the narrator"}},"required": [@@ -4059,11 +4686,6 @@],"default": "auto"},- "keep_voice": {- "type": "boolean",- "description": "Run HolosTTS (Ukrainian) segments of an untrained voice through the zero-shot converter",- "default": true- },"exact_stress": {"type": "boolean","description": "false speaks Ukrainian with OmniVoice even when HolosTTS is installed",@@ -4788,9 +5410,21 @@"type": "string","description": "Recording language (ISO 639-1)"},+ "book": {+ "type": "string",+ "description": "The book this voice was made for (Book's character voices)"+ },+ "book_role": {+ "type": "string",+ "description": "Its role in that book: narrator, men or women"+ },"bundle": {"type": "string","description": "Absolute path of a voice bundle (.mimvoice) to import instead of the paths"+ },+ "into": {+ "type": "string",+ "description": "A voice whose reference is replaced, keeping its id"}}},@@ -5706,6 +6340,15 @@"language": {"type": "string","description": "New recording language (ISO 639-1)"+ },+ "book_role": {+ "type": "string",+ "enum": [+ "narrator",+ "men",+ "women"+ ],+ "description": "The role a book voice reads"}},"required": [@@ -7593,6 +8236,137 @@]}},+ {+ "name": "book.cast_progress",+ "job": true,+ "description": "Progress of book.cast.",+ "data": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "The cast's key: the chapters, language and mode"+ },+ "pct": {+ "type": "number",+ "description": "0-100"+ }+ }+ }+ },+ {+ "name": "book.cast_done",+ "job": true,+ "description": "book.cast found the speakers.",+ "data": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "The cast's key: the chapters, language and mode"+ },+ "mode": {+ "type": "string",+ "description": "fast or careful"+ },+ "narrator": {+ "type": "object",+ "properties": {+ "first_person": {+ "type": "boolean",+ "description": "The book is told by an I who is a character"+ },+ "name": {+ "type": "string",+ "description": "That narrator's name"+ }+ }+ },+ "characters": {+ "type": "array",+ "description": "The speaking characters, most lines first (at most 30)",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Name"+ },+ "gender": {+ "type": "string",+ "enum": [+ "m",+ "f"+ ],+ "description": "m or f"+ },+ "lines": {+ "type": "integer",+ "description": "Lines"+ }+ }+ }+ },+ "lines": {+ "type": "object",+ "properties": {+ "men": {+ "type": "integer",+ "description": "Lines read by the men's voice"+ },+ "women": {+ "type": "integer",+ "description": "Lines read by the women's voice"+ },+ "narrator": {+ "type": "integer",+ "description": "Speech lines left to the narrator"+ }+ }+ },+ "voices": {+ "type": "object",+ "description": "OmniVoice design terms for a voice of each role (voices.design description)",+ "properties": {+ "narrator": {+ "type": "string",+ "description": "The narrator's voice"+ },+ "men": {+ "type": "string",+ "description": "The men's voice"+ },+ "women": {+ "type": "string",+ "description": "The women's voice"+ }+ }+ }+ }+ }+ },+ {+ "name": "book.cast_error",+ "job": true,+ "description": "book.cast failed or was cancelled.",+ "data": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "The cast's key: the chapters, language and mode"+ },+ "code": {+ "type": "string",+ "description": "Error code (cancelled, not_ready, internal)"+ },+ "message": {+ "type": "string",+ "description": "What went wrong"+ }+ }+ }+ },{"name": "redub.progress","job": true,diff --git a/crates/desktop/src/ui/book.rs b/crates/desktop/src/ui/book.rsindex 4ea2efa..f83c558 100644--- a/crates/desktop/src/ui/book.rs+++ b/crates/desktop/src/ui/book.rs@@ -1,17 +1,17 @@//! Book mode of Speak: read a whole book in the active voice, one file per chapter.use super::components::{- Button, Tone, accent_glass, badge, empty_state, glass_card, icon_button, icon_el, icons, progress_bar,- section_panel, segmented, status_dot,+ Button, Tone, accent_glass, dropdown_chip, empty_state, glass_card, icon_button, icon_el, icons, popover,+ progress_bar, section_panel, segmented, status_dot,};use super::playbar;-use super::shell::{self, EngineStatus};+use super::shell::{self, EngineStatus, VoiceInfo};use super::theme::{Palette, motion, radius, ty};use super::voices::kit;use crate::engine::EngineMsg;use crate::engine::protocol::{- self, BookChapterDone, BookChapterIn, BookChapterRow, BookDone, BookParams, BookProgress, BookStarted, BookSummary,- TextImport,+ self, BookCast, BookCastProgress, BookChapterDone, BookChapterIn, BookChapterRow, BookDone, BookParams,+ BookProgress, BookStarted, BookSummary, CastMode, CastVoices, TextImport,};use crate::state::{AppState, Screen};use rune::{El, ScrollSpec, TextEdit, col, el, row, text};@@ -25,12 +25,6 @@ pub const LONG_WORDS: u32 = 5000;pub const TEXT_EXTS: &[&str] =&["txt", "md", "markdown", "html", "htm", "xhtml", "epub", "docx", "odt", "rtf", "fb2", "pdf", "srt", "vtt"];-/// Generation seconds per audio second until a book has measured its own (an RTX 4070 measured 0.2-0.4 with-/// Best for an untrained voice; voice conversion adds to it).-fn guess_rtf(quality: protocol::Quality) -> f32 {- if quality == protocol::Quality::Fast { 0.3 } else { 0.5 }-}-pub fn is_text_path(p: &Path) -> bool {let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("").to_lowercase();name.ends_with(".fb2.zip")@@ -61,6 +55,9 @@ pub struct Draft {pub auto: Option<(String, Vec<DraftChapter>)>,/// For "Undo split"; edits made since are dropped with it.pub before_split: Option<Vec<DraftChapter>>,+ /// The book its chapters are read into: one book, more chapters added to it as they are picked.+ #[serde(default)]+ pub book_id: Option<String>,}fn draft_chapters(list: &[protocol::TextChapter]) -> Vec<DraftChapter> {@@ -75,8 +72,84 @@ fn draft_chapters(list: &[protocol::TextChapter]) -> Vec<DraftChapter> {.collect()}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Role {+ Narrator,+ Men,+ Women,+}++impl Role {+ fn id(self) -> &'static str {+ match self {+ Role::Narrator => "narrator",+ Role::Men => "men",+ Role::Women => "women",+ }+ }++ fn from_id(id: &str) -> Option<Role> {+ [Role::Narrator, Role::Men, Role::Women].into_iter().find(|r| r.id() == id)+ }++ fn name(self) -> &'static str {+ match self {+ Role::Narrator => "Narrator",+ Role::Men => "Men",+ Role::Women => "Women",+ }+ }++ fn description(self, v: &CastVoices) -> &str {+ match self {+ Role::Narrator => &v.narrator,+ Role::Men => &v.men,+ Role::Women => &v.women,+ }+ }+}++#[derive(Default)]+struct Cast {+ req: Option<u64>,+ /// The engine's key of the running `book.cast` job.+ job: Option<String>,+ pct: f32,+ cancelling: bool,+ /// [`chapter_fingerprint`]s of the chapters the engine has searched (`book.cast_status`), in any grouping.+ searched: Vec<u64>,+ /// Chapters without dialogue: nothing for Gemma to read, so they are not marked as read by it.+ speechless: Vec<u64>,+ status_req: Option<u64>,+ /// [`included_key`] of the last search asked: its error goes once other chapters are picked.+ asked_key: u64,+ /// [`status_key`] of the chapters `searched` answers for.+ status_for: u64,+ found: Option<BookCast>,+ error: Option<String>,+ /// The book's narrator; the voice picked at the top when none is set.+ narrator: Option<String>,+ men: Option<String>,+ women: Option<String>,+ design: Option<(u64, Role)>,+ /// Takes of this Generate that Design found unclear (noise instead of the words).+ unclear: u8,+ /// Generated samples, one per role at most: they become voices only when the book starts.+ samples: Vec<(Role, Value)>,+ /// `voices.import` requests that turn samples into voices before the book starts.+ imports: Vec<(u64, Role)>,+ /// `voices.import` requests that add a sample to Your voices as soon as Generate made it.+ adopting: Vec<(u64, Role)>,+ /// The gender picked for a role's Generate ("male" or "female"); a role not listed takes Gemma's or the default.+ genders: Vec<(Role, String)>,+}+pub struct BookState {pub shown: bool,+ /// Files with a draft kept (and their titles), for Your books.+ drafts: Vec<(PathBuf, String)>,+ /// Generation seconds per audio second this computer has measured, for Best and for Fast.+ measured_rtf: [Option<f32>; 2],picking: bool,importing: Option<(u64, Purpose)>,pub draft: Option<Draft>,@@ -99,8 +172,6 @@ pub struct BookState {pub recent: Vec<BookSummary>,pub m4b: bool,pub read_titles: bool,- /// Ukrainian with exact stress through the voice converter: closer to the voice, about four times slower.- pub keep_voice: bool,pub expressiveness: f32,settings_loaded: bool,draft_restored: bool,@@ -110,6 +181,23 @@ pub struct BookState {m4b_making: bool,m4b_progress: (f32, Option<f32>),memory_wait: Option<f32>,+ /// 1 to 3: the narrator, then a voice for men's and/or women's lines.+ pub voices: u8,+ /// With two voices: whose lines the second one reads.+ pub second: Role,+ pub cast_mode: CastMode,+ cast: Cast,+ role_menu: Option<Role>,+ /// Which voice of the book "Change voice" changes.+ voice_role: Role,+ /// [`text_key`] of each chapter of the draft's book, by its index there.+ book_keys: Vec<u64>,+ link_req: Option<u64>,+ /// The restored draft's book is asked for once the engine runs.+ relink: bool,+ add_req: Option<u64>,+ /// `book.progress` of the "cast" stage: percent.+ cast_stage: Option<f32>,}/// Must match the engine's `narration.EXPRESSIVENESS`.@@ -119,6 +207,8 @@ impl Default for BookState {fn default() -> Self {BookState {shown: false,+ drafts: Vec::new(),+ measured_rtf: [None, None],picking: false,importing: None,draft: None,@@ -137,7 +227,6 @@ impl Default for BookState {recent: Vec::new(),m4b: false,read_titles: true,- keep_voice: false,expressiveness: EXPRESSIVENESS,settings_loaded: false,draft_restored: false,@@ -147,6 +236,17 @@ impl Default for BookState {m4b_making: false,m4b_progress: (0.0, None),memory_wait: None,+ voices: 1,+ second: Role::Men,+ cast_mode: CastMode::Fast,+ cast: Cast::default(),+ role_menu: None,+ voice_role: Role::Narrator,+ book_keys: Vec::new(),+ link_req: None,+ relink: false,+ add_req: None,+ cast_stage: None,}}}@@ -204,11 +304,16 @@ pub fn set_mode(s: &mut AppState, book: bool) {}fn opened(s: &mut AppState, file: TextImport, purpose: Purpose) {+ let to_text = purpose == Purpose::Auto && file.words <= LONG_WORDS;if !file.language.is_empty()&& s.shell.languages.iter().any(|l| l.code == file.language)&& file.language != super::speak::language(s){- super::speak::set_language(s, &file.language);+ // A book carries its language in its own draft; set here, it would land in the draft being left.+ if to_text {+ s.book.shown = false;+ super::speak::set_language(s, &file.language);+ }if file.language_detected {shell::toast(s,@@ -220,7 +325,7 @@ fn opened(s: &mut AppState, file: TextImport, purpose: Purpose) {for w in file.warnings.iter().take(2) {shell::toast(s, Tone::Warning, w.clone());}- if purpose == Purpose::Auto && file.words <= LONG_WORDS {+ if to_text {let joined = file.chapters.iter()@@ -248,16 +353,34 @@ fn opened(s: &mut AppState, file: TextImport, purpose: Purpose) {),);}+ stash_current(s);+ if let Some(saved) = read_slot(&file.path) {+ s.book.cast = Cast::default();+ if saved.cast.file.as_deref() == Some(saved.draft.file.path.as_path()) {+ restore_cast(&mut s.book.cast, saved.cast);+ }+ s.book.draft = Some(saved.draft);+ s.book.book_keys.clear();+ s.book.renaming = None;+ s.book.shown = true;+ link_book(s);+ return;+ }let chapters = draft_chapters(&file.chapters);let mut file = file;let auto = file.parts.take().filter(|p| !p.chapters.is_empty()).map(|p| (p.how, draft_chapters(&p.chapters)));file.chapters.clear(); // the texts live in the draft chapters (edited there)- s.book.draft = Some(Draft { file, chapters, auto, before_split: None });+ s.book.draft = Some(Draft { file, chapters, auto, before_split: None, book_id: None });+ // Another book: its speakers and voices are its own.+ s.book.cast = Cast::default();s.book.renaming = None;s.book.shown = true;}fn toggle_include(s: &mut AppState, i: usize) {+ if reading_locked(s) {+ return;+ }if let Some(c) = s.book.draft.as_mut().and_then(|d| d.chapters.get_mut(i)) {c.include = !c.include;}@@ -283,6 +406,9 @@ fn commit_rename(s: &mut AppState) {}fn auto_split(s: &mut AppState) {+ if reading_locked(s) {+ return;+ }commit_rename(s);let Some(d) = s.book.draft.as_mut() else { return };let Some((_, parts)) = d.auto.as_ref() else { return };@@ -292,6 +418,9 @@ fn auto_split(s: &mut AppState) {}fn undo_split(s: &mut AppState) {+ if reading_locked(s) {+ return;+ }s.book.renaming = None;if let Some(d) = s.book.draft.as_mut()&& let Some(before) = d.before_split.take()@@ -309,6 +438,7 @@ fn split_how(how: &str) -> &'static str {}}+/// The split's note and its button, shown under the totals.fn split_line(p: Palette, d: &Draft) -> Option<El> {let (how, parts) = d.auto.as_ref()?;let (msg, button) = if d.before_split.is_some() {@@ -342,11 +472,8 @@ fn split_line(p: Palette, d: &Draft) -> Option<El> {.w_full().gap(10.0).center_y()- .px(10.0)- .py(8.0)- .radius(super::theme::radius::CONTROL)- .fill(p.accent.alpha(0.07))- .border(1.0, p.accent.alpha(0.2))+ .pt(8.0)+ .border_sides([1.0, 0.0, 0.0, 0.0], p.well_rim).child(text(msg).font(ty::CAPTION).color(p.text_dim).wrap().grow(1.0).min_w(0.0)).child(button.build(p)),)@@ -354,6 +481,9 @@ fn split_line(p: Palette, d: &Draft) -> Option<El> {/// Joins chapter `i + 1` into chapter `i`; its title becomes a paragraph of the text.fn merge_next(s: &mut AppState, i: usize) {+ if reading_locked(s) {+ return;+ }commit_rename(s);let Some(d) = s.book.draft.as_mut() else { return };if i + 1 >= d.chapters.len() {@@ -369,6 +499,9 @@ fn merge_next(s: &mut AppState, i: usize) {/// Cuts chapter `i` in two at the paragraph break nearest its middle.fn split(s: &mut AppState, i: usize) {+ if reading_locked(s) {+ return;+ }commit_rename(s);let Some(d) = s.book.draft.as_mut() else { return };let Some(c) = d.chapters.get(i).cloned() else { return };@@ -399,63 +532,512 @@ fn split(s: &mut AppState, i: usize) {d.chapters.splice(i..=i, [first, second]);}-fn start_blocker(s: &AppState) -> Option<&'static str> {+fn start_blocker(s: &AppState) -> Option<String> {match &s.shell.engine {EngineStatus::Ready { .. } => {}- EngineStatus::Idle | EngineStatus::Starting { .. } => return Some("Waiting for the engine to start…"),- _ => return Some("The engine is not running. Press Retry above."),+ EngineStatus::Idle | EngineStatus::Starting { .. } => return Some("Waiting for the engine to start…".into()),+ _ => return Some("The engine is not running. Press Retry above.".into()),}- if shell::active_voice(s).is_none() {- return Some("Add a voice first (from files or by reading aloud), or pick one at the top right.");+ if !role_ready(s, Role::Narrator) {+ return Some("Pick or generate a voice for the narrator.".into());}if s.speak.is_generating() {- return Some("Wait for the text being spoken to finish.");+ return Some("Wait for the text being spoken to finish.".into());}if super::design::generating(s) {- return Some("Wait for Design to finish making a voice.");+ return Some("Wait for Design to finish making a voice.".into());}if s.book.running() {- return Some("Another book is being read: pause it first.");+ return Some("Another book is being read: pause it first.".into());}if s.book.draft.as_ref().is_some_and(|d| !d.chapters.iter().any(|c| c.include)) {- return Some("Tick at least one chapter.");+ return Some("Tick at least one chapter.".into());+ }+ if s.book.cast.design.is_some() || !s.book.cast.imports.is_empty() || !s.book.cast.adopting.is_empty() {+ return Some("Wait for the voice being made.".into());+ }+ if cast_running(s) {+ return Some("Wait for finding who speaks to finish, or cancel it.".into());+ }+ if s.book.voices > 1 {+ if !super::setuprun::has(s, "cast") {+ return Some("Install Character voices first.".into());+ }+ if s.book.cast.found.is_none() {+ return Some("Find who speaks first.".into());+ }+ if let Some(why) = unsearched_note(s) {+ return Some(why);+ }+ for role in character_roles(s.book.voices, s.book.second) {+ if !role_ready(s, *role) {+ return Some(if *role == Role::Men {+ "Pick a voice for the men's lines.".into()+ } else {+ "Pick a voice for the women's lines.".into()+ });+ }+ }}None}+fn character_roles(voices: u8, second: Role) -> &'static [Role] {+ match (voices, second) {+ (3, _) => &[Role::Men, Role::Women],+ (2, Role::Women) => &[Role::Women],+ (2, _) => &[Role::Men],+ _ => &[],+ }+}++fn role_voice(s: &AppState, role: Role) -> Option<&VoiceInfo> {+ let find = |id: Option<&str>| id.and_then(|id| s.shell.voices.iter().find(|v| v.id == id));+ match role {+ Role::Narrator => find(s.book.cast.narrator.as_deref()).or_else(|| find(s.shell.active_voice.as_deref())),+ Role::Men => find(s.book.cast.men.as_deref()),+ Role::Women => find(s.book.cast.women.as_deref()),+ }+}++fn sample(s: &AppState, role: Role) -> Option<&Value> {+ s.book.cast.samples.iter().find(|(r, _)| *r == role).map(|(_, t)| t)+}++/// A generated sample, or else a voice picked for the role.+fn role_ready(s: &AppState, role: Role) -> bool {+ sample(s, role).is_some() || role_voice(s, role).is_some()+}++/// The roles this reading uses: the narrator and the character voices.+fn used_roles(s: &AppState) -> Vec<Role> {+ std::iter::once(Role::Narrator).chain(character_roles(s.book.voices, s.book.second).iter().copied()).collect()+}++/// A book voice made earlier for this book and role (opened again), for a role nobody picked yet.+fn reuse_book_voices(s: &mut AppState) {+ let Some(title) = s.book.draft.as_ref().map(book_title) else { return };+ for role in [Role::Narrator, Role::Men, Role::Women] {+ let empty = match role {+ Role::Narrator => s.book.cast.narrator.is_none(),+ Role::Men => s.book.cast.men.is_none(),+ Role::Women => s.book.cast.women.is_none(),+ };+ let found = s+ .shell+ .voices+ .iter()+ .rev()+ .find(|v| v.book.as_deref() == Some(title.as_str()) && v.book_role.as_deref() == Some(role.id()))+ .map(|v| v.id.clone());+ if let (true, Some(id)) = (empty, found) {+ set_role_voice(s, role, &id);+ }+ }+}++fn cast_voice(s: &AppState, role: Role) -> Option<&str> {+ if !character_roles(s.book.voices, s.book.second).contains(&role) {+ return None;+ }+ role_voice(s, role).map(|v| v.id.as_str())+}++/// The language the book is read in: its own (found in the file, or picked in Style while Book is shown).+pub fn book_language(s: &AppState) -> String {+ match s.book.draft.as_ref().filter(|d| !d.file.language.is_empty()) {+ Some(d) => d.file.language.clone(),+ None => super::speak::language(s),+ }+}++fn set_role_voice(s: &mut AppState, role: Role, id: &str) {+ s.book.cast.samples.retain(|(r, _)| *r != role);+ match role {+ Role::Narrator => s.book.cast.narrator = Some(id.to_owned()),+ Role::Men => s.book.cast.men = Some(id.to_owned()),+ Role::Women => s.book.cast.women = Some(id.to_owned()),+ }+}++fn included(d: &Draft) -> Vec<BookChapterIn<'_>> {+ d.chapters.iter().filter(|c| c.include).map(|c| BookChapterIn { title: &c.title, text: &c.text }).collect()+}++fn book_title(d: &Draft) -> String {+ if d.file.title.trim().is_empty() { d.file.name.clone() } else { d.file.title.clone() }+}++/// Length and opening stand for the text: the draft changes a text only by splitting or joining chapters.+fn chapter_fingerprint(c: &DraftChapter) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ c.text.len().hash(&mut h);+ c.text.chars().take(32).for_each(|ch| ch.hash(&mut h));+ h.finish()+}++/// What `book.cast_status` depends on: every chapter's text (not whether it is picked), the mode and the language.+fn status_key(s: &AppState) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ for c in s.book.draft.iter().flat_map(|d| &d.chapters) {+ chapter_fingerprint(c).hash(&mut h);+ }+ (s.book.cast_mode.as_str(), book_language(s)).hash(&mut h);+ h.finish()+}++fn included_key(s: &AppState) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ for c in s.book.draft.iter().flat_map(|d| &d.chapters).filter(|c| c.include) {+ chapter_fingerprint(c).hash(&mut h);+ }+ s.book.cast_mode.as_str().hash(&mut h);+ h.finish()+}++/// Every picked chapter was searched before: the engine answers from what it kept, without Gemma.+fn fetch_kept_cast(s: &AppState) -> bool {+ s.book.voices > 1+ && s.book.cast.found.is_none()+ && s.book.cast.error.is_none()+ && !cast_running(s)+ && status_known(s)+ && s.book.draft.as_ref().is_some_and(|d| d.chapters.iter().any(|c| c.include))+ && unsearched_note(s).is_none()+}++fn status_known(s: &AppState) -> bool {+ s.book.cast.status_req.is_none() && s.book.cast.status_for == status_key(s)+}++/// Asks the engine which chapters were searched before, whenever the chapters, the mode or the language change.+fn ask_status(s: &mut AppState) {+ if s.book.voices < 2+ || cast_running(s)+ || s.book.cast.status_req.is_some()+ || !shell::engine_ready(s)+ || !super::setuprun::has(s, "cast")+ {+ return;+ }+ let key = status_key(s);+ if key == s.book.cast.status_for {+ return;+ }+ let Some(d) = s.book.draft.as_ref() else { return };+ let all: Vec<BookChapterIn<'_>> =+ d.chapters.iter().map(|c| BookChapterIn { title: &c.title, text: &c.text }).collect();+ let (_, params) = protocol::book_cast(&all, &book_language(s), s.book.cast_mode);+ s.book.cast.status_req = shell::request(s, "book.cast_status", params);+ s.book.cast.status_for = key;+}++/// "10 of 40 chapters…" when chapters picked after the last search have no speakers found.+fn unsearched_note(s: &AppState) -> Option<String> {+ let d = s.book.draft.as_ref()?;+ let picked: Vec<&DraftChapter> = d.chapters.iter().filter(|c| c.include).collect();+ if !status_known(s) {+ return None;+ }+ let todo = picked.iter().filter(|c| !chapter_searched(s, c)).count();+ (todo > 0).then(|| {+ format!("{todo} of {} chapters are not analysed yet: press Find who speaks to analyse only them.", picked.len())+ })+}++/// A search ended: ask again which chapters are searched.+fn searched(c: &mut Cast) {+ c.status_for = 0;+}++/// Gemma has read this chapter's lines for the mode picked now.+fn chapter_searched(s: &AppState, c: &DraftChapter) -> bool {+ s.book.cast.searched.contains(&chapter_fingerprint(c))+}++fn cast_running(s: &AppState) -> bool {+ s.book.cast.req.is_some() || s.book.cast.job.is_some()+}++/// Book's speaker search has the GPU: the speech models are paused until it ends.+pub fn finding_speakers(s: &AppState) -> bool {+ cast_running(s)+}++/// Only another mode drops the speakers found: chapters not searched yet are searched on their own, and the language+/// settles only after the voices load (a passing value dropped them).+fn drop_stale_cast(s: &mut AppState) -> bool {+ let c = &s.book.cast;+ if cast_running(s) || (c.found.is_none() && c.error.is_none()) {+ return false;+ }+ if c.error.is_some() && c.asked_key != included_key(s) {+ s.book.cast.error = None;+ return true;+ }+ if c.found.as_ref().is_none_or(|f| f.mode.is_empty() || f.mode == s.book.cast_mode.as_str()) {+ return false;+ }+ s.book.cast.found = None;+ s.book.cast.error = None;+ true+}++fn find_speakers(s: &mut AppState) {+ search(s, false);+}++/// `again`: Gemma reads every ticked chapter, those it read before too.+fn search(s: &mut AppState, again: bool) {+ commit_rename(s);+ let Some(d) = s.book.draft.as_ref() else { return };+ let lang = book_language(s);+ let mode = s.book.cast_mode;+ let (m, mut p) = protocol::book_cast(&included(d), &lang, mode);+ if again {+ p["again"] = json!(true);+ }+ let key = included_key(s);+ let req = shell::request(s, m, p);+ let c = &mut s.book.cast;+ c.asked_key = key;+ c.req = req;+ c.found = None;+ c.pct = 0.0;+ c.error = req.is_none().then(|| "Could not reach the engine.".to_owned());+}++fn cancel_cast(s: &mut AppState) {+ if s.book.cast.job.is_some()+ && !s.book.cast.cancelling+ && shell::request(s, "book.cast_cancel", json!({})).is_some()+ {+ s.book.cast.cancelling = true;+ }+}++fn generate_blocker(s: &AppState) -> Option<String> {+ if s.speak.is_generating() {+ Some("Generate when the text being spoken is done.".into())+ } else if super::design::generating(s) {+ Some("Generate when Design has made its voice.".into())+ } else if s.book.running() {+ Some("A book is being read: pause it to make a voice.".into())+ } else if super::train::is_training(s) {+ Some("A voice is training and is using the GPU. Generate when it finishes.".into())+ } else if cast_running(s) {+ Some("Generate when the speakers are found.".into())+ } else if s.book.voices > 1 {+ unsearched_note(s)+ } else {+ None+ }+}++fn sample_text(lang: &str, d: &Draft) -> String {+ let known = super::design::default_text(lang);+ if !known.is_empty() {+ return known.to_owned();+ }+ let mut out = String::new();+ for w in d.chapters.iter().filter(|c| c.include).flat_map(|c| c.text.split_whitespace()) {+ if !out.is_empty() {+ out.push(' ');+ }+ out.push_str(w);+ let n = out.chars().count();+ if (n >= 80 && w.ends_with(['.', '!', '?', '…'])) || n >= 200 {+ break;+ }+ }+ out+}++/// Design now and then makes noise for a description; such a take is made again this many times before giving up.+const UNCLEAR_TRIES: u8 = 3;++fn generate_role(s: &mut AppState, role: Role) {+ if generate_blocker(s).is_some()+ || s.book.cast.design.is_some()+ || !s.book.cast.imports.is_empty()+ || !s.book.cast.adopting.is_empty()+ {+ return;+ }+ s.book.cast.unclear = 0;+ request_design(s, role);+}++/// The design terms with the gender the user picked in place of Gemma's or the default one.+fn with_gender(description: &str, gender: Option<&str>) -> String {+ let Some(gender) = gender else { return description.to_owned() };+ let rest: Vec<&str> = description.split(", ").filter(|t| !matches!(t.trim(), "male" | "female")).collect();+ std::iter::once(gender).chain(rest).collect::<Vec<_>>().join(", ")+}++fn request_design(s: &mut AppState, role: Role) {+ // Chapters without dialogue bring no suggested voices: plain ones for each role then.+ let plain = CastVoices {+ narrator: "male, middle-aged, low pitch".into(),+ men: "male, young adult, moderate pitch".into(),+ women: "female, young adult, moderate pitch".into(),+ };+ let found = s.book.cast.found.as_ref().and_then(|c| c.voices.clone());+ let voices = &found.unwrap_or(plain);+ let Some(d) = s.book.draft.as_ref() else { return };+ let lang = book_language(s);+ let params = json!({+ "model": "omnivoice",+ "language": lang,+ "text": sample_text(&lang, d),+ "description": with_gender(role.description(voices), s.book.cast.genders.iter().find(|(r, _)| *r == role).map(|(_, g)| g.as_str())),+ // HolosTTS's reading goes through the zero-shot converter, which gave the sample a foreign accent.+ "exact_stress": false,+ });+ match shell::request(s, "voices.design", params) {+ Some(id) => s.book.cast.design = Some((id, role)),+ None => shell::toast(s, Tone::Danger, "Could not reach the engine."),+ }+}++/// Turns the samples of the roles in use into voices (marked as this book's); the book starts once all are made.+fn import_samples(s: &mut AppState) -> bool {+ let Some(title) = s.book.draft.as_ref().map(book_title) else { return false };+ let lang = book_language(s);+ let wanted: Vec<(Role, Value)> =+ used_roles(s).into_iter().filter_map(|r| sample(s, r).map(|t| (r, t.clone()))).collect();+ for (role, take) in wanted {+ let Some(params) = import_params(&title, &lang, role, &take) else { continue };+ match shell::request(s, "voices.import", params) {+ Some(id) => s.book.cast.imports.push((id, role)),+ None => {+ shell::toast(s, Tone::Danger, "Could not reach the engine.");+ s.book.cast.imports.clear();+ return false;+ }+ }+ }+ !s.book.cast.imports.is_empty()+}++fn import_params(title: &str, lang: &str, role: Role, take: &Value) -> Option<Value> {+ let reference = take.get("reference").and_then(Value::as_str)?;+ Some(json!({+ "name": format!("{title} · {}", role.id()),+ "reference_path": reference,+ "language": take.get("language").and_then(Value::as_str).unwrap_or(lang),+ "book": title,+ "book_role": role.id(),+ }))+}++/// Adds a sample Generate made to Your voices, named after the book and the role; the book's voice for the role, if it+/// has one, is made anew instead.+fn adopt_sample(s: &mut AppState, role: Role) {+ let Some(title) = s.book.draft.as_ref().map(book_title) else { return };+ let lang = book_language(s);+ let Some(mut params) = sample(s, role).and_then(|t| import_params(&title, &lang, role, t)) else { return };+ let old = s+ .shell+ .voices+ .iter()+ .rev()+ .find(|v| v.book.as_deref() == Some(title.as_str()) && v.book_role.as_deref() == Some(role.id()));+ if let Some(old) = old {+ params["into"] = json!(old.id);+ }+ if let Some(id) = shell::request(s, "voices.import", params) {+ s.book.cast.adopting.push((id, role));+ }+}++fn sample_path(s: &AppState, role: Role) -> Option<PathBuf> {+ sample(s, role).and_then(|t| t.get("path")).and_then(Value::as_str).map(PathBuf::from)+}++/// What the role's ▶ plays: its generated sample, else the clip its voice speaks from in the book's language.+fn role_audio(s: &AppState, role: Role) -> Option<PathBuf> {+ if let Some(path) = sample_path(s, role) {+ return Some(path);+ }+ let v = role_voice(s, role)?;+ let lang = book_language(s);+ let file = if v.references.contains(&lang) { format!("reference_{lang}.wav") } else { "reference.wav".into() };+ Some(super::onboarding::data_dir().join("voices").join(&v.id).join(file))+}++fn take_playing(s: &AppState, path: &Path) -> bool {+ s.playbar.now.as_ref().is_some_and(|n| n.path == path && n.status == playbar::Status::Playing)+}++fn play_take(s: &mut AppState, role: Role) {+ let Some(path) = role_audio(s, role) else { return };+ let name = match role_voice(s, role) {+ Some(v) if sample(s, role).is_none() => v.name.clone(),+ _ => format!("New voice · {}", role.id()),+ };+ let what = format!("Book · {}", role.id());+ if let Err(e) = playbar::toggle(s, &path, name, what, playbar::Source::Speak) {+ shell::toast(s, Tone::Danger, e);+ }+}++const CAST_NAMES: usize = 3;++fn cast_caption(c: &BookCast) -> String {+ let (men, women, narrator) = c.lines.as_ref().map_or((0, 0, 0), |l| (l.men, l.women, l.narrator));+ let mut parts = vec![+ format!("Men: {} lines", group(men)),+ format!("Women: {} lines", group(women)),+ format!("Narrator: {}", group(narrator)),+ ];+ let mut cast: Vec<_> = c.characters.iter().collect();+ cast.sort_by_key(|x| std::cmp::Reverse(x.lines));+ if !cast.is_empty() {+ let names: Vec<&str> = cast.iter().take(CAST_NAMES).map(|x| x.name.as_str()).collect();+ let more = if cast.len() > CAST_NAMES { ", …" } else { "" };+ parts.push(format!("{}{more}", names.join(", ")));+ }+ parts.join(" · ")+}+fn start(s: &mut AppState) {commit_rename(s);+ drop_stale_cast(s);if let Some(why) = start_blocker(s) {shell::toast(s, Tone::Warning, why);return;}- let (Some(d), Some(voice)) = (s.book.draft.as_ref(), shell::active_voice(s)) else { return };- let lang = super::speak::language(s);+ if import_samples(s) {+ return;+ }+ let (Some(d), Some(voice)) = (s.book.draft.as_ref(), role_voice(s, Role::Narrator)) else { return };+ let lang = book_language(s);let out = super::formats::output_format(s);- let title = if d.file.title.trim().is_empty() { d.file.name.clone() } else { d.file.title.clone() };+ let title = book_title(d);let req = protocol::book_start(&BookParams {title: &title,source: d.file.path.to_str(),format: Some(&d.file.format),- chapters: d- .chapters- .iter()- .filter(|c| c.include)- .map(|c| BookChapterIn { title: &c.title, text: &c.text })- .collect(),+ chapters: included(d),voice_id: &voice.id,language: &lang,expressiveness: s.book.expressiveness,voice_match: s.speak.voice_match,quality: s.speak.quality,speed: s.speak.speed,- accent: super::speak::accent_param(s, &lang),+ accent: super::speak::accent_param(s, &lang).map(|_| protocol::NativeVoice::Auto),output_format: &out,m4b: s.book.m4b,read_titles: s.book.read_titles,exact_stress: s.speak.exact_stress,- keep_voice: s.book.keep_voice,model: &super::speak::model(s),+ men: cast_voice(s, Role::Men),+ women: cast_voice(s, Role::Women),+ cast: if s.book.voices > 1 { s.book.cast_mode } else { CastMode::Fast },});shell::stop_audio(s);match shell::request(s, req.0, req.1) {@@ -474,7 +1056,8 @@ fn resume(s: &mut AppState) {shell::toast(s, Tone::Warning, "Wait for Design to finish making a voice.");return;}- let (m, p) = protocol::book_id_request("book.resume", &id);+ let (m, mut p) = protocol::book_id_request("book.resume", &id);+ settings_now(s, &mut p);match shell::request(s, m, p) {Some(r) => s.book.resume_req = Some(r),None => shell::toast(s, Tone::Danger, "Could not reach the engine."),@@ -485,7 +1068,14 @@ fn resume(s: &mut AppState) {fn reread(s: &mut AppState, voice: Option<String>, chapters: Option<Vec<u32>>) {s.book.voice_menu = None;let Some(id) = s.book.project.as_ref().map(|p| p.id.clone()) else { return };- let (m, p) = protocol::book_reread(&id, voice.as_deref(), chapters.as_deref());+ let role = s.book.project.as_ref().map_or(Role::Narrator, |b| {+ if book_roles(b).contains(&s.book.voice_role) { s.book.voice_role } else { Role::Narrator }+ });+ let role = role.id();+ let (m, mut p) = protocol::book_reread(&id, voice.as_deref().map(|v| (role, v)), chapters.as_deref());+ if voice.is_none() {+ settings_now(s, &mut p);+ }match shell::request(s, m, p) {Some(r) => s.book.reread_req = Some(r),None => shell::toast(s, Tone::Danger, "Could not reach the engine."),@@ -503,6 +1093,233 @@ fn pick_book_voice(s: &mut AppState, voice: String) {}}+/// The voice a book reads a role with.+fn book_role_voice(b: &BookSummary, role: Role) -> Option<&str> {+ match role {+ Role::Narrator => b.voice_id.as_deref(),+ _ => b.voices.as_ref().and_then(|v| v.get(role.id())).and_then(|v| v.as_deref()),+ }+}++fn book_roles(b: &BookSummary) -> Vec<Role> {+ [Role::Narrator, Role::Men, Role::Women].into_iter().filter(|r| book_role_voice(b, *r).is_some()).collect()+}++/// Whitespace aside, the text a book keeps of a chapter.+fn text_key(text: &str) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ text.trim().hash(&mut h);+ h.finish()+}++/// The book the draft's chapters are read into, while it is the one loaded.+fn linked(s: &AppState) -> Option<&BookSummary> {+ let id = s.book.draft.as_ref()?.book_id.as_deref()?;+ s.book.project.as_ref().filter(|b| b.id == id)+}++/// A draft chapter's place in its book and how far it is read.+fn book_row<'a>(s: &'a AppState, c: &DraftChapter) -> Option<(&'a BookSummary, &'a BookChapterRow)> {+ let b = linked(s)?;+ let key = text_key(&c.text);+ let at = s.book.book_keys.iter().position(|k| *k == key)?;+ Some((b, b.chapter_list.iter().find(|r| r.index as usize == at)?))+}++/// A book read from the draft's file before: the draft goes on with it rather than making another.+fn same_file_book(s: &AppState) -> Option<String> {+ let d = s.book.draft.as_ref().filter(|d| d.book_id.is_none())?;+ let path = d.file.path.to_str()?;+ s.book+ .recent+ .iter()+ .filter(|b| b.source.as_deref() == Some(path))+ .max_by(|a, b| a.id.cmp(&b.id))+ .map(|b| b.id.clone())+}++/// Draft, In progress or Finished: the book the draft sets up, as far as it is read.+fn draft_status(s: &AppState) -> (&'static str, Tone, bool) {+ let id = s.book.draft.as_ref().and_then(|d| d.book_id.as_deref());+ let b = id.and_then(|id| s.book.project.iter().chain(&s.book.recent).find(|b| b.id == id));+ match b {+ Some(b) if b.status == "running" => ("In progress", Tone::Accent, true),+ Some(b) if b.chapters_done == 0 => ("Draft", Tone::Neutral, false),+ Some(b) => {+ let all = s+ .book+ .draft+ .iter()+ .flat_map(|d| &d.chapters)+ .filter(|c| c.include)+ .all(|c| book_row(s, c).is_some_and(|(_, r)| r.status == "done"));+ if all && b.status == "done" {+ ("Finished", Tone::Success, false)+ } else {+ ("In progress", Tone::Warning, false)+ }+ }+ None => ("Draft", Tone::Neutral, false),+ }+}++/// Takes a chapter out of the draft (the file is not changed).+fn remove_chapter(s: &mut AppState, i: usize) {+ if reading_locked(s) {+ return;+ }+ commit_rename(s);+ if let Some(d) = s.book.draft.as_mut()+ && i < d.chapters.len()+ && d.chapters.len() > 1+ {+ d.chapters.remove(i);+ }+}++/// Asks the draft's book for its chapters' texts, to know which draft chapters it holds.+fn link_book(s: &mut AppState) {+ let Some(id) = s.book.draft.as_ref().and_then(|d| d.book_id.clone()) else { return };+ s.book.link_req = shell::request(s, "book.get", json!({ "id": id, "text": true }));+}++/// The cells of a chapter read into the book: how far, read again, play.+fn read_cells(s: &AppState, p: Palette, mut r: El, b: &BookSummary, c: &BookChapterRow, include: bool) -> El {+ let idx = c.index;+ let running = b.status == "running";+ let (mark, help): (El, String) = match c.status.as_str() {+ "done" => (icon_el(&icons::CHECK, 14.0, p.ok), format!("Read: {} of audio", fmt_len(c.audio_s))),+ "partial" if running => (+ status_dot(p, Tone::Accent, true),+ if c.segments > 0 {+ format!("Reading: part {} of {}", c.segment.min(c.segments), c.segments)+ } else {+ "Reading…".into()+ },+ ),+ "partial" => (+ icon_el(&icons::PAUSE, 13.0, p.warn),+ format!("Stopped at part {} of {}", c.segment, c.segments.max(c.segment)),+ ),+ _ => (el().size(10.0, 10.0).radius(5.0).border(1.0, p.text_faint), "Waiting to be read".into()),+ };+ // Only what applies is shown: read again once the chapter is read and the book is not being read.+ if c.status == "done" && !running && s.book.reread_req.is_none() {+ r = r.child(small_icon(p, format!("book-redo{idx}"), &icons::REFRESH, "Read this chapter again", move |s| {+ reread(s, None, Some(vec![idx]))+ }));+ }+ r = r.child(+ el().key(format!("book-state{idx}")).size(28.0, 28.0).center().label(help.clone()).help(help).child(mark),+ );+ r = r.child(if c.status == "done" {+ let playing = chapter_playing(s, idx);+ let btn = el()+ .key(format!("book-play{idx}"))+ .role("button")+ .label(if playing { "Pause" } else { "Play" })+ .size(28.0, 28.0)+ .radius(14.0)+ .center()+ .hover(rune::Color::WHITE.alpha(0.1))+ .focusable(true)+ .motion(motion::UI)+ .on_press(move |s: &mut AppState| play_chapter(s, idx))+ .child(icon_el(if playing { &icons::PAUSE } else { &icons::PLAY }, 12.0, p.on_accent));+ accent_glass(p, btn)+ } else {+ el()+ });+ if !include { r.opacity(0.7) } else { r }+}++/// The draft's voices and Output choices, for the chapters its book reads from now on (resumed, read again).+fn settings_now(s: &AppState, params: &mut Value) {+ if linked(s).is_none() {+ return;+ }+ params["voice_id"] = json!(role_voice(s, Role::Narrator).map(|v| v.id.clone()));+ if s.book.voices > 1 {+ params["voices"] = json!({ "men": cast_voice(s, Role::Men), "women": cast_voice(s, Role::Women) });+ params["cast"] = json!(s.book.cast_mode.as_str());+ }+ for (key, on) in [("m4b", s.book.m4b), ("read_titles", s.book.read_titles), ("exact_stress", s.speak.exact_stress)]+ {+ params[key] = json!(on);+ }+}++/// Hands the Output choices to the draft's book at once: one being read makes its M4B by the box ticked last.+fn send_settings(s: &mut AppState) {+ let Some(id) = linked(s).map(|b| b.id.clone()) else { return };+ let params = json!({ "id": id, "m4b": s.book.m4b, "read_titles": s.book.read_titles });+ let _ = shell::request(s, "book.settings", params);+}++/// A chapter of the draft's book is read and its file is there.+fn has_files(s: &AppState) -> bool {+ linked(s).is_some_and(|b| b.chapter_list.iter().any(|c| c.path.as_ref().is_some_and(|p| p.is_file())))+}++/// While the draft's book is read, its chapters and voices stay as they are: Pause unlocks them.+fn reading_locked(s: &AppState) -> bool {+ linked(s).is_some_and(|b| b.status == "running") || s.book.start_req.is_some() || s.book.add_req.is_some()+}++/// The ticked chapters the book does not have yet, with their place in the draft.+fn new_chapters(s: &AppState) -> Vec<(usize, &DraftChapter)> {+ let Some(d) = s.book.draft.as_ref() else { return Vec::new() };+ let have: Vec<u64> = if linked(s).is_some() { s.book.book_keys.clone() } else { Vec::new() };+ d.chapters.iter().enumerate().filter(|(_, c)| c.include && !have.contains(&text_key(&c.text))).collect()+}++fn read_blocker(s: &AppState) -> Option<String> {+ let Some(b) = linked(s) else { return start_blocker(s) };+ if b.status == "running" {+ return None;+ }+ if new_chapters(s).is_empty() {+ let waiting = s+ .book+ .draft+ .iter()+ .flat_map(|d| &d.chapters)+ .filter(|c| c.include)+ .any(|c| book_row(s, c).is_some_and(|(_, r)| r.status != "done"));+ return (!waiting).then(|| "The ticked chapters are read: ↻ beside one reads it again.".to_owned());+ }+ start_blocker(s)+}++/// Reads the ticked chapters: a new book the first time, then more chapters into the same one.+fn read_book(s: &mut AppState) {+ if linked(s).is_none() {+ start(s);+ return;+ }+ if let Some(why) = read_blocker(s) {+ shell::toast(s, Tone::Warning, why);+ return;+ }+ let Some(id) = s.book.draft.as_ref().and_then(|d| d.book_id.clone()) else { return };+ let chapters: Vec<Value> = new_chapters(s)+ .into_iter()+ .map(|(i, c)| json!({ "title": c.title, "text": c.text, "number": i + 1 }))+ .collect();+ if chapters.is_empty() {+ resume(s);+ return;+ }+ let voice = role_voice(s, Role::Narrator).map(|v| v.id.clone());+ let mut params = json!({ "id": id, "chapters": chapters, "voice_id": voice });+ settings_now(s, &mut params);+ match shell::request(s, "book.add", params) {+ Some(r) => s.book.add_req = Some(r),+ None => shell::toast(s, Tone::Danger, "Could not reach the engine."),+ }+}+fn keep_made_chapters(s: &mut AppState, voice: String) {let partial: Vec<u32> = s.book@@ -531,21 +1348,198 @@ fn stop(s: &mut AppState, how: &'static str) {}}-fn reset_partial(p: &mut BookSummary) {- for c in &mut p.chapter_list {- if c.status != "done" {- c.status = "waiting".into();- c.segment = 0;- c.audio_s = 0.0;+fn reset_partial(p: &mut BookSummary) {+ for c in &mut p.chapter_list {+ if c.status != "done" {+ c.status = "waiting".into();+ c.segment = 0;+ c.audio_s = 0.0;+ }+ }+}++/// One line of Your books: a book read or being set up, opened in the same workspace.+struct Entry {+ key: String,+ title: String,+ path: Option<PathBuf>,+ book: Option<String>,+ word: &'static str,+ tone: Tone,+ pulse: bool,+ detail: String,+ current: bool,+}++/// Every book the engine has, and every draft kept for a file no book was read from yet.+fn book_entries(s: &AppState) -> Vec<Entry> {+ let cur = s.book.draft.as_ref();+ let cur_path = cur.map(|d| d.file.path.clone());+ let mut out = Vec::new();+ let mut books: Vec<&BookSummary> =+ s.book.recent.iter().map(|b| s.book.project.as_ref().filter(|p| p.id == b.id).unwrap_or(b)).collect();+ books.sort_by_key(|b| !of_active_voice(s, b));+ for b in books.into_iter().take(12) {+ let path = b.source.as_ref().map(PathBuf::from);+ let current =+ cur.is_some_and(|d| d.book_id.as_deref() == Some(b.id.as_str())) || (path.is_some() && path == cur_path);+ let (word, tone, pulse, detail) = if current {+ let (w, t, p) = draft_status(s);+ let d = cur.expect("current");+ (+ w,+ t,+ p,+ format!("{} of {} chapters picked", d.chapters.iter().filter(|c| c.include).count(), d.chapters.len()),+ )+ } else {+ let (w, t) = status_word(b);+ (+ w,+ t,+ b.status == "running",+ format!("{} of {} chapters · {}", b.chapters_done, b.chapters, fmt_len(b.totals.audio_s)),+ )+ };+ let path = if current { cur_path.clone() } else { path };+ out.push(Entry {+ key: b.id.clone(),+ title: b.title.clone(),+ path,+ book: Some(b.id.clone()),+ word,+ tone,+ pulse,+ detail,+ current,+ });+ }+ let mut drafts: Vec<(PathBuf, String)> = s.book.drafts.clone();+ if let Some(d) = cur+ && !drafts.iter().any(|(p, _)| *p == d.file.path)+ {+ drafts.push((d.file.path.clone(), book_title(d)));+ }+ for (path, title) in drafts {+ if out.iter().any(|e| e.path.as_ref() == Some(&path)) {+ continue;+ }+ let current = cur_path.as_ref() == Some(&path);+ let (word, tone, pulse) = if current { draft_status(s) } else { ("Draft", Tone::Neutral, false) };+ let detail = match cur.filter(|_| current) {+ Some(d) => {+ format!("{} of {} chapters picked", d.chapters.iter().filter(|c| c.include).count(), d.chapters.len())+ }+ None => "not read yet".to_owned(),+ };+ let key = format!("draft-{:016x}", text_key(&path.to_string_lossy()));+ out.push(Entry { key, title, path: Some(path), book: None, word, tone, pulse, detail, current });+ }+ out+}++fn slot_dir() -> PathBuf {+ super::onboarding::data_dir().join("book-drafts")+}++/// Where the draft of a file is kept while another book is open.+fn slot_path(path: &Path) -> PathBuf {+ slot_dir().join(format!("{:016x}.json", text_key(&path.to_string_lossy())))+}++fn save_drafts_index(drafts: &[(PathBuf, String)]) {+ let _ = std::fs::create_dir_all(slot_dir());+ if let Ok(b) = serde_json::to_vec(drafts) {+ let _ = std::fs::write(slot_dir().join("index.json"), b);+ }+}++fn load_drafts_index() -> Vec<(PathBuf, String)> {+ std::fs::read(slot_dir().join("index.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()+}++#[cfg(test)]+thread_local! {+ static STASHED: std::cell::RefCell<Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>> = const { std::cell::RefCell::new(None) };+}++/// Keeps the open draft in its file's slot, so the book comes back as it was left.+fn stash_current(s: &mut AppState) {+ let Some(d) = s.book.draft.clone() else { return };+ #[cfg(test)]+ STASHED.with(|k| {+ if let Some(k) = k.borrow().as_ref() {+ *k.lock().unwrap() = Some(d.file.language.clone());+ }+ });+ if !s.book.drafts.iter().any(|(p, _)| *p == d.file.path) {+ s.book.drafts.push((d.file.path.clone(), book_title(&d)));+ }+ if s.shell.scripted() {+ return;+ }+ let saved = Saved { draft: d.clone(), cast: saved_now(s), shown: true };+ if let Ok(b) = serde_json::to_vec(&saved) {+ let _ = std::fs::create_dir_all(slot_dir());+ let _ = std::fs::write(slot_path(&d.file.path), b);+ }+ save_drafts_index(&s.book.drafts);+}++fn read_slot(path: &Path) -> Option<Saved> {+ std::fs::read(slot_path(path)).ok().and_then(|b| serde_json::from_slice::<Saved>(&b).ok())+}++/// Opens a book of the list in the workspace: its kept draft, else its file read again.+fn open_entry(s: &mut AppState, path: Option<PathBuf>, book: Option<String>) {+ s.book.shown = true;+ let Some(path) = path else {+ shell::toast(s, Tone::Warning, "This book's file is not known: open it with Open book.");+ return;+ };+ if s.book.draft.as_ref().is_some_and(|d| d.file.path == path) {+ return;+ }+ stash_current(s);+ if let Some(saved) = read_slot(&path) {+ let mut draft = saved.draft;+ if draft.book_id.is_none() {+ draft.book_id = book;}+ s.book.cast = Cast::default();+ if saved.cast.file.as_deref() == Some(draft.file.path.as_path()) {+ restore_cast(&mut s.book.cast, saved.cast);+ }+ s.book.draft = Some(draft);+ s.book.book_keys.clear();+ s.book.renaming = None;+ link_book(s);+ return;+ }+ if !path.is_file() {+ shell::toast(s, Tone::Warning, format!("{} is not where it was: open it with Open book.", path.display()));+ return;}+ import(s, path, Purpose::Book);}-fn open_book(s: &mut AppState, id: &str) {- let (m, p) = protocol::book_id_request("book.get", id);- s.book.get_req = shell::request(s, m, p);- s.book.draft = None;- s.book.shown = true;+/// Takes a book off the list: its draft, and the engine's record of it (the audio files stay).+fn remove_entry(s: &mut AppState, path: Option<PathBuf>, book: Option<String>) {+ if let Some(id) = book.as_deref() {+ forget_book(s, id);+ }+ if let Some(path) = path {+ s.book.drafts.retain(|(p, _)| *p != path);+ if !s.shell.scripted() {+ let _ = std::fs::remove_file(slot_path(&path));+ save_drafts_index(&s.book.drafts);+ }+ if s.book.draft.as_ref().is_some_and(|d| d.file.path == path) {+ s.book.draft = None;+ s.book.book_keys.clear();+ s.book.cast = Cast::default();+ }+ }}fn forget_book(s: &mut AppState, id: &str) {@@ -560,7 +1554,11 @@ fn forget_book(s: &mut AppState, id: &str) {fn close(s: &mut AppState) {s.book.renaming = None;- if s.book.draft.take().is_none() && !s.book.running() {+ stash_current(s);+ s.book.draft = None;+ s.book.book_keys.clear();+ s.book.cast = Cast::default();+ if !s.book.running() {s.book.project = None;}}@@ -646,6 +1644,13 @@ pub fn on_engine(s: &mut AppState, msg: &EngineMsg) {s.book.stopping = None;s.book.start_req = None;s.book.resume_req = None;+ let c = &mut s.book.cast;+ if c.req.take().is_some() | c.job.take().is_some() {+ c.error = Some("The voice engine stopped. Try again once it is running.".into());+ }+ c.cancelling = false;+ c.design = None;+ c.imports.clear();if let Some(p) = s.book.project.as_mut().filter(|p| p.status == "running") {p.status = "paused".into();p.interrupted = true;@@ -671,7 +1676,10 @@ fn on_response(s: &mut AppState, id: u64, result: &Result<Value, protocol::Enginb.start_req = None;match result.clone().and_then(protocol::parse_result::<BookStarted>) {Ok(st) => {- let Some(d) = b.draft.take() else { return };+ let Some(d) = b.draft.as_mut() else { return };+ d.book_id = Some(st.id.clone());+ b.book_keys = d.chapters.iter().filter(|c| c.include).map(|c| text_key(&c.text)).collect();+ let d = &*d;let rows = d.chapters.iter()@@ -703,6 +1711,103 @@ fn on_response(s: &mut AppState, id: u64, result: &Result<Value, protocol::Engin}Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),}+ } else if b.cast.status_req == Some(id) {+ b.cast.status_req = None;+ let answer = result.clone().ok().and_then(|v| v.get("searched").and_then(Value::as_array).cloned());+ match (answer, s.book.draft.as_ref()) {+ (Some(list), Some(d)) if list.len() == d.chapters.len() => {+ s.book.cast.searched = d+ .chapters+ .iter()+ .zip(list)+ .filter(|(_, yes)| yes.as_bool() == Some(true))+ .map(|(c, _)| chapter_fingerprint(c))+ .collect();+ let speech = result.as_ref().ok().and_then(|v| v.get("speech")).and_then(Value::as_array);+ s.book.cast.speechless = speech+ .filter(|l| l.len() == d.chapters.len())+ .map(|l| {+ d.chapters+ .iter()+ .zip(l)+ .filter(|(_, yes)| yes.as_bool() == Some(false))+ .map(|(c, _)| chapter_fingerprint(c))+ .collect()+ })+ .unwrap_or_default();+ }+ _ => s.book.cast.status_for = 0,+ }+ } else if b.cast.req == Some(id) {+ b.cast.req = None;+ match result.clone().and_then(protocol::parse_result::<BookCast>) {+ Ok(c) if c.job.is_some() => b.cast.job = Some(c.key),+ Ok(c) => {+ b.cast.found = Some(c);+ searched(&mut b.cast);+ reuse_book_voices(s);+ }+ Err(e) => b.cast.error = Some(friendly(&e)),+ }+ } else if let Some((_, role)) = b.cast.design.filter(|(r, _)| *r == id) {+ b.cast.design = None;+ match result {+ Ok(take) if take.get("clear").and_then(Value::as_bool) == Some(false) => {+ s.book.cast.unclear += 1;+ if s.book.cast.unclear < UNCLEAR_TRIES {+ request_design(s, role);+ } else {+ shell::toast(s, Tone::Warning, "The voice came out as noise three times. Press Generate again.");+ }+ }+ Ok(take) => {+ s.book.cast.samples.retain(|(r, _)| *r != role);+ s.book.cast.samples.push((role, take.clone()));+ adopt_sample(s, role);+ }+ Err(e) => shell::toast(s, Tone::Danger, friendly(e)),+ }+ } else if let Some(at) = b.cast.adopting.iter().position(|(r, _)| *r == id) {+ let (_, role) = b.cast.adopting.remove(at);+ match result.as_ref().map(|v| v.get("voice").and_then(VoiceInfo::from_json)) {+ Ok(Some(info)) => {+ let voice = info.id.clone();+ match s.shell.voices.iter_mut().find(|v| v.id == voice) {+ Some(v) => *v = info,+ None => s.shell.voices.push(info),+ }+ // The clip is replaced in place: the player would resume the old one at the same path.+ if let Some(path) = role_audio(s, role) {+ playbar::stop_path(s, &[path.as_path()]);+ }+ set_role_voice(s, role, &voice);+ shell::refresh_voices(s);+ }+ Ok(None) => shell::toast(s, Tone::Danger, "The engine did not return the new voice."),+ Err(e) => shell::toast(s, Tone::Danger, friendly(e)),+ }+ } else if let Some(at) = b.cast.imports.iter().position(|(r, _)| *r == id) {+ let (_, role) = b.cast.imports.remove(at);+ match result.as_ref().map(|v| v.get("voice").and_then(VoiceInfo::from_json)) {+ Ok(Some(info)) => {+ let voice = info.id.clone();+ s.shell.voices.retain(|v| v.id != voice);+ s.shell.voices.push(info);+ shell::refresh_voices(s);+ set_role_voice(s, role, &voice);+ if s.book.cast.imports.is_empty() {+ start(s);+ }+ }+ Ok(None) => {+ s.book.cast.imports.clear();+ shell::toast(s, Tone::Danger, "The engine did not return the new voice.");+ }+ Err(e) => {+ s.book.cast.imports.clear();+ shell::toast(s, Tone::Danger, friendly(e));+ }+ }} else if b.resume_req == Some(id) {b.resume_req = None;match result.clone().and_then(protocol::parse_result::<BookStarted>) {@@ -717,6 +1822,38 @@ fn on_response(s: &mut AppState, id: u64, result: &Result<Value, protocol::Engin}Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),}+ } else if b.link_req == Some(id) {+ b.link_req = None;+ match result.clone().and_then(protocol::parse_result::<BookSummary>) {+ Ok(p) => {+ let rows = result.as_ref().ok().and_then(|v| v.get("chapter_list")).and_then(Value::as_array);+ b.book_keys = rows+ .map(|r| r.iter().map(|r| text_key(r.get("text").and_then(Value::as_str).unwrap_or(""))).collect())+ .unwrap_or_default();+ if b.project.as_ref().is_none_or(|q| q.id == p.id || q.status != "running") {+ b.project = Some(p);+ }+ }+ Err(e) => {+ if e.code == "not_found"+ && let Some(d) = b.draft.as_mut()+ {+ d.book_id = None;+ }+ b.book_keys.clear();+ }+ }+ } else if b.add_req == Some(id) {+ b.add_req = None;+ match result.clone().and_then(protocol::parse_result::<BookSummary>) {+ Ok(p) => {+ b.project = Some(p);+ request_list(s);+ link_book(s);+ resume(s);+ }+ Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),+ }} else if b.reread_req == Some(id) {b.reread_req = None;match result.clone().and_then(protocol::parse_result::<BookSummary>) {@@ -774,15 +1911,6 @@ fn on_response(s: &mut AppState, id: u64, result: &Result<Value, protocol::Engin}}-fn voice_label(s: &AppState, b: &BookSummary) -> Option<String> {- let id = b.voice_id.as_ref()?;- match s.shell.voices.iter().find(|v| &v.id == id) {- Some(v) => Some(v.name.clone()),- None if !s.shell.voices.is_empty() => Some("voice deleted".into()),- None => None,- }-}-fn of_active_voice(s: &AppState, b: &BookSummary) -> bool {b.voice_id.is_some() && b.voice_id == s.shell.active_voice}@@ -817,10 +1945,40 @@ fn on_event(s: &mut AppState, name: &str, data: &Value) {s.book.m4b_stage(pr.stage.as_deref() == Some("m4b"));s.book.m4b_progress = (pr.stage_pct.unwrap_or(0.0), pr.stage_eta_s);s.book.memory_wait = if pr.stage.as_deref() == Some("memory") { pr.retry_in_s } else { None };+ s.book.cast_stage = (pr.stage.as_deref() == Some("cast")).then(|| pr.stage_pct.unwrap_or(0.0));+ }+ "book.cast_progress" if cast_event(s, data) => {+ if let Ok(pr) = serde_json::from_value::<BookCastProgress>(data.clone()) {+ s.book.cast.pct = pr.pct;+ }+ }+ "book.cast_done" if cast_event(s, data) => {+ let c = &mut s.book.cast;+ (c.req, c.job, c.cancelling) = (None, None, false);+ match serde_json::from_value::<BookCast>(data.clone()) {+ Ok(found) => {+ c.found = Some(found);+ searched(c);+ }+ Err(e) => c.error = Some(e.to_string()),+ }+ }+ "book.cast_error" if cast_event(s, data) => {+ let c = &mut s.book.cast;+ (c.req, c.job, c.cancelling) = (None, None, false);+ if data.get("code").and_then(Value::as_str) != Some("cancelled") {+ c.error =+ Some(data.get("message").and_then(Value::as_str).unwrap_or("Something went wrong.").to_owned());+ }}"book.chapter" if shown => {let Ok(ch) = serde_json::from_value::<BookChapterDone>(data.clone()) else { return };let totals = serde_json::from_value(data.clone()).unwrap_or_default();+ if let Some(r) = ch.rtf.filter(|r| *r > 0.0) {+ let slot = &mut s.book.measured_rtf[usize::from(s.speak.quality == protocol::Quality::Fast)];+ *slot = Some(slot.map_or(r, |old| old * 0.7 + r * 0.3));+ s.book.settings_dirty = true;+ }let p = s.book.project.as_mut().expect("shown");p.totals = totals;p.chapters_done += 1;@@ -884,6 +2042,12 @@ fn on_event(s: &mut AppState, name: &str, data: &Value) {}}+/// The answer to `book.cast` may come after its first events.+fn cast_event(s: &AppState, data: &Value) -> bool {+ let c = &s.book.cast;+ c.req.is_some() || (c.job.is_some() && c.job.as_deref() == data.get("key").and_then(Value::as_str))+}+impl BookState {fn m4b_stage(&mut self, on: bool) {if on {@@ -899,6 +2063,67 @@ fn request_list(s: &mut AppState) {s.book.listed = true;}+/// What `book-draft.json` holds: the draft, and the speakers found and voices picked for it.+#[derive(serde::Serialize, serde::Deserialize)]+struct Saved {+ #[serde(flatten)]+ draft: Draft,+ #[serde(default)]+ cast: SavedCast,+ #[serde(default)]+ shown: bool,+}++#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]+struct SavedCast {+ /// The file these speakers and voices were found for: another one's are not brought back.+ #[serde(default)]+ file: Option<PathBuf>,+ #[serde(default)]+ narrator: Option<String>,+ found: Option<BookCast>,+ men: Option<String>,+ women: Option<String>,+ samples: Vec<(String, Value)>,+ #[serde(default)]+ genders: Vec<(String, String)>,+}++fn saved_now(s: &AppState) -> SavedCast {+ saved_cast(&s.book.cast, s.book.draft.as_ref().map(|d| d.file.path.as_path()))+}++fn saved_cast(c: &Cast, file: Option<&Path>) -> SavedCast {+ SavedCast {+ file: file.map(Path::to_path_buf),+ narrator: c.narrator.clone(),+ found: c.found.clone(),+ men: c.men.clone(),+ women: c.women.clone(),+ samples: c.samples.iter().map(|(r, v)| (r.id().to_string(), v.clone())).collect(),+ genders: c.genders.iter().map(|(r, g)| (r.id().to_string(), g.clone())).collect(),+ }+}++fn restore_cast(c: &mut Cast, saved: SavedCast) {+ c.narrator = saved.narrator;+ c.found = saved.found;+ c.men = saved.men;+ c.women = saved.women;+ c.samples = saved.samples.into_iter().filter_map(|(r, v)| Some((Role::from_id(&r)?, v))).collect();+ c.genders = saved.genders.into_iter().filter_map(|(r, g)| Some((Role::from_id(&r)?, g))).collect();+}++fn saved_fingerprint(s: &AppState) -> Option<u64> {+ use std::hash::{Hash, Hasher};+ let d = s.book.draft.as_ref()?;+ let mut h = std::collections::hash_map::DefaultHasher::new();+ fingerprint(d).hash(&mut h);+ serde_json::to_string(&saved_now(s)).unwrap_or_default().hash(&mut h);+ s.book.shown.hash(&mut h);+ Some(h.finish())+}+fn draft_path() -> std::path::PathBuf {super::onboarding::data_dir().join("book-draft.json")}@@ -917,24 +2142,30 @@ fn fingerprint(d: &Draft) -> u64 {fn keep_draft(s: &mut AppState) -> bool {if !s.book.draft_restored {s.book.draft_restored = true;+ s.book.drafts = load_drafts_index();if s.book.draft.is_none() {- let restored = std::fs::read(draft_path()).ok().and_then(|b| serde_json::from_slice::<Draft>(&b).ok());- if let Some(d) = restored {- s.book.draft_saved = Some(fingerprint(&d));- s.book.draft = Some(d);+ let restored = std::fs::read(draft_path()).ok().and_then(|b| serde_json::from_slice::<Saved>(&b).ok());+ if let Some(saved) = restored {+ if saved.cast.file.as_deref() == Some(saved.draft.file.path.as_path()) {+ restore_cast(&mut s.book.cast, saved.cast);+ }+ s.book.draft = Some(saved.draft);+ s.book.shown = saved.shown;+ s.book.relink = true;+ s.book.draft_saved = saved_fingerprint(s);return true;}}}- let now = s.book.draft.as_ref().map(fingerprint);+ let now = saved_fingerprint(s);if now == s.book.draft_saved {return false;}s.book.draft_saved = now;- let draft = s.book.draft.clone();+ let saved = s.book.draft.clone().map(|draft| Saved { draft, cast: saved_now(s), shown: s.book.shown });std::thread::spawn(move || {let path = draft_path();- match draft {+ match saved {Some(d) => {let tmp = path.with_extension("json.tmp");let ok = serde_json::to_vec(&d).ok().is_some_and(|b| std::fs::write(&tmp, b).is_ok());@@ -951,7 +2182,26 @@ fn keep_draft(s: &mut AppState) -> bool {}pub fn settle(s: &mut AppState) -> bool {- let mut changed = false;+ let mut changed = drop_stale_cast(s);+ ask_status(s);+ if s.book.relink && shell::engine_ready(s) {+ s.book.relink = false;+ link_book(s);+ }+ if s.book.cast.narrator.is_none() && s.book.cast.found.is_some() && !s.shell.voices.is_empty() {+ reuse_book_voices(s);+ }+ if let Some(id) = same_file_book(s) {+ if let Some(d) = s.book.draft.as_mut() {+ d.book_id = Some(id);+ }+ link_book(s);+ changed = true;+ }+ if fetch_kept_cast(s) && s.book.importing.is_none() && shell::engine_ready(s) {+ find_speakers(s);+ changed = true;+ }if !s.shell.scripted() {changed |= keep_draft(s);}@@ -965,22 +2215,40 @@ pub fn settle(s: &mut AppState) -> bool {s.book.m4b = super::onboarding::setting("book_m4b").and_then(|v| v.as_bool()).unwrap_or(false);s.book.read_titles =super::onboarding::setting("book_read_titles").and_then(|v| v.as_bool()).unwrap_or(true);- s.book.keep_voice =- super::onboarding::setting("book_keep_voice").and_then(|v| v.as_bool()).unwrap_or(false);s.book.expressiveness = super::onboarding::setting("book_expressiveness").and_then(|v| v.as_f64()).map(|v| v as f32).unwrap_or(EXPRESSIVENESS);+ s.book.voices =+ super::onboarding::setting("book_voices").and_then(|v| v.as_u64()).map_or(1, |n| n.clamp(1, 3) as u8);+ s.book.second = match super::onboarding::setting("book_second").as_ref().and_then(Value::as_str) {+ Some("women") => Role::Women,+ _ => Role::Men,+ };+ s.book.cast_mode = super::onboarding::setting("book_cast")+ .and_then(|v| serde_json::from_value(v).ok())+ .unwrap_or_default();+ let rtf = |key: &str| {+ super::onboarding::setting(key).and_then(|v| v.as_f64()).map(|v| v as f32).filter(|v| *v > 0.0)+ };+ s.book.measured_rtf = [rtf("book_rtf_best"), rtf("book_rtf_fast")];changed = true;} else if s.book.settings_dirty {s.book.settings_dirty = false;super::onboarding::save_setting("book_m4b", json!(s.book.m4b));super::onboarding::save_setting("book_read_titles", json!(s.book.read_titles));- super::onboarding::save_setting("book_keep_voice", json!(s.book.keep_voice));super::onboarding::save_setting("book_expressiveness",json!((s.book.expressiveness * 100.0).round() / 100.0),);+ super::onboarding::save_setting("book_voices", json!(s.book.voices));+ super::onboarding::save_setting("book_second", json!(s.book.second.id()));+ super::onboarding::save_setting("book_cast", json!(s.book.cast_mode.as_str()));+ for (key, v) in ["book_rtf_best", "book_rtf_fast"].iter().zip(s.book.measured_rtf) {+ if let Some(v) = v {+ super::onboarding::save_setting(key, json!((v * 1000.0).round() / 1000.0));+ }+ }}if !s.book.listed && shell::engine_ready(s) {request_list(s);@@ -1022,12 +2290,9 @@ pub fn panel(s: &AppState, p: Palette) -> El {let head =row().key("book-head").pin(None, Some(14.5), Some(22.0), None).gap(10.0).center_y().child(mode_switch(s, p));let mut c = section_panel(p, "Book").key("book-panel").grow(1.0).min_w(0.0).h_full().gap(12.0).child(head);- c = if let Some(d) = &s.book.draft {- c.child(draft_view(s, p, d))- } else if let Some(b) = &s.book.project {- c.child(project_view(s, p, b))- } else {- c.child(empty_view(s, p))+ c = match s.book.draft.as_ref() {+ Some(d) => c.child(draft_view(s, p, d)),+ None => c.child(empty_view(s, p)),};c}@@ -1103,33 +2368,58 @@ fn draft_view(s: &AppState, p: Palette, d: &Draft) -> El {let words: u32 = inc.iter().map(|c| c.words).sum();let speed = s.speak.speed.max(0.5);let audio = inc.iter().map(|c| c.est_s).sum::<f32>() / speed;- let make = audio * guess_rtf(s.speak.quality);- let totals = row()+ let measured = s.book.measured_rtf[usize::from(s.speak.quality == protocol::Quality::Fast)];+ let make = measured.map(|r| audio * r);+ let stat = |value: String, what: &str| {+ col()+ .grow(1.0)+ .min_w(0.0)+ .gap(2.0)+ .child(text(value).font(ty::TITLE).color(p.text).truncate())+ .child(text(what.to_owned()).font(ty::CAPTION).color(p.text_faint).truncate())+ };+ let stats = row()+ .w_full()+ .gap(16.0)+ .child(stat(format!("{} of {}", inc.len(), d.chapters.len()), "chapters"))+ .child(stat(group(words), "words"))+ .child(stat(format!("~{}", fmt_len(audio)), "of audio"))+ .child(match make {+ Some(m) => stat(format!("~{}", fmt_len(m)), "to make"),+ None => stat("After chapter 1".to_owned(), "time to make"),+ });+ let totals = col().key("book-totals").w_full()- .gap(8.0)- .center_y()- .flex_wrap()- .child(badge(p, &format!("{} of {} chapters", inc.len(), d.chapters.len()), Tone::Accent))- .child(badge(p, &format!("{} words", group(words)), Tone::Neutral))- .child(badge(p, &format!("about {} of audio", fmt_len(audio)), Tone::Neutral))- .child(badge(p, &format!("about {} to make", fmt_len(make)), Tone::Neutral));+ .gap(10.0)+ .px(18.0)+ .py(12.0)+ .radius(radius::CONTROL)+ .fill(p.well)+ .border(1.0, p.well_rim)+ .child(stats)+ .children(split_line(p, d));let list = col().w_full().gap(2.0).children(d.chapters.iter().enumerate().map(|(i, c)| draft_row(s, p, i, c, i + 1 == d.chapters.len())));- let block = start_blocker(s);- let voice = shell::active_voice(s).map(|v| v.name.clone()).unwrap_or_else(|| "no voice".into());- let hint = block.map(str::to_owned).unwrap_or_else(|| {+ let linked = linked(s);+ let block = read_blocker(s);+ let voice = role_voice(s, Role::Narrator).map(|v| v.name.clone()).unwrap_or_else(|| "no voice".into());+ let hint = block.clone().unwrap_or_else(|| {+ if linked.is_some() {+ return "The ticked chapters not read yet are read into the same book and folder".to_owned();+ }format!("Read by {voice} in {} · saved as {} files, one per chapter",super::lang::name(&super::speak::language(s)),super::formats::output_format(s).to_uppercase())});- let starting = s.book.start_req.is_some();- let bar =- row()+ let starting = s.book.start_req.is_some() || s.book.add_req.is_some();+ let bar = match linked.filter(|b| b.status == "running") {+ Some(b) => project_bar(s, p, b),+ None => row().key("book-bar").w_full().gap(16.0)@@ -1139,6 +2429,14 @@ fn draft_view(s: &AppState, p: Palette, d: &Draft) -> El {text(hint).font(ty::CAPTION).color(if block.is_some() { p.warn } else { p.text_faint }).wrap(),),)+ .children(has_files(s).then(|| {+ Button::new("Open folder")+ .ghost()+ .icon(&icons::FOLDER)+ .key("book-open-folder")+ .on_press(open_folder)+ .build(p)+ })).child(Button::new(if starting { "Starting…" } else { "Read the book" }).primary()@@ -1146,9 +2444,10 @@ fn draft_view(s: &AppState, p: Palette, d: &Draft) -> El {.icon(&icons::SPARKLE).key("book-start").disabled(block.is_some() || starting)- .on_press(start)+ .on_press(read_book).build(p),- );+ ),+ };let mut c = col().key("book-draft").w_full()@@ -1160,25 +2459,389 @@ fn draft_view(s: &AppState, p: Palette, d: &Draft) -> El {if let Some(w) = f.warnings.first() {c = c.child(text(w.clone()).font(ty::CAPTION).color(p.warn).wrap());}- if let Some(split) = split_line(p, d) {- c = c.child(split);+ if let Some(b) = linked.filter(|b| b.status == "running" || b.chapters_done > 0) {+ c = c.child(progress_block(s, p, b));}- c.child(chapter_scroller(p, list)).child(bar)+ c = c.child(chapter_scroller(p, Some(select_all_row(p, d)), list));+ c = c.child(cast_view(s, p));+ c.child(bar)}-fn chapter_scroller(p: Palette, list: El) -> El {- super::components::well(p).key("book-chapters").w_full().grow(1.0).min_h(120.0).padding(6.0).child(- col()- .key("book-chapters-scroll")- .w_full()- .grow(1.0)- .min_h(0.0)- .scroll(ScrollSpec { stick_bottom: false })- .scroll_edge_fade(14.0)- .child(list),+fn cast_view(s: &AppState, p: Palette) -> El {+ let b = &s.book;+ let label = |t: &str| text(t.to_owned()).font(ty::LABEL).color(p.text);+ let locked = reading_locked(s);+ let lock = |e: El| if locked { e.disabled(true).opacity(0.42) } else { e };+ let count = lock(segmented(+ p,+ "book-voices",+ &["One voice", "Two voices", "Three voices"],+ usize::from(b.voices.clamp(1, 3) - 1),+ |s, i| {+ if reading_locked(s) {+ return;+ }+ s.book.voices = i as u8 + 1;+ s.book.settings_dirty = true;+ },+ ));+ let c = col()+ .key("book-cast")+ .w_full()+ .gap(10.0)+ .child(row().key("book-voices-row").w_full().gap(12.0).center_y().child(label("Voices")).child(count));+ if b.voices < 2 {+ return c.child(roles_view(s, p));+ }+ if !super::setuprun::has(s, "cast") {+ let says = "Reading each speaker's lines in their own voice needs a language model that finds who speaks: \+ Gemma 4 12B (7.4 GB)."+ .to_owned();+ return c.child(super::setuprun::install_line_says(s, p, "cast", "Character voices", Some(says)));+ }+ let mut c = c;+ if b.voices == 2 {+ let second =+ lock(segmented(p, "book-second", &["Men", "Women"], usize::from(b.second == Role::Women), |s, i| {+ if reading_locked(s) {+ return;+ }+ s.book.second = if i == 1 { Role::Women } else { Role::Men };+ s.book.settings_dirty = true;+ }));+ c = c.child(+ row()+ .key("book-second-row")+ .w_full()+ .gap(12.0)+ .center_y()+ .child(label("The second voice reads:"))+ .child(second),+ );+ }+ let mode = lock(segmented(+ p,+ "book-accuracy",+ &["Fast", "Careful"],+ usize::from(b.cast_mode == CastMode::Careful),+ |s, i| {+ if reading_locked(s) {+ return;+ }+ s.book.cast_mode = if i == 1 { CastMode::Careful } else { CastMode::Fast };+ s.book.settings_dirty = true;+ },+ ));+ let hint = if b.cast_mode == CastMode::Careful {+ "Careful reads the book twice, so it takes about twice as long, and leaves the lines it is unsure of to the narrator."+ } else {+ "Fast reads the book once."+ };+ let mut block = col()+ .key("book-accuracy-row")+ .w_full()+ .gap(4.0)+ .child(+ row()+ .w_full()+ .gap(12.0)+ .center_y()+ .child(label("Accuracy"))+ .child(mode)+ .child(el().grow(1.0))+ .children(find_action(s, p)),+ )+ .child(text(hint).font(ty::CAPTION).color(p.text_faint).wrap());+ if let Some(status) = find_status(s, p) {+ block = block.child(status);+ }+ c.child(block).child(roles_view(s, p))+}++/// Find who speaks, or Cancel while it runs; nothing once the speakers are found.+fn find_action(s: &AppState, p: Palette) -> Option<El> {+ let c = &s.book.cast;+ if cast_running(s) {+ return Some(+ Button::new(if c.cancelling { "Cancelling…" } else { "Cancel" })+ .ghost()+ .small()+ .key("book-find-cancel")+ .disabled(c.cancelling || c.job.is_none())+ .on_press(cancel_cast)+ .build(p),+ );+ }+ if reading_locked(s) {+ return None;+ }+ if c.found.is_some() && unsearched_note(s).is_none() {+ return Some(+ Button::new("Search again")+ .ghost()+ .small()+ .icon(&icons::REFRESH)+ .key("book-find-again")+ .help("Gemma reads the ticked chapters again, even those read before")+ .disabled(!shell::engine_ready(s))+ .on_press(|s| search(s, true))+ .build(p),+ );+ }+ let none = s.book.draft.as_ref().is_none_or(|d| !d.chapters.iter().any(|c| c.include));+ Some(+ Button::new("Find who speaks")+ .secondary()+ .small()+ .icon(&icons::USER)+ .key("book-find-go")+ .disabled(none || !shell::engine_ready(s))+ .on_press(find_speakers)+ .build(p),+ )+}++fn find_status(s: &AppState, p: Palette) -> Option<El> {+ let c = &s.book.cast;+ let (line, color) = if cast_running(s) {+ (format!("Finding who speaks… {:.0}%", c.pct), p.text)+ } else {+ match (&c.found, &c.error) {+ (Some(found), _) => (cast_caption(found), p.text_dim),+ (None, Some(e)) => (e.clone(), p.warn),+ (None, None) => return None,+ }+ };+ Some(text(line).key("book-find").font(ty::CAPTION).color(color).wrap())+}++fn roles_view(s: &AppState, p: Palette) -> El {+ let found = s.book.cast.found.is_some() || s.book.voices < 2;+ let blocker = generate_blocker(s);+ let roles = std::iter::once(Role::Narrator).chain(character_roles(s.book.voices, s.book.second).iter().copied());+ let mut c = col().key("book-roles").w_full().gap(6.0);+ for role in roles {+ c = c.child(role_row(s, p, role, found && blocker.is_none()));+ }+ if reading_locked(s) {+ return c.child(+ text("Voices, accuracy and chapters stay as they are while the book is read: pause it to change them.")+ .font(ty::CAPTION)+ .color(p.text_faint)+ .wrap(),+ );+ }+ if found && let Some(why) = blocker.filter(|why| start_blocker(s).as_ref() != Some(why)) {+ c = c.child(text(why).font(ty::CAPTION).color(p.warn).wrap());+ }+ c+}++fn role_row(s: &AppState, p: Palette, role: Role, can: bool) -> El {+ let c = &s.book.cast;+ let voice = role_voice(s, role);+ let name = if sample(s, role).is_some() {+ "New voice (generated)"+ } else {+ voice.map_or("Pick a voice", |v| v.name.as_str())+ };+ let picker = dropdown_chip(+ p,+ &format!("book-role-{}", role.id()),+ &icons::USER,+ name,+ format!("{} voice: {name}", role.name()),+ !reading_locked(s),+ move |s| s.book.role_menu = Some(role),+ );+ let making = role_making(s, role);+ let busy = c.design.is_some() || !c.imports.is_empty() || !c.adopting.is_empty();+ let mut r = row()+ .key(format!("book-role-row-{}", role.id()))+ .w_full()+ .gap(10.0)+ .center_y()+ .child(text(role.name()).font(ty::LABEL).color(p.text_dim).w(80.0))+ .child(gender_pick(s, p, role))+ .child(row().grow(1.0).min_w(0.0).gap(10.0).center_y().child(picker).child(role_mismatch(p, role, voice)));+ if let Some(path) = role_audio(s, role) {+ let playing = take_playing(s, &path);+ let btn = el()+ .key(format!("book-role-play-{}", role.id()))+ .role("button")+ .label(if playing { "Pause" } else { "Play" })+ .size(28.0, 28.0)+ .radius(14.0)+ .center()+ .hover(rune::Color::WHITE.alpha(0.1))+ .focusable(true)+ .motion(motion::UI)+ .on_press(move |s: &mut AppState| {+ if !role_making(s, role) {+ play_take(s, role)+ }+ })+ .child(icon_el(if playing { &icons::PAUSE } else { &icons::PLAY }, 12.0, p.on_accent));+ let btn = accent_glass(p, btn);+ r = r.child(if making { btn.disabled(true).opacity(0.42) } else { btn });+ }+ r.child(+ Button::new(if making { "Generating…" } else { "Generate" })+ .secondary()+ .small()+ .icon(&icons::SPARKLE)+ .key(format!("book-role-gen-{}", role.id()))+ .disabled(!can || busy || !shell::engine_ready(s))+ .on_press(move |s| generate_role(s, role))+ .build(p),+ )+}++fn role_making(s: &AppState, role: Role) -> bool {+ let c = &s.book.cast;+ c.design.is_some_and(|(_, r)| r == role)+ || c.imports.iter().any(|(_, r)| *r == role)+ || c.adopting.iter().any(|(_, r)| *r == role)+}++/// Who Generate makes for the role: Auto is Gemma's choice, or else the role's default.+fn gender_pick(s: &AppState, p: Palette, role: Role) -> El {+ const GENDERS: [&str; 2] = ["male", "female"];+ let at = s+ .book+ .cast+ .genders+ .iter()+ .find(|(r, _)| *r == role)+ .and_then(|(_, g)| GENDERS.iter().position(|x| x == g))+ .map_or(0, |i| i + 1);+ let pick =+ segmented(p, &format!("book-role-gender-{}", role.id()), &["Auto", "Male", "Female"], at, move |s, i| {+ if reading_locked(s) {+ return;+ }+ s.book.cast.genders.retain(|(r, _)| *r != role);+ if i > 0 {+ s.book.cast.genders.push((role, GENDERS[i - 1].to_owned()));+ }+ });+ if reading_locked(s) { pick.disabled(true).opacity(0.42) } else { pick }+}++/// A book voice made for another role than the one it is picked for.+fn role_mismatch(p: Palette, role: Role, voice: Option<&VoiceInfo>) -> El {+ let Some(made) = voice.and_then(|v| v.book_role.as_deref()).filter(|r| *r != role.id()) else { return el() };+ let why = format!("Expected {}, got {made}", role.id());+ row()+ .key(format!("book-role-mismatch-{}", role.id()))+ .gap(6.0)+ .center_y()+ .label(why.clone())+ .help(format!("{why}: this voice was made for the {made} of its book"))+ .child(icon_el(&icons::ALERT, 14.0, p.warn))+ .child(text(why).font(ty::CAPTION).color(p.warn))+}++fn role_menu(s: &AppState, p: Palette, role: Role) -> El {+ let chosen = role_voice(s, role).map(|v| v.id.as_str());+ let mut list = col().w_full().gap(2.0);+ let (own, book) = shell::by_kind(&s.shell.voices);+ for (i, v) in own.iter().chain(&book).enumerate() {+ if i == own.len() {+ list = list.child(shell::group_heading(p, "Book voices"));+ }+ let on = chosen == Some(v.id.as_str());+ let id = v.id.clone();+ list = list.child(+ row()+ .key(format!("book-role-voice-{}", v.id))+ .role("button")+ .label(v.name.clone())+ .w_full()+ .h(38.0)+ .px(12.0)+ .gap(10.0)+ .center_y()+ .radius(19.0)+ .fill(if on { p.accent.alpha(0.14) } else { rune::Color::TRANSPARENT })+ .hover(p.glass_hover)+ .focusable(true)+ .on_press(move |s: &mut AppState| {+ set_role_voice(s, role, &id);+ s.book.role_menu = None;+ })+ .child(text(v.name.clone()).font(ty::LABEL).color(p.text).grow(1.0).truncate())+ .child(el().w(16.0).children(on.then(|| icon_el(&icons::CHECK, 14.0, p.accent)))),+ );+ }+ if s.shell.voices.is_empty() {+ list = list.child(text("No voices yet").font(ty::CAPTION).color(p.text_faint).px(12.0).py(10.0));+ }+ popover(+ p,+ "book-role-menu",+ &format!("book-role-{}", role.id()),+ 280.0,+ rune::Align::Start,+ |s: &mut AppState| s.book.role_menu = None,+ list,)}+fn chapter_scroller(p: Palette, head: Option<El>, list: El) -> El {+ let scroll = col()+ .key("book-chapters-scroll")+ .w_full()+ .grow(1.0)+ .min_h(0.0)+ .scroll(ScrollSpec { stick_bottom: false })+ .scroll_edge_fade(14.0)+ .child(list);+ super::components::well(p)+ .key("book-chapters")+ .w_full()+ .grow(1.0)+ .min_h(120.0)+ .padding(6.0)+ .child(col().w_full().grow(1.0).min_h(0.0).gap(4.0).children(head).child(scroll))+}++fn toggle_all(s: &mut AppState) {+ if reading_locked(s) {+ return;+ }+ if let Some(d) = s.book.draft.as_mut() {+ let all = d.chapters.iter().all(|c| c.include);+ for c in &mut d.chapters {+ c.include = !all;+ }+ }+}++fn select_all_row(p: Palette, d: &Draft) -> El {+ let all = d.chapters.iter().all(|c| c.include);+ let n = d.chapters.iter().filter(|c| c.include).count();+ row()+ .key("book-select-all")+ .w_full()+ .min_h(36.0)+ .px(8.0)+ .gap(10.0)+ .center_y()+ .border_sides([0.0, 0.0, 1.0, 0.0], p.well_rim)+ .child(check_box(p, "book-inc-all".into(), all, toggle_all))+ .child(+ text(if all { "Deselect all" } else { "Select all" })+ .key("book-select-all-label")+ .font(ty::LABEL)+ .color(p.text_dim)+ .role("button")+ .on_press(toggle_all),+ )+ .child(el().grow(1.0))+ .child(text(format!("{n} of {} selected", d.chapters.len())).font(ty::CAPTION).color(p.text_faint))+}+fn check_box(p: Palette, key: String, on: bool, on_press: impl Fn(&mut AppState) + 'static) -> El {let b = el().key(key)@@ -1233,15 +2896,45 @@ fn draft_row(s: &AppState, p: Palette, i: usize, c: &DraftChapter, last: bool) -.child(check_box(p, format!("book-inc{i}"), c.include, move |s| toggle_include(s, i))).child(text(format!("{}", i + 1)).font(ty::NUM).color(p.text_faint).w(26.0)).child(el().grow(1.0).min_w(0.0).child(title))- .child(text(meta).font(ty::CAPTION).color(p.text_faint));+ .child(+ text(meta)+ .font(ty::CAPTION)+ .color(p.text_faint)+ .help("Words, and about how long this chapter's audio will be"),+ );+ if s.book.voices > 1 {+ let speechless = s.book.cast.speechless.contains(&chapter_fingerprint(c));+ r = r.child(if chapter_searched(s, c) {+ let (help, color) = if speechless {+ ("No dialogue: the narrator reads it all, so it needs no search", p.warn)+ } else {+ ("Speakers found: Gemma has read this chapter, so it needs no new search", p.accent)+ };+ el().key(format!("book-searched{i}")).size(28.0, 28.0).center().label(help).help(help).child(icon_el(+ &icons::BRAIN,+ 15.0,+ color,+ ))+ } else {+ el()+ });+ }+ if let Some((b, row)) = book_row(s, c) {+ return read_cells(s, p, r, b, row, c.include);+ }r = r.child(small_icon(p, format!("book-split{i}"), &SPLIT, "Split this chapter in two", move |s| split(s, i)));- r = r.child(if last {- el().size(28.0, 28.0)- } else {- small_icon(p, format!("book-merge{i}"), &MERGE, "Join the next chapter into this one", move |s| {+ if !last {+ r = r.child(small_icon(p, format!("book-merge{i}"), &MERGE, "Join the next chapter into this one", move |s| {merge_next(s, i)- })- });+ }));+ }+ r = r.child(small_icon(+ p,+ format!("book-remove{i}"),+ &icons::TRASH,+ "Remove this chapter from the book",+ move |s| remove_chapter(s, i),+ ));if !c.include {r = r.opacity(0.7);}@@ -1281,37 +2974,17 @@ fn status_word(b: &BookSummary) -> (&'static str, Tone) {}}-fn project_view(s: &AppState, p: Palette, b: &BookSummary) -> El {- let (word, tone) = status_word(b);- let mut sub = Vec::new();- if let Some(f) = b.format.as_ref().filter(|f| !f.is_empty()) {- sub.push(f.to_uppercase());- }- sub.push(format!("{} chapters", b.chapters));- if let Some(l) = b.language.as_ref().filter(|l| !l.is_empty()) {- sub.push(super::lang::name(l).to_string());- }- if b.words > 0 {- sub.push(format!("{} words", group(b.words)));- }+fn progress_block(s: &AppState, p: Palette, b: &BookSummary) -> El {let running = b.status == "running";- let right = row()- .gap(8.0)- .center_y()- .child(badge(p, word, tone))- .children(- b.folder- .is_some()- .then(|| icon_button(p, "book-folder", &icons::FOLDER, "Open the book's folder", open_folder)),- )- .children((!running).then(|| {- icon_button(p, "book-close", &icons::CLOSE, "Close this book (it stays in the list on the right)", close)- }));let t = &b.totals;let k = (b.current + 1).min(b.chapters.max(1));let label = match b.status.as_str() {+ "running" if s.book.cast_stage.is_some() => {+ format!("Finding who speaks… {:.0}%", s.book.cast_stage.unwrap_or(0.0))+ }"running" if s.book.m4b_making => format!("Making the M4B… {:.0}%", s.book.m4b_progress.0),"running" => format!("Chapter {k} of {} · {:.0}%", b.chapters, t.percent),+ "done" if b.chapters == 1 => "The chapter is read".to_owned(),"done" => format!("All {} chapters read", b.chapters),_ => format!("{} of {} chapters done · {:.0}%", b.chapters_done, b.chapters, t.percent),};@@ -1338,7 +3011,7 @@ fn project_view(s: &AppState, p: Palette, b: &BookSummary) -> El {if b.status == "done" && t.elapsed_s > 0.0 {facts.push(format!("made in {}", fmt_len(t.elapsed_s)));}- let progress = col()+ col().key("book-progress").w_full().gap(8.0)@@ -1353,113 +3026,14 @@ fn project_view(s: &AppState, p: Palette, b: &BookSummary) -> El {).child(progress_bar(p,- Some(if making {+ Some(if let Some(pct) = s.book.cast_stage.filter(|_| running) {+ pct / 100.0+ } else if making {s.book.m4b_progress.0 / 100.0} else {(t.percent / 100.0).max(if running { 0.01 } else { 0.0 })}),- ));- let list = col().w_full().gap(2.0).children(b.chapter_list.iter().map(|c| project_row(s, p, b, c)));- let mut c = col()- .key("book-project")- .w_full()- .grow(1.0)- .min_h(0.0)- .gap(12.0)- .child(file_card(p, &b.title, sub.join(" · "), right))- .child(progress);- if let Some(e) = b.error.as_ref().filter(|_| b.status == "error") {- c = c.child(- text(format!("Stopped: {}. Resume tries again from the same place.", e.message))- .font(ty::CAPTION)- .color(p.bad)- .wrap(),- );- }- if b.interrupted && b.status == "paused" {- c = c.child(- text("The app closed while this book was being read. Resume continues where it stopped.")- .font(ty::CAPTION)- .color(p.text_dim)- .wrap(),- );- }- c.child(chapter_scroller(p, list)).child(project_bar(s, p, b))-}--fn project_row(s: &AppState, p: Palette, b: &BookSummary, c: &BookChapterRow) -> El {- let idx = c.index;- let running = b.status == "running";- let (mark, meta): (El, String) = match c.status.as_str() {- "done" => (icon_el(&icons::CHECK, 14.0, p.ok), {- let mut m = fmt_len(c.audio_s);- if let Some(r) = c.rtf.filter(|r| *r > 0.0) {- m.push_str(&format!(" · made in {}", fmt_len(r * c.audio_s)));- }- m- }),- "partial" if running => (- status_dot(p, Tone::Accent, true),- if c.segments > 0 {- format!("part {} of {}", c.segment.min(c.segments), c.segments)- } else {- "starting…".into()- },- ),- "partial" => (- icon_el(&icons::PAUSE, 13.0, p.warn),- format!("stopped at part {} of {}", c.segment, c.segments.max(c.segment)),- ),- _ => (- el().size(10.0, 10.0).radius(5.0).border(1.0, p.text_faint),- if c.words > 0 { format!("{} words", group(c.words)) } else { String::new() },- ),- };- let on = c.status == "partial" && running;- let mut r = row()- .key(format!("book-row{idx}"))- .w_full()- .min_h(40.0)- .px(8.0)- .gap(10.0)- .center_y()- .radius(radius::CONTROL)- .fill(if on { p.accent.alpha(0.08) } else { rune::Color::TRANSPARENT })- .child(el().w(20.0).center().child(mark))- .child(text(format!("{}", idx + 1)).font(ty::NUM).color(p.text_faint).w(26.0))- .child(- text(c.title.clone())- .font(ty::LABEL)- .color(if c.status == "waiting" { p.text_dim } else { p.text })- .truncate()- .grow(1.0)- .min_w(0.0),- )- .child(text(meta).font(ty::CAPTION).color(p.text_faint));- if c.status == "done" && !running && s.book.reread_req.is_none() {- r = r.child(small_icon(p, format!("book-redo{idx}"), &icons::REFRESH, "Read this chapter again", move |s| {- reread(s, None, Some(vec![idx]))- }));- }- if c.status == "done" {- let playing = chapter_playing(s, idx);- let btn = el()- .key(format!("book-play{idx}"))- .role("button")- .label(if playing { "Pause" } else { "Play" })- .size(28.0, 28.0)- .radius(14.0)- .center()- .hover(rune::Color::WHITE.alpha(0.1))- .focusable(true)- .motion(motion::UI)- .on_press(move |s: &mut AppState| play_chapter(s, idx))- .child(icon_el(if playing { &icons::PAUSE } else { &icons::PLAY }, 12.0, p.on_accent));- r = r.child(accent_glass(p, btn));- } else {- r = r.child(el().size(28.0, 28.0));- }- r+ ))}fn project_bar(s: &AppState, p: Palette, b: &BookSummary) -> El {@@ -1469,6 +3043,10 @@ fn project_bar(s: &AppState, p: Palette, b: &BookSummary) -> El {"Waiting for free memory…".to_owned(),format!("The computer ran short of memory. Reading goes on from the same sentence in {}; closing other programs helps.", fmt_len(s.book.memory_wait.unwrap_or(0.0))),),+ "running" if s.book.stopping.is_none() && s.book.cast_stage.is_some() => (+ "Finding who speaks…".to_owned(),+ "Each line's speaker is found before the first chapter is read in its voice.".to_owned(),+ ),"running" if s.book.stopping.is_none() && s.book.m4b_making => ("Making the M4B…".to_owned(),"Every chapter is read and its file is in the book's folder. Now all of them are joined into one audiobook file with chapter marks.".to_owned(),@@ -1574,14 +3152,19 @@ fn project_bar(s: &AppState, p: Palette, b: &BookSummary) -> El {}pub fn voice_overlay(s: &AppState, p: Palette) -> Option<El> {+ if let Some(role) = s.book.role_menu.filter(|_| s.book.draft.is_some()) {+ return Some(role_menu(s, p, role));+ }let pick = s.book.voice_menu.as_ref()?;let b = s.book.project.as_ref()?;let name = |id: &str| super::voices::voice_name(s, id).unwrap_or(id).to_owned();+ let roles = book_roles(b);+ let role = if roles.contains(&s.book.voice_role) { s.book.voice_role } else { Role::Narrator };let body = match pick {None => {let mut list = col().w_full().gap(2.0);for v in &s.shell.voices {- let current = b.voice_id.as_deref() == Some(v.id.as_str());+ let current = book_role_voice(b, role) == Some(v.id.as_str());let id = v.id.clone();let mut r = row().key(format!("book-voice-{}", v.id))@@ -1609,14 +3192,27 @@ pub fn voice_overlay(s: &AppState, p: Palette) -> Option<El> {}list = list.child(r);}+ let names: Vec<&str> = roles.iter().map(|r| r.name()).collect();+ let at = roles.iter().position(|r| *r == role).unwrap_or(0);+ let tabs = (roles.len() > 1).then(|| {+ let roles = roles.clone();+ segmented(p, "book-voice-role", &names, at, move |s, i| s.book.voice_role = roles[i])+ });+ let head = match role {+ Role::Narrator => "Read this book with",+ Role::Men => "Read men's lines with",+ Role::Women => "Read women's lines with",+ };col().w_full().gap(6.0)- .child(text("Read this book with").font(ty::LABEL).color(p.text).px(12.0).pt(4.0))+ .children(tabs.map(|t| el().px(6.0).pt(4.0).child(t)))+ .child(text(head).font(ty::LABEL).color(p.text).px(12.0).pt(4.0)).child(list)}Some(id) => {- let (new, old) = (name(id), b.voice_id.as_deref().map(name).unwrap_or_else(|| "another voice".to_owned()));+ let (new, old) =+ (name(id), book_role_voice(b, role).map(name).unwrap_or_else(|| "another voice".to_owned()));let (all, keep) = (id.clone(), id.clone());col().w_full()@@ -1680,83 +3276,66 @@ pub fn side_panel(s: &AppState, p: Palette, own_scroll: bool) -> El {.gap(8.0).center_y().child(super::formats::output_chip(s, p, "book-outfmt"));- let m4b = kit::checkbox(&p, s.book.m4b, "Also make one M4B audiobook with chapter marks", |s| {+ let m4b = kit::checkbox(&p, s.book.m4b, "Also make an M4B audiobook", |s| {s.book.m4b = !s.book.m4b;s.book.settings_dirty = true;+ send_settings(s);});- let titles = kit::checkbox(&p, s.book.read_titles, "Read each chapter's title first", |s| {+ let titles = kit::checkbox(&p, s.book.read_titles, "Read chapter titles", |s| {s.book.read_titles = !s.book.read_titles;s.book.settings_dirty = true;});// Keyed slots: both checkboxes have the same own key. The inset keeps the scroll area's clip off their border.- let mut opts = col()+ let opts = col().key("book-opts").w_full().pl(2.0).gap(10.0)- .child(el().key("book-opt-m4b").w_full().child(m4b))- .child(el().key("book-opt-titles").w_full().child(titles));- if super::speak::language(s) == "uk" && super::setuprun::has(s, "ukrainian") && s.speak.exact_stress {- let keep = kit::checkbox(&p, s.book.keep_voice, "Closer voice with exact stress (about 4× slower)", |s| {- s.book.keep_voice = !s.book.keep_voice;- s.book.settings_dirty = true;- });- opts = opts.child(col().key("book-opt-keep-voice").w_full().gap(4.0).child(keep)- .child(text(if s.book.keep_voice {- "Each part is passed through the voice converter, so it sounds more like the voice."- } else {- "Recommended for books: Ukrainian with exact stress at about 20× real time; the voice sounds less like the original."- }).font(ty::CAPTION).color(p.text_faint).wrap().pl(34.0)));- }+ .child(el().key("book-opt-m4b").w_full().help("One file with chapter marks, for audiobook players").child(m4b))+ .child(+ el().key("book-opt-titles").w_full().help("Each chapter starts with its title read aloud").child(titles),+ );let mut list = col().w_full().gap(6.0);- let shown = s.book.project.as_ref().map(|b| b.id.as_str());- let mut books: Vec<&BookSummary> =- s.book.recent.iter().map(|b| s.book.project.as_ref().filter(|p| p.id == b.id).unwrap_or(b)).collect();- books.sort_by_key(|b| !of_active_voice(s, b));- for b in books.iter().copied().take(12) {- let id = b.id.clone();- let id2 = b.id.clone();- let (word, tone) = status_word(b);- let on = shown == Some(b.id.as_str());- let mut detail = format!("{} of {} chapters · {}", b.chapters_done, b.chapters, fmt_len(b.totals.audio_s));- if let Some(voice) = voice_label(s, b) {- detail = format!("{voice} · {detail}");- }- let mut card =- row()- .key(format!("book-recent-{}", b.id))- .w_full()- .px(10.0)- .py(8.0)- .gap(8.0)- .center_y()- .radius(radius::CONTROL)- .fill(if on { p.accent.alpha(0.12) } else { p.glass_hover.alpha(0.0) })- .hover(p.glass_hover)- .focusable(true)- .on_press(move |s: &mut AppState| open_book(s, &id))- .child(- col()- .grow(1.0)- .min_w(0.0)- .gap(2.0)- .child(text(b.title.clone()).font(ty::LABEL).color(p.text).truncate())- .child(row().gap(6.0).center_y().child(status_dot(p, tone, b.status == "running")).child(- text(format!("{word} · {detail}")).font(ty::CAPTION).color(p.text_faint).truncate(),- )),- );- if b.status != "running" {+ let entries = book_entries(s);+ for e in &entries {+ let (path, book) = (e.path.clone(), e.book.clone());+ let (path2, book2) = (e.path.clone(), e.book.clone());+ let mut card = row()+ .key(format!("book-recent-{}", e.key))+ .w_full()+ .px(10.0)+ .py(8.0)+ .gap(8.0)+ .center_y()+ .radius(radius::CONTROL)+ .fill(if e.current { p.accent.alpha(0.12) } else { p.glass_hover.alpha(0.0) })+ .hover(p.glass_hover)+ .focusable(true)+ .role("button")+ .label(format!("Open {}", e.title))+ .on_press(move |s: &mut AppState| open_entry(s, path.clone(), book.clone()))+ .child(+ col()+ .grow(1.0)+ .min_w(0.0)+ .gap(2.0)+ .child(text(e.title.clone()).font(ty::LABEL).color(p.text).truncate())+ .child(row().gap(6.0).center_y().child(status_dot(p, e.tone, e.pulse)).child(+ text(format!("{} · {}", e.word, e.detail)).font(ty::CAPTION).color(p.text_faint).truncate(),+ )),+ );+ if !e.pulse {card = card.child(small_icon(p,- format!("book-forget-{}", b.id),+ format!("book-forget-{}", e.key),&icons::TRASH,"Remove from the list (the audio files stay)",- move |s| forget_book(s, &id2),+ move |s| remove_entry(s, path2.clone(), book2.clone()),));}list = list.child(card);}- let books = if books.is_empty() {+ let books = if entries.is_empty() {col().key("book-recent-empty").w_full().child(text("Books you read appear here, so you can come back to them.").font(ty::CAPTION)@@ -1841,7 +3420,13 @@ fn scene_file() -> TextImport {}fn scene_project(s: &mut AppState, status: &str, done: usize, seg: (u32, u32)) {- scene_base(s);+ scene_imported(s);+ for (i, c) in s.book.draft.as_mut().expect("draft").chapters.iter_mut().enumerate() {+ c.text = format!("Chapter {i}.");+ c.include = true;+ }+ s.book.book_keys = (0..CHAPTERS.len()).map(|i| text_key(&format!("Chapter {i}."))).collect();+ s.book.draft.as_mut().expect("draft").book_id = Some("under-the-old-lime-tree-20261113-101500".into());let rows = CHAPTERS.iter().enumerate()@@ -1928,7 +3513,7 @@ pub fn scene_imported(s: &mut AppState) {include: i > 0,}).collect();- s.book.draft = Some(Draft { file: scene_file(), chapters, auto: None, before_split: None });+ s.book.draft = Some(Draft { file: scene_file(), chapters, auto: None, before_split: None, book_id: None });s.book.recent = vec![BookSummary {id: "kobzar-20261101-090000".into(),title: "Кобзар".into(),@@ -1970,6 +3555,7 @@ pub fn scene_autosplit_offer(s: &mut AppState) {chapters: vec![one("Тіні забутих предків", 15796)],auto: Some(("length".into(), parts)),before_split: None,+ book_id: None,});}@@ -2021,12 +3607,78 @@ pub fn scene_finished(s: &mut AppState) {);}+pub fn scene_voice_roles(s: &mut AppState) {+ scene_project(s, "done", CHAPTERS.len(), (0, 0));+ let first = s.shell.voices.first().map(|v| v.id.clone());+ if let Some(b) = s.book.project.as_mut() {+ b.voices = Some([("men".to_owned(), first.clone()), ("women".to_owned(), first)].into_iter().collect());+ }+ s.book.voice_role = Role::Men;+ s.book.voice_menu = Some(None);+}++pub fn scene_linked(s: &mut AppState) {+ scene_imported(s);+ for (i, c) in s.book.draft.as_mut().unwrap().chapters.iter_mut().enumerate() {+ c.text = format!("Chapter {i}.");+ }+ s.book.draft.as_mut().unwrap().book_id = Some("moby".into());+ s.book.book_keys = (1..4).map(|i| text_key(&format!("Chapter {i}."))).collect();+ let row = |i: u32, status: &str| BookChapterRow {+ index: i,+ title: CHAPTERS[i as usize + 1].0.into(),+ status: status.into(),+ audio_s: 900.0,+ segment: 12,+ segments: 40,+ ..Default::default()+ };+ s.book.project = Some(BookSummary {+ id: "moby".into(),+ title: "Moby-Dick".into(),+ status: "running".into(),+ folder: Some(PathBuf::from("/tmp/books/Moby-Dick")),+ chapters: 3,+ chapters_done: 1,+ chapter_list: vec![row(0, "done"), row(1, "partial"), row(2, "waiting")],+ totals: protocol::BookTotals { audio_s: 900.0, percent: 45.0, ..Default::default() },+ ..Default::default()+ });+}+pub fn scene_empty(s: &mut AppState) {scene_base(s);}+pub fn scene_three_voices(s: &mut AppState) {+ scene_imported(s);+ s.shell.components = None;+ s.book.voices = 3;+ s.book.cast_mode = CastMode::Careful;+}++pub fn scene_cast_found(s: &mut AppState) {+ scene_three_voices(s);+ let who = |name: &str, gender: &str, lines: u32| crate::engine::protocol::CastCharacter {+ name: name.into(),+ gender: gender.into(),+ lines,+ };+ if let Some(d) = s.book.draft.as_ref() {+ s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();+ }+ s.book.cast.found = Some(BookCast {+ key: "k".into(),+ characters: vec![who("Martin Eden", "m", 1312), who("Ruth", "f", 256), who("Arthur", "m", 90)],+ lines: Some(crate::engine::protocol::CastLines { men: 1402, women: 268, narrator: 40 }),+ ..Default::default()+ });+}+pub fn scenes() -> &'static [super::Scene] {&[+ ("book_three_voices", scene_three_voices),+ ("book_cast_found", scene_cast_found),("book_autosplit_offer", scene_autosplit_offer),("book_autosplit_done", scene_autosplit_done),("book_empty", scene_empty),@@ -2038,6 +3690,8 @@ pub fn scenes() -> &'static [super::Scene] {("book_paused", scene_paused),("book_interrupted", scene_interrupted),("book_finished", scene_finished),+ ("book_linked", scene_linked),+ ("book_voice_roles", scene_voice_roles),]}@@ -2060,6 +3714,7 @@ mod draft_tests {chapters: vec![one("Частина 1", "Іван був"), one("Частина 2", "дев'ятнадцятою дитиною")],auto: Some(("length".into(), vec![one("1", "a")])),before_split: Some(vec![one("Тіні", "Іван був дев'ятнадцятою")]),+ book_id: None,}}@@ -2160,13 +3815,6 @@ mod voice_tests {s}- #[test]- fn every_book_is_listed_with_its_voice() {- let s = state();- let labels: Vec<Option<String>> = s.book.recent.iter().map(|b| voice_label(&s, b)).collect();- assert_eq!(labels, [Some("TARAS".into()), Some("SAGE".into()), Some("voice deleted".into())]);- }-#[test]fn the_active_voices_unfinished_book_opens_first() {let mut s = state();@@ -2175,3 +3823,384 @@ mod voice_tests {assert_eq!(unfinished_of_voice(&s).as_deref(), Some("a"));}}++#[cfg(test)]+mod cast_tests {+ use super::*;+ use crate::engine::protocol::{CastCharacter, CastLines};++ fn found() -> BookCast {+ let who =+ |name: &str, gender: &str, lines: u32| CastCharacter { name: name.into(), gender: gender.into(), lines };+ BookCast {+ key: "k".into(),+ characters: vec![+ who("Ruth", "f", 256),+ who("Martin Eden", "m", 1312),+ who("Arthur", "m", 90),+ who("Mrs. Morse", "f", 12),+ ],+ lines: Some(CastLines { men: 1402, women: 268, narrator: 40 }),+ ..Default::default()+ }+ }++ fn state(voices: u8, second: Role) -> AppState {+ let mut s = AppState::default();+ scene_imported(&mut s);+ s.book.voices = voices;+ s.book.second = second;+ s+ }++ fn take_found(s: &mut AppState) {+ let d = s.book.draft.as_ref().unwrap();+ s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();+ s.book.cast.found = Some(BookCast { mode: s.book.cast_mode.as_str().into(), ..found() });+ }++ #[test]+ fn a_noise_take_is_not_kept_as_a_voice() {+ let mut s = state(3, Role::Men);+ take_found(&mut s);+ let noise = json!({"clear": false, "path": "/t/a.wav", "reference": "/t/voice.wav", "language": "en"});+ for tries in 1..=UNCLEAR_TRIES {+ s.book.cast.design = Some((7, Role::Men));+ on_response(&mut s, 7, &Ok(noise.clone()));+ assert_eq!(s.book.cast.unclear, tries);+ }+ assert!(s.book.cast.samples.is_empty());+ }++ #[test]+ fn a_generated_sample_becomes_a_voice_only_when_the_book_starts() {+ let mut s = state(3, Role::Men);+ s.shell.components = None;+ take_found(&mut s);+ let take = json!({"clear": true, "path": "/t/a.wav", "reference": "/t/voice.wav", "language": "uk"});+ for _ in 0..2 {+ s.book.cast.design = Some((7, Role::Men));+ on_response(&mut s, 7, &Ok(take.clone()));+ }+ assert_eq!(s.book.cast.samples.len(), 1, "a new sample replaces the old one");+ assert!(role_ready(&s, Role::Men));+ s.book.cast.women = Some("pro".into());+ let voices = s.shell.voices.len();+ assert_eq!(start_blocker(&s), None);+ assert_eq!(s.shell.voices.len(), voices, "nothing is made before the book starts");+ s.book.cast.imports.push((9, Role::Men));+ let made = json!({"voice": {"id": "book-men", "name": "Book · men", "language": "uk", "book": "Book", "book_role": "men"}});+ on_response(&mut s, 9, &Ok(made));+ assert_eq!(s.book.cast.men.as_deref(), Some("book-men"));+ assert!(s.book.cast.samples.is_empty() && s.book.cast.imports.is_empty());+ }++ #[test]+ fn the_speakers_and_picked_voices_come_back_after_a_restart() {+ let mut s = state(3, Role::Men);+ take_found(&mut s);+ s.book.cast.women = Some("pro".into());+ s.book.cast.samples.push((Role::Men, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));+ s.book.shown = true;+ let saved = Saved { draft: s.book.draft.clone().unwrap(), cast: saved_now(&s), shown: true };+ let bytes = serde_json::to_vec(&saved).unwrap();+ let back: Saved = serde_json::from_slice(&bytes).unwrap();+ let mut t = state(3, Role::Men);+ restore_cast(&mut t.book.cast, back.cast);+ assert!(back.shown);+ assert_eq!(saved_now(&t), saved_now(&s));+ assert!(!drop_stale_cast(&mut t), "the speakers found stay with the same chapters");+ let old = serde_json::to_vec(&s.book.draft).unwrap();+ assert!(serde_json::from_slice::<Saved>(&old).is_ok(), "a draft saved before still opens");+ }++ #[test]+ fn every_role_with_a_voice_can_be_heard() {+ let mut s = state(3, Role::Men);+ assert_eq!(role_audio(&s, Role::Women), None);+ s.book.cast.women = Some(s.shell.voices[0].id.clone());+ assert!(role_audio(&s, Role::Women).is_some_and(|p| p.ends_with("reference.wav")));+ s.book.cast.samples.push((Role::Women, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));+ assert_eq!(role_audio(&s, Role::Women), Some(PathBuf::from("/t/a.wav")));+ }++ #[test]+ fn the_engines_answer_marks_the_chapters_searched() {+ let mut s = state(3, Role::Men);+ for (i, c) in s.book.draft.as_mut().unwrap().chapters.iter_mut().enumerate() {+ c.text = format!("Chapter {i} text.");+ }+ let n = s.book.draft.as_ref().unwrap().chapters.len();+ s.book.cast.status_req = Some(5);+ s.book.cast.status_for = status_key(&s);+ assert!(!status_known(&s), "not before the answer");+ let answer: Vec<bool> = (0..n).map(|i| i == 1 || i == 2).collect();+ on_response(&mut s, 5, &Ok(json!({ "searched": answer })));+ assert!(status_known(&s));+ let d = s.book.draft.as_ref().unwrap();+ assert!(chapter_searched(&s, &d.chapters[1]) && chapter_searched(&s, &d.chapters[2]));+ assert!(!chapter_searched(&s, &d.chapters[3]));+ let picked = d.chapters.iter().filter(|c| c.include).count();+ let todo = d.chapters.iter().filter(|c| c.include && !chapter_searched(&s, c)).count();+ assert_eq!(+ unsearched_note(&s),+ Some(format!(+ "{todo} of {picked} chapters are not analysed yet: press Find who speaks to analyse only them."+ ))+ );+ s.book.cast_mode = CastMode::Fast;+ s.book.cast_mode = CastMode::Careful;+ assert!(!status_known(&s), "another mode asks the engine again");+ assert_eq!(unsearched_note(&s), None, "nothing is claimed while unknown");+ }++ #[test]+ fn a_book_read_with_several_voices_changes_each() {+ let mut b = BookSummary { voice_id: Some("n".into()), ..Default::default() };+ assert_eq!(book_roles(&b), vec![Role::Narrator]);+ b.voices = Some([("men".to_owned(), Some("m".to_owned())), ("women".to_owned(), None)].into_iter().collect());+ assert_eq!(book_roles(&b), vec![Role::Narrator, Role::Men]);+ assert_eq!(book_role_voice(&b, Role::Men), Some("m"));+ }++ #[test]+ fn chapters_searched_before_bring_their_speakers_back_by_themselves() {+ let mut s = state(3, Role::Men);+ s.shell.components = None;+ let d = s.book.draft.as_ref().unwrap();+ s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();+ s.book.cast.status_for = status_key(&s);+ assert!(fetch_kept_cast(&s), "book.cast is asked, and answers from what the engine kept");+ s.book.cast.error = Some("busy".into());+ s.book.cast.asked_key = included_key(&s);+ assert!(!fetch_kept_cast(&s), "not again after an error for the same chapters");+ toggle_include(&mut s, 1);+ assert!(drop_stale_cast(&mut s), "the error goes with other chapters picked");+ assert!(fetch_kept_cast(&s));+ }++ #[test]+ fn the_list_shows_one_line_per_book_and_the_draft_of_each() {+ let mut s = state(3, Role::Men);+ let path = s.book.draft.as_ref().unwrap().file.path.clone();+ s.book.recent[0].source = Some(path.to_string_lossy().into_owned());+ s.book.draft.as_mut().unwrap().book_id = Some(s.book.recent[0].id.clone());+ let entries = book_entries(&s);+ assert_eq!(+ entries.iter().filter(|e| e.path.as_ref() == Some(&path)).count(),+ 1,+ "the book and its draft are one line"+ );+ assert!(entries.iter().any(|e| e.current));+ s.book.drafts.push((PathBuf::from("/books/other.epub"), "Other".into()));+ assert!(book_entries(&s).iter().any(|e| e.title == "Other" && e.word == "Draft" && !e.current));+ close(&mut s);+ assert!(s.book.draft.is_none());+ assert!(book_entries(&s).iter().any(|e| e.path.as_ref() == Some(&path)), "a closed draft stays in the list");+ }++ #[test]+ fn the_draft_reads_more_chapters_into_its_book() {+ let mut s = AppState::default();+ scene_linked(&mut s);+ let fresh: Vec<usize> = new_chapters(&s).iter().map(|(i, _)| *i).collect();+ assert_eq!(fresh, vec![4, 5, 6, 7, 8], "ticked chapters the book lacks, by their place");+ let d = s.book.draft.as_ref().unwrap();+ assert_eq!(book_row(&s, &d.chapters[1]).map(|(_, r)| r.status.as_str()), Some("done"));+ assert!(book_row(&s, &d.chapters[4]).is_none());+ assert_eq!(read_blocker(&s), None, "a running book shows its own bar");+ s.book.project.as_mut().unwrap().status = "done".into();+ for c in s.book.draft.as_mut().unwrap().chapters.iter_mut() {+ c.include = c.text == "Chapter 1.";+ }+ assert_eq!(read_blocker(&s).as_deref(), Some("The ticked chapters are read: ↻ beside one reads it again."));+ }++ #[test]+ fn a_file_read_before_goes_on_in_its_book() {+ let mut s = state(1, Role::Men);+ let path = s.book.draft.as_ref().unwrap().file.path.to_str().unwrap().to_owned();+ s.book.recent[0].source = Some(path);+ let id = s.book.recent[0].id.clone();+ assert_eq!(same_file_book(&s), Some(id.clone()));+ s.book.draft.as_mut().unwrap().book_id = Some(id);+ assert_eq!(same_file_book(&s), None);+ let before = s.book.draft.as_ref().unwrap().chapters.len();+ remove_chapter(&mut s, 0);+ assert_eq!(s.book.draft.as_ref().unwrap().chapters.len(), before - 1);+ close(&mut s);+ assert!(s.book.draft.is_none());+ }++ #[test]+ fn picking_a_voice_drops_the_roles_sample() {+ let mut s = state(3, Role::Men);+ s.book.cast.samples.push((Role::Women, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));+ set_role_voice(&mut s, Role::Women, "pro");+ assert!(sample(&s, Role::Women).is_none());+ assert_eq!(s.book.cast.women.as_deref(), Some("pro"));+ }++ #[test]+ fn the_book_keeps_its_language_and_narrator() {+ let mut s = state(3, Role::Men);+ let first = s.shell.voices[0].id.clone();+ s.shell.active_voice = None;+ s.book.draft.as_mut().unwrap().file.language = "uk".into();+ assert_eq!(book_language(&s), "uk");+ s.shell.languages = ["en", "uk"]+ .iter()+ .map(|c| crate::engine::protocol::SpeechLanguage {+ code: (*c).into(),+ name: String::new(),+ native: String::new(),+ common: true,+ })+ .collect();+ let active = s.shell.active_voice.clone();+ set_role_voice(&mut s, Role::Narrator, &first);+ assert_eq!(s.shell.active_voice, active, "the book's narrator leaves the voice at the top alone");+ assert_eq!(role_voice(&s, Role::Narrator).map(|v| v.id.as_str()), Some(first.as_str()));+ assert_eq!(book_language(&s), "uk");+ }++ #[test]+ fn one_box_selects_or_clears_every_chapter() {+ let mut s = state(1, Role::Men);+ toggle_all(&mut s);+ assert!(s.book.draft.as_ref().unwrap().chapters.iter().all(|c| c.include));+ toggle_all(&mut s);+ assert!(s.book.draft.as_ref().unwrap().chapters.iter().all(|c| !c.include));+ }++ #[test]+ fn one_voice_reads_as_before() {+ let mut s = state(1, Role::Men);+ s.shell.components = Some(Vec::new());+ assert_eq!(start_blocker(&s), None);+ assert_eq!((cast_voice(&s, Role::Men), cast_voice(&s, Role::Women)), (None, None));+ }++ #[test]+ fn character_voices_need_the_component() {+ let mut s = state(3, Role::Men);+ s.shell.components = Some(vec!["speech".into()]);+ assert_eq!(start_blocker(&s).as_deref(), Some("Install Character voices first."));+ }++ #[test]+ fn two_voices_need_the_speakers_and_the_second_voice() {+ let mut s = state(2, Role::Women);+ assert_eq!(start_blocker(&s).as_deref(), Some("Find who speaks first."));+ take_found(&mut s);+ assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the women's lines."));+ s.book.cast.men = Some("pro".into());+ assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the women's lines."));+ s.book.cast.women = Some("pro".into());+ assert_eq!(start_blocker(&s), None);+ assert_eq!((cast_voice(&s, Role::Men), cast_voice(&s, Role::Women)), (None, Some("pro")));+ }++ #[test]+ fn three_voices_need_both_voices_and_no_running_search() {+ let mut s = state(3, Role::Women);+ take_found(&mut s);+ s.book.cast.women = Some("pro".into());+ assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the men's lines."));+ s.book.cast.men = Some("deleted".into());+ assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the men's lines."));+ s.book.cast.men = Some("me".into());+ assert_eq!(start_blocker(&s), None);+ s.book.cast.job = Some("k".into());+ assert_eq!(start_blocker(&s).as_deref(), Some("Wait for finding who speaks to finish, or cancel it."));+ }++ #[test]+ fn the_summary_names_the_main_characters() {+ assert_eq!(+ cast_caption(&found()),+ "Men: 1,402 lines · Women: 268 lines · Narrator: 40 · Martin Eden, Ruth, Arthur, …"+ );+ let few = BookCast { characters: found().characters[..1].to_vec(), lines: None, ..Default::default() };+ assert_eq!(cast_caption(&few), "Men: 0 lines · Women: 0 lines · Narrator: 0 · Ruth");+ }++ #[test]+ fn a_result_goes_stale_with_other_chapters_or_mode_but_not_language() {+ let mut s = state(2, Role::Men);+ take_found(&mut s);+ assert!(!drop_stale_cast(&mut s));+ toggle_include(&mut s, 0);+ assert!(!drop_stale_cast(&mut s), "a part of the chapters found needs no new search");+ toggle_include(&mut s, 0);+ assert!(!drop_stale_cast(&mut s), "nor does picking a chapter again");+ s.book.draft.as_mut().unwrap().chapters[1].text.push_str(" More.");+ assert!(!drop_stale_cast(&mut s), "a chapter not searched yet keeps what was found");+ let d = s.book.draft.as_ref().unwrap();+ let unread = chapter_fingerprint(&d.chapters[1]);+ let picked = d.chapters.iter().filter(|c| c.include).count();+ s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).filter(|f| *f != unread).collect();+ s.book.cast.status_for = status_key(&s);+ assert_eq!(+ start_blocker(&s),+ Some(format!("1 of {picked} chapters are not analysed yet: press Find who speaks to analyse only them."))+ );+ assert_eq!(generate_blocker(&s), start_blocker(&s));+ let text = &mut s.book.draft.as_mut().unwrap().chapters[1].text;+ text.truncate(text.len() - 6);++ take_found(&mut s);+ s.book.cast_mode = CastMode::Careful;+ assert!(drop_stale_cast(&mut s));++ take_found(&mut s);+ crate::ui::speak::set_language(&mut s, "de");+ assert!(!drop_stale_cast(&mut s), "the language settles only after the voices load");++ take_found(&mut s);+ s.book.cast.error = Some("busy".into());+ s.book.cast.job = Some("k".into());+ s.book.cast_mode = CastMode::Fast;+ assert!(!drop_stale_cast(&mut s), "a search still running keeps what it shows");+ }++ #[test]+ fn a_picked_gender_replaces_gemmas() {+ assert_eq!(+ with_gender("female, elderly, low pitch, american accent", Some("male")),+ "male, elderly, low pitch, american accent"+ );+ assert_eq!(with_gender("male, young adult", None), "male, young adult");+ assert_eq!(with_gender("young adult, moderate pitch", Some("female")), "female, young adult, moderate pitch");+ }++ #[test]+ fn opening_a_book_leaves_the_language_of_the_draft_it_leaves() {+ let mut s = AppState::default();+ s.book.shown = true;+ let mut uk = scene_file();+ uk.path = std::env::temp_dir().join("mimvox-test-uk.epub");+ uk.language = "uk".into();+ s.book.draft =+ Some(Draft { file: uk.clone(), chapters: vec![], auto: None, before_split: None, book_id: None });+ s.shell.languages = ["en", "uk", "de"]+ .iter()+ .map(|c| crate::engine::protocol::SpeechLanguage {+ code: (*c).into(),+ name: String::new(),+ native: String::new(),+ common: true,+ })+ .collect();+ let mut en = scene_file();+ en.path = std::env::temp_dir().join("mimvox-test-de.epub");+ en.language = "de".into();+ en.words = LONG_WORDS + 1;+ let left = std::sync::Arc::new(std::sync::Mutex::new(None));+ STASHED.with(|k| *k.borrow_mut() = Some(left.clone()));+ opened(&mut s, en, Purpose::Book);+ STASHED.with(|k| *k.borrow_mut() = None);+ assert_eq!(left.lock().unwrap().as_deref(), Some("uk"), "the draft left keeps its language");+ assert_eq!(book_language(&s), "de");+ }+}diff --git a/crates/desktop/src/ui/components.rs b/crates/desktop/src/ui/components.rsindex 58cf662..05e1c99 100644--- a/crates/desktop/src/ui/components.rs+++ b/crates/desktop/src/ui/components.rs@@ -31,6 +31,11 @@ pub mod icons {"chip",r#"<rect x="4" y="4" width="8" height="8" rx="1.6"/><path d="M6.6 6.6H9.4V9.4H6.6ZM6 1.8V4M10 1.8V4M6 12V14.2M10 12V14.2M1.8 6H4M1.8 10H4M12 6H14.2M12 10H14.2"/>"#);+ stroke_icon!(+ BRAIN,+ "brain",+ r#"<path d="M6.9 3.1C6.3 2.4 5 2.5 4.6 3.5C3.2 3.6 2.4 5 3 6.2C2 7 2.1 8.9 3.2 9.4C2.9 10.9 4 12.3 5.4 12.1C5.9 13 6.6 13.1 6.9 12.7Z"/><path d="M9.1 3.1C9.7 2.4 11 2.5 11.4 3.5C12.8 3.6 13.6 5 13 6.2C14 7 13.9 8.9 12.8 9.4C13.1 10.9 12 12.3 10.6 12.1C10.1 13 9.4 13.1 9.1 12.7Z"/><path d="M4.6 3.5C4.5 4.4 5 5 5.6 5.2M3.2 9.4C4.1 9.5 4.8 9 5 8.2"/><path d="M11.4 3.5C11.5 4.4 11 5 10.4 5.2M12.8 9.4C11.9 9.5 11.2 9 11 8.2"/>"#+ );stroke_icon!(FOLDER,"folder",diff --git a/crates/desktop/src/ui/design.rs b/crates/desktop/src/ui/design.rsindex fd06118..15b6a92 100644--- a/crates/desktop/src/ui/design.rs+++ b/crates/desktop/src/ui/design.rs@@ -222,7 +222,7 @@ pub fn settle(s: &mut AppState) -> bool {false}-fn default_text(code: &str) -> &'static str {+pub fn default_text(code: &str) -> &'static str {TEXTS.iter().find(|(c, _)| *c == code).map_or("", |(_, t)| t)}@@ -386,6 +386,8 @@ fn other_job(s: &AppState) -> Option<&'static str> {Some("A book is being read. Pause it in Book mode to make a voice.")} else if super::train::is_training(s) {Some("A voice is training and is using the GPU. Generate when it finishes.")+ } else if super::book::finding_speakers(s) {+ Some("Book is finding who speaks and is using the GPU. Generate when it finishes.")} else {None}diff --git a/crates/desktop/src/ui/lang.rs b/crates/desktop/src/ui/lang.rsindex 9c24b65..b1d9b85 100644--- a/crates/desktop/src/ui/lang.rs+++ b/crates/desktop/src/ui/lang.rs@@ -193,7 +193,7 @@ fn pick(s: &mut AppState, target: Target, code: &str) {fn current(s: &AppState, target: Target) -> String {match target {- Target::Speak => super::speak::language(s),+ Target::Speak => super::speak::style_language(s),Target::RedubFrom => s.redub.from.clone(),Target::RedubTo => s.redub.to.clone(),Target::Reference => String::new(),diff --git a/crates/desktop/src/ui/onboarding.rs b/crates/desktop/src/ui/onboarding.rsindex 558b538..046e7c1 100644--- a/crates/desktop/src/ui/onboarding.rs+++ b/crates/desktop/src/ui/onboarding.rs@@ -13,6 +13,12 @@ use crate::ui::theme::{self, Palette, radius, ty};use crate::ui::voices::kit::{self, BtnKind};pub fn data_dir() -> PathBuf {+ // Tests write settings and drafts: never into the user's data folder.+ if cfg!(test) {+ return std::env::var_os("MIMVOX_DATA")+ .map(PathBuf::from)+ .unwrap_or_else(|| std::env::temp_dir().join(format!("mimvox-test-{}", std::process::id())));+ }crate::engine::default_data_dir().unwrap_or_else(|| PathBuf::from("."))}diff --git a/crates/desktop/src/ui/redub.rs b/crates/desktop/src/ui/redub.rsindex b8d1c58..da3115a 100644--- a/crates/desktop/src/ui/redub.rs+++ b/crates/desktop/src/ui/redub.rs@@ -1026,6 +1026,14 @@ fn engine_blocker(s: &AppState) -> Option<&'static str> {if super::train::is_training(s) {return Some("A voice is training and is using the GPU. Redub is back when it finishes.");}+ if super::book::finding_speakers(s) {+ return Some("Book is finding who speaks and is using the GPU. Redub is back when it finishes.");+ }+ // A subtitled video of a transcript is ffmpeg only and is made beside a book.+ let video_only = s.redub.mode == RedubMode::Subtitles && s.redub.kept_segments().next().is_some();+ if s.book.running() && !video_only {+ return Some("A book is being read: pause it (Speak, Book) to redub. Subtitle video works meanwhile.");+ }if s.speak.is_generating() {return Some("Speech is being generated on the Speak tab. Try again in a moment.");}diff --git a/crates/desktop/src/ui/setuprun.rs b/crates/desktop/src/ui/setuprun.rsindex 5e9c599..a5fc0f2 100644--- a/crates/desktop/src/ui/setuprun.rs+++ b/crates/desktop/src/ui/setuprun.rs@@ -73,7 +73,7 @@ pub struct Component {pub what: &'static str,}-pub const COMPONENTS: [Component; 10] = [+pub const COMPONENTS: [Component; 11] = [Component {id: "speech",label: "Speech engine",@@ -129,6 +129,12 @@ pub const COMPONENTS: [Component; 10] = [gb: 1.5,what: "Ukrainian with exact word stress in Speak, Book and Redub (HolosTTS): every word as the dictionary and the sentence say.",},+ Component {+ id: "cast",+ label: "Character voices",+ gb: 7.4,+ what: "Book reads men's and women's lines in their own voices: finds who speaks each line (Gemma 4 12B on the GPU). Needs a GPU with 10 GB or a Mac.",+ },];pub const SPEECH_MODELS: [&str; 3] = ["omnivoice", "voxcpm", "chatterbox"];@@ -887,6 +893,11 @@ fn mid_sentence(label: &str) -> String {}pub fn install_line(s: &AppState, p: Palette, id: &str, what: &str) -> El {+ install_line_says(s, p, id, what, None)+}++/// [`install_line`] with its own sentence in place of "<what> needs <component> (<size>)".+pub fn install_line_says(s: &AppState, p: Palette, id: &str, what: &str, says: Option<String>) -> El {use super::components::Button;let Some(c) = component(id) else { return el() };let this = s.setup.adding.as_deref() == Some(id) && running(s);@@ -917,7 +928,7 @@ pub fn install_line(s: &AppState, p: Palette, id: &str, what: &str) -> El {let line = if this {format!("Installing {}… {:.0}%", c.label, progress(s) * 100.0)} else {- format!("{what} needs {} ({:.1} GB).", mid_sentence(c.label), c.gb)+ says.unwrap_or_else(|| format!("{what} needs {} ({:.1} GB).", mid_sentence(c.label), c.gb))};row().key(format!("install-line-{id}"))diff --git a/crates/desktop/src/ui/shell.rs b/crates/desktop/src/ui/shell.rsindex fb2970e..5457fd0 100644--- a/crates/desktop/src/ui/shell.rs+++ b/crates/desktop/src/ui/shell.rs@@ -52,6 +52,9 @@ pub struct VoiceInfo {pub references: Vec<String>,/// Detected by the engine; `None` until the speech worker has transcribed the clip.pub reference_language: Option<String>,+ /// Made by Book for this book and role ("men", "women", "narrator").+ pub book: Option<String>,+ pub book_role: Option<String>,}impl VoiceInfo {@@ -99,6 +102,8 @@ impl VoiceInfo {.and_then(Value::as_str).filter(|l| !l.is_empty()).map(str::to_owned),+ book: v.get("book").and_then(Value::as_str).filter(|b| !b.is_empty()).map(str::to_owned),+ book_role: v.get("book_role").and_then(Value::as_str).map(str::to_owned),})}}@@ -207,12 +212,17 @@ impl Default for ShellState {icon_cache: None,toasts: Vec::new(),audio_error: None,- data_dir: crate::engine::default_data_dir().unwrap_or_else(std::env::temp_dir),+ data_dir: if cfg!(test) {+ super::onboarding::data_dir()+ } else {+ crate::engine::default_data_dir().unwrap_or_else(std::env::temp_dir)+ },preparing: None,warm_for: None,warm_req: None,next_toast: 0,- scripted: headless_run(),+ // Tests never write the user's files (the book draft, settings).+ scripted: headless_run() || cfg!(test),voices_req: None,first_voice_list: true,gpu: false,@@ -990,6 +1000,8 @@ pub fn engine_look(s: &AppState) -> EngineLook {look(Tone::Danger, "Not enough memory", false, false)} else if models_missing(s) {look(Tone::Danger, "Models missing", false, false)+ } else if any("paused") && super::book::finding_speakers(s) {+ look(Tone::Neutral, "Finding speakers · speech paused", false, false)} else if any("paused") {look(Tone::Neutral, "Training · speech paused", false, false)} else if any("loading") {@@ -1011,7 +1023,8 @@ pub fn engine_details(s: &AppState) -> (String, Vec<String>) {if super::setuprun::running(s) {return ("Setup is running; the engine starts again by itself when it finishes.".to_owned(), Vec::new());}- engine_help(&s.shell.engine, super::setuprun::has(s, "training"), s.shell.tts_message.as_deref())+ let finding = super::book::finding_speakers(s);+ engine_help(&s.shell.engine, super::setuprun::has(s, "training"), s.shell.tts_message.as_deref(), finding)}fn engine_pill(s: &AppState, p: Palette, tight: bool) -> El {@@ -1055,10 +1068,17 @@ fn engine_pill(s: &AppState, p: Palette, tight: bool) -> El {.child(icon_el(&icons::SLIDERS, 14.0, p.text_dim).a11y_hidden())}-fn engine_help(engine: &EngineStatus, training: bool, tts_message: Option<&str>) -> (String, Vec<String>) {+/// `finding`: Book's speaker search, not training, has paused the speech models.+fn engine_help(+ engine: &EngineStatus,+ training: bool,+ tts_message: Option<&str>,+ finding: bool,+) -> (String, Vec<String>) {let model = |m: &Option<String>| match m.as_deref() {Some("ready") => "ready".to_owned(),Some("loading") => "loading…".to_owned(),+ Some("paused") if finding => "paused while Book finds who speaks".to_owned(),Some("paused") => "paused while a voice trains".to_owned(),Some("missing") => "not installed".to_owned(),Some("no_memory") => "not enough memory (RAM)".to_owned(),@@ -1077,6 +1097,8 @@ fn engine_help(engine: &EngineStatus, training: bool, tts_message: Option<&str>)"Speech cannot run on this computer: it has too little memory (RAM) for the speech model on the processor."} else if missing {"Some models are not installed: run setup again."+ } else if any("paused") && finding {+ "Book is finding who speaks: the speech models are paused so it has the GPU. They come back when it ends."} else if any("paused") {"A voice is training: the speech models are paused so training has the GPU. They come back when training ends or pauses."} else if any("loading") {@@ -1164,13 +1186,26 @@ fn voice_pill(s: &AppState, p: Palette) -> El {.child(icon_el(&icons::CHEVRON_DOWN, 12.0, p.text_dim))}+/// The user's own voices, then the ones Book made for its books.+pub fn by_kind(voices: &[VoiceInfo]) -> (Vec<&VoiceInfo>, Vec<&VoiceInfo>) {+ voices.iter().partition(|v| v.book.is_none())+}++pub fn group_heading(p: Palette, title: &str) -> El {+ text(title.to_owned()).font(ty::OVERLINE).color(p.text_faint).px(12.0).pt(8.0).pb(2.0)+}+fn voice_menu(s: &AppState, p: Palette) -> El {let scrim = el().key("voice-scrim").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).on_press(|s: &mut AppState| s.shell.voice_menu_open = false);let mut list = col().w_full().gap(2.0);- for v in &s.shell.voices {+ let (own, book) = by_kind(&s.shell.voices);+ for (i, v) in own.iter().chain(&book).enumerate() {+ if i == own.len() {+ list = list.child(group_heading(p, "Book voices"));+ }let id = v.id.clone();let on = s.shell.active_voice.as_deref() == Some(v.id.as_str());list = list.child(@@ -1294,7 +1329,7 @@ mod tests {let models = json!({"tts": "no_memory", "rvc": "ready", "tts_message": WHY});on_engine(&mut s, &EngineMsg::Event(Event { event: "models".into(), job: None, data: models }));assert_eq!(s.shell.tts_message.as_deref(), Some(WHY));- let (help, facts) = engine_help(&s.shell.engine, true, s.shell.tts_message.as_deref());+ let (help, facts) = engine_help(&s.shell.engine, true, s.shell.tts_message.as_deref(), false);assert!(help.starts_with("Speech cannot run on this computer"), "{help}");assert!(help.ends_with("\nNot enough memory (RAM) for speech on the processor: it needs 11 GB."), "{help}");assert_eq!(facts, ["Device: CPU", "Speech model: not enough memory (RAM)", "Voice conversion: ready"]);diff --git a/crates/desktop/src/ui/speak.rs b/crates/desktop/src/ui/speak.rsindex 8abe7ab..cdd848b 100644--- a/crates/desktop/src/ui/speak.rs+++ b/crates/desktop/src/ui/speak.rs@@ -241,6 +241,12 @@ pub fn language(s: &AppState) -> String {/// The voice's own language is stored as "no choice".pub fn set_language(s: &mut AppState, code: &str) {+ if s.book.shown+ && let Some(d) = s.book.draft.as_mut()+ {+ d.file.language = code.to_owned();+ return;+ }let Some(v) = shell::active_voice(s).cloned() else { return };if code == v.lang() {s.speak.languages.remove(&v.id);@@ -324,6 +330,9 @@ fn blocker(s: &AppState) -> Option<&'static str> {if s.book.running() {return Some("A book is being read. Pause it in Book mode to speak other text.");}+ if super::book::finding_speakers(s) {+ return Some("Book is finding who speaks and is using the GPU. Speak when it finishes.");+ }if super::design::generating(s) {return Some("Design is making a voice. Speak when it is done.");}@@ -928,13 +937,18 @@ fn hint_line(s: &AppState, p: Palette, block: Option<&'static str>) -> El {text("Ctrl+Enter to generate").font(ty::CAPTION).color(p.text_faint)}-fn exact_ukrainian(s: &AppState) -> bool {- language(s) == "uk" && super::setuprun::has(s, "ukrainian") && s.speak.exact_stress+/// The language the Style panel is for: the book's in Book mode, else the text's.+pub(crate) fn style_language(s: &AppState) -> String {+ if s.screen == Screen::Speak && s.book.shown { super::book::book_language(s) } else { language(s) }}-fn toggle_exact_stress(s: &mut AppState) {- s.speak.exact_stress = !s.speak.exact_stress;- super::onboarding::save_setting("exact_stress", serde_json::json!(s.speak.exact_stress));+/// HolosTTS reads: Ukrainian with exact stress, and a model that hands it over (Auto or OmniVoice).+fn exact_ukrainian(s: &AppState) -> bool {+ let lang = style_language(s);+ lang == "uk"+ && super::setuprun::has(s, "ukrainian")+ && s.speak.exact_stress+ && matches!(model_for(s, &lang).as_str(), "auto" | "omnivoice")}pub(crate) fn style_panel(s: &AppState, p: Palette) -> El {@@ -969,14 +983,11 @@ pub(crate) fn style_panel(s: &AppState, p: Palette) -> El {}}).build(p);- let mut m = Slider::new("match", "Voice match", s.speak.voice_match, 0.3, 1.0)+ let m = Slider::new("match", "Voice match", s.speak.voice_match, 0.3, 1.0).step(0.05).ends("Natural", "Closest to me").on_change(|s, v| s.speak.voice_match = v).build(p);- if !trained {- m = m.opacity(0.5);- }let quality = row().key("quality").w_full()@@ -1013,29 +1024,32 @@ pub(crate) fn style_panel(s: &AppState, p: Palette) -> El {if let Some(row) = model_row(s, p) {c = c.child(row);}- if s.screen == Screen::Speak && accent_applies(s, &language(s)) {+ if s.screen == Screen::Speak && accent_applies(s, &style_language(s)) {c = c.child(accent_block(s, p, "speak-accent"));}- // Ukrainian with exact stress (HolosTTS) reads like a narrator: no sampling to make livelier, no decoding steps.+ // HolosTTS reads like a narrator (no sampling, no decoding steps); Voice match needs a trained voice: what does not+ // apply is not shown.let narrator = s.screen == Screen::Speak && exact_ukrainian(s);- let (expr, quality) = if narrator { (expr.opacity(0.5), quality.opacity(0.5)) } else { (expr, quality) };- c = if super::redub::converting(s) { c.child(m) } else { c.child(speed).child(expr).child(m).child(quality) };- if narrator {- c = c.child(text("Ukrainian with exact stress reads evenly, like a narrator: Expressiveness and Quality do not change it.")- .font(ty::CAPTION).color(p.text_faint).wrap());+ if !super::redub::converting(s) {+ c = c.child(speed);+ if !narrator {+ c = c.child(expr);+ }}- if !trained && shell::active_voice(s).is_some() {- c = c.child(- text("Voice match applies once this voice is trained.").font(ty::CAPTION).color(p.text_faint).wrap(),- );- } else if trained && !super::setuprun::has(s, "training") {+ if trained {+ c = c.child(m);+ }+ if !super::redub::converting(s) && !narrator {+ c = c.child(quality);+ }+ if trained && !super::setuprun::has(s, "training") {c = c.child(super::setuprun::install_line(s, p, "training", "Voice match"));}c}pub fn model(s: &AppState) -> String {- model_for(s, &language(s))+ model_for(s, &style_language(s))}/// The Model choice for text in `code`: Auto when the chosen model does not speak it.@@ -1047,7 +1061,7 @@ pub fn model_for(s: &AppState, code: &str) -> String {/// Speak's language, or the language Redub speaks (none in Convert voice).fn model_language(s: &AppState) -> Option<String> {match s.screen {- Screen::Speak => Some(language(s)),+ Screen::Speak => Some(style_language(s)),Screen::Redub => super::redub::speech_language(s),_ => None,}@@ -1066,6 +1080,9 @@ fn model_label(s: &AppState, id: &str) -> String {if id == "auto" {return "Auto".to_owned();}+ if id == "holos" {+ return "HolosTTS".to_owned();+ }s.shell.speech_models.iter().find(|m| m.id == id).map_or_else(|| id.to_owned(), |m| m.name.clone())}@@ -1077,12 +1094,17 @@ fn auto_help(s: &AppState) -> &'static str {}}+/// HolosTTS is offered for Ukrainian when it is installed: it is picked as a model, not a checkbox.+fn holos_offered(s: &AppState, code: &str) -> bool {+ code == "uk" && s.screen == Screen::Speak && super::setuprun::has(s, "ukrainian")+}+fn model_row(s: &AppState, p: Palette) -> Option<El> {- if s.shell.speech_models.len() < 2 {+ let code = model_language(s)?;+ if s.shell.speech_models.len() < 2 && !holos_offered(s, &code) {return None;}- let code = model_language(s)?;- let chosen = model_for(s, &code);+ let chosen = if exact_ukrainian(s) { "holos".to_owned() } else { model_for(s, &code) };let unsupported = (s.speak.model != "auto" && chosen == "auto").then(|| s.shell.speech_models.iter().find(|m| m.id == s.speak.model)).flatten()@@ -1099,7 +1121,7 @@ fn model_row(s: &AppState, p: Palette) -> Option<El> {.gap(1.0).min_w(0.0).child(text("Model").font(ty::LABEL).color(p.text))- .child(text("What clones the voice").font(ty::CAPTION).color(p.text_faint)),+ .child(text("What reads the text in the voice").font(ty::CAPTION).color(p.text_faint)),).child(dropdown_chip(p,@@ -1126,13 +1148,18 @@ pub fn model_overlay(s: &AppState, p: Palette) -> Option<El> {.key("speak-model-scrim").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).on_press(|s: &mut AppState| s.speak.model_menu = false);- let chosen = model_for(s, &code);- let mut ids = vec!["auto".to_owned()];+ let holos = holos_offered(s, &code);+ let chosen = if exact_ukrainian(s) { "holos".to_owned() } else { model_for(s, &code) };+ let mut ids = if holos { vec!["holos".to_owned()] } else { vec!["auto".to_owned()] };ids.extend(s.shell.speech_models.iter().map(|m| m.id.clone()));let mut list = col().w_full().gap(2.0);for id in ids {let on = chosen == id;- let help = if id == "auto" { auto_help(s) } else { model_help(&id) };+ let help = match id.as_str() {+ "auto" => auto_help(s),+ "holos" => "Ukrainian with exact stress from the dictionary; a + before a vowel changes one",+ _ => model_help(&id),+ };let label = model_label(s, &id);let pick = id.clone();list = list.child(@@ -1193,13 +1220,21 @@ pub fn model_languages(s: &AppState) -> Option<&[String]> {}fn pick_model(s: &mut AppState, id: &str) {+ // HolosTTS is OmniVoice's place with exact stress on; another model turns exact stress off.+ let holos = id == "holos";+ if s.speak.exact_stress != holos && holos_offered(s, &style_language(s)) {+ s.speak.exact_stress = holos;+ super::onboarding::save_setting("exact_stress", serde_json::json!(holos));+ }+ let id = if holos { "omnivoice" } else { id };s.speak.model = id.to_owned();s.speak.model_dirty = true;- if s.screen != Screen::Speak {+ // A book keeps its language: a model that does not speak it gives way to Auto, as the note under Model says.+ if s.screen != Screen::Speak || s.book.shown {return;}let Some(langs) = model_languages(s).map(<[String]>::to_vec) else { return };- if langs.contains(&language(s)) {+ if langs.contains(&style_language(s)) {return;}let own = shell::active_voice(s).map(|v| v.lang().to_owned());@@ -1213,7 +1248,7 @@ fn pick_model(s: &mut AppState, id: &str) {}fn language_row(s: &AppState, p: Palette) -> El {- let code = language(s);+ let code = style_language(s);let voice = shell::active_voice(s);let head = row().key("speak-lang")@@ -1230,19 +1265,10 @@ fn language_row(s: &AppState, p: Palette) -> El {).child(lang::chip(&p, "speak-lang-chip", &lang::label(&code), lang::Target::Speak, voice.is_some()));let mut c = col().w_full().gap(8.0).child(head);- // With HolosTTS the engine reads Ukrainian with dictionary stress; without it OmniVoice guesses, and a "+"- // before a vowel is a hint it often follows.- if code == "uk" && super::setuprun::has(s, "ukrainian") {- c = c.child(el().key("speak-exact-stress").w_full().child(super::voices::kit::checkbox(- &p,- s.speak.exact_stress,- "Exact stress (HolosTTS)",- toggle_exact_stress,- )));- }if exact_ukrainian(s) {- c = c.child(text("Every word as the dictionary and the sentence say. A + before a vowel changes one: співак+ом. The voice can sound less like the original: turn it off to compare.")- .font(ty::CAPTION).color(p.text_faint).wrap());+ c = c.child(+ text("A + before a vowel changes a word's stress: співак+ом.").font(ty::CAPTION).color(p.text_faint).wrap(),+ );} else if code == "uk" {c = c.child(text("Wrong stress? Type + before the stressed vowel: співак+ом.")@@ -1393,7 +1419,8 @@ pub(crate) fn accent_block(s: &AppState, p: Palette, key: &str) -> El {),);}- if native {+ // A book's voices each get the native speaker closest to their own pitch.+ if native && !(s.screen == Screen::Speak && s.book.shown) {let v = s.speak.native_voice;let sel = match v {NativeVoice::Auto => 0,diff --git a/crates/desktop/src/ui/train.rs b/crates/desktop/src/ui/train.rsindex 1143ece..8e68545 100644--- a/crates/desktop/src/ui/train.rs+++ b/crates/desktop/src/ui/train.rs@@ -681,13 +681,19 @@ fn setup_view(s: &AppState, p: &Palette) -> El {Some("cpu") => "Expect many hours without a GPU.".to_string(),_ => format!("About {} on an RTX 4070-class GPU.", fmt_dur(epochs as f32 * SECONDS_PER_EPOCH_CUDA)),};+ let book = s.book.running() || super::book::finding_speakers(s);out.child(col().w_full().items_center().gap(10.0).pt(6.0)- .child(kit::big_button(p, "Start training", can_train, start))+ .child(kit::big_button(p, "Start training", can_train && !book, start))+ .children(book.then(|| {+ text("A book is being read and holds the GPU: pause it (Speak, Book) to train.")+ .font(ty::CAPTION)+ .color(p.warn)+ })).child(text(est).font(ty::CAPTION).color(p.text_dim)).child(text("You can keep using the other screens while it trains.").font(ty::CAPTION).color(p.text_faint)),)diff --git a/crates/desktop/src/ui/voices.rs b/crates/desktop/src/ui/voices.rsindex 91739b6..5b9af0a 100644--- a/crates/desktop/src/ui/voices.rs+++ b/crates/desktop/src/ui/voices.rs@@ -215,7 +215,18 @@ pub fn view(s: &AppState, cx: &mut Cx<AppState>) -> El {if s.shell.voices.is_empty() {list = list.child(empty_state(&p, shell::engine_ready(s)));}- for info in &s.shell.voices {+ let (own, book) = shell::by_kind(&s.shell.voices);+ for info in own {+ list = list.child(voice_card(s, &p, info));+ }+ if !book.is_empty() {+ list = list.child(kit::header(+ &p,+ "Book voices",+ "Made by Book for the books you read, named after the book and the role.",+ ));+ }+ for info in book {list = list.child(voice_card(s, &p, info));}@@ -315,7 +326,25 @@ fn voice_card(s: &AppState, p: &Palette, info: &VoiceInfo) -> El {meta = meta.child(text(format!("{} epochs", info.trained_epochs)).font(ty::CAPTION).color(p.text_dim));}- let info_col = col().grow(1.0).min_w(0.0).gap(6.0).child(title).child(meta);+ let mut info_col = col().grow(1.0).min_w(0.0).gap(6.0).child(title).child(meta);+ if info.book.is_some() {+ // Which lines of its book this voice reads; Book fills its roles by it.+ const ROLES: [&str; 3] = ["narrator", "men", "women"];+ let at = ROLES.iter().position(|r| Some(*r) == info.book_role.as_deref()).unwrap_or(0);+ let rid = id.clone();+ info_col =+ info_col.child(row().gap(8.0).center_y().child(text("Reads").font(ty::CAPTION).color(p.text_dim)).child(+ crate::ui::components::segmented(+ *p,+ &format!("voice-role-{}", info.id),+ &["Narrator", "Men", "Women"],+ at,+ move |s, i| {+ send(s, Tag::Rename, "voices.rename", json!({ "id": rid, "book_role": ROLES[i] }));+ },+ ),+ ));+ }let mut actions = row().key(format!("voice-actions-{}", info.id)).gap(8.0).center_y().instant_changes();if renaming.is_some() {@@ -416,6 +445,26 @@ pub(crate) fn scene_list(s: &mut AppState) {s.shell.voices = demo_voices();s.shell.active_voice = Some("my-voice".into());}+fn scene_book_voices(s: &mut AppState) {+ scene_list(s);+ for role in ["narrator", "men", "women"] {+ s.shell.voices.push(VoiceInfo {+ id: format!("martin-eden-{role}"),+ name: format!("Martin Eden · {role}"),+ language: "en".into(),+ book: Some("Martin Eden".into()),+ book_role: Some(role.into()),+ ..Default::default()+ });+ }+}++fn scene_book_voices_menu(s: &mut AppState) {+ scene_book_voices(s);+ s.screen = Screen::Speak;+ s.shell.voice_menu_open = true;+}+fn scene_paused(s: &mut AppState) {scene_list(s);let paused = |epoch, interrupted| {@@ -462,6 +511,8 @@ fn scene_error(s: &mut AppState) {pub fn scenes() -> &'static [super::Scene] {&[("voices-list", scene_list),+ ("voices-book", scene_book_voices),+ ("voices-book-menu", scene_book_voices_menu),("voices-paused", scene_paused),("voices-empty", scene_empty),("voices-loading", scene_loading),diff --git a/crates/engine-client/src/protocol.rs b/crates/engine-client/src/protocol.rsindex 874f4a2..121d890 100644--- a/crates/engine-client/src/protocol.rs+++ b/crates/engine-client/src/protocol.rs@@ -1360,6 +1360,9 @@ pub struct BookSummary {pub language: Option<String>,#[serde(default)]pub voice_id: Option<String>,+ /// The voices of men's and women's lines, for a book read with several voices.+ #[serde(default)]+ pub voices: Option<std::collections::BTreeMap<String, Option<String>>>,/// `new` | `running` | `paused` | `done` | `error` | `cancelled`.#[serde(default)]pub status: String,@@ -1480,15 +1483,106 @@ pub struct BookParams<'a> {pub m4b: bool,pub read_titles: bool,pub exact_stress: bool,- pub keep_voice: bool,/// `auto` or a `SpeechModel` id.pub model: &'a str,+ /// Character voices: the men's and the women's lines; the narrator reads the rest.+ pub men: Option<&'a str>,+ pub women: Option<&'a str>,+ pub cast: CastMode,+}++/// How carefully `book.cast` finds who speaks: careful reads twice and leaves lines it is unsure of to the narrator.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum CastMode {+ #[default]+ Fast,+ Careful,+}++impl CastMode {+ pub fn as_str(self) -> &'static str {+ match self {+ CastMode::Fast => "fast",+ CastMode::Careful => "careful",+ }+ }+}++pub fn book_cast(chapters: &[BookChapterIn<'_>], language: &str, cast: CastMode) -> Request {+ ("book.cast", json!({ "chapters": chapters, "language": language, "cast": cast.as_str() }))+}++#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct CastCharacter {+ pub name: String,+ /// `m` | `f`.+ pub gender: String,+ #[serde(default, deserialize_with = "de::u32_or_zero")]+ pub lines: u32,+}++#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct CastNarrator {+ #[serde(default)]+ pub first_person: bool,+ #[serde(default)]+ pub name: String,+}++#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct CastLines {+ #[serde(default, deserialize_with = "de::u32_or_zero")]+ pub men: u32,+ #[serde(default, deserialize_with = "de::u32_or_zero")]+ pub women: u32,+ #[serde(default, deserialize_with = "de::u32_or_zero")]+ pub narrator: u32,+}++/// OmniVoice design terms for a voice of each role (`voices.design` `description`).+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct CastVoices {+ #[serde(default)]+ pub narrator: String,+ #[serde(default)]+ pub men: String,+ #[serde(default)]+ pub women: String,+}++/// `book.cast`'s answer (`job` null when the cast was found before) and `book.cast_done`'s data.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct BookCast {+ #[serde(default)]+ pub key: String,+ /// `fast` | `careful`.+ #[serde(default)]+ pub mode: String,+ #[serde(default)]+ pub job: Option<String>,+ #[serde(default)]+ pub narrator: Option<CastNarrator>,+ #[serde(default)]+ pub characters: Vec<CastCharacter>,+ #[serde(default)]+ pub lines: Option<CastLines>,+ #[serde(default)]+ pub voices: Option<CastVoices>,+}++/// `book.cast_progress`: `pct` is 0-100.+#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct BookCastProgress {+ #[serde(default)]+ pub key: String,+ #[serde(default, deserialize_with = "de::f32_or_zero")]+ pub pct: f32,}pub fn book_start(p: &BookParams<'_>) -> Request {let params = json!({"exact_stress": p.exact_stress,- "keep_voice": p.keep_voice,"model": p.model,"title": p.title,"source": p.source,@@ -1504,17 +1598,25 @@ pub fn book_start(p: &BookParams<'_>) -> Request {"m4b": p.m4b,"read_titles": p.read_titles,});- ("book.start", with_accent(params, p.accent))+ let mut params = with_accent(params, p.accent);+ if p.men.is_some() || p.women.is_some() {+ params["voices"] = json!({ "men": p.men, "women": p.women });+ params["cast"] = json!(p.cast.as_str());+ }+ ("book.start", params)}pub fn book_id_request(method: &'static str, id: &str) -> Request {(method, json!({ "id": id }))}-pub fn book_reread(id: &str, voice_id: Option<&str>, chapters: Option<&[u32]>) -> Request {+/// `voice`: (`narrator` | `men` | `women`, the voice id) to read on with.+pub fn book_reread(id: &str, voice: Option<(&str, &str)>, chapters: Option<&[u32]>) -> Request {let mut params = json!({ "id": id });- if let Some(v) = voice_id {- params["voice_id"] = json!(v);+ match voice {+ Some(("narrator", v)) => params["voice_id"] = json!(v),+ Some((role, v)) => params["voices"] = json!({ role: v }),+ None => {}}if let Some(c) = chapters {params["chapters"] = json!(c);diff --git a/docs/usage.md b/docs/usage.mdindex 2b58c6e..04b97c3 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -782,16 +782,14 @@ model trained for that. Numbers, dates, abbreviations and Roman numerals are spe(*Розділ XII* is read as "розділ дванадцятий", *Людовік XIV* as "Людовік чотирнадцятий"). It works with everyvoice, also one recorded in another language: only the timbre comes from the reference clip, never the accent.-HolosTTS on its own keeps less of a voice than the main speech model, so a voice that is not trained is run through the-native-accent converter afterwards in Speak to bring its timbre back (a trained voice uses its own model, as always).-That makes it about as fast as the main speech model. A book skips it by default and reads Ukrainian at about 20× real-time; **Closer voice with exact stress** under Output turns the converter on for a book (about four times slower). **Exact stress (HolosTTS)** in the Style panel turns it off for what you-make next: Ukrainian is then read by the main speech model, which sounds closer to the voice but guesses the stress (a-**+** fixes a word). A book keeps the setting it started with.+HolosTTS keeps less of a voice than the main speech model; a trained voice gets its timbre back from its own model, as+always. HolosTTS is a choice of the **Model** menu for Ukrainian: pick **OmniVoice** there instead and Ukrainian is read by the+main speech model, which sounds closer to the voice but guesses the stress (a **+** fixes a word). A book reads its+next chapters with the model picked when they start.- If Mimvox stresses a word wrongly anyway (a rare word, a name, a heteronym whose grammar does not decide it, suchas *за́мок* / *замо́к*), put **+** before the stressed vowel and that word is spoken so: `з+амок`, `зам+ок`.-- It reads evenly, like a narrator: **Expressiveness** and **Quality** do not change it (they are dimmed), **Speed**+- It reads evenly, like a narrator: **Expressiveness** and **Quality** do not change it, so they are not shown; **Speed**does. It is also fast: about a tenth of a second of work per second of speech.- A trained voice still gets its voice match (RVC) afterwards, as in any language.@@ -962,10 +960,11 @@ after closing the app.such as *Chapter 1*, *CHAPTER IV*, *Розділ 1* in a text file.2. Check the list. Untick what you do not want read (a table of contents, notes). Click a title to rename it.The split button cuts a chapter in two at the paragraph nearest its middle; the join button joins the next chapter- into this one. The badges show the chapters, words, about how long the audio will be and how long it takes to make.+ into this one. A bar above the list shows the chapters, words, about how long the audio will be and how long the+ book takes to make, which shows once this computer has read its first chapter.**No chapters, or very long ones?** Many files have no chapter marks Mimvox can see, and a whole novella comes in- as one chapter of two hours. Then a line above the list offers **Split automatically**, and **Undo split** puts the+ as one chapter of two hours. Then the bottom of the totals panel offers **Split automatically**, and **Undo split** puts thechapters of the file back (with any renaming or joining done since). It looks at the shape of the text, so it worksin every language, and splits each chapter longer than about half an hour by the first of these it finds:- **chapter titles that are not marked as headings**: lines such as *Chapter 4*, *Розділ IV*, a bare *XII* or *12*,@@ -984,8 +983,8 @@ after closing the app.voice is gone), the active voice's books first.3. Set the voice, language and Style as for Speak. **Expressiveness** has its own value in Book mode, **0.60** bydefault: a steadier narrator for long listening. In the **Output** panel pick the format ("Save as"), and tick- **Also make one M4B audiobook with chapter marks** if you want a single file for an audiobook player. **Read each- chapter's title first** reads the title, then pauses, before the text; a chapter whose text already opens with its+ **Also make an M4B audiobook** if you want a single file for an audiobook player. **Read chapter+ titles** reads the title, then pauses, before the text; a chapter whose text already opens with itstitle (within its first few short lines) is read as it is, so the heading is not heard twice.4. Press **Read the book**. The panel shows *Chapter k of n*, the percentage, how much audio is made out of theexpected total, when the whole book will be ready, and the speed (for example *20× faster than real time*: an hour@@ -998,11 +997,16 @@ after closing the app.6. While the book is paused or finished, **Change voice** reads it on with another voice: when chapters are alreadymade, choose **Read all chapters again** or keep them and read only the rest with the new voice (an unfinishedchapter always starts again, so no chapter mixes two voices). The circular arrow on a finished chapter reads that- chapter again. Either way the book goes on reading at once, and the old chapter files are replaced.+ chapter again. Either way the book goes on reading at once, and the old chapter files are replaced. A book read+ with several voices asks first which one to change: **Narrator**, **Men** or **Women**.+7. Reading happens in the book you set up: each chapter read gets a ✓ with ▶ to play it and ↻ to read it again, and+ **Read the book** later reads the ticked chapters not read yet into the same book and folder, with the voices set+ then. Files are numbered by the chapter's place in the file, so an M4B made later keeps the book's order.If the app closes while a book is being read, the book is shown again the next time, marked *Interrupted*: press-**Resume**. The **Your books** list on the right keeps every book; click one to open it, or the trash button to remove-it from the list (its audio files stay).+**Resume**. The **Your books** list on the right has one line per book, read or not yet (*Draft*, *In progress*,+*Finished*); click one to open it in the same place, as you left it, or the trash button to remove it from the list+(its audio files stay).How it sounds: Mimvox reads whole sentences (a sentence is cut only when it is very long, and then only at a comma,semicolon, colon or dash), keeps the punctuation the model uses for intonation, and inserts pauses that follow it:@@ -1017,6 +1021,35 @@ native accent adds a voice conversion per segment and is slower. The estimate bereplaced by the measured pace once the book runs. A 350,000-token novel is roughly 28-30 hours of audio: about 5-15hours of generation, paused whenever you need the computer. As MP3 that is about 2.5 GB (192 kbps); as WAV about 9 GB.+#### Character voices: men and women in their own voices++With the optional **Character voices** component (Settings > Components, 7.4 GB: llama.cpp and the Gemma 4 12B+language model; it needs a GPU with 10 GB of memory or a Mac), a book can be read by up to three voices.++1. Open the book as above. Under **Voices** choose **One voice** (everything in the active voice, as before), **Two+ voices** (the narrator and one more voice; pick whether the second voice reads the **Men** or the **Women**, and the+ narrator reads everything else) or **Three voices** (a narrator, a voice for every man, a voice for every woman).+2. **Accuracy**: **Fast** reads the book once; **Careful** reads it twice and leaves the lines the two readings+ disagree on to the narrator: fewer lines in the wrong voice, a few more read by the narrator, twice the time.+3. Press **Find who speaks**. The model reads the book on the GPU (the speech models leave the GPU meanwhile) and+ reports how many lines each voice gets and who speaks most. On an RTX 4070 a novel takes about 15-20 minutes; asking+ again for the same chapters and language is instant.+4. For each role pick a saved voice, or press **Generate**: Mimvox makes a sample voice that suits the book (the+ narrator calm, the characters ordinary people of the main characters' age) with OmniVoice. Play it, and press+ Generate again for another one; picking a saved voice drops the sample.+5. **Read the book**. The samples you kept become voices then, named after the book and the role. They are listed+ apart, under **Book voices** in the voice menu and on the Voices screen, and the same book opened again picks them+ up for its roles.++How the lines are shared: speech goes to the voice of the speaker's gender, the author's words in the same paragraph+(*"Wait, Arthur," he said*, or after a dash, *— Стривайте, Артуре,— мовив він*) stay with the narrator. In a book told+in the first person, the narrator's own lines are the narrator's. Thoughts in quotes (*"He understands," was his+thought*) and letters whose writer never speaks are read by the narrator, a little more expressively; a letter whose+writer speaks elsewhere is read in the writer's voice. A word quoted in narration (*what a "lift" was*) stays+narration. This works in any language the speech models speak: the model finds both the speaker and the remark. On+English, Ukrainian, German, French, Italian and Spanish novels 96-100% of the lines got the right voice and at most 2%+the wrong one (Careful: about 1%); the slips are mostly in long conversations without "he said".+#### Example: an EPUB to MP3 chapters1. Speak, switch to **Book**, **Open book…**, choose `Meditations.epub`. Three chapters appear, *English (detected)*.diff --git a/engine/src/mimvox_engine/book.py b/engine/src/mimvox_engine/book.pyindex 5017b85..2319d50 100644--- a/engine/src/mimvox_engine/book.py+++ b/engine/src/mimvox_engine/book.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport contextlibimport gc+import hashlibimport jsonimport loggingimport os@@ -15,6 +16,7 @@ import subprocessimport threadingimport timeimport unicodedata+from collections import Counterfrom collections.abc import Iteratorfrom dataclasses import dataclassfrom pathlib import Path@@ -22,7 +24,7 @@ from typing import Anyimport numpy as np-from . import accent, aio, backends, config, media, narration, paths, reflang, rvc, speech, tts, voices, zsvc+from . import accent, aio, backends, cast, config, media, narration, paths, reflang, rvc, speech, tts, voices, zsvcfrom . import audio_util as aufrom .backends import SynthParamsfrom .registry import Context, EngineError, method@@ -38,6 +40,12 @@ M4B_BITRATE = "96k"MAX_CHARS = 20_000_000WAV_LIMIT = 0xFFFFFFFF - 1024 # a RIFF WAV cannot pass 4 GB: RF64 above thatHOLDER = "a book is being read; pause it (Speak, Book) to use speech, Redub or training"+CAST_HOLDER = "the speakers of a book are being found; wait for it or cancel it"+ROLES = ("men", "women")+CAST_LIST = 30+EMPTY_S = 0.05 # OmniVoice now and then gives no audio for a two-word piece such as "he said."+EMPTY_TRIES = 2+_CASTING: list[str | None] = [None] # loop thread only: the job of a running book.castMEMORY_RETRY_WAIT_S = (20.0, 60.0, 180.0, 300.0)_RUNNING: dict[str, str] = {} # loop thread only@@ -253,6 +261,7 @@ def summary(data: config.DataDir, book: dict[str, Any], state: dict[str, Any]) -"format": book.get("format"),"language": (book.get("settings") or {}).get("language"),"voice_id": (book.get("settings") or {}).get("voice_id"),+ "voices": (book.get("settings") or {}).get("voices"),"status": status,"interrupted": interrupted,"job": _RUNNING.get(bid),@@ -326,9 +335,17 @@ def _settings(params: dict[str, Any]) -> dict[str, Any]:lang, _ = tts.speech_language(params)m4b = params.get("m4b", False)titles = params.get("read_titles", True)- keep_voice = params.get("keep_voice", False)- if not isinstance(m4b, bool) or not isinstance(titles, bool) or not isinstance(keep_voice, bool):- raise EngineError("bad_request", "'m4b', 'read_titles' and 'keep_voice' must be true or false")+ if not isinstance(m4b, bool) or not isinstance(titles, bool):+ raise EngineError("bad_request", "'m4b' and 'read_titles' must be true or false")+ chosen = params.get("voices") or {}+ if (+ not isinstance(chosen, dict)+ or any(k not in ROLES for k in chosen)+ or any(v is not None and (not isinstance(v, str) or not v) for v in chosen.values())+ ):+ raise EngineError("bad_request", '\'voices\' must be {"men"?: voice id, "women"?: voice id}')+ mode = _cast_mode(params)+ roles = {r: chosen.get(r) for r in ROLES}return {"voice_id": voice_id,"language": lang,@@ -343,14 +360,31 @@ def _settings(params: dict[str, Any]) -> dict[str, Any]:"output_format": params.get("output_format") or "wav","m4b": m4b,"read_titles": titles,- "keep_voice": keep_voice,+ "voices": roles,+ "cast": mode if any(roles.values()) else None,}-async def _voice(ctx: Context, data: config.DataDir, st: dict[str, Any]) -> _Voice:+def _cast_mode(params: dict[str, Any]) -> str:+ mode = params.get("cast") or "fast"+ if mode not in cast.MODES:+ raise EngineError("bad_request", f"'cast' must be one of {', '.join(cast.MODES)}")+ return str(mode)+++async def _voices(ctx: Context, data: config.DataDir, st: dict[str, Any]) -> dict[str, _Voice]:+ """The narrator (the book's voice) and the character voices its settings name."""+ out = {"narrator": await _voice(ctx, data, st)}+ for role, vid in (st.get("voices") or {}).items():+ if vid:+ out[role] = await _voice(ctx, data, st, vid)+ return out+++async def _voice(ctx: Context, data: config.DataDir, st: dict[str, Any], voice_id: str | None = None) -> _Voice:lang, backend = tts.speech_language(st)tts.check_backend_ready(backend)- voice_id = st["voice_id"]+ voice_id = voice_id or st["voice_id"]meta = await aio.run_io(voices.read_meta, data, voice_id)out_fmt = await aio.run_io(media.output_format, st)voice_match = float(st["voice_match"])@@ -370,8 +404,6 @@ async def _voice(ctx: Context, data: config.DataDir, st: dict[str, Any]) -> _Voirequested, st.get("native_voice") or "auto", lang, has_pth, voice_match, zs_worker is not None)zs = tts.zero_shot(ctx, choice, zs_worker, ref, st["quality"])- if zs is None and not use_rvc and st.get("keep_voice", False):- zs = await tts.holos_timbre(ctx, backend, data, ref, st["quality"])ref_fields = await aio.run_io(reflang.fields, ref, lang, choice.accent == "native-us")return _Voice(backend,@@ -406,7 +438,10 @@ def _clean_chapters(raw: Any) -> list[dict[str, Any]]:if not count_words(text):continuetotal += len(text)- out.append({"title": title, "text": text, "words": count_words(text)})+ row: dict[str, Any] = {"title": title, "text": text, "words": count_words(text)}+ if isinstance(c.get("number"), int) and not isinstance(c.get("number"), bool) and c["number"] > 0:+ row["number"] = c["number"]+ out.append(row)if not out:raise EngineError("bad_request", "nothing to read: every chapter is empty")if total > MAX_CHARS:@@ -435,10 +470,7 @@ def _create(while folder.exists() or any(_folder_taken(data, folder)):n += 1folder = root / f"{name} ({n})"- width = max(2, len(str(len(chapters))))- for i, c in enumerate(chapters):- c["file"] = f"{i + 1:0{width}d} - {safe_name(c['title'], 60) or 'Chapter'}"- c["chars"] = _flat_chars(spoken_text(c, settings["read_titles"]))+ _name_files(chapters, settings, len(chapters))book = {"id": bid,"title": title,@@ -459,6 +491,40 @@ def _create(return book+def _name_files(chapters: list[dict[str, Any]], settings: dict[str, Any], total: int) -> None:+ """Files numbered by the chapter's place in the source (`number`), else by its place among those read."""+ width = max(2, len(str(total)))+ for i, c in enumerate(chapters):+ n = c.get("number") or i + 1+ c["file"] = f"{n:0{width}d} - {safe_name(c['title'], 60) or 'Chapter'}"+ c["chars"] = _flat_chars(spoken_text(c, settings["read_titles"]))+++def _add_chapters(+ data: config.DataDir, bid: str, chapters: list[dict[str, Any]], overrides: dict[str, Any] | None = None+) -> int:+ """Appends the chapters the book lacks (by text), read on with the voices in ``overrides`` from now on."""+ with _LOCK:+ book, state = _load(data, bid)+ _apply(book, overrides or {})+ have = {str(c.get("text") or "") for c in book["chapters"]}+ new = [c for c in chapters if c["text"] not in have]+ if not new:+ return 0+ numbers = [int(c.get("number") or 0) for c in book["chapters"] + new]+ _name_files(new, book["settings"], max([len(book["chapters"]) + len(new), *numbers]))+ start = len(book["chapters"])+ for i, c in enumerate(new):+ c.setdefault("number", start + i + 1)+ book["chapters"] += new+ book["words"] = sum(int(c["words"]) for c in book["chapters"])+ state["chapters"] += [_new_chapter_state() for _ in new]+ state["status"] = "paused" if state.get("status") == "done" else state.get("status")+ _write_json(book_dir(data, bid) / "book.json", book)+ _save_state(data, bid, state)+ return len(new)++def _folder_taken(data: config.DataDir, folder: Path) -> list[bool]:out = []try:@@ -525,7 +591,10 @@ async def _start_new(ctx: Context, data: config.DataDir, params: dict[str, Any],settings = _settings(params)chapters = _clean_chapters(params.get("chapters"))title = re.sub(r"\s+", " ", str(params.get("title") or "")).strip() or "Book"- v = await _voice(ctx, data, settings)+ if settings["cast"] and not cast.installed(data.root):+ raise EngineError("not_ready", "Character voices are not installed: add them in Settings > Components")+ vs = await _voices(ctx, data, settings)+ v = vs["narrator"]if tts.is_busy():raise EngineError("busy", tts.busy_message("another generation is running"))settings["output_format"] = v.out_fmt@@ -533,7 +602,7 @@ async def _start_new(ctx: Context, data: config.DataDir, params: dict[str, Any],fmt = params.get("format") if isinstance(params.get("format"), str) else Nonebook = await aio.run_io(_create, data, title, source, fmt, chapters, settings, ref)try:- job = _start(ctx, data, book["id"], v)+ job = _start(ctx, data, book["id"], vs)except EngineError: # another job took the slot while the project was writtenawait aio.run_io(shutil.rmtree, book_dir(data, book["id"]), ignore_errors=True)raise@@ -551,6 +620,176 @@ async def _start_new(ctx: Context, data: config.DataDir, params: dict[str, Any],}+def _cast_summary(found: dict[str, Any]) -> dict[str, Any]:+ return {+ "mode": found.get("mode"),+ "narrator": found.get("narrator"),+ "characters": (found.get("characters") or [])[:CAST_LIST],+ "lines": found.get("lines"),+ "voices": found.get("voices"),+ }+++@method("book.cast")+async def book_cast(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ """Finds who speaks in a book before it is read: the result is kept, and book.start of the same chapters, language+ and mode uses it. ``"again": true`` reads every chapter with speech again, kept results or not."""+ data = config.data_dir(ctx)+ chapters = _clean_chapters(params.get("chapters"))+ lang, _ = tts.speech_language(params)+ mode = _cast_mode(params)+ again = params.get("again", False)+ if not isinstance(again, bool):+ raise EngineError("bad_request", "'again' must be true or false")+ texts = [c["text"] for c in chapters]+ key = cast.key(texts, lang, mode)+ found = None if again else await aio.run_io(_cached_cast, data, texts, lang, mode)+ if found is not None:+ return {"key": key, "job": None, **_cast_summary(found)}+ if not cast.installed(data.root):+ raise EngineError("not_ready", "Character voices are not installed: add them in Settings > Components")+ book = {"settings": {"language": lang, "cast": mode}}+ if again:+ todo = [t for t in texts if any(cast.has_speech(p) for p in cast.paragraphs(t))]+ await aio.run_io(lambda: _cast_path(data, key).unlink(missing_ok=True))+ else:+ todo = await aio.run_io(_unsearched, data, texts, lang, mode)+ job = tts.start_exclusive(+ ctx, lambda j: _cast_job(ctx, j, data, texts, todo, book, key), "another generation is running", CAST_HOLDER+ )+ _CASTING[0] = job+ return {"key": key, "job": job}+++async def _cast_job(+ ctx: Context, job: str, data: config.DataDir, texts: list[str], todo: list[str], book: dict[str, Any], key: str+) -> None:+ def progress(pct: float) -> None:+ ctx.emit("book.cast_progress", {"key": key, "pct": round(pct * 100, 1)}, job=job)++ def end(event: str, payload: dict[str, Any]) -> None:+ _CASTING[0] = None+ tts.release_job(job)+ ctx.emit(event, {"key": key, **payload}, job=job)++ try:+ progress(0.0)+ found = await _search(ctx, data, texts, todo, book, progress, job)+ end("book.cast_done", _cast_summary(found))+ except asyncio.CancelledError:+ end("book.cast_error", {"code": "cancelled", "message": "finding the speakers was cancelled"})+ except EngineError as exc:+ end("book.cast_error", {"code": exc.code, "message": exc.message})+ except Exception as exc:+ log.exception("finding the speakers failed")+ end("book.cast_error", {"code": "internal", "message": f"{type(exc).__name__}: {exc}"})+ finally:+ _CASTING[0] = None+ tts.release_job(job)+++@method("book.cast_status")+async def book_cast_status(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ """``{"chapters": [{"title","text"}], "language", "cast"}`` -> ``{"searched": [bool, ...]}``: which chapters need no+ new search, one per chapter given (an empty one or one without speech needs none)."""+ data = config.data_dir(ctx)+ raw = params.get("chapters")+ if not isinstance(raw, list):+ raise EngineError("bad_request", '\'chapters\' must be a list of {"title", "text"}')+ lang, _ = tts.speech_language(params)+ mode = _cast_mode(params)+ texts = [str(c.get("text") or "").strip() if isinstance(c, dict) else "" for c in raw]+ index = await aio.run_io(_load_index, data, lang, mode)+ speech = [any(cast.has_speech(p) for p in cast.paragraphs(t)) for t in texts]+ return {"searched": [_chapter_cast(index, t) is not None for t in texts], "speech": speech}+++@method("book.cast_cancel")+async def book_cast_cancel(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ job = _CASTING[0]+ if job is None:+ return {"cancelled": False}+ ctx.cancel(job)+ return {"cancelled": True}+++async def _overrides(data: config.DataDir, params: dict[str, Any]) -> dict[str, Any]:+ """The settings a request changes for the chapters read from now on: ``voice_id``, ``voices`` (the roles given),+ ``cast`` and the flags; each voice named must have a recording."""+ out: dict[str, Any] = {}+ voice_id = params.get("voice_id")+ if voice_id is not None:+ if not isinstance(voice_id, str) or not voice_id:+ raise EngineError("bad_request", "'voice_id' must be a voice id")+ out["voice_id"] = voice_id+ roles = params.get("voices")+ if roles is not None:+ if not isinstance(roles, dict) or any(r not in ("men", "women") for r in roles):+ raise EngineError("bad_request", '\'voices\' must be {"men"?, "women"?}')+ out["voices"] = {r: v for r, v in roles.items() if v is None or isinstance(v, str)}+ if params.get("cast") is not None:+ out["cast"] = _cast_mode(params)+ for flag in ("m4b", "read_titles", "exact_stress"):+ if params.get(flag) is not None:+ if not isinstance(params[flag], bool):+ raise EngineError("bad_request", f"'{flag}' must be true or false")+ out[flag] = params[flag]+ for vid in [out.get("voice_id"), *(out.get("voices") or {}).values()]:+ if vid:+ await aio.run_io(voices.read_meta, data, vid)+ if not await aio.run_io(data.reference(vid).is_file):+ raise EngineError("not_found", "this voice has no recording yet (reference.wav is missing)")+ return out+++def _apply(book: dict[str, Any], overrides: dict[str, Any]) -> bool:+ """Puts ``overrides`` in the book's settings; whether one changed."""+ st, changed = book["settings"], False+ for key, given in overrides.items():+ value = {**(st.get("voices") or {}), **given} if key == "voices" else given+ if st.get(key) != value:+ st[key] = value+ changed = True+ return changed+++def _set_settings(data: config.DataDir, bid: str, overrides: dict[str, Any]) -> dict[str, Any]:+ with _LOCK:+ book, _ = _load(data, bid)+ if _apply(book, overrides):+ _write_json(book_dir(data, bid) / "book.json", book)+ return book+++@method("book.add")+async def book_add(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ """``{"id", "chapters": [{"title","text","number"?}], "voice_id"?, "voices"?, "cast"?}`` -> as ``book.get``: adds+ the chapters the book lacks, read into its folder by ``book.resume`` (with the voices given, from now on)."""+ data = config.data_dir(ctx)+ bid = str(params.get("id") or "")+ if bid in _RUNNING or bid in _REREADING:+ raise EngineError("busy", "this book is being read; pause it first")+ chapters = _clean_chapters(params.get("chapters"))+ overrides = await _overrides(data, params)+ added = await aio.run_io(_add_chapters, data, bid, chapters, overrides)+ if not added:+ raise EngineError("bad_request", "these chapters are in the book already")+ book, state = await aio.run_io(_load, data, bid)+ return {**summary(data, book, state), "settings": book.get("settings"), "chapter_list": _chapter_rows(book, state)}+++@method("book.settings")+async def book_settings(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:+ """``{"id", ...}`` -> ``{}``: the settings of ``book.add`` for what the book reads from now on, also while it is+ read (an M4B ticked then is made when the reading ends)."""+ data = config.data_dir(ctx)+ bid = str(params.get("id") or "")+ overrides = await _overrides(data, params)+ if overrides:+ await aio.run_io(_set_settings, data, bid, overrides)+ return {}++@method("book.resume")async def book_resume(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:data = config.data_dir(ctx)@@ -560,6 +799,9 @@ async def book_resume(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:raise EngineError("busy", "this book is being read already")if state.get("status") == "done":raise EngineError("bad_request", "this book is finished")+ overrides = await _overrides(data, params)+ if overrides:+ book = await aio.run_io(_set_settings, data, bid, overrides)return {"id": bid,"folder": book["folder"],@@ -569,17 +811,18 @@ async def book_resume(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:async def _resume(ctx: Context, data: config.DataDir, bid: str, book: dict[str, Any]) -> dict[str, Any]:- v = await _voice(ctx, data, book["settings"])- return {"job": _start(ctx, data, bid, v), **v.choice.fields(), **v.ref_fields}+ vs = await _voices(ctx, data, book["settings"])+ v = vs["narrator"]+ return {"job": _start(ctx, data, bid, vs), **v.choice.fields(), **v.ref_fields}-def _start(ctx: Context, data: config.DataDir, bid: str, v: _Voice) -> str:+def _start(ctx: Context, data: config.DataDir, bid: str, vs: dict[str, _Voice]) -> str:"""Loop thread, with no await since the busy checks."""if bid in _RUNNING:raise EngineError("busy", "this book is being read already")if bid in _REREADING:raise EngineError("busy", "this book is being reread")- job = tts.start_exclusive(ctx, lambda j: _run(ctx, j, data, bid, v), "another generation is running", HOLDER)+ job = tts.start_exclusive(ctx, lambda j: _run(ctx, j, data, bid, vs), "another generation is running", HOLDER)_RUNNING[bid] = job_STOP.pop(bid, None)return job@@ -696,14 +939,8 @@ async def _reread_checked(data: config.DataDir, bid: str, params: dict[str, Any]chapters = sorted(set(raw))else:raise EngineError("bad_request", f"'chapters' must be chapter indexes from 0 to {n - 1}")- voice_id = params.get("voice_id")- if voice_id is not None:- if not isinstance(voice_id, str) or not voice_id:- raise EngineError("bad_request", "'voice_id' must be a voice id")- await aio.run_io(voices.read_meta, data, voice_id)- if not await aio.run_io(data.reference(voice_id).is_file):- raise EngineError("not_found", "this voice has no recording yet (reference.wav is missing)")- await aio.run_io(_reread, data, bid, book, state, voice_id, chapters)+ overrides = await _overrides(data, params)+ await aio.run_io(_reread, data, bid, book, state, overrides, chapters)return {**summary(data, book, state), "settings": book.get("settings"), "chapter_list": _chapter_rows(book, state)}@@ -712,12 +949,11 @@ def _reread(bid: str,book: dict[str, Any],state: dict[str, Any],- voice_id: str | None,+ overrides: dict[str, Any],chapters: list[int],) -> None:with _LOCK:- if voice_id is not None and voice_id != book["settings"].get("voice_id"):- book["settings"]["voice_id"] = voice_id+ if _apply(book, overrides):_write_json(book_dir(data, bid) / "book.json", book)for k in chapters:cs = state["chapters"][k]@@ -780,31 +1016,58 @@ def _pcm(x: np.ndarray) -> bytes:return (np.clip(x, -1.0, 1.0) * 32767.0).round().astype("<i2").tobytes()+Seg = tuple[str, int, str, str]++def _prepare_chapter(- data: config.DataDir, bid: str, k: int, book: dict[str, Any], state: dict[str, Any], count: Any-) -> list[tuple[str, int, str]]:+ data: config.DataDir,+ bid: str,+ k: int,+ book: dict[str, Any],+ state: dict[str, Any],+ count: Any,+ roles: dict[str, Any] | None = None,+) -> list[Seg]:with _LOCK:- return _prepare_chapter_locked(data, bid, k, book, state, count)+ return _prepare_chapter_locked(data, bid, k, book, state, count, roles)def _prepare_chapter_locked(- data: config.DataDir, bid: str, k: int, book: dict[str, Any], state: dict[str, Any], count: Any-) -> list[tuple[str, int, str]]:+ data: config.DataDir,+ bid: str,+ k: int,+ book: dict[str, Any],+ state: dict[str, Any],+ count: Any,+ roles: dict[str, Any] | None,+) -> list[Seg]:+ """roles: the chapter in the cast, its "roles" and "remarks" by paragraph."""path = _segs_path(data, bid, k)cs = state["chapters"][k]saved = _read_json(path)- segs: list[tuple[str, int, str]] | None = None+ segs: list[Seg] | None = Noneif saved and cs.get("status") == "partial":- segs = [(str(t), int(p), str(kind)) for t, p, kind in saved.get("segments") or []]+ segs = [+ (str(s[0]), int(s[1]), str(s[2]), str(s[3]) if len(s) > 3 else "narrator")+ for s in saved.get("segments") or []+ ]if not segs:ch = book["chapters"][k]text = str(ch.get("text") or "")title = ch.get("title") if book["settings"].get("read_titles", True) else Noneif title and heading_in_text(str(title), text):title = None- segs = narration.segments(title, text, count)+ found = roles or {}+ said, cut = dict(found.get("roles") or {}), dict(found.get("remarks") or {})+ lang = str(book["settings"].get("language") or "")+ split = (+ None+ if roles is None+ else (lambda j, par: cast.pieces(par, said.get(str(j), "n"), cut.get(str(j), ()), lang))+ )+ segs = narration.voiced_segments(title, text, count, split)if not segs:- segs = [(".", narration.PAUSES["end"], "end")]+ segs = [(".", narration.PAUSES["end"], "end", "narrator")]path.parent.mkdir(parents=True, exist_ok=True)_write_json(path, {"segments": [list(s) for s in segs]})cs.clear()@@ -1038,7 +1301,7 @@ def _make_m4b(lst, meta = work / "m4b.txt", work / "m4b.meta"rows, t = [], 0lines = [";FFMETADATA1", f"title={_ffmeta(str(book.get('title') or 'Book'))}", "genre=Audiobook"]- for c, cs in zip(book["chapters"], state["chapters"]):+ for c, cs in sorted(zip(book["chapters"], state["chapters"]), key=lambda p: str(p[0].get("file") or "")):if cs.get("status") != "done" or not cs.get("path"):continuerows.append("file '" + str(cs["path"]).replace("'", "'\\''") + "'")@@ -1152,7 +1415,214 @@ def _progress_locked(book: dict[str, Any], state: dict[str, Any], k: int) -> dic}-async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, v: _Voice) -> None:+@dataclass+class _Live:+ """A voice as a running book uses it: the reference it is spoken from and how it is converted."""++ v: _Voice+ choice: accent.Choice+ zs: zsvc.Bound | None+ index_rate: float+ synth_ref: str | Path+ ref_text: str | None+ pitch: int+++async def _live(v: _Voice) -> _Live:+ choice, zs, index_rate = v.choice, v.zs, v.rvc_rate+ native = await aio.run_io(accent.prepare, choice, v.ref, v.voice_match) if choice.accent == "native-us" else None+ if choice.accent == "native-us" and native is None:+ choice = accent.Choice("own", choice.native_voice, "unavailable")+ if native is None and choice.converter == "zero-shot":+ zs = None+ if native is not None:+ return _Live(v, choice, zs, native.index_rate, native.ref.path, native.ref.text, native.pitch)+ return _Live(v, choice, zs, index_rate, v.ref, None, 0)+++def _cast_path(data: config.DataDir, key: str) -> Path:+ return data.root / "cast" / f"{key}.json"+++def _index_path(data: config.DataDir, language: str, mode: str) -> Path:+ return data.root / "cast" / f"lines-{language}-{mode}.json"+++def _line_keys(paras: list[str], i: int) -> list[str]:+ """With both neighbours, with one, then alone: a line keeps its result when chapters are joined or split."""+ prev = paras[i - 1] if i else ""+ nxt = paras[i + 1] if i + 1 < len(paras) else ""++ def h(*parts: str) -> str:+ return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:20]++ return [h("c", prev, paras[i], nxt), h("l", prev, paras[i]), h("r", paras[i], nxt), h("p", paras[i])]+++def _load_index(data: config.DataDir, language: str, mode: str) -> dict[str, Any]:+ return _read_json(_index_path(data, language, mode)) or {"entries": [], "keys": {}}+++def _save_cast(data: config.DataDir, key: str, found: dict[str, Any], texts: list[str]) -> None:+ """The book's result, and each speech line's in an index by its text: any part of the book, joined or split+ differently, is read later without a new search."""+ path = _cast_path(data, key)+ path.parent.mkdir(parents=True, exist_ok=True)+ _write_json(path, found)+ lang, mode = str(found.get("language")), str(found.get("mode"))+ index = _load_index(data, lang, mode)+ entries, keys = index["entries"], index["keys"]+ for text, ch in zip(texts, found.get("chapters") or [], strict=False):+ paras = cast.paragraphs(text)+ for i, par in enumerate(paras):+ if not cast.has_speech(par):+ continue+ n = str(i)+ entries.append(+ {+ "r": (ch.get("roles") or {}).get(n),+ "s": (ch.get("speakers") or {}).get(n),+ "m": (ch.get("remarks") or {}).get(n),+ "b": key,+ }+ )+ *exact, alone = _line_keys(paras, i)+ for k in exact:+ keys[k] = len(entries) - 1+ keys[alone] = len(entries) - 1 if keys.get(alone, len(entries) - 1) == len(entries) - 1 else -1+ _write_json(_index_path(data, lang, mode), index)+++def _chapter_cast(index: dict[str, Any], text: str) -> dict[str, Any] | None:+ """A chapter's result put together from its lines found before; None while one of them was never searched."""+ entries, keys = index["entries"], index["keys"]+ paras = cast.paragraphs(text)+ chapter: dict[str, dict[str, Any]] = {"roles": {}, "speakers": {}, "remarks": {}}+ books: Counter[str] = Counter()+ for i, par in enumerate(paras):+ if not cast.has_speech(par):+ continue+ at = next((keys[k] for k in _line_keys(paras, i) if keys.get(k, -1) >= 0), None)+ if at is None:+ return None+ e = entries[at]+ books[e["b"]] += 1+ for field, name in (("r", "roles"), ("s", "speakers"), ("m", "remarks")):+ if e.get(field) is not None:+ chapter[name][str(i)] = e[field]+ return {"book": books.most_common(1)[0][0] if books else None, "chapter": chapter}+++def _unsearched(data: config.DataDir, texts: list[str], language: str, mode: str) -> list[str]:+ index = _load_index(data, language, mode)+ return [t for t in texts if _chapter_cast(index, t) is None]+++def _merged_characters(books: list[dict[str, Any]]) -> list[dict[str, Any]]:+ lines: Counter[str] = Counter()+ gender: dict[str, str] = {}+ for b in books:+ for c in b.get("characters") or []:+ lines[c["name"]] += int(c.get("lines") or 0)+ gender.setdefault(c["name"], c.get("gender", ""))+ return [{"name": n, "gender": gender[n], "lines": k} for n, k in lines.most_common()]+++def _cached_cast(data: config.DataDir, texts: list[str], language: str, mode: str) -> dict[str, Any] | None:+ """The result for these chapters, put together from the chapters found before; None if one was never searched."""+ key = cast.key(texts, language, mode)+ found = _read_json(_cast_path(data, key))+ if found is not None:+ return found+ index = _load_index(data, language, mode)+ parts = [_chapter_cast(index, text) for text in texts]+ if any(p is None for p in parts):+ return None+ keys = Counter(str(p["book"]) for p in parts if p.get("book"))+ books = [b for k, _ in keys.most_common() if (b := _read_json(_cast_path(data, k)))]+ if not books: # no speech in any of them: nothing to search, every line is the narrator's+ books = [{"version": cast.VERSION, "mode": mode, "language": language, "narrator": {}, "characters": []}]+ chapters = [p["chapter"] for p in parts]+ counts = Counter(r for ch in chapters for r in (ch.get("roles") or {}).values())+ found = {+ **books[0],+ "characters": _merged_characters(books),+ "lines": {"men": counts["m"], "women": counts["f"], "narrator": counts["n"] + counts["e"]},+ "chapters": chapters,+ }+ _cast_path(data, key).parent.mkdir(parents=True, exist_ok=True)+ _write_json(_cast_path(data, key), found) # its chapters keep pointing at the search that found them+ return found+++def _cast_key(book: dict[str, Any]) -> str:+ st = book["settings"]+ return cast.key([str(c.get("text") or "") for c in book["chapters"]], str(st.get("language")), str(st["cast"]))+++async def _cast_stage(+ ctx: Context, job: str, data: config.DataDir, bid: str, book: dict[str, Any], state: dict[str, Any]+) -> list[dict[str, Any]]:+ """Each chapter's speech paragraphs, their roles and remarks, found once per book (and kept from book.cast)."""+ texts = [str(c.get("text") or "") for c in book["chapters"]]+ st = book["settings"]+ found = await aio.run_io(_cached_cast, data, texts, str(st.get("language")), str(st["cast"]))+ if found is None:+ k = next((k for k, cs in enumerate(state["chapters"]) if cs.get("status") != "done"), 0)++ def progress(pct: float) -> None:+ ctx.emit(+ "book.progress",+ {**_progress(book, state, k), "stage": "cast", "stage_pct": round(pct * 100, 1)},+ job=job,+ )++ progress(0.0)+ todo = await aio.run_io(_unsearched, data, texts, str(st.get("language")), str(st["cast"]))+ found = await _search(ctx, data, texts, todo, book, progress, job)+ return list(found.get("chapters") or [])+++async def _search(+ ctx: Context,+ data: config.DataDir,+ texts: list[str],+ todo: list[str],+ book: dict[str, Any],+ progress: cast.Progress,+ job: str,+) -> dict[str, Any]:+ """Searches only the chapters never searched (`todo`), then puts the result for `texts` together."""+ st = book["settings"]+ lang, mode = str(st.get("language")), str(st["cast"])+ if todo:+ found = await _analyze(ctx, data, todo, book, progress, job)+ await aio.run_io(_save_cast, data, cast.key(todo, lang, mode), found, todo)+ whole = await aio.run_io(_cached_cast, data, texts, lang, mode)+ if whole is None:+ raise EngineError("internal", "the speakers found could not be put together")+ return whole+++async def _analyze(+ ctx: Context,+ data: config.DataDir,+ texts: list[str],+ book: dict[str, Any],+ progress: cast.Progress,+ job: str,+) -> dict[str, Any]:+ """The analysis with the speech models out of the GPU's way, loaded again after."""+ st = book["settings"]+ await tts.release_gpu(ctx, job)+ try:+ return await cast.analyze(data.root, texts, str(st.get("language")), str(st["cast"]), progress)+ finally:+ await tts.load_models(ctx)+++async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, vs: dict[str, _Voice]) -> None:+ v = vs["narrator"]t_start = time.time()jobdir = data.tmp / jobbook: dict[str, Any] | None = None@@ -1168,93 +1638,118 @@ async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, v: _Voicestate["status"], state["error"] = "running", Noneawait aio.run_io(_save_state, data, bid, state)await aio.run_io(jobdir.mkdir, parents=True, exist_ok=True)- choice, zs, index_rate, worker = v.choice, v.zs, v.rvc_rate, v.worker- native = (- await aio.run_io(accent.prepare, choice, v.ref, v.voice_match) if choice.accent == "native-us" else None- )- if choice.accent == "native-us" and native is None:- choice = accent.Choice("own", choice.native_voice, "unavailable")- if native is None and choice.converter == "zero-shot":- zs = None- synth_ref, ref_text, pitch = (native.ref.path, native.ref.text, native.pitch) if native else (v.ref, None, 0)- if native is not None:- index_rate = native.index_rate+ roles = await _cast_stage(ctx, job, data, bid, book, state) if book["settings"].get("cast") else None+ lives = {name: await _live(vv) for name, vv in vs.items()}+ choice = lives["narrator"].choiceawait speech.yield_gpu()todo_ch = [k for k, cs in enumerate(state["chapters"]) if cs.get("status") != "done"]log.info(- "book %s (%s): %d of %d chapter(s) to read, %s, accent %s",+ "book %s (%s): %d of %d chapter(s) to read, %s, accent %s, voices %s",bid,job,len(todo_ch),len(book["chapters"]),v.lang,choice.accent,+ ", ".join(lives),)- turn = zs.turn if zs is not None else None- todo: asyncio.Queue[tuple[int, int, int, str | None, str, int, str] | None] = asyncio.Queue(maxsize=2)+ todo: asyncio.Queue[tuple[int, int, int, str | None, str, int, str, str] | None] = asyncio.Queue(maxsize=2)last_at = [time.time()]session = {"audio_s": 0.0, "elapsed_s": 0.0, "retries": 0}- judge = narration.Judge()+ judges: dict[str, narration.Judge] = {}for cs in state["chapters"]:for m in cs.get("stats") or []:if m.get("spc") is not None and m.get("kind") != "title":- judge.accept(m)-- async def synth(k: int, i: int, seg: str, tag: str = "tts") -> str:- async with zsvc.gpu_turn(turn):+ judges.setdefault(str(m.get("voice") or "narrator"), narration.Judge()).accept(m)++ def who(voice: str) -> tuple[_Live, float, str]:+ """The voice that reads a segment, its expressiveness, and the judge it is measured against."""+ if voice in lives:+ return lives[voice], max(v.temperature, narration.CHARACTER_EXPRESSIVENESS), voice+ if voice == "expressive":+ return lives["narrator"], narration.EXPRESSIVE_NARRATOR, voice+ return lives["narrator"], v.temperature, "narrator"++ async def synth(k: int, i: int, seg: str, voice: str, tag: str = "tts") -> str:+ lv, temperature, _ = who(voice)+ async with zsvc.gpu_turn(lv.zs.turn if lv.zs is not None else None):return await v.backend.synthesize(seg,v.lang,- synth_ref,+ lv.synth_ref,SynthParams(out_path=jobdir / f"c{k}_s{i}_{tag}.wav",- temperature=v.temperature,+ temperature=temperature,quality=v.quality,duration_factor=v.duration_factor,- reference_text=ref_text,+ reference_text=lv.ref_text,),)- async def convert(k: int, i: int, path: str, tag: str = "") -> str | Path:- if zs is not None:+ async def convert(k: int, i: int, path: str, voice: str, tag: str = "") -> str | Path:+ lv = who(voice)[0]+ if lv.zs is not None:dst = jobdir / f"c{k}_s{i}_vc{tag}.wav"- await zs.convert(path, dst)+ await lv.zs.convert(path, dst)return dst- if worker is not None:+ if lv.v.worker is not None:dst = jobdir / f"c{k}_s{i}_rvc{tag}.wav"- await worker.convert(path, dst, v.pth, v.idx, index_rate, pitch=pitch)+ await lv.v.worker.convert(path, dst, lv.v.pth, lv.v.idx, lv.index_rate, pitch=lv.pitch)return dstreturn pathasync def produce() -> None:for k in todo_ch:- segs = await aio.run_io(_prepare_chapter, data, bid, k, book, state, v.backend.count_tokens)+ parts = None if roles is None else roles[k]+ segs = await aio.run_io(_prepare_chapter, data, bid, k, book, state, v.backend.count_tokens, parts)start = int(state["chapters"][k].get("segment") or 0)ctx.emit("book.progress", _progress(book, state, k), job=job)for i in range(start, len(segs)):- seg, pause, kind = segs[i]+ seg, pause, kind, voice = segs[i]t0 = time.time()- path = await synth(k, i, seg)+ path = await synth(k, i, seg, voice)log.info(- "book %s ch %d seg %d/%d (%s): %.2fs", bid, k + 1, i + 1, len(segs), kind, time.time() - t0+ "book %s ch %d seg %d/%d (%s, %s): %.2fs",+ bid,+ k + 1,+ i + 1,+ len(segs),+ kind,+ voice,+ time.time() - t0,)- await todo.put((k, i, len(segs), path, seg, pause, kind))+ await todo.put((k, i, len(segs), path, seg, pause, kind, voice))if start >= len(segs): # every segment was committed before a stop: only the chapter file is missing- await todo.put((k, len(segs) - 1, len(segs), None, "", 0, ""))+ await todo.put((k, len(segs) - 1, len(segs), None, "", 0, "", "narrator"))await todo.put(None)- async def add_segment(k: int, i: int, path: str, seg: str, pause: int, kind: str) -> None:+ async def add_segment(k: int, i: int, path: str, seg: str, pause: int, kind: str, voice: str) -> None:files = [path]- src = await convert(k, i, path)+ src = await convert(k, i, path, voice)files.append(src)x, m = await aio.run_io(_segment_audio, src, len(seg))+ for again in range(EMPTY_TRIES):+ if m["dur"] >= EMPTY_S:+ break+ log.warning("book %s ch %d seg %d: no speech in %r, made again", bid, k + 1, i + 1, seg)+ p_again = await synth(k, i, seg, voice, f"empty{again}")+ s_again = await convert(k, i, p_again, voice, f"e{again}")+ files += [p_again, s_again]+ x, m = await aio.run_io(_segment_audio, s_again, len(seg))+ silent = m["dur"] < EMPTY_S+ if silent:+ x = au.silence(narration.PAUSES["voice"])+ m = {**m, "dur": round(len(x) / SR, 3)}+ judged_by = who(voice)[2]+ judge = judges.setdefault(judged_by, narration.Judge())# a title is read differently on purpose: it neither judges nor is judged- score, why = judge.deviation(m) if QUALITY_CHECKS and kind != "title" else (0.0, [])+ checked = QUALITY_CHECKS and kind != "title" and not silent+ score, why = judge.deviation(m) if checked else (0.0, [])retried = Noneif score > 1.0:session["retries"] += 1- p2 = await synth(k, i, seg, "tts2")- s2 = await convert(k, i, p2, "2")+ p2 = await synth(k, i, seg, voice, "tts2")+ s2 = await convert(k, i, p2, voice, "2")files += [p2, s2]x2, m2 = await aio.run_io(_segment_audio, s2, len(seg))score2, _why2 = judge.deviation(m2)@@ -1276,14 +1771,15 @@ async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, v: _Voice)if score2 < score:x, m = x2, m2- fix_db = judge.level_fix_db(m) if QUALITY_CHECKS else 0.0+ fix_db = judge.level_fix_db(m) if checked else 0.0if fix_db:x = x * np.float32(10 ** (fix_db / 20.0))- if kind != "title":+ if kind != "title" and not silent:judge.accept(m)stat = {"i": i,"kind": kind,+ "voice": judged_by,"pause_ms": pause,"chars": len(seg),"dur": m["dur"],@@ -1315,9 +1811,9 @@ async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, v: _Voice)async def consume() -> None:- async for k, i, n, path, seg, pause, kind in aio.queue_items(todo):+ async for k, i, n, path, seg, pause, kind, voice in aio.queue_items(todo):if path is not None:- await add_segment(k, i, path, seg, pause, kind)+ await add_segment(k, i, path, seg, pause, kind, voice)if i == n - 1:# Shielded like the commit; a stop meanwhile takes effect once the chapter is reported.fut = asyncio.ensure_future(aio.run_io(_finish_chapter, data, bid, book, state, k, v.out_fmt))@@ -1390,7 +1886,8 @@ async def _run(ctx: Context, job: str, data: config.DataDir, bid: str, v: _Voicetodo = asyncio.Queue(maxsize=2)last_at[0] = time.time()m4b = None- if book["settings"].get("m4b"):+ latest = await aio.run_io(_read_json, book_dir(data, bid) / "book.json") # M4B may be ticked while it reads+ if (latest or book)["settings"].get("m4b"):last_k = len(book["chapters"]) - 1ctx.emit("book.progress", {**_progress(book, state, last_k), "stage": "m4b", "stage_pct": 0.0}, job=job)diff --git a/engine/src/mimvox_engine/cast.py b/engine/src/mimvox_engine/cast.pynew file mode 100644index 0000000..115b93d--- /dev/null+++ b/engine/src/mimvox_engine/cast.py@@ -0,0 +1,722 @@+"""Who speaks each line of a book: a local instruct model (llama.cpp's llama-server, started only while it reads)+marks every paragraph with speech as a man's or a woman's line, the narrator's, a thought or a letter."""++from __future__ import annotations++import asyncio+import contextlib+import hashlib+import importlib.util+import json+import logging+import os+import re+import socket+import sys+import time+import urllib.error+import urllib.request+from collections import Counter, deque+from collections.abc import Callable, Sequence+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from . import aio, components, narration+from .registry import EngineError++log = logging.getLogger("mimvox.cast")++COMPONENT = "cast"+LLAMA_DIR = "llama"+MODEL_DIR = "llm"+MODEL_FILE = "gemma-4-12b-it-Q4_K_M.gguf"+CTX = 12288+START_TIMEOUT_S = 240.0+REQUEST_TIMEOUT_S = 600.0+BEFORE, BODY, AFTER = 3000, 8000, 2000 # characters of context before, numbered text, context after+CLIP = 1500+KNOWN = 40 # characters named in each request so that one person keeps one name+TOKENS_PER_LINE = 14+NARRATOR_SAMPLE = 6000+OPENING = 3000+MODES = ("fast", "careful")+VERSION = 2++GRAMMAR = 'root ::= line+\nline ::= "[" [0-9]+ "] " [mfixtl] " " [^\\n\\[\\](|]{1,40} "\\n"'+# Remarks: the narrator's words copied out of a dash line; never a capital, a dash or a quote first, so that no spoken+# words can be copied, and at most three, so that a loop cannot start.+REMARK_GRAMMAR = (+ 'root ::= line+\nline ::= "[" [0-9]+ "]" (" -" | remark (remark remark?)?) "\\n"\n'+ 'remark ::= " | " [^\\n|—–«»"“”„「」『』A-ZÀ-ÖØ-ÞА-ЯЁІЇЄҐΑ-Ω] [^\\n|—–«»"“”„「」『』]{0,120}'+)+REMARK_LINE = re.compile(r"^\[(\d+)\]((?:\s*\|[^|\n]+)*)", re.MULTILINE)+REMARKS_PER_REQUEST = 40+TOKENS_PER_REMARK_LINE = 40+REMARKS_ASK = (+ "Each numbered line below is a line of dialogue from a book: it starts with a dash, then the spoken words, and it "+ "may contain remarks of the narrator (who speaks and how: 'dijo Carlos con mal humor', 's’écria-t-il', 'мовив "+ "він', 'disse Geppetto', 'he said, trying to hide it'). For every numbered line, copy each remark exactly as "+ "written, after ' | ', in order; never copy the spoken words. Answer ' -' for a line that is all speech.\n"+ "Example:\n[1] — Wait, Arthur,— he said, trying to hide it.— This is too much.\n"+ "[2] — Good morning.\n[3] — ¡Eh! — gritó el viajero —. Buen amigo, sujeta ese perro.\n"+ "Answer:\n[1] | he said, trying to hide it.\n[2] -\n[3] | gritó el viajero\n\nLines:\n"+)+LINE = re.compile(r"^\[(\d+)\] ([mfixtl]) (.+)$", re.MULTILINE)+SPEECH = re.compile(r'^\s*[—–]|["“«»„‹「『]')+DASH = re.compile(r"^\s*[—–]\s*")+DASH_SPLIT = re.compile(r"(?<=[,.!?…])\s*[—–]\s*")+QUOTE = re.compile(r'“[^”]*”|«[^»]*»|»[^«]*«|„[^“”]*[“”]|‹[^›]*›|「[^」]*」|『[^』]*』|"[^"]*"')+# The model copies remarks out of dash lines in any language; where it gave none, or one not in the line, these rules+# for the languages the app is used most in cut the line, then any dash after punctuation does.+# Spanish sets a remark off with a dash that need not follow punctuation: "—Hola —dijo él—. ¿Cómo estás?"+DASH_LOOSE = re.compile(r"\s+[—–]\s*|[—–](?=[\s.,;:!?]|$)")+# French puts the remark between commas: "— Eh! Monsieur, s’écria-t-il, monsieur, qui…", ", dit d’Artagnan."+FR_VERBS = (+ "dit|répondit|reprit|demanda|continua|ajouta|murmura|fit|répliqua|cria|poursuivit|interrompit|répéta|observa|"+ "s’écria|s'écria|s’exclama|s'exclama|insista|balbutia|hasarda|objecta|conclut|songea|pensa|se dit|se demanda|"+ "criait|disait|répondait|murmurait"+)+# Verbs a Spanish, Italian or Portuguese remark opens with, so that "— dijo Carlos — algo de…" is a remark although+# the speech goes on in small letters after it.+LOOSE_LANGUAGES = ("es", "it", "pt")+SAY = re.compile(+ r"^(?:(?:gli|le|lo|la|si|ne|mi|ti|ci|vi|se|me|te|nos|os|lhe)\s+)?"+ r"(?:dijo|dice|murmuró|exclamó|gritó|preguntó|respondió|contestó|añadió|repuso|replicó|observó|continuó|"+ r"interrumpió|afirmó|declaró|insistió|suspiró|pensó|indicó|manifestó|agregó|prosiguió|decía|preguntaba|"+ r"disse|rispose|gridò|domandò|esclamò|soggiunse|replicò|continuò|aggiunse|chiese|osservò|urlò|mormorò|"+ r"fece|ripeté|ripetè|borbottò|riprese|pensò|diceva|rispondeva|"+ r"respondeu|perguntou|exclamou|gritou|murmurou|acrescentou|continuou|replicou|retrucou)\b"+)+FR_REMARK = re.compile(+ rf"([,!?…])\s+((?:[\wàâçéèêëîïôûùüÿœ’'-]+-(?:t-\s?)?(?:il|elle|ils|elles|on)\b|(?:(?:avait|a)\s+)?(?:{FR_VERBS})\s+"+ r"[^,.!?;]{1,40})[^,.!?;]*)([,.!?;]|$)"+)+QUOTE_MIN_WORDS = 3+TITLES = {"mr", "mrs", "miss", "ms", "dr", "sir", "lady", "lord", "the", "містер", "місіс", "міс", "пан", "пані"}+GENERIC = {"", "narrator", "i", "me", "the narrator", "none", "unknown", "оповідач"}++RULES = (+ "How dialogue works in novels:\n"+ "- A paragraph with speech normally belongs to one speaker. In many languages (Ukrainian, Russian, French) "+ "speech starts with a dash instead of quotes, and the author's remark follows after another dash: "+ "'— Wait, Arthur,— he said.' The words after the second dash are the remark, not speech.\n"+ "- A tag such as 'said Elizabeth' or 'she cried' names the speaker; an action in the same paragraph "+ "('Emma smiled. \"...\"') usually does too.\n"+ "- Untagged lines in a conversation alternate between the people talking: count the turns back from the last "+ "tagged line.\n"+ "- A person addressed by name or as 'sir', 'papa', 'my dear' in one line is usually the one who answers in the "+ "next line.\n"+ "- A new paragraph means a new speaker unless the previous paragraph's speech was left open.\n"+ "- Read the paragraphs after a line as well: replies often reveal who spoke."+)+CODES = (+ "Gender codes: m = male character, f = female character, i = the book's first-person narrator ('I' who tells the "+ "story), l = written words read in the text (a letter, a note, a telegram, an inscription): give the writer's "+ "name, t = a thought: only when the text says the words were not said aloud ('was his thought', 'he thought', "+ "'she said to herself'); words said, told or concluded to another person are speech, even when they describe "+ "reasoning, x = not speech by one person (a title, a song, a word quoted in narration) or impossible to tell. Use "+ "the same name for the same character every time."+)+EXAMPLE = """Example:+[12] f Elizabeth+[13] m Mr. Darcy+[14] l Mr. Collins+[15] x song"""+PROMPTS = (+ "You are an expert reader of novels. In the text, some paragraphs start with a number in brackets, like [12]. "+ "For every numbered paragraph, decide who speaks its first spoken words.\n"+ + RULES+ + "\nAnswer with one line per numbered paragraph, in order: the number in brackets, the gender code, the speaker's "+ "name. " + CODES + "\n" + EXAMPLE,+ "You read novels closely and keep track of every conversation. Paragraphs marked with a number in brackets, like "+ "[12], contain spoken or written words. For each of them, work out which character says them, and whether that "+ "character is a man or a woman.\n"+ + RULES+ + "\nWrite one line per numbered paragraph, in order: the number in brackets, the gender code, the character's "+ "name. " + CODES + "\n" + EXAMPLE,+)+NARRATOR_SCHEMA = {+ "type": "object",+ "properties": {"first_person": {"type": "boolean"}, "name": {"type": "string"}},+ "required": ["first_person", "name"],+}+NARRATOR_ASK = (+ "Is this book told in the first person, by an 'I' who is a character? If so, what is that narrator's name (as "+ "other characters call them)? If the name is not in this text, give the name you know from the book, or an empty "+ "string.\n\n"+)+VOICE_TERMS = {+ "gender": ["male", "female"],+ "age": ["teenager", "young adult", "middle-aged", "elderly"],+ "pitch": ["very low pitch", "low pitch", "moderate pitch", "high pitch", "very high pitch"],+}+VOICES_ASK = (+ "An audiobook of this book will be read by synthetic voices: a narrator, one voice for every male character and "+ "one for every female character. Choose each voice from fixed terms.\n"+ "- The narrator: calm, measured and pleasant to listen to for hours. A book told in the first person gets its "+ "narrator's gender.\n"+ "- The male and the female voice: ordinary, natural people of the age of the book's main characters.\n"+ "Main speaking characters: {cast}\n"+ "{narrator}Opening of the book:\n"+ "{opening}"+)++Progress = Callable[[float], None]+++class LlmError(Exception):+ pass+++def server_path(data_root: str | Path) -> Path:+ name = "llama-server.exe" if sys.platform == "win32" else "llama-server"+ return Path(data_root) / "runtime" / LLAMA_DIR / name+++def model_path(data_root: str | Path) -> Path:+ return Path(data_root) / "runtime" / "models" / MODEL_DIR / MODEL_FILE+++def installed(data_root: str | Path, honour_off: bool = True) -> bool:+ if honour_off and components.off(COMPONENT):+ return False+ return server_path(data_root).is_file() and model_path(data_root).is_file()+++def _library_dirs() -> list[str]:+ """The CUDA runtime and cuBLAS that came with torch, which the CUDA build of llama-server links against."""+ out: list[str] = []+ for pkg in ("nvidia", "torch"):+ spec = importlib.util.find_spec(pkg)+ for root in (spec.submodule_search_locations or []) if spec else []:+ base = Path(root)+ found = [base / "lib"] if pkg == "torch" else [*base.glob("*/lib"), *base.glob("*/bin")]+ out += [str(p) for p in found if p.is_dir()]+ return out+++def _env() -> dict[str, str]:+ env = dict(os.environ)+ key = "PATH" if sys.platform == "win32" else "DYLD_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH"+ env[key] = os.pathsep.join([*_library_dirs(), *([env[key]] if env.get(key) else [])])+ return env+++def _free_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("127.0.0.1", 0))+ return int(s.getsockname()[1])+++class Server:+ """llama-server on a free local port, the whole model on the GPU."""++ def __init__(self, binary: Path, model: Path) -> None:+ self.binary, self.model = binary, model+ self.proc: asyncio.subprocess.Process | None = None+ self.port = 0+ self.tail: deque[str] = deque(maxlen=12)+ self._drain: asyncio.Task[None] | None = None++ async def start(self) -> None:+ self.port = _free_port()+ args = [+ str(self.binary),+ *("-m", str(self.model), "--host", "127.0.0.1", "--port", str(self.port)),+ *("-ngl", "999", "--fit", "off", "-c", str(CTX), "-np", "1", "-fa", "on"),+ *("-ctk", "q8_0", "-ctv", "q8_0", "--no-webui", "--reasoning", "off"),+ ]+ t0 = time.time()+ self.proc = await asyncio.create_subprocess_exec(+ *args,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.PIPE,+ env=_env(),+ )+ try:+ await asyncio.wait_for(self._until_ready(), START_TIMEOUT_S)+ except TimeoutError:+ await self.stop()+ raise LlmError(f"the language model did not start in {START_TIMEOUT_S:.0f} s") from None+ except BaseException:+ await self.stop()+ raise+ assert self.proc.stderr is not None+ self._drain = aio.spawn(self._read_rest(self.proc.stderr), name="llama-server-log")+ log.info("llama-server ready on port %d in %.1fs (%s)", self.port, time.time() - t0, self.model.name)++ async def _until_ready(self) -> None:+ assert self.proc is not None+ assert self.proc.stderr is not None+ while line := await self.proc.stderr.readline():+ text = line.decode("utf-8", "replace").rstrip()+ self.tail.append(text)+ if "listening on" in text or "server is listening" in text:+ return+ await self.proc.wait()+ raise LlmError(f"the language model stopped while loading ({' / '.join(list(self.tail)[-4:])})")++ async def _read_rest(self, stream: asyncio.StreamReader) -> None:+ while line := await stream.readline():+ self.tail.append(line.decode("utf-8", "replace").rstrip())++ async def stop(self) -> None:+ proc, self.proc = self.proc, None+ if proc is not None and proc.returncode is None:+ proc.terminate()+ try:+ await asyncio.wait_for(proc.wait(), 10.0)+ except TimeoutError:+ proc.kill()+ await proc.wait()+ if self._drain is not None:+ self._drain.cancel()+ with contextlib.suppress(asyncio.CancelledError, Exception):+ await self._drain++ def _post(self, body: dict[str, Any]) -> dict[str, Any]:+ req = urllib.request.Request(+ f"http://127.0.0.1:{self.port}/v1/chat/completions",+ data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT_S) as res: # noqa: S310 - a fixed local http URL+ return json.loads(res.read())+ except (urllib.error.URLError, OSError, ValueError) as exc:+ raise LlmError(f"the language model did not answer ({exc})") from None++ async def ask(self, messages: list[dict[str, str]], max_tokens: int, **extra: Any) -> str:+ body = {+ "messages": messages,+ "temperature": 0,+ "max_tokens": max_tokens,+ "chat_template_kwargs": {"enable_thinking": False},+ **extra,+ }+ res = await aio.run_io(self._post, body)+ try:+ return str(res["choices"][0]["message"]["content"] or "")+ except (KeyError, IndexError, TypeError):+ raise LlmError(f"unexpected answer from the language model: {str(res)[:200]}") from None+++def paragraphs(text: str) -> list[str]:+ """The paragraphs of a chapter as narration.segments reads them."""+ return [p for p in narration.clean_text(text).split("\n\n") if p.strip()]+++def has_speech(par: str) -> bool:+ return bool(SPEECH.search(par))+++def key(chapters: Sequence[str], language: str, mode: str) -> str:+ h = hashlib.sha256(json.dumps([VERSION, mode, language, list(chapters)], ensure_ascii=False).encode())+ return h.hexdigest()[:24]+++@dataclass+class Line:+ gender: str+ name: str+++@dataclass+class Window:+ """One request: paragraphs lo to hi numbered, with unnumbered context around them."""++ before: int+ lo: int+ hi: int+ after: int+ numbered: list[int] = field(default_factory=list)+++def windows(paras: Sequence[str], offset: int = 0) -> list[Window]:+ out: list[Window] = []+ start = 0+ while start < len(paras):+ budget = BODY // 2 if offset and start == 0 else BODY+ end, size = start, 0+ while end < len(paras) and (size + len(paras[end]) < budget or end == start):+ size += len(paras[end])+ end += 1+ b, s = start, 0+ while b > 0 and s + len(paras[b - 1]) < BEFORE:+ b -= 1+ s += len(paras[b])+ a, s = end, 0+ while a < len(paras) and s + len(paras[a]) < AFTER:+ s += len(paras[a])+ a += 1+ w = Window(b, start, end, a, [i for i in range(start, end) if has_speech(paras[i])])+ if w.numbered:+ out.append(w)+ start = end+ return out+++def _clip(p: str) -> str:+ return p if len(p) <= CLIP else p[:CLIP] + "…"+++def render(paras: Sequence[str], w: Window, only: Sequence[int] | None = None) -> str:+ marked = set(w.numbered if only is None else only)+ parts = [_clip(paras[i]) for i in range(w.before, w.lo)]+ parts += [(f"[{i}] " if i in marked else "") + _clip(paras[i]) for i in range(w.lo, w.hi)]+ parts += [_clip(paras[i]) for i in range(w.hi, w.after)]+ return "\n\n".join(parts)+++def _name(raw: str) -> str:+ """A character's name without the underscores and stray letters the model sometimes glues on ("Martin Eden_m")."""+ name = re.sub(r"_+\w?$", "", raw.strip()).replace("_", " ")+ return re.sub(r"\s+", " ", name).strip()+++def parse(answer: str, wanted: Sequence[int]) -> dict[int, Line]:+ keep = set(wanted)+ out: dict[int, Line] = {}+ for m in LINE.finditer(answer):+ n = int(m.group(1))+ if n in keep and n not in out:+ out[n] = Line(m.group(2), _name(m.group(3)))+ return out+++class Reader:+ """Reads one book: every speech paragraph of every chapter gets a Line."""++ def __init__(self, server: Server, prompt: str) -> None:+ self.server = server+ self.prompt = prompt+ self.names: Counter[str] = Counter()+ self.gender_of: dict[str, str] = {}++ async def _request(self, text: str, count: int) -> str:+ known = ", ".join(f"{n} {self.gender_of[n]}" for n, _ in self.names.most_common(KNOWN)) or "none yet"+ messages = [+ {"role": "system", "content": self.prompt},+ {"role": "user", "content": f"Characters met so far (name gender): {known}\n\nTEXT:\n{text}"},+ ]+ return await self.server.ask(messages, TOKENS_PER_LINE * count + 40, grammar=GRAMMAR)++ async def window(self, paras: Sequence[str], w: Window) -> dict[int, Line]:+ got = parse(await self._request(render(paras, w), len(w.numbered)), w.numbered)+ lost = [i for i in w.numbered if i not in got]+ if lost:+ half = len(lost) // 2 + 1+ for part in (lost[:half], lost[half:]):+ if not part:+ continue+ lo, hi = part[0], part[-1] + 1+ sub = Window(max(w.before, lo - 25), lo, hi, min(len(paras), hi + 8), part)+ got.update(parse(await self._request(render(paras, sub, part), len(part)), part))+ for line in got.values():+ if line.gender in "mf":+ self.names[line.name] += 1+ self.gender_of[line.name] = line.gender+ return got+++async def _remarks(server: Server, lines: Sequence[str]) -> list[list[str]]:+ """The narrator's remarks in each of these dash lines (without their opening dash), in one request with no other+ task."""+ text = "\n".join(f"[{n + 1}] — {_clip(line)}" for n, line in enumerate(lines))+ answer = await server.ask(+ [{"role": "user", "content": REMARKS_ASK + text}],+ TOKENS_PER_REMARK_LINE * len(lines) + 40,+ grammar=REMARK_GRAMMAR,+ )+ out: list[list[str]] = [[] for _ in lines]+ for m in REMARK_LINE.finditer(answer):+ n = int(m.group(1)) - 1+ if 0 <= n < len(lines):+ out[n] = [r.strip() for r in m.group(2).split("|")[1:] if len(re.findall(r"\w", r)) >= 3]+ return out+++def _sample(chapters: Sequence[Sequence[str]], chars: int) -> str:+ text: list[str] = []+ for paras in chapters:+ for p in paras:+ if sum(len(t) for t in text) >= chars:+ return "\n\n".join(text)+ text.append(p)+ return "\n\n".join(text)+++async def _narrator(server: Server, chapters: Sequence[Sequence[str]]) -> dict[str, Any]:+ answer = await server.ask(+ [{"role": "user", "content": NARRATOR_ASK + _sample(chapters, NARRATOR_SAMPLE)}],+ 60,+ response_format={"type": "json_schema", "json_schema": {"name": "narrator", "schema": NARRATOR_SCHEMA}},+ )+ try:+ got = json.loads(answer)+ return {"first_person": bool(got.get("first_person")), "name": str(got.get("name") or "").strip()}+ except (ValueError, AttributeError):+ return {"first_person": False, "name": ""}+++def _voices_schema() -> dict[str, Any]:+ role = {+ "type": "object",+ "properties": {k: {"type": "string", "enum": v} for k, v in VOICE_TERMS.items()},+ "required": list(VOICE_TERMS),+ }+ return {"type": "object", "properties": dict.fromkeys(("narrator", "men", "women"), role), "required": ["narrator"]}+++def describe(choice: dict[str, str], role: str, language: str) -> str:+ """OmniVoice's design terms for one role; the gender of a character voice is the role's."""+ gender = {"men": "male", "women": "female"}.get(role) or choice.get("gender") or "male"+ terms = [gender, choice.get("age") or "young adult", choice.get("pitch") or "moderate pitch"]+ if language == "en":+ terms.append("american accent")+ return ", ".join(terms)+++async def _voices(+ server: Server, chapters: Sequence[Sequence[str]], cast: list[dict[str, Any]], narrator: dict[str, Any], lang: str+) -> dict[str, str]:+ who = ", ".join(f"{c['name']} ({c['gender']}, {c['lines']} lines)" for c in cast[:12]) or "unknown"+ told = f"The book is told in the first person by {narrator['name']}.\n" if narrator.get("first_person") else ""+ ask = VOICES_ASK.format(cast=who, narrator=told, opening=_sample(chapters, OPENING))+ answer = await server.ask(+ [{"role": "user", "content": ask}],+ 200,+ response_format={"type": "json_schema", "json_schema": {"name": "voices", "schema": _voices_schema()}},+ )+ try:+ got = json.loads(answer)+ except ValueError:+ got = {}+ return {role: describe(got.get(role) or {}, role, lang) for role in ("narrator", "men", "women")}+++def _tokens(name: str) -> set[str]:+ return {w for w in re.findall(r"\w+", name.lower()) if w not in TITLES}+++def roles(lines: dict[int, Line], narrator: dict[str, Any], gender_of: dict[str, str]) -> dict[int, str]:+ """Each speech paragraph's role: m or f a man's or a woman's line, e the narrator reading a thought or the letter+ of an unknown writer, n the narrator's plain voice."""+ name = narrator.get("name", "") if narrator.get("first_person") else ""+ mine = _tokens(name)+ first = min(mine, key=lambda w: name.lower().find(w)) if mine else None+ out: dict[int, str] = {}+ for i, ln in lines.items():+ g = ln.gender+ toks = _tokens(ln.name)+ if g in "mf" and mine and toks & mine and (len(mine) == 1 or first in toks):+ g = "i"+ if g == "l":+ writer = gender_of.get(ln.name) or next((gender_of[k] for k in gender_of if _tokens(k) & toks), None)+ g = writer or "e"+ out[i] = {"m": "m", "f": "f", "t": "e", "e": "e"}.get(g, "n")+ return out+++def _cast(lines: Sequence[dict[int, Line]]) -> tuple[list[dict[str, Any]], dict[str, str]]:+ counts: Counter[tuple[str, str]] = Counter()+ for ch in lines:+ for ln in ch.values():+ if ln.gender in "mf" and ln.name.lower() not in GENERIC:+ counts[ln.name, ln.gender] += 1+ gender_of: dict[str, str] = {}+ total: Counter[str] = Counter()+ for (name, g), n in counts.most_common():+ gender_of.setdefault(name, g)+ total[name] += n+ cast = [{"name": n, "gender": gender_of[n], "lines": c} for n, c in total.most_common()]+ return cast, gender_of+++async def analyze(+ data_root: str | Path,+ chapters: Sequence[str],+ language: str,+ mode: str,+ progress: Progress,+) -> dict[str, Any]:+ """The cast of a book (chapters: their texts) and the role of every speech paragraph."""+ if mode not in MODES:+ raise EngineError("bad_request", f"'cast' must be one of {', '.join(MODES)}")+ if not installed(data_root):+ raise EngineError("not_ready", "Character voices are not installed: add them in Settings > Components")+ pars = [paragraphs(t) for t in chapters]+ passes = [(PROMPTS[0], 0)] + ([(PROMPTS[1], 1)] if mode == "careful" else [])+ plan = [[windows(p, offset) for p in pars] for _, offset in passes]+ dashed = [(k, i) for k, p in enumerate(pars) for i, par in enumerate(p) if DASH.match(par)]+ steps = sum(len(ws) for per in plan for ws in per) + 2 + -(-len(dashed) // REMARKS_PER_REQUEST)+ done = [0]++ def tick() -> None:+ done[0] += 1+ progress(min(1.0, done[0] / steps))++ server = Server(server_path(data_root), model_path(data_root))+ t0 = time.time()+ try:+ await server.start()+ narrator = await _narrator(server, pars)+ tick()+ runs: list[list[dict[int, Line]]] = []+ for (prompt, _), per in zip(passes, plan, strict=True):+ reader = Reader(server, prompt)+ found: list[dict[int, Line]] = []+ for paras, ws in zip(pars, per, strict=True):+ got: dict[int, Line] = {}+ for w in ws:+ got.update(await reader.window(paras, w))+ tick()+ found.append(got)+ runs.append(found)+ cast, gender_of = _cast(runs[0])+ chapter_roles: list[dict[int, str]] = []+ for k in range(len(pars)):+ mine = roles(runs[0][k], narrator, gender_of)+ if len(runs) > 1:+ other = roles(runs[1][k], narrator, gender_of)+ mine = {i: (r if other.get(i, r) == r else "n") for i, r in mine.items()}+ chapter_roles.append(mine)+ spoken = [(k, i) for k, i in dashed if chapter_roles[k].get(i) in ("m", "f", "e")]+ chapter_remarks: list[dict[str, list[str]]] = [{} for _ in pars]+ for start in range(0, len(spoken), REMARKS_PER_REQUEST):+ batch = spoken[start : start + REMARKS_PER_REQUEST]+ got = await _remarks(server, [DASH.sub("", pars[k][i], count=1) for k, i in batch])+ for (k, i), found in zip(batch, got, strict=True):+ if found:+ chapter_remarks[k][str(i)] = found+ tick()+ voices = await _voices(server, pars, cast, narrator, language)+ tick()+ except LlmError as exc:+ raise EngineError("internal", f"Finding the speakers failed: {exc}") from None+ finally:+ await server.stop()+ counts = Counter(r for ch in chapter_roles for r in ch.values())+ log.info("cast of %d chapter(s) in %.0fs (%s): %s", len(pars), time.time() - t0, mode, dict(counts))+ return {+ "version": VERSION,+ "mode": mode,+ "language": language,+ "narrator": narrator,+ "characters": cast,+ "lines": {"men": counts["m"], "women": counts["f"], "narrator": counts["n"] + counts["e"]},+ "voices": voices,+ "chapters": [+ {+ "roles": {str(i): r for i, r in sorted(ch.items())},+ "speakers": {str(i): [ln.gender, ln.name] for i, ln in sorted(found.items())},+ "remarks": remarks,+ }+ for ch, found, remarks in zip(chapter_roles, runs[0], chapter_remarks, strict=True)+ ],+ }+++def _long_quote(q: str) -> bool:+ return len(q.split()) >= QUOTE_MIN_WORDS+++def _find(body: str, remark: str, at: int) -> tuple[int, int] | None:+ """Where the model's copy of a remark is in the line, its spaces and apostrophes as it pleases."""+ words = [re.escape(w) for w in re.split(r"\s+", remark.replace("’", "'").strip()) if w]+ if not words:+ return None+ m = re.compile(r"\s+".join(words).replace("'", "['’]")).search(body, at)+ return (m.start(), m.end()) if m else None+++def _cut(body: str, remarks: Sequence[str], voice: str) -> list[tuple[str, str]] | None:+ """The speech around the model's remarks, found in order in the line; None when one is not there."""+ parts: list[tuple[str, str]] = []+ at = 0+ for r in remarks:+ span = _find(body, r, at)+ if span is None:+ return None+ k, end = span+ parts += [(body[at:k].strip(" —–"), voice), (body[k:end].strip(" —–"), "narrator")]+ at = end+ return [*parts, (body[at:].strip(" —–"), voice)]+++def _loose_parts(body: str, voice: str) -> list[tuple[str, str]]:+ """A remark starts with a small letter and opens with a verb of saying, ends the paragraph, or is closed by a dash+ before punctuation or a new sentence ("—dijo él—. ¿Cómo…"); any other dash is a pause in the speech."""+ cuts = list(DASH_LOOSE.finditer(body))+ texts = [body[a:b] for a, b in zip([0] + [m.end() for m in cuts], [m.start() for m in cuts] + [len(body)])]+ parts: list[tuple[str, str]] = []+ for i, t in enumerate(texts):+ text = t.strip()+ if not text:+ continue+ nxt = texts[i + 1].lstrip() if i + 1 < len(texts) else ""+ closed = i + 1 == len(texts) or nxt[:1] in ".,;:!?¡¿" or nxt[:1].isupper()+ remark = bool(parts) and parts[-1][1] == voice and text[:1].islower() and (closed or bool(SAY.match(text)))+ if remark:+ parts.append((text, "narrator"))+ elif parts and parts[-1][1] == voice:+ parts[-1] = (f"{parts[-1][0]} — {text}", voice)+ else:+ parts.append((text.lstrip(".,;: "), voice))+ return parts+++def _dash_parts(body: str, voice: str, language: str) -> list[tuple[str, str]]:+ """A dash line's speech and remarks. A remark starts with a small letter; a piece that does not is the speech going+ on after a pause dash."""+ if language in LOOSE_LANGUAGES:+ return _loose_parts(body, voice)+ if language == "fr":+ closed = re.match(r"([^«]*?»)\s*(\S.*)$", body, re.DOTALL)+ if closed:+ return [*_dash_parts(closed.group(1), voice, "fr"), (closed.group(2), "narrator")]+ out, last = [], 0+ for m in FR_REMARK.finditer(body):+ out.append((body[last : m.start(1) + 1], voice))+ out.append((m.group(2) + (m.group(3) if m.group(3) != "," else ""), "narrator"))+ last = m.end()+ return [*out, (body[last:], voice)]+ return [(t, voice if k % 2 == 0 else "narrator") for k, t in enumerate(DASH_SPLIT.split(body))]+++def pieces(par: str, role: str, remarks: Sequence[str] = (), language: str = "") -> list[tuple[str, str]]:+ """A paragraph in voiced pieces: the speech in the role's voice, the author's words in the narrator's. The role is+ one of roles(); a piece's voice is narrator, expressive, men or women. A dash line is cut at the remarks the model+ copied out of it, or else at every dash after punctuation; quoted speech is cut at its quotes."""+ if role not in ("m", "f", "e"):+ return [(par, "narrator")]+ voice = {"m": "men", "f": "women", "e": "expressive"}[role]+ parts: list[tuple[str, str]] = []+ if DASH.match(par):+ body = DASH.sub("", par, count=1)+ cut = _cut(body, remarks, voice) if remarks else None+ if cut is None:+ parts = _dash_parts(body, voice, language)+ else:+ parts = [p for t, v in cut for p in (_dash_parts(t, voice, language) if v == voice else [(t, v)])]+ else:+ last = 0+ for k, m in enumerate(QUOTE.finditer(par)):+ if k > 0 and not _long_quote(m.group(0)):+ continue+ parts.append((par[last : m.start()], "narrator"))+ parts.append((m.group(0), voice))+ last = m.end()+ parts.append((par[last:], "narrator"))+ merged: list[tuple[str, str]] = []+ for t, v in parts:+ text = t.strip().lstrip(",;: ") if v == "narrator" else t.strip()+ if not re.search(r"\w", text):+ continue+ if merged and merged[-1][1] == v:+ merged[-1] = (merged[-1][0] + " " + text, v)+ else:+ merged.append((text, v))+ return merged or [(par, "narrator")]diff --git a/engine/src/mimvox_engine/components.py b/engine/src/mimvox_engine/components.pyindex c4260b7..b913fea 100644--- a/engine/src/mimvox_engine/components.py+++ b/engine/src/mimvox_engine/components.py@@ -22,6 +22,7 @@ OPTIONAL = ("ukrainian","voxcpm","chatterbox",+ "cast",)_off: set[str] = set()diff --git a/engine/src/mimvox_engine/design.py b/engine/src/mimvox_engine/design.pyindex 2cfa391..0bb7592 100644--- a/engine/src/mimvox_engine/design.py+++ b/engine/src/mimvox_engine/design.py@@ -158,14 +158,7 @@ async def _exact_stress(ctx: Context, data: config.DataDir, text: str, designed:waited += 0.5if HOLOS.status() != "ready":return False- said = out.with_name("holos.wav")- await HOLOS.synthesize(text, "uk", str(designed), SynthParams(out_path=said))- zs = await tts.holos_timbre(ctx, HOLOS, data, str(designed), "best")- if zs is None:- await aio.run_io(said.replace, out)- else:- await zs.convert(str(said), str(out))- await aio.run_io(said.unlink, True)+ await HOLOS.synthesize(text, "uk", str(designed), SynthParams(out_path=out))return Truediff --git a/engine/src/mimvox_engine/narration.py b/engine/src/mimvox_engine/narration.pyindex f2952f2..754e746 100644--- a/engine/src/mimvox_engine/narration.py+++ b/engine/src/mimvox_engine/narration.py@@ -11,6 +11,8 @@ from scipy.signal import resample_poly, sosfilt, sosfilt_ziBUDGET_TOKENS = 90 # OmniVoice tokens: ~270 characters, ~15 sEXPRESSIVENESS = 0.6 # steadier than Speak's 0.8; the user's setting wins+CHARACTER_EXPRESSIVENESS = 0.85 # character voices speak livelier than the narrator+EXPRESSIVE_NARRATOR = 1.2 # thoughts and letters; 1.5 dropped words, 0.9 was not heard (Martin Eden, 2026-11-30)PAUSES: dict[str, int] = { # silence heard after a segment (ms), by how it ends"clause": 220, # a long sentence cut at , ; : —@@ -19,6 +21,7 @@ PAUSES: dict[str, int] = { # silence heard after a segment (ms), by how it ends"exclaim": 440,"ellipsis": 620, # … mid-paragraph"dialogue": 650, # a paragraph end followed by a dialogue line+ "voice": 260, # between the speech and the author's words of one paragraph, read by different voices"paragraph": 820, # any other paragraph end"title": 1200, # after the chapter title"end": 700, # the end of a chapter file (the next file starts with LEAD_MS)@@ -56,6 +59,7 @@ def clean_text(text: str) -> str:p = re.sub(r"(?<=\S) ?--+ ?(?=\S)", " — ", p) # word--word / word -- wordp = re.sub(r"(?<=\w) [-–] (?=\w)", " — ", p) # spaced hyphen or en dash between wordsp = re.sub(r"^[-–]\s", "— ", p) # a dialogue line opened with a hyphen+ p = re.sub(r"^--+\s*", "— ", p) # or with two (Project Gutenberg's Spanish)p = p.replace("―", "—").replace("``", "“").replace("''", "”")p = re.sub(r"!{2,}", "!", p)p = re.sub(r"\?{2,}", "?", p)@@ -84,30 +88,45 @@ def _end_kind(seg: str) -> str:def segments(title: str | None, text: str, count: Callable[[str], int]) -> list[tuple[str, int, str]]:"""``(segment, pause_after_ms, kind)``; the ``title``, when given, is a segment of its own."""+ return [(t, p, k) for t, p, k, _ in voiced_segments(title, text, count)]+++Split = Callable[[int, str], list[tuple[str, str]]]+++def voiced_segments(+ title: str | None, text: str, count: Callable[[str], int], split: Split | None = None+) -> list[tuple[str, int, str, str]]:+ """``(segment, pause_after_ms, kind, voice)``: ``split(index, paragraph)`` gives a paragraph's pieces and the voice+ of each (``cast.pieces``); without it every segment is the narrator's."""pars = [p for p in clean_text(text).split("\n\n") if p.strip()]from . import tts- out: list[tuple[str, int, str]] = []+ out: list[tuple[str, int, str, str]] = []if title and title.strip():t = clean_text(title).replace("\n\n", " ")if not re.search(r"[.!?…:;]$", t.rstrip(_CLOSERS)):t += "."for seg, _ in tts.segment_text(t, count, fixed=BUDGET_TOKENS):- out.append((seg, PAUSES["clause"], "clause"))+ out.append((seg, PAUSES["clause"], "clause", "narrator"))if out:- out[-1] = (out[-1][0], PAUSES["title"], "title")+ out[-1] = (out[-1][0], PAUSES["title"], "title", "narrator")for j, par in enumerate(pars):- segs = tts.segment_text(par, count, fixed=BUDGET_TOKENS)- for i, (seg, _) in enumerate(segs):- if i < len(segs) - 1:- kind = _end_kind(seg)- elif j + 1 < len(pars):- kind = "dialogue" if is_dialogue(pars[j + 1]) else "paragraph"- else:- kind = "end"- out.append((seg, PAUSES[kind], kind))+ parts = split(j, par) if split is not None else [(par, "narrator")]+ for n, (piece, voice) in enumerate(parts):+ segs = tts.segment_text(piece, count, fixed=BUDGET_TOKENS)+ for i, (seg, _) in enumerate(segs):+ if i < len(segs) - 1:+ kind = _end_kind(seg)+ elif n < len(parts) - 1:+ kind = "voice"+ elif j + 1 < len(pars):+ kind = "dialogue" if is_dialogue(pars[j + 1]) else "paragraph"+ else:+ kind = "end"+ out.append((seg, PAUSES[kind], kind, voice))if out and out[-1][2] != "end":- out[-1] = (out[-1][0], PAUSES["end"], "end")+ out[-1] = (out[-1][0], PAUSES["end"], "end", out[-1][3])return out@@ -184,6 +203,8 @@ def _gated(energies: np.ndarray) -> float | None:def lufs(x: np.ndarray, sr: int) -> float | None:+ if len(x) == 0:+ return Nonesub = sr // 10y = sosfilt(_k_sos(sr), np.asarray(x, dtype=np.float64))n = len(y) // sub@@ -214,6 +235,8 @@ def f0_track(x: np.ndarray, sr: int) -> np.ndarray:def measure(x: np.ndarray, sr: int, chars: int) -> dict[str, Any]:"""Loudness (LUFS), median pitch (Hz or None), length and seconds per character of a trimmed segment."""+ if len(x) == 0:+ return {"lufs": None, "f0": None, "dur": 0.0, "spc": 0.0, "chars": chars}f0 = f0_track(x, sr)v = f0[f0 > 0]dur = len(x) / float(sr)diff --git a/engine/src/mimvox_engine/redub/handlers.py b/engine/src/mimvox_engine/redub/handlers.pyindex 00a9933..3d7ff34 100644--- a/engine/src/mimvox_engine/redub/handlers.py+++ b/engine/src/mimvox_engine/redub/handlers.py@@ -64,8 +64,11 @@ def _models_not_loading() -> None:raise EngineError("not_ready", "the models are loading, or the GPU is in use by a training; try again soon")-def _reg_job(ctx: Context, fn: Any, error_event: str = "redub.error", speech_job: bool = False) -> str:- """A job that does not use the speech worker (``speech_job=False``) first has it hand its GPU memory back."""+def _reg_job(+ ctx: Context, fn: Any, error_event: str = "redub.error", speech_job: bool = False, exclusive: bool = True+) -> str:+ """A job that does not use the speech worker (``speech_job=False``) first has it hand its GPU memory back; one that+ is not ``exclusive`` runs beside a book or a generation (ffmpeg only)."""async def run(job: str) -> None:def finish(event: str, payload: dict[str, Any]) -> None:@@ -89,7 +92,7 @@ def _reg_job(ctx: Context, fn: Any, error_event: str = "redub.error", speech_jobfinally:tts.release_job(job)- return tts.start_exclusive(ctx, run)+ return tts.start_exclusive(ctx, run) if exclusive else ctx.start_job(run)@method("redub.probe")@@ -967,5 +970,5 @@ async def _subtitles_only(ctx: Context, data: config.DataDir, path: Path, paramsfinally:await aio.run_io(shutil.rmtree, workdir, ignore_errors=True)- # ffmpeg only: the speech worker keeps its GPU memory.- return {"job": _reg_job(ctx, work, speech_job=True)}+ # ffmpeg only: the speech worker keeps its GPU memory, and a book being read goes on.+ return {"job": _reg_job(ctx, work, speech_job=True, exclusive=False)}diff --git a/engine/src/mimvox_engine/server.py b/engine/src/mimvox_engine/server.pyindex c34e086..1b7bfb3 100644--- a/engine/src/mimvox_engine/server.py+++ b/engine/src/mimvox_engine/server.py@@ -278,7 +278,7 @@ def _zero_shot_vc(ctx: Server) -> bool:def _components(ctx: Server, translators: list[str], zero_shot_vc: bool) -> list[str]:"""Setup's COMPONENTS found on disk, turned off or not."""- from . import rvc, speech+ from . import cast, rvc, speechfrom .backends import holos, omnivoicefrom .backends.clone import CHATTERBOX, VOXCPM@@ -293,6 +293,7 @@ def _components(ctx: Server, translators: list[str], zero_shot_vc: bool) -> list"ukrainian": holos.installed(ctx.runtime, honour_off=False),"voxcpm": VOXCPM.installed(ctx.runtime, honour_off=False),"chatterbox": CHATTERBOX.installed(ctx.runtime, honour_off=False),+ "cast": cast.installed(ctx.data_dir, honour_off=False),}return [name for name, ok in found.items() if ok]diff --git a/engine/src/mimvox_engine/tts.py b/engine/src/mimvox_engine/tts.pyindex 093c183..c8be1b2 100644--- a/engine/src/mimvox_engine/tts.py+++ b/engine/src/mimvox_engine/tts.py@@ -415,6 +415,11 @@ def speech_language(params: dict[str, Any], key: str = "language") -> tuple[str,if not isinstance(exact, bool):raise EngineError("bad_request", "'exact_stress' must be true or false")model = params.get("model") or "auto"+ if model == "omnivoice" and exact:+ # OmniVoice with exact stress: Ukrainian is read by HolosTTS, as with "auto"; it fell back to OmniVoice before.+ holos = backends.by_name("holos")+ if holos is not None and lang in holos.languages and holos.available():+ return lang, holosif model != "auto":return lang, named_model(model, lang)backend = backends.for_language(lang, skip=() if exact else ("holos",))@@ -509,11 +514,6 @@ async def tts_generate(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:# native-us: RVC for a trained voice, else the zero-shot converter; without either the voice's own referencechoice = accent.choose(requested, native_voice, lang, has_pth, index_rate, zs_worker is not None)zs = zero_shot(ctx, choice, zs_worker, ref, quality)- keep_voice = params.get("keep_voice", True)- if not isinstance(keep_voice, bool):- raise EngineError("bad_request", "'keep_voice' must be true or false")- if zs is None and not use_rvc and keep_voice:- zs = await holos_timbre(ctx, backend, data, ref, quality)# The clip that will speak and its real language (a foreign one carries its accent into `lang`).ref_fields = await aio.run_io(reflang.fields, ref, lang, choice.accent == "native-us")segs = segment_text(text, backend.count_tokens)@@ -562,20 +562,6 @@ async def tts_generate(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:}-async def holos_timbre(- ctx: Context, backend: backends.TtsBackend, data: config.DataDir, ref: str, quality: str-) -> zsvc.Bound | None:- """HolosTTS keeps little of an untrained voice's timbre (ECAPA 0.76 to the reference, against 0.94 for OmniVoice);- the zero-shot converter brings it back to 0.88. None for another backend or without the converter."""- if backend.name != "holos":- return None- worker = await aio.run_io(zsvc.get, ctx.runtime, data.root)- if worker is None:- return None- vram = float((getattr(ctx, "device", None) or {}).get("vram_gb") or 0.0)- return zsvc.Bound(worker, ref, zsvc.turn_lock(vram), quality)--def zero_shot(ctx: Context, choice: accent.Choice, worker: zsvc.ZsvcWorker | None, ref: str, quality: str = "best") -> zsvc.Bound | None:@@ -969,10 +955,11 @@ async def _warm(await aio.run_io(shutil.rmtree, warm_dir, ignore_errors=True)-async def release_gpu(ctx: Context) -> None:- """Unload the speech models and stop the worker processes for training. Raises ``busy`` during a generation; until- :func:`reacquire_gpu` finishes, the models report ``paused`` and ``tts.generate`` answers ``not_ready``."""- if _ACTIVE[0] is not None:+async def release_gpu(ctx: Context, holder: str | None = None) -> None:+ """Unload the speech models and stop the worker processes for training. Raises ``busy`` during a generation other+ than ``holder``'s; until :func:`reacquire_gpu` finishes, the models report ``paused`` and ``tts.generate`` answers+ ``not_ready``."""+ if _ACTIVE[0] is not None and _ACTIVE[0] != holder:raise EngineError("busy", busy_message("a generation is running; wait for it or cancel it before training"))_set_status(ctx, tts="paused", rvc="paused")for b in backends.all_backends():diff --git a/engine/src/mimvox_engine/voices.py b/engine/src/mimvox_engine/voices.pyindex 8668994..504192c 100644--- a/engine/src/mimvox_engine/voices.py+++ b/engine/src/mimvox_engine/voices.py@@ -241,6 +241,8 @@ def describe(data: config.DataDir, voice_id: str) -> dict[str, Any]:"trained_at": meta.get("trained_at") if trained else None,"training_paused": paused_training(meta),"references": _language_references(vdir),+ "book": meta.get("book"),+ "book_role": meta.get("book_role"),**_reference_languages(vdir),}@@ -331,10 +333,15 @@ def voices_create(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:@method("voices.rename")def voices_rename(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:- """``{"id", "name"}`` renames; ``{"id", "language"}`` (name optional) changes the recording language."""+ """``{"id", "name"}`` renames; ``{"id", "language"}`` (name optional) changes the recording language;+ ``{"id", "book_role"}`` changes the role a book voice reads (``narrator``, ``men``, ``women``)."""data = config.data_dir(ctx)vid = params.get("id")- name = _clean_name(params) if "name" in params or "language" not in params else None+ role = params.get("book_role")+ if role is not None and role not in ("narrator", "men", "women"):+ raise EngineError("bad_request", "'book_role' must be narrator, men or women")+ other = "language" in params or role is not None+ name = _clean_name(params) if "name" in params or not other else Nonelanguage = _clean_language(params) if params.get("language") not in (None, "") else Nonewith _LOCK:meta = read_meta(data, str(vid))@@ -342,6 +349,8 @@ def voices_rename(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:meta["name"] = nameif language is not None:meta["language"] = language+ if role is not None:+ meta["book_role"] = role_write_json(data.voice(meta["id"]) / "voice.json", meta)return {"voice": describe(data, meta["id"])}@@ -389,6 +398,19 @@ def _atomic_copy(src: Path, dst: Path) -> None:tmp.replace(dst)+def _replace_reference(data: config.DataDir, vid: str, ref_src: Path | None) -> dict[str, Any]:+ """A voice made anew from another clip keeps its id, so the books that read with it keep it too."""+ if ref_src is None:+ raise EngineError("bad_request", "'into' needs a 'reference_path'")+ with _LOCK:+ read_meta(data, vid)+ y, sr = media.read_audio(ref_src)+ sf.write(data.reference(vid), y, sr, subtype="PCM_16", format="WAV")+ for cached in data.voice(vid).glob("reference.*.json"):+ cached.unlink(missing_ok=True)+ return {"voice": describe(data, vid)}++def import_voice(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:"""A failure removes the half-made voice again."""data = config.data_dir(ctx)@@ -413,6 +435,8 @@ def import_voice(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:raise EngineError("bad_request", "dataset_dir has no part<N> audio files (wav, mp3, m4a, flac, ...)")if not (ref_src or parts):raise EngineError("bad_request", "give a 'reference_path' and/or a 'dataset_dir' with part<N>.wav files")+ if params.get("into") not in (None, ""):+ return _replace_reference(data, str(params["into"]), ref_src)created = voices_create(ctx, {"name": params.get("name"), "preset": params.get("preset"), "language": params.get("language")}@@ -445,6 +469,14 @@ def import_voice(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:if m:meta["trained_epochs"] = int(m.group(1))_write_json(vdir / "voice.json", meta)+ book = {+ k: params[k].strip() for k in ("book", "book_role") if isinstance(params.get(k), str) and params[k].strip()+ }+ if book:+ with _LOCK:+ meta = read_meta(data, vid)+ meta.update(book)+ _write_json(vdir / "voice.json", meta)except BaseException:shutil.rmtree(vdir, ignore_errors=True)raisediff --git a/engine/tests/test_book.py b/engine/tests/test_book.pyindex fcc8371..b9b4693 100644--- a/engine/tests/test_book.py+++ b/engine/tests/test_book.py@@ -92,7 +92,7 @@ def run(data, bid, on_start=None, backend=None):async def main():job = f"job{time.time_ns()}"book._RUNNING[bid] = job- task = asyncio.ensure_future(book._run(ctx, job, data, bid, voice(backend)))+ task = asyncio.ensure_future(book._run(ctx, job, data, bid, {"narrator": voice(backend)}))if on_start:on_start(asyncio.get_running_loop(), task)try:diff --git a/engine/tests/test_cast.py b/engine/tests/test_cast.pynew file mode 100644index 0000000..21736da--- /dev/null+++ b/engine/tests/test_cast.py@@ -0,0 +1,474 @@+import asyncio+import json+import re+import time++import numpy as np+import pytest+from mimvox_engine import book, cast, narration+from mimvox_engine.cast import Line+from mimvox_engine.registry import EngineError+from test_book import Backend, Ctx, voice++UK = "— Стривайте, Артуре,— мовив він, намагаючись приховати збентеження.— Це трохи забагато для мене."+EN = "“That’s all right,” Arthur answered. “You mustn’t be frightened at us.” He wondered what a “lift” was."+++def test_a_dash_line_is_split_into_speech_and_remark():+ assert cast.pieces(UK, "m") == [+ ("Стривайте, Артуре,", "men"),+ ("мовив він, намагаючись приховати збентеження.", "narrator"),+ ("Це трохи забагато для мене.", "men"),+ ]+++def test_quoted_speech_is_split_and_a_quoted_word_stays_narration():+ assert cast.pieces(EN, "m") == [+ ("“That’s all right,”", "men"),+ ("Arthur answered.", "narrator"),+ ("“You mustn’t be frightened at us.”", "men"),+ ("He wondered what a “lift” was.", "narrator"),+ ]+++def test_a_thought_is_read_by_the_expressive_narrator():+ par = "He took it so quietly that the boy thought: “He understands. He’ll see me through.”"+ assert cast.pieces(par, "e") == [+ ("He took it so quietly that the boy thought:", "narrator"),+ ("“He understands. He’ll see me through.”", "expressive"),+ ]+++def test_the_narrator_role_keeps_the_paragraph_whole():+ assert cast.pieces(EN, "n") == [(EN, "narrator")]+++def test_parse_cleans_names_the_model_garbles():+ answer = "[1] m Martin Eden_\n[2] m Martin Eden_m\n[3] f Daisy_Buchanan\n"+ assert [ln.name for ln in cast.parse(answer, [1, 2, 3]).values()] == [+ "Martin Eden",+ "Martin Eden",+ "Daisy Buchanan",+ ]+++def test_an_empty_segment_does_not_break_the_measurement():+ m = narration.measure(np.zeros(0, dtype=np.float32), 24000, 8)+ assert (m["dur"], m["lufs"], m["f0"]) == (0.0, None, None)+++def test_parse_keeps_only_the_numbered_lines_asked_for():+ answer = "[3] m Martin Eden\n[5] f Ruth\n[9] m Someone\n[3] f Again\n"+ assert cast.parse(answer, [3, 5, 7]) == {3: Line("m", "Martin Eden"), 5: Line("f", "Ruth")}+++def test_windows_number_every_speech_paragraph_once():+ paras = [("“Hi,” she said. " if i % 3 == 0 else "Narration goes on. ") * 40 for i in range(60)]+ for offset in (0, 1):+ numbered = [i for w in cast.windows(paras, offset) for i in w.numbered]+ assert numbered == [i for i in range(60) if i % 3 == 0]+++def test_the_first_person_narrator_reads_his_own_lines():+ lines = {1: Line("m", "Nick"), 2: Line("i", "Nick Carraway"), 3: Line("m", "Tom"), 4: Line("f", "Daisy")}+ got = cast.roles(lines, {"first_person": True, "name": "Nick Carraway"}, {"Tom": "m", "Daisy": "f"})+ assert got == {1: "n", 2: "n", 3: "m", 4: "f"}+++def test_a_letter_is_read_by_its_writer_when_the_writer_speaks():+ lines = {1: Line("l", "Irene Adler"), 2: Line("l", "a stranger"), 3: Line("t", "Martin"), 4: Line("x", "song")}+ got = cast.roles(lines, {"first_person": False, "name": ""}, {"Irene": "f"})+ assert got == {1: "f", 2: "e", 3: "e", 4: "n"}+++def test_voiced_segments_put_a_short_pause_between_voices():+ segs = narration.voiced_segments(None, UK, Backend().count_tokens, lambda j, par: cast.pieces(par, "m"))+ assert [s[3] for s in segs] == ["men", "narrator", "men"]+ assert [s[2] for s in segs[:2]] == ["voice", "voice"]+ assert segs[-1][2] == "end"+++def test_segments_without_a_split_are_unchanged():+ text = "One. Two.\n\nThree."+ assert narration.segments("T", text, Backend().count_tokens) == [+ s[:3] for s in narration.voiced_segments("T", text, Backend().count_tokens)+ ]+++def test_the_key_depends_on_the_text_the_language_and_the_mode():+ k = cast.key(["a"], "en", "fast")+ assert k == cast.key(["a"], "en", "fast")+ assert len({k, cast.key(["b"], "en", "fast"), cast.key(["a"], "uk", "fast"), cast.key(["a"], "en", "careful")}) == 4+++class FakeServer:+ """Answers like llama-server: every numbered paragraph a man's line, unless it mentions Ruth."""++ def __init__(self, binary, model):+ self.asked = 0++ async def start(self):+ pass++ async def stop(self):+ pass++ async def ask(self, messages, max_tokens, **extra):+ self.asked += 1+ text = messages[-1]["content"]+ schema = (extra.get("response_format") or {}).get("json_schema", {}).get("name")+ if schema == "narrator":+ return json.dumps({"first_person": False, "name": ""})+ if schema == "voices":+ return json.dumps({"narrator": {"gender": "female", "age": "middle-aged", "pitch": "low pitch"}})+ if "copy each remark" in text:+ lines = re.findall(r"^\[(\d+)\] ", text.split("Lines:")[-1], re.MULTILINE)+ return "".join(f"[{n}] -\n" for n in lines)+ found = re.finditer(r"^\[(\d+)\] (.*)$", text, re.MULTILINE)+ out = [f"[{m.group(1)}] {'f Ruth' if 'Ruth' in m.group(2) else 'm Martin'}" for m in found]+ return "\n".join(out) + "\n"+++CHAPTERS = ["Narration.\n\n“Hello,” said Ruth.\n\n“Hi,” he said.", "More.\n\n“Bye,” Martin said."]+++def fake_llm(monkeypatch, tmp_path):+ monkeypatch.setattr(cast, "Server", FakeServer)+ monkeypatch.setattr(cast, "installed", lambda root: True)+++def test_analyze_finds_the_cast_and_the_roles(fake_llm, tmp_path):+ seen = []+ got = asyncio.run(cast.analyze(tmp_path, CHAPTERS, "en", "fast", seen.append))+ assert got["chapters"][0]["roles"] == {"1": "f", "2": "m"}+ assert got["chapters"][1]["roles"] == {"1": "m"}+ assert [c["name"] for c in got["characters"]] == ["Martin", "Ruth"]+ assert got["lines"] == {"men": 2, "women": 1, "narrator": 0}+ assert got["voices"]["narrator"] == "female, middle-aged, low pitch, american accent"+ assert got["voices"]["men"].startswith("male, ")+ assert seen[-1] == 1.0+++def test_careful_sends_a_disagreement_to_the_narrator(fake_llm, tmp_path, monkeypatch):+ real = cast.Reader.window+ passes = []++ async def window(self, paras, w):+ got = await real(self, paras, w)+ passes.append(self.prompt)+ if self.prompt == cast.PROMPTS[1] and 1 in got and "Ruth" in paras[1]:+ got[1] = Line("m", "Martin")+ return got++ monkeypatch.setattr(cast.Reader, "window", window)+ got = asyncio.run(cast.analyze(tmp_path, CHAPTERS, "en", "careful", lambda p: None))+ assert set(passes) == set(cast.PROMPTS)+ assert got["chapters"][0]["roles"] == {"1": "n", "2": "m"}+++def test_analyze_without_the_component_is_not_ready(tmp_path):+ with pytest.raises(EngineError) as e:+ asyncio.run(cast.analyze(tmp_path, CHAPTERS, "en", "fast", lambda p: None))+ assert e.value.code == "not_ready"+++def test_voices_must_be_men_or_women(monkeypatch):+ monkeypatch.setattr(book.tts, "speech_language", lambda params, key="language": ("en", Backend()))+ s = book._settings({"voice_id": "v", "voices": {"men": "a"}, "cast": "careful"})+ assert s["voices"] == {"men": "a", "women": None}+ assert s["cast"] == "careful"+ assert book._settings({"voice_id": "v"})["cast"] is None+ for bad in ({"children": "a"}, {"men": 3}, ["a"]):+ with pytest.raises(EngineError):+ book._settings({"voice_id": "v", "voices": bad})+ with pytest.raises(EngineError):+ book._settings({"voice_id": "v", "voices": {"men": "a"}, "cast": "slow"})+++def data(tmp_path):+ from mimvox_engine import config++ (tmp_path / "tmp").mkdir(parents=True)+ return config.DataDir(tmp_path)+++def test_a_book_reads_each_line_in_its_voice(data, monkeypatch):+ monkeypatch.setattr(book, "QUALITY_CHECKS", False)+ settings = {+ "voice_id": "v",+ "language": "en",+ "read_titles": False,+ "output_format": "wav",+ "m4b": False,+ "voices": {"men": "m", "women": None},+ "cast": "fast",+ }+ texts = ["Narration here.\n\n“Hello there, my friend,” said Ruth.\n\n“Hi to you too,” he said."]+ b = book._create(data, "Cast Book", None, None, [{"title": "One", "text": texts[0], "words": 12}], settings)+ found = {"chapters": [{"roles": {"1": "f", "2": "m"}, "remarks": {}}]}+ book._save_cast(data, book._cast_key(b), found, texts)+ ctx = Ctx()++ async def main():+ job = f"job{time.time_ns()}"+ book._RUNNING[b["id"]] = job+ await book._run(ctx, job, data, b["id"], {"narrator": voice(), "men": voice()})++ asyncio.run(main())+ assert ctx.names("book.done", "book.error") == ["book.done"]+ stats = json.loads((book.book_dir(data, b["id"]) / "stats" / "001.json").read_text(encoding="utf-8"))+ assert [s["voice"] for s in stats["segments"]] == ["narrator", "narrator", "narrator", "men", "narrator"]+++def test_a_part_of_a_book_found_before_needs_no_new_search(data):+ one = "Narration.\n\n“Hello there,” said Ruth."+ two = "More narration.\n\n“Hi,” he said."+ found = {+ "version": cast.VERSION,+ "mode": "careful",+ "language": "uk",+ "narrator": {"first_person": False, "name": ""},+ "characters": [{"name": "Ruth", "gender": "f", "lines": 1}],+ "voices": {"narrator": "a", "men": "b", "women": "c"},+ "lines": {"men": 1, "women": 1, "narrator": 0},+ "chapters": [{"roles": {"1": "f"}, "remarks": {}}, {"roles": {"1": "m"}, "remarks": {}}],+ }+ book._save_cast(data, cast.key([one, two], "uk", "careful"), found, [one, two])+ part = book._cached_cast(data, [two, "Cover"], "uk", "careful")+ assert part is not None+ assert [c["roles"] for c in part["chapters"]] == [{"1": "m"}, {}]+ assert part["lines"] == {"men": 1, "women": 0, "narrator": 0}+ assert part["characters"] == found["characters"]+ assert book._cached_cast(data, [two], "uk", "fast") is None+ three = "New.\n\n“Unread,” she said."+ assert book._cached_cast(data, [two, three], "uk", "careful") is None+ assert book._unsearched(data, [one, three, "Cover"], "uk", "careful") == [three]+ later = {**found, "characters": [{"name": "Ruth", "gender": "f", "lines": 2}], "chapters": [{"roles": {"1": "f"}}]}+ book._save_cast(data, cast.key([three], "uk", "careful"), later, [three])+ joined = book._cached_cast(data, [one + "\n\n" + two], "uk", "careful")+ assert joined is not None, "chapters joined keep the speakers found"+ assert joined["chapters"][0]["roles"] == {"1": "f", "3": "m"}+ whole = book._cached_cast(data, [one, two, three], "uk", "careful")+ assert whole is not None+ assert [c["roles"] for c in whole["chapters"]] == [{"1": "f"}, {"1": "m"}, {"1": "f"}]+ assert whole["characters"] == [{"name": "Ruth", "gender": "f", "lines": 3}]+++def test_more_chapters_join_the_book_in_their_place(data):+ settings = {+ "voice_id": "v",+ "language": "uk",+ "read_titles": True,+ "output_format": "wav",+ "m4b": False,+ "voices": {"men": "a", "women": None},+ "cast": "careful",+ }+ chapters = [{"title": "Two", "text": "Second chapter.", "words": 2, "number": 2}]+ b = book._create(data, "Book", None, None, chapters, settings)+ state = json.loads((book.book_dir(data, b["id"]) / "state.json").read_text(encoding="utf-8"))+ state["status"] = "done"+ book._save_state(data, b["id"], state)+ more = [{"title": "One", "text": "First chapter.", "words": 2, "number": 1}, *chapters]+ assert book._add_chapters(data, b["id"], book._clean_chapters(more)) == 1+ b2, st2 = book._load(data, b["id"])+ assert [c["file"] for c in b2["chapters"]] == ["02 - Two", "01 - One"]+ assert st2["status"] == "paused" and len(st2["chapters"]) == 2+ assert book._add_chapters(data, b["id"], book._clean_chapters(more)) == 0+ book._reread(data, b["id"], b2, st2, {"voices": {"women": "w"}, "m4b": True}, [])+ st = book._load(data, b["id"])[0]["settings"]+ assert st["voices"] == {"men": "a", "women": "w"} and st["m4b"] is True+++def test_chapters_without_speech_need_no_search(data):+ found = book._cached_cast(data, ["Title page.", "An epigraph."], "en", "careful")+ assert found is not None and found["characters"] == []+ assert [c["roles"] for c in found["chapters"]] == [{}, {}]+++def test_a_search_again_reads_every_chapter_with_speech(data, monkeypatch):+ calls = []++ async def analyze(ctx, data_, texts, book_, progress, job):+ calls.append(list(texts))+ return {+ "version": cast.VERSION,+ "mode": "fast",+ "language": "en",+ "narrator": {},+ "characters": [],+ "voices": None,+ "chapters": [{"roles": {}} for _ in texts],+ }++ monkeypatch.setattr(book, "_analyze", analyze)+ texts = ["Title.", "Narration.\n\n“Hi there,” she said."]+ bk = {"settings": {"language": "en", "cast": "fast"}}+ asyncio.run(book._search(None, data, texts, [texts[1]], bk, lambda p: None, "job"))+ assert calls == [[texts[1]]]+ assert book._unsearched(data, texts, "en", "fast") == []+++def test_settings_change_while_a_book_waits(data):+ settings = {"voice_id": "v", "language": "uk", "read_titles": True, "output_format": "wav", "m4b": False}+ b = book._create(data, "Book", None, None, [{"title": "One", "text": "Text.", "words": 1}], settings)+ book._set_settings(data, b["id"], {"m4b": True})+ assert book._load(data, b["id"])[0]["settings"]["m4b"] is True+++ ("par", "remarks", "want"),+ [+ (+ "— Pues yo he observado en la Nela — dijo Carlos — algo de inteligencia.",+ ["dijo Carlos"],+ [("Pues yo he observado en la Nela", "men"), ("dijo Carlos", "narrator"), ("algo de inteligencia.", "men")],+ ),+ (+ "— ¡Lili, Lili!… — gritaba Sofía, esperando que se detuviera.",+ ["gritaba Sofía, esperando que se detuviera."],+ [("¡Lili, Lili!…", "men"), ("gritaba Sofía, esperando que se detuviera.", "narrator")],+ ),+ (+ "— Eh! Monsieur, s'écria-t-il, monsieur, qui vous cachez là!",+ ["s’écria-t-il,"],+ [("Eh! Monsieur,", "men"), ("s'écria-t-il,", "narrator"), ("monsieur, qui vous cachez là!", "men")],+ ),+ (+ "— Anche per questa volta ti perdono: — gli disse la Fata — ma guai a te!",+ ["gli disse la Fata"],+ [+ ("Anche per questa volta ti perdono:", "men"),+ ("gli disse la Fata", "narrator"),+ ("ma guai a te!", "men"),+ ],+ ),+ ],+)+def test_a_dash_line_is_cut_at_the_remarks_the_model_copied(par, remarks, want):+ assert cast.pieces(par, "m", remarks) == want+++def test_a_remark_not_in_the_line_falls_back_to_the_dashes():+ assert cast.pieces(UK, "m", ["сказала вона"]) == cast.pieces(UK, "m")+++def test_remarks_are_read_from_their_own_answer(monkeypatch):+ class Remarks:+ async def ask(self, messages, max_tokens, **extra):+ assert "grammar" in extra+ return "[1] | dijo Carlos | y se fue\n[2] -\n[3] | -\n"++ got = asyncio.run(cast._remarks(Remarks(), ["Hola — dijo Carlos — y se fue.", "Bien.", "Sí."]))+ assert got == [["dijo Carlos", "y se fue"], [], []]+++def test_german_quotes_are_speech():+ par = "»Effi, komm«, sagte die Mama, »wir müssen gehen.«"+ assert cast.has_speech(par)+ assert cast.pieces(par, "f") == [+ ("»Effi, komm«", "women"),+ ("sagte die Mama,", "narrator"),+ ("»wir müssen gehen.«", "women"),+ ]+++def test_two_hyphens_open_a_dialogue_line():+ assert narration.clean_text("--No puedo equivocarme — murmuró —. Me dijeron.").startswith("— No puedo")+++ ("language", "par", "want"),+ [+ (+ "es",+ "— ¡Zapatos a la Nela! — exclamó Sofía riendo —. Y yo pregunto: ¿para qué?",+ [+ ("¡Zapatos a la Nela!", "men"),+ ("exclamó Sofía riendo", "narrator"),+ ("Y yo pregunto: ¿para qué?", "men"),+ ],+ ),+ (+ "fr",+ "— Ce cheval est bouton d’or, reprit l’inconnu continuant ses investigations, voilà tout.",+ [+ ("Ce cheval est bouton d’or,", "men"),+ ("reprit l’inconnu continuant ses investigations", "narrator"),+ ("voilà tout.", "men"),+ ],+ ),+ (+ "fr",+ "— Paie, maroufle», s’écria le voyageur toujours galopant.",+ [("Paie, maroufle»", "men"), ("s’écria le voyageur toujours galopant.", "narrator")],+ ),+ (+ "it",+ "— Anche per questa volta ti perdono: — gli disse la Fata — ma guai a te!",+ [+ ("Anche per questa volta ti perdono:", "men"),+ ("gli disse la Fata", "narrator"),+ ("ma guai a te!", "men"),+ ],+ ),+ ],+)+def test_without_the_models_remarks_the_languages_rules_cut_the_line(language, par, want):+ assert cast.pieces(par, "m", (), language) == want+ assert cast.pieces(par, "m", ["a remark that is not there"], language) == want+++def test_the_languages_rules_also_cut_what_the_model_left_as_speech():+ par = "— ¡Zapatos a la Nela! — exclamó Sofía riendo —. Y yo pregunto — dijo luego — ¿para qué?"+ assert cast.pieces(par, "f", ["dijo luego"], "es") == [+ ("¡Zapatos a la Nela!", "women"),+ ("exclamó Sofía riendo", "narrator"),+ ("Y yo pregunto", "women"),+ ("dijo luego", "narrator"),+ ("¿para qué?", "women"),+ ]+++def test_a_voice_can_be_made_in_any_language_a_speech_model_speaks(tmp_path):+ from mimvox_engine import backends, voices+ from mimvox_engine.registry import EngineError++ class Ctx:+ data_dir = str(tmp_path)++ assert "it" in backends.languages()+ made = voices.voices_create(Ctx(), {"name": "Narratore", "language": "it"})["voice"]+ assert voices.read_meta(voices.config.data_dir(Ctx()), made["id"])["language"] == "it"+ with pytest.raises(EngineError):+ voices.voices_create(Ctx(), {"name": "Nobody", "language": "xx"})+++def test_a_book_is_detected_among_every_language_the_speech_models_speak(tmp_path, monkeypatch):+ from mimvox_engine import backends, textimport, textlang++ seen = {}++ def detect(text, among):+ seen["among"] = set(among)+ return "ja" if "ja" in among else None++ monkeypatch.setattr(textlang, "detect", detect)+ monkeypatch.setattr(backends, "languages", lambda: {"en", "ja", "uk"})+ book = tmp_path / "book.txt"+ book.write_text("吾輩は猫である。名前はまだ無い。\n\nどこで生れたかとんと見当がつかぬ。", encoding="utf-8")+ got = textimport.text_import(None, {"path": str(book)})+ assert got["language"] == "ja"+ assert {"ja", "en", "uk"} <= seen["among"]+++def test_the_installed_component_is_reported_even_when_turned_off(tmp_path, monkeypatch):+ cast.server_path(tmp_path).parent.mkdir(parents=True)+ cast.server_path(tmp_path).write_bytes(b"x")+ cast.model_path(tmp_path).parent.mkdir(parents=True)+ cast.model_path(tmp_path).write_bytes(b"x")+ monkeypatch.setattr(cast.components, "off", lambda name: name == "cast")+ assert cast.installed(tmp_path, honour_off=False)+ assert not cast.installed(tmp_path)diff --git a/engine/tests/test_setup_tool.py b/engine/tests/test_setup_tool.pyindex 83b0e45..cdaba06 100644--- a/engine/tests/test_setup_tool.py+++ b/engine/tests/test_setup_tool.py@@ -533,3 +533,36 @@ def test_a_download_still_to_fetch_counts_what_is_missing(tmp_path, monkeypatch)(tmp_path / "config.json").write_text("x" * 20)assert setup.hf_bytes("a/b", tmp_path) == 3_000_000assert setup.hf_bytes("a/b", tmp_path, ("config.json",)) == 0+++def test_character_voices_take_the_gemma_file_sing_left(tmp_path, monkeypatch):+ s = make(tmp_path / "data")+ old = s.models_dir / setup.CAST_OLD_DIR / setup.CAST_FILE+ old.parent.mkdir(parents=True)+ old.write_bytes(b"gemma")+ monkeypatch.setattr(setup, "CAST_SIZE", 5)+ monkeypatch.setattr(setup, "CAST_SHA256", setup.sha256_of(old))+ monkeypatch.setattr(setup, "fetch_checked", lambda *a: pytest.fail("downloaded again"))+ s.cast_model()+ assert (s.models_dir / setup.CAST_DIR / setup.CAST_FILE).read_bytes() == b"gemma"+ assert not old.parent.exists()+++def test_llama_build_follows_the_gpu(tmp_path, nvidia):+ s = make(tmp_path / "a")+ s.detect()+ assert "cuda" in s.llama_build()[0]+ assert (+ "macos-arm64"+ in setup.Setup(root=tmp_path, plat="macos", arch="arm64", data_dir=tmp_path / "b", uv_path="uv").llama_build()[+ 0+ ]+ )+++def test_character_voices_are_left_out_on_a_small_gpu(tmp_path, nvidia, capsys):+ s = make(tmp_path / "data")+ s.detect()+ s.resolve_components(setup.parse_args([]))+ assert "cast" not in s.components+ assert "Character voices left out" in capsys.readouterr().outdiff --git a/engine/tests/test_speech_models.py b/engine/tests/test_speech_models.pyindex 7bfac67..e36ff1e 100644--- a/engine/tests/test_speech_models.py+++ b/engine/tests/test_speech_models.py@@ -64,6 +64,13 @@ def test_a_model_that_does_not_speak_the_language_is_refused(tmp_path):assert e.value.code == "bad_request" and "Ukrainian" in e.value.message+def test_omnivoice_with_exact_stress_reads_ukrainian_with_holos(monkeypatch):+ holos = backends.by_name("holos")+ monkeypatch.setattr(holos, "available", lambda: True)+ assert tts.speech_language({"language": "uk", "model": "omnivoice"})[1] is holos+ assert tts.speech_language({"language": "uk", "model": "omnivoice", "exact_stress": False})[1] is not holos++def test_an_unknown_or_missing_model(tmp_path):probe(install(tmp_path))with pytest.raises(EngineError) as e:diff --git a/engine/tests/test_voice_design.py b/engine/tests/test_voice_design.pyindex 5065914..ffc5870 100644--- a/engine/tests/test_voice_design.py+++ b/engine/tests/test_voice_design.py@@ -174,14 +174,10 @@ def test_ukrainian_is_read_again_by_holos(tmp_path, ctx, monkeypatch):sf.write(params.out_path, np.zeros(48000, np.float32), 24000)return str(params.out_path)- async def no_converter(*_a):- return None-monkeypatch.setattr(OMNIVOICE, "_status", "ready")monkeypatch.setattr(OMNIVOICE, "design", fake_design([]))monkeypatch.setattr(HOLOS, "_status", "ready")monkeypatch.setattr(HOLOS, "synthesize", holos_says)- monkeypatch.setattr(tts, "holos_timbre", no_converter)res = run(ctx, model="omnivoice", language="uk", text="Привіт", description="male")assert res["exact_stress"] is True and res["duration_s"] == 2.0assert res["path"].endswith("speech.wav") and res["reference"].endswith("voice.wav")@@ -369,5 +365,55 @@ def test_a_voice_can_be_made_in_any_language_a_speech_model_speaks(tmp_path, monassert voices.read_meta(voices.config.data_dir(Ctx()), made["id"])["language"] == "it"voices.voices_rename(Ctx(), {"id": made["id"], "language": "en"})assert voices.read_meta(voices.config.data_dir(Ctx()), made["id"])["language"] == "en"+ voices.voices_rename(Ctx(), {"id": made["id"], "book_role": "men"})+ meta = voices.read_meta(voices.config.data_dir(Ctx()), made["id"])+ assert meta["book_role"] == "men" and meta["name"] == "Narratore"+ with pytest.raises(EngineError):+ voices.voices_rename(Ctx(), {"id": made["id"], "book_role": "children"})with pytest.raises(EngineError):voices.voices_create(Ctx(), {"name": "Nobody", "language": "xx"})+++def test_a_voice_made_anew_keeps_its_id(tmp_path):+ import numpy as np+ import soundfile as sf+ from mimvox_engine import voices++ class Ctx:+ data_dir = str(tmp_path)++ clip = tmp_path / "a.wav"+ sf.write(clip, np.zeros(16000, dtype=np.float32), 16000)+ made = voices.import_voice(Ctx(), {"name": "Book · men", "reference_path": str(clip)})["voice"]+ data = voices.config.data_dir(Ctx())+ (data.voice(made["id"]) / "reference.omnivoice.json").write_text("{}")+ sf.write(clip, np.ones(8000, dtype=np.float32) * 0.1, 16000)+ again = voices.import_voice(Ctx(), {"name": "Book · men", "reference_path": str(clip), "into": made["id"]})["voice"]+ assert again["id"] == made["id"]+ assert len(sf.read(data.reference(made["id"]))[0]) == 8000+ assert not (data.voice(made["id"]) / "reference.omnivoice.json").exists()+ assert len(list((tmp_path / "voices").iterdir())) == 1+++def test_a_voice_made_for_a_book_remembers_the_book_and_role(tmp_path):+ from mimvox_engine import voices++ class Ctx:+ data_dir = str(tmp_path)++ ref = tmp_path / "take.wav"+ t = np.linspace(0, 3.0, 72000, endpoint=False)+ sf.write(ref, (0.2 * np.sin(2 * np.pi * 180 * t)).astype(np.float32), 24000)+ made = voices.voices_import(+ Ctx(),+ {+ "name": "Мартін Іден · men",+ "reference_path": str(ref),+ "language": "uk",+ "book": "Мартін Іден",+ "book_role": "men",+ },+ )["voice"]+ assert (made["book"], made["book_role"]) == ("Мартін Іден", "men")+ plain = voices.voices_import(Ctx(), {"name": "Mine", "reference_path": str(ref), "language": "uk"})["voice"]+ assert plain["book"] is Nonediff --git a/tools/setup/setup.py b/tools/setup/setup.pyindex e6f3a90..faaa79e 100644--- a/tools/setup/setup.py+++ b/tools/setup/setup.py@@ -4,6 +4,7 @@ before anything else is installed."""from __future__ import annotationsimport argparse+import contextlibimport hashlibimport jsonimport os@@ -206,6 +207,56 @@ DEMUCS_DIR = "demucs"DEMUCS_FILE = "hdemucs_high_trained.pt"DEMUCS_SIZE = 334_697_255DEMUCS_SHA256 = "a004b2790d73ffeaa535db458a1a79b539dfdbafbccc31f275d07e632ebd7816"+# llama.cpp's prebuilt llama-server (MIT) for Character voices: (archive, its SHA-256) per platform, GPU and+# architecture; the CUDA builds use the CUDA runtime and cuBLAS that come with the engine's torch.+LLAMA_RELEASE = "b12818"+LLAMA_URL = "https://github.com/ggml-org/llama.cpp/releases/download/{release}/{name}"+LLAMA_BUILDS = {+ ("linux", "x64", "cuda"): (+ "llama-b12818-bin-ubuntu-cuda-12.8-x64.tar.gz",+ "15357a570be29f2698d6d0a1e4e0a891f50adf7eb67a81b12b6ea1159ebdabf8",+ ),+ ("linux", "x64", "vulkan"): (+ "llama-b12818-bin-ubuntu-vulkan-x64.tar.gz",+ "d9eb24826e4fd20ca3ca22feb2087faae21184606fd595602ca8704510b78317",+ ),+ ("linux", "arm64", "vulkan"): (+ "llama-b12818-bin-ubuntu-vulkan-arm64.tar.gz",+ "e007a8c3fd71f8da5f7cfc654094460e581b59a813b86bc5e6b81b5586ef441e",+ ),+ ("windows", "x64", "cuda"): (+ "llama-b12818-bin-win-cuda-12.4-x64.zip",+ "3966a614a31b695c13f80649b393e32e0f5b65e5a3d57a58be2afa1f9ddd8265",+ ),+ ("windows", "x64", "vulkan"): (+ "llama-b12818-bin-win-vulkan-x64.zip",+ "b4ae261e98b2d74a2fa2167175d5f5441a3219fb2592228d207223cb5e961982",+ ),+ ("windows", "arm64", "vulkan"): (+ "llama-b12818-bin-win-vulkan-arm64.zip",+ "225bd3d1611fa55842c146d11923a1cc55bab17a587673eac8bdfe1c4c554bc9",+ ),+ ("macos", "arm64", "metal"): (+ "llama-b12818-bin-macos-arm64.tar.gz",+ "b05fc72e0ed39d343f7e955d3fc67087ea56e161dc0cfb462f5f0163af372234",+ ),+ ("macos", "x64", "metal"): (+ "llama-b12818-bin-macos-x64.tar.gz",+ "fb387c67db69f9b40ff920a54353f235b8c112744a662350a3f129940dfaf85a",+ ),+}+LLAMA_DIR = "llama" # <runtime>/llama, also in engine/src/mimvox_engine/cast.py+LLAMA_STAMP = ".mimvox-llama"+# Gemma 4 12B instruct (Apache-2.0), Q4_K_M: who speaks each line of a book (engine cast.py).+CAST_REPO = "unsloth/gemma-4-12b-it-GGUF"+CAST_REVISION = "fc034cfff751157913579611efad8462ac1be606"+CAST_FILE = "gemma-4-12b-it-Q4_K_M.gguf"+CAST_SIZE = 7_121_861_440+CAST_SHA256 = "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42"+CAST_DIR = "llm"+CAST_OLD_DIR = "lyrics" # where the dropped Sing feature kept the same file+CAST_GB = 7.4+CAST_MIN_VRAM_GB = 10.0 # 7.7 GB on the GPU while it reads, plus the desktop's shareENGINE_DIR = "engine"UV_PYTHON_DIR = "python" # <runtime>/python, also in move_runtime.fix_venv_paths and crates/desktop/src/ui/setuprun.rsENGINE_PYTHON = "3.14"@@ -269,6 +320,7 @@ COMPONENTS = {"ukrainian": UKRAINIAN_GB, # HolosTTS: Ukrainian with exact word stress"voxcpm": 6.0,"chatterbox": 4.3,+ "cast": CAST_GB, # Gemma 4 12B and llama.cpp: Book mode reads each character's lines in a man's or woman's voice}SPEECH_MODELS = ("omnivoice", "voxcpm", "chatterbox")# Portable ffmpeg for Windows when Applio (which brings one) is not installed.@@ -814,6 +866,8 @@ class Setup:"speech_models": 2.5,"better_translation": NLLB_BIG_DOWNLOAD_GB,"separation": SEPARATION_GB,+ "cast_runtime": 0.3,+ "cast_model": CAST_SIZE / 1e9,"zero_shot_vc": ZERO_SHOT_GB,"holos_env": UKRAINIAN_GB - 0.9,"holos_models": 0.9,@@ -837,6 +891,8 @@ class Setup:"speech_models": lambda: self._has(models / NLLB_DIR, NLLB_REQUIRED),"better_translation": self.has_better_translation,"separation": (models / DEMUCS_DIR / DEMUCS_FILE).is_file,+ "cast_runtime": self.has_llama,+ "cast_model": (models / CAST_DIR / CAST_FILE).is_file,"zero_shot_vc": self.has_zero_shot_vc,"holos_env": lambda: self.holos_python().exists(),"holos_models": (self.holos_models / HOLOS_STAMP).is_file,@@ -1050,6 +1106,17 @@ class Setup:"Better translation left out: it runs on an NVIDIA or AMD GPU (--add better_translation installs it ""anyway).")+ if (+ "cast" in chosen+ and not args.components+ and not (previous and "cast" in previous)+ and not (self.gpu.backend == "mps" or (self.gpu.backend == "cuda" and self.gpu.vram_gb >= CAST_MIN_VRAM_GB))+ ):+ chosen.discard("cast")+ say(+ f"Character voices left out: they need a GPU with {CAST_MIN_VRAM_GB:g} GB of memory or a Mac "+ "(--add cast installs them anyway)."+ )if args.add:chosen |= parse(args.add)if args.better_translation == "yes":@@ -1141,6 +1208,7 @@ class Setup:"ukrainian": "Ukrainian speech (HolosTTS)","voxcpm": "VoxCPM2 voice cloning","chatterbox": "Chatterbox voice cloning",+ "cast": "character voices for books (Gemma 4 12B)",}chosen = [c for c in COMPONENTS if c in self.components]parts = ", ".join(f"{labels[c]} ~{COMPONENTS[c]:g} GB" for c in chosen)@@ -1749,6 +1817,7 @@ class Setup:"native_accent": [self.seed_vc, self.seed_vc_models],"music_removal": [self.models_dir / DEMUCS_DIR],"ukrainian": [self.holos_venv.parent, self.holos_models],+ "cast": [self.llama_dir, self.models_dir / CAST_DIR],**{name: [self.clone_venv(name).parent, self.clone_models_dir(name)] for name in CLONE_MODELS},}[component]@@ -1860,6 +1929,81 @@ class Setup:size = (target / "model.safetensors").stat().st_size / 1e9say(f"Better translation model: ready ({size:.1f} GB).")+ @property+ def llama_dir(self) -> Path:+ return self.runtime / LLAMA_DIR++ def llama_build(self) -> tuple[str, str]:+ """The llama.cpp archive for this machine: CUDA with an NVIDIA GPU, Metal on a Mac, Vulkan otherwise (it also+ runs on the CPU)."""+ arch = "arm64" if self.arch == "arm64" else "x64"+ if self.plat == "macos":+ kind = "metal"+ elif self.gpu.vendor == "nvidia" and arch == "x64":+ kind = "cuda"+ else:+ kind = "vulkan"+ build = LLAMA_BUILDS.get((self.plat, arch, kind))+ if build is None:+ raise SetupError(f"llama.cpp has no prebuilt server for {self.plat} on {arch}.")+ return build++ def has_llama(self) -> bool:+ exe = "llama-server.exe" if self.plat == "windows" else "llama-server"+ stamp = self.llama_dir / LLAMA_STAMP+ try:+ return (self.llama_dir / exe).is_file() and stamp.read_text().strip() == self.llama_build()[0]+ except (OSError, SetupError):+ return False++ def cast_runtime(self) -> None:+ if self.has_llama():+ say("Character voices runtime (llama.cpp): present.")+ return+ name, sha256 = self.llama_build()+ say(f"Character voices runtime: downloading llama.cpp {LLAMA_RELEASE} ({name})...")+ url = LLAMA_URL.format(release=LLAMA_RELEASE, name=name)+ expect_download(url_bytes(url))+ archive = self.temp_dir() / name+ fetch_checked(url, archive, sha256, "llama.cpp")+ unpack = self.temp_dir() / "llama-unpack"+ _rmtree(unpack)+ unpack.mkdir(parents=True)+ if name.endswith(".zip"):+ with zipfile.ZipFile(archive) as z:+ z.extractall(unpack) # noqa: S202 - zipfile drops absolute paths and ".." from member names+ else:+ with tarfile.open(archive) as tar:+ tar.extractall(unpack, filter="data")+ entries = list(unpack.iterdir())+ root = entries[0] if len(entries) == 1 and entries[0].is_dir() else unpack+ _rmtree(self.llama_dir)+ shutil.move(str(root), str(self.llama_dir))+ _rmtree(unpack)+ archive.unlink(missing_ok=True)+ (self.llama_dir / LLAMA_STAMP).write_text(name + "\n")+ if not self.has_llama():+ raise SetupError(f"llama-server is missing from {name}.")+ say(f"Character voices runtime: installed in {self.llama_dir}.")++ def cast_model(self) -> None:+ target = self.models_dir / CAST_DIR / CAST_FILE+ if target.is_file():+ say("Character voices model (Gemma 4 12B): present.")+ return+ old = self.models_dir / CAST_OLD_DIR / CAST_FILE+ if old.is_file() and old.stat().st_size == CAST_SIZE and sha256_of(old) == CAST_SHA256:+ target.parent.mkdir(parents=True, exist_ok=True)+ old.replace(target)+ with contextlib.suppress(OSError):+ old.parent.rmdir()+ say("Character voices model (Gemma 4 12B): moved from the earlier lyrics folder.")+ return+ say(f"Character voices model: downloading Gemma 4 12B (about {CAST_SIZE / 1e9:.1f} GB, resumable)...")+ expect_download(CAST_SIZE)+ url = f"https://huggingface.co/{CAST_REPO}/resolve/{CAST_REVISION}/{CAST_FILE}"+ fetch_checked(url, target, CAST_SHA256, "the character voices model")+def separation_model(self) -> None:target = self.models_dir / DEMUCS_DIR / DEMUCS_FILEif target.is_file() and target.stat().st_size == DEMUCS_SIZE:@@ -2520,6 +2664,14 @@ def fetch_checked(url: str, target: Path, sha256: str, label: str) -> None:say(f"Saved {target}.")+def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for block in iter(lambda: handle.read(1 << 20), b""):+ digest.update(block)+ return digest.hexdigest()++def fetch_demucs(models_dir: Path) -> Path:"""Resumable through a ``.part`` file, checked against the pinned SHA-256."""folder = models_dir / DEMUCS_DIR@@ -2740,6 +2892,7 @@ def remove_components(setup: Setup, value: str) -> int:"native_accent": "Native accent","music_removal": "Music removal","ukrainian": "Ukrainian speech",+ "cast": "Character voices",**{name: f"{spec['label']} voice cloning" for name, spec in CLONE_MODELS.items()},}plan = [(f"remove_{c}", f"Removing {labels[c].lower()}") for c in items] + [("runtime_toml", "Finishing")]@@ -2910,6 +3063,10 @@ def main(argv: Sequence[str] | None = None) -> int:plan.append(("better_translation", "Better translation model"))if has("music_removal"):plan.append(("separation", "Music removal model"))+ if has("cast"):+ plan.append(("cast_runtime", "Character voices: runtime"))+ if models:+ plan.append(("cast_model", "Character voices: model"))if zero_shot:plan.append(("zero_shot_vc", "Native accent converter"))ukrainian = has("ukrainian")@@ -2975,6 +3132,11 @@ def main(argv: Sequence[str] | None = None) -> int:attempt("separation", setup.separation_model)else:skipped("omnivoice", "whisper", "speech_models", "better_translation", "separation")+ if has("cast") and attempt("cast_runtime", setup.cast_runtime):+ if models:+ attempt("cast_model", setup.cast_model)+ else:+ skipped("cast_model")if zero_shot and setup.engine_python().exists():attempt("zero_shot_vc", setup.zero_shot_vc_runtime)else: