Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

fix: safe deletes in setup, Design takes and Search again (#186)

Taras Hevlich5e901fb86e37
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0288e5..caa51a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,12 @@
## Unreleased
+* **Deleting a design take can no longer delete anything else:** a take id from a program (API, MCP) must be one the
+ app made; before, the id ".." deleted the whole data folder.
+* **A setup step that cannot delete or move a file fails on its own** (a file in use on Windows, say) instead of
+ stopping the whole setup; removing a component that is a link to another drive removes only the link.
+* **Search again keeps the speakers found before** until the new search is done; a busy engine or a cancel no longer
+ leaves the book without them.
* **Setup finishes again with Character voices:** a first install with them (on by default with a GPU of 10 GB or a
Mac) stopped at "Character voices: runtime" with a FileNotFoundError, and so did adding them in Settings > Modules.
* **Release pages start with a download table:** the Windows, Linux and macOS installers, each a direct link, above
diff --git a/engine/src/mimvox_engine/book.py b/engine/src/mimvox_engine/book.py
index 2319d50..2bcdf4a 100644
--- a/engine/src/mimvox_engine/book.py
+++ b/engine/src/mimvox_engine/book.py
@@ -651,18 +651,27 @@ async def book_cast(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
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
+ ctx,
+ lambda j: _cast_job(ctx, j, data, texts, todo, book, key, again),
+ "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
+ ctx: Context,
+ job: str,
+ data: config.DataDir,
+ texts: list[str],
+ todo: list[str],
+ book: dict[str, Any],
+ key: str,
+ again: bool,
) -> None:
def progress(pct: float) -> None:
ctx.emit("book.cast_progress", {"key": key, "pct": round(pct * 100, 1)}, job=job)
@@ -674,7 +683,7 @@ async def _cast_job(
try:
progress(0.0)
- found = await _search(ctx, data, texts, todo, book, progress, job)
+ found = await _search(ctx, data, texts, todo, book, progress, job, again=again)
end("book.cast_done", _cast_summary(found))
except asyncio.CancelledError:
end("book.cast_error", {"code": "cancelled", "message": "finding the speakers was cancelled"})
@@ -1591,13 +1600,17 @@ async def _search(
book: dict[str, Any],
progress: cast.Progress,
job: str,
+ again: bool = False,
) -> dict[str, Any]:
- """Searches only the chapters never searched (`todo`), then puts the result for `texts` together."""
+ """Searches only the chapters never searched (`todo`), then puts the result for `texts` together. With `again`
+ the result kept for `texts` goes only once the new search is saved, so a refused or cancelled one keeps it."""
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)
+ if again and cast.key(todo, lang, mode) != cast.key(texts, lang, mode):
+ await aio.run_io(lambda: _cast_path(data, cast.key(texts, lang, mode)).unlink(missing_ok=True))
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")
diff --git a/engine/src/mimvox_engine/design.py b/engine/src/mimvox_engine/design.py
index 0bb7592..26dc5bf 100644
--- a/engine/src/mimvox_engine/design.py
+++ b/engine/src/mimvox_engine/design.py
@@ -8,6 +8,7 @@ import itertools
import json
import logging
import math
+import re
import shutil
import time
from pathlib import Path
@@ -72,6 +73,9 @@ def folder(data: config.DataDir) -> Path:
return data.root / "design"
+TAKE_ID = re.compile(r"\d{8}-\d{6}-\d{9}")
+
+
def _new_take(root: Path) -> Path:
now = time.time_ns()
take = root / f"{time.strftime('%Y%m%d-%H%M%S', time.localtime(now / 1e9))}-{now % 10**9:09d}"
@@ -309,7 +313,7 @@ def voices_design_delete(ctx: Context, params: dict[str, Any]) -> dict[str, Any]
doomed = [p for p in root.iterdir() if (p / "take.json").is_file()] if root.is_dir() else []
else:
take = params.get("id")
- if not isinstance(take, str) or not take or Path(take).name != take or not (root / take).is_dir():
+ if not isinstance(take, str) or not TAKE_ID.fullmatch(take) or not (root / take).is_dir():
raise EngineError("not_found", f"no design take {take!r}")
doomed = [root / take]
for p in doomed:
diff --git a/engine/tests/test_cast.py b/engine/tests/test_cast.py
index 21736da..19b0237 100644
--- a/engine/tests/test_cast.py
+++ b/engine/tests/test_cast.py
@@ -472,3 +472,56 @@ def test_the_installed_component_is_reported_even_when_turned_off(tmp_path, monk
monkeypatch.setattr(cast.components, "off", lambda name: name == "cast")
assert cast.installed(tmp_path, honour_off=False)
assert not cast.installed(tmp_path)
+
+
+def test_a_search_again_that_cannot_start_keeps_the_result(data, monkeypatch):
+ one = "Narration.\n\n“Hello there,” said Ruth."
+ two = "No dialogue in this one."
+ found = {
+ "version": cast.VERSION,
+ "mode": "fast",
+ "language": "en",
+ "narrator": {"first_person": False, "name": ""},
+ "characters": [{"name": "Ruth", "gender": "f", "lines": 1}],
+ "lines": {"men": 0, "women": 1, "narrator": 0},
+ "chapters": [{"roles": {"1": "f"}, "remarks": {}}, {"roles": {}, "remarks": {}}],
+ }
+ book._save_cast(data, cast.key([one, two], "en", "fast"), found, [one, two])
+ monkeypatch.setattr(cast, "installed", lambda root: True)
+
+ def busy(*_a):
+ raise EngineError("busy", "another generation is running")
+
+ monkeypatch.setattr(book.tts, "start_exclusive", busy)
+ chapters = [{"title": "One", "text": one}, {"title": "Two", "text": two}]
+ params = {"chapters": chapters, "language": "en", "cast": "fast", "again": True}
+ with pytest.raises(EngineError):
+ asyncio.run(book.book_cast(Ctx(str(data.root)), params))
+ kept = book._cached_cast(data, [one, two], "en", "fast")
+ assert kept is not None and kept["characters"] == found["characters"]
+
+
+def test_a_search_again_replaces_the_result_of_the_whole_book(data, monkeypatch):
+ one = "Narration.\n\n“Hello there,” said Ruth."
+ two = "No dialogue in this one."
+ old = {
+ "version": cast.VERSION,
+ "mode": "fast",
+ "language": "en",
+ "narrator": {"first_person": False, "name": ""},
+ "characters": [{"name": "Ruth", "gender": "f", "lines": 1}],
+ "chapters": [{"roles": {"1": "f"}, "remarks": {}}, {"roles": {}, "remarks": {}}],
+ }
+ book._save_cast(data, cast.key([one, two], "en", "fast"), old, [one, two])
+ new = {**old, "characters": [{"name": "Rob", "gender": "m", "lines": 1}], "chapters": [{"roles": {"1": "m"}}]}
+
+ async def analyze(*_a):
+ return new
+
+ monkeypatch.setattr(book, "_analyze", analyze)
+ b = {"settings": {"language": "en", "cast": "fast"}}
+ found = asyncio.run(
+ book._search(Ctx(str(data.root)), data, [one, two], [one], b, lambda p: None, "job1", again=True)
+ )
+ assert found["characters"] == new["characters"]
+ assert [c["roles"] for c in found["chapters"]] == [{"1": "m"}, {}]
diff --git a/engine/tests/test_setup_tool.py b/engine/tests/test_setup_tool.py
index d6ac82d..59f7808 100644
--- a/engine/tests/test_setup_tool.py
+++ b/engine/tests/test_setup_tool.py
@@ -597,3 +597,19 @@ def test_character_voices_are_left_out_on_a_small_gpu(tmp_path, nvidia, capsys):
s.resolve_components(setup.parse_args([]))
assert "cast" not in s.components
assert "Character voices left out" in capsys.readouterr().out
+
+
+def test_rmtree_skips_a_missing_path_and_leaves_a_links_target(tmp_path):
+ setup._rmtree(tmp_path / "never-made")
+ target = tmp_path / "models-on-another-drive"
+ (target / "omnivoice").mkdir(parents=True)
+ (target / "omnivoice" / "model.safetensors").write_bytes(b"w")
+ link = tmp_path / "runtime" / "models"
+ link.parent.mkdir()
+ link.symlink_to(target, target_is_directory=True)
+ setup._rmtree(link)
+ assert not link.exists() and not link.is_symlink()
+ assert (target / "omnivoice" / "model.safetensors").read_bytes() == b"w"
+ assert (target.stat().st_mode & 0o777) != 0o700 or os.name == "nt"
+ setup._rmtree(target)
+ assert not target.exists()
diff --git a/engine/tests/test_voice_design.py b/engine/tests/test_voice_design.py
index ffc5870..f699c83 100644
--- a/engine/tests/test_voice_design.py
+++ b/engine/tests/test_voice_design.py
@@ -1,5 +1,6 @@
import asyncio
import types
+from pathlib import Path
import numpy as np
import pytest
@@ -213,11 +214,15 @@ def test_takes_are_deleted_one_by_one_or_all(tmp_path, ctx, monkeypatch):
ids = [run(ctx, model="voxcpm", language="en", text=f"Take {i}")["id"] for i in range(3)]
left = design.voices_design_delete(ctx, {"id": ids[1]})["takes"]
assert [t["id"] for t in left] == [ids[2], ids[0]]
- for bad in ("../voices", "", None, "nope"):
+ keep = Path(ctx.data_dir) / "voices" / "mine.txt"
+ keep.parent.mkdir(parents=True, exist_ok=True)
+ keep.write_text("x")
+ for bad in ("../voices", "..", ".", "", None, "nope", f"{ids[0]}/.."):
with pytest.raises(EngineError) as e:
design.voices_design_delete(ctx, {"id": bad})
assert e.value.code == "not_found"
assert design.voices_design_delete(ctx, {"all": True})["takes"] == []
+ assert keep.is_file()
def test_an_omnivoice_take_nobody_can_hear_is_made_again(tmp_path, ctx, monkeypatch, hears_the_text):
diff --git a/tools/setup/setup.py b/tools/setup/setup.py
index 03996ee..059007e 100644
--- a/tools/setup/setup.py
+++ b/tools/setup/setup.py
@@ -2914,10 +2914,17 @@ def ask_data_dir(plat: str, default: Path) -> Path:
def _rmtree(path: Path) -> None:
- if not os.path.lexists(path):
+ """Deletes a folder; a symlink or junction is removed as a link and its target stays."""
+ if path.is_symlink():
+ path.unlink()
+ return
+ if path.is_junction():
+ path.rmdir()
return
- def writable(func, target, _exc) -> None: # noqa: ANN001 - shutil's callback
+ def writable(func, target, exc) -> None: # noqa: ANN001 - shutil's callback
+ if isinstance(exc, FileNotFoundError):
+ return
# Windows refuses to delete read-only files (git objects, some wheels).
Path(target).chmod(0o700)
func(target)
@@ -3153,7 +3160,7 @@ def main(argv: Sequence[str] | None = None) -> int:
meter = StepMeter(setup.data_dir, step_id, setup.step_gb(step_id)) if GUI else None
try:
step()
- except SetupError as error:
+ except (SetupError, OSError) as error:
say(f"Failed: {error}")
failed.append(str(error))
event(event="step", id=step_id, state="fail", message=str(error))