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.

21.7 KB
Raw Blame
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."]


@pytest.fixture
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"})


@pytest.fixture
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


@pytest.mark.parametrize(
    ("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")


@pytest.mark.parametrize(
    ("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)


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"}, {}]