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.

31.3 KB
Raw Blame
"""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")]