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.

12.5 KB
Raw Blame
"""``voices.design``: a take in a new voice made from a description, kept as a voice with ``voices.import``."""

from __future__ import annotations

import asyncio
import difflib
import itertools
import json
import logging
import math
import re
import shutil
import time
from pathlib import Path
from typing import Any

import numpy as np
import soundfile as sf

from . import aio, backends, config, dubmix, reflang, tts
from .backends import SynthParams
from .backends.holos import HOLOS
from .backends.omnivoice import OMNIVOICE
from .registry import Context, EngineError, method

log = logging.getLogger("mimvox.design")

KEEP = 40
TRIES = 3
CLEAR = 0.6
HOLOS_WAIT_S = 120.0
HEARD_MIN = 30
HEAR_S = 12.0
DESCRIPTION_MAX = 400
# VoxCPM2 takes came out anywhere from -30 to -42 LUFS, OmniVoice ones at -23 to -25.
LOUDNESS = -23.0
LOUDNESS_RANGE = (-40.0, -10.0)
PEAK_DBFS = -1.0
# VoxCPM2's hum stood 11-15 dB over the neighbouring bands in 3 takes of 11; the other 8 at most 8 dB.
HUM_DB = 10.0

_running: list[asyncio.Task[dict[str, Any]] | None] = [None]


def _designer(model: Any, lang: str) -> backends.TtsBackend:
    if model in (None, "", "auto"):
        for b in backends.all_backends():
            if b.designs and b.status() != "missing" and lang in b.languages:
                return b
        raise EngineError(
            "not_ready", f"No model installed here makes voices that speak {lang!r}: add OmniVoice or VoxCPM2"
        )
    backend = tts.named_model(model, lang)
    if not backend.designs:
        names = ", ".join(b.name for b in backends.all_backends() if b.designs)
        raise EngineError("bad_request", f"{backend.label} cannot make a voice from a description (use {names})")
    return backend


def _text(params: dict[str, Any], key: str, limit: int | None, required: bool) -> str:
    value = params.get(key) or ""
    if not isinstance(value, str):
        raise EngineError("bad_request", f"'{key}' must be a string")
    value = " ".join(value.split())
    if required and not value:
        raise EngineError("bad_request", f"'{key}' must be a non-empty string")
    if limit is not None and len(value) > limit:
        raise EngineError("bad_request", f"The {key} is longer than {limit} characters: make it shorter.")
    return value


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}"
    take.mkdir(parents=True)
    return take


def _prune(root: Path) -> None:
    takes = sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.name, reverse=True)
    for old in takes[KEEP:]:
        shutil.rmtree(old, ignore_errors=True)


def _read(take: Path) -> dict[str, Any] | None:
    try:
        meta = json.loads((take / "take.json").read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None
    paths = {k: take / meta[k] for k in ("path", "reference") if isinstance(meta.get(k), str)}
    if "path" not in paths or "reference" not in paths or not all(p.is_file() for p in paths.values()):
        return None
    d = take.name
    when = f"{d[0:4]}-{d[4:6]}-{d[6:8]} {d[9:11]}:{d[11:13]}:{d[13:15]}"
    return {**meta, "id": d, "when": when, **{k: str(p) for k, p in paths.items()}}


def _save(take: Path, meta: dict[str, Any]) -> dict[str, Any]:
    (take / "take.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
    _prune(take.parent)
    out = _read(take)
    if out is None:
        raise EngineError("internal", "the take could not be kept")
    return out


def said(text: str, heard: str) -> float:
    """How well what Whisper heard matches ``text`` (0..1), letters and digits only. Whisper hears one stretch of a
    long take, so the stretch is matched against the part of the text it fits best; less than HEARD_MIN letters heard
    counts for less."""
    norm = lambda t: "".join(ch for ch in t.casefold() if ch.isalnum())  # noqa: E731
    a, b = norm(text), norm(heard)
    if not a or not b:
        return 0.0
    n = len(b)
    if len(a) <= n * 5 // 4:
        return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio()
    step = max(1, n // 4)
    best = max(
        difflib.SequenceMatcher(None, a[i : i + n], b, autojunk=False).ratio()
        for i in range(0, len(a) - n + step, step)
    )
    return best * min(1.0, n / min(len(a), HEARD_MIN))


async def _hear(path: Path) -> str:
    """Whisper's transcript of the first HEAR_S of a take ("" when it heard no speech): the whole of a long take took
    28 s on the CPU, where Whisper goes when the card is full."""
    head = path.with_name("heard.wav")
    await aio.run_io(_head, path, head)
    try:
        await OMNIVOICE.inspect(str(head), detect=False)
        side = await aio.run_io(reflang.read_sidecar, head)
        return str((side or {}).get("text") or "")
    finally:
        await aio.run_io(_drop_heard, head)


def _head(src: Path, dst: Path) -> None:
    info = sf.info(src)
    x, sr = sf.read(src, frames=int(HEAR_S * info.samplerate), dtype="float32")
    sf.write(dst, x, sr)


def _drop_heard(head: Path) -> None:
    for p in head.parent.glob(head.stem + ".*"):
        p.unlink(missing_ok=True)


async def _exact_stress(ctx: Context, data: config.DataDir, text: str, designed: Path, out: Path) -> bool:
    """Ukrainian read by HolosTTS in the designed voice, as Speak reads it; False without HolosTTS."""
    waited = 0.0
    while HOLOS.status() == "loading" and waited < HOLOS_WAIT_S:
        await asyncio.sleep(0.5)
        waited += 0.5
    if HOLOS.status() != "ready":
        return False
    await HOLOS.synthesize(text, "uk", str(designed), SynthParams(out_path=out))
    return True


@method("voices.design")
async def voices_design(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """``{"model", "language", "text", "description"?, "exact_stress"?}`` -> a take as in ``voices.design_takes``."""
    lang = params.get("language")
    if not isinstance(lang, str) or not lang.strip():
        raise EngineError("bad_request", "'language' must be a language code such as \"en\"")
    lang = lang.strip().lower()
    backend = _designer(params.get("model"), lang)
    text = _text(params, "text", None, required=True)
    description = _text(params, "description", DESCRIPTION_MAX, required=False)
    exact = params.get("exact_stress", True)
    if not isinstance(exact, bool):
        raise EngineError("bad_request", "'exact_stress' must be true or false")
    loudness = params.get("loudness", LOUDNESS)
    low, high = LOUDNESS_RANGE
    if isinstance(loudness, bool) or not isinstance(loudness, (int, float)) or not low <= loudness <= high:
        raise EngineError("bad_request", f"'loudness' must be a number of LUFS from {low:.0f} to {high:.0f}")
    tts.check_backend_ready(backend)
    with tts.holding("Design is making a voice; try again when it is done", "another generation is running"):
        task = asyncio.ensure_future(_make(ctx, backend, lang, text, description, exact, float(loudness)))
        _running[0] = task
        try:
            return await task
        except asyncio.CancelledError:
            current = asyncio.current_task()
            if current is not None and current.cancelling():
                raise
            raise EngineError("cancelled", "Design was cancelled") from None
        finally:
            _running[0] = None


@method("voices.design_cancel")
async def voices_design_cancel(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """``{}`` -> ``{"cancelled"}``: stops the take ``voices.design`` is making (it answers ``cancelled``)."""
    task = _running[0]
    if task is None or task.done():
        return {"cancelled": False}
    task.cancel()
    return {"cancelled": True}


def level(path: Path, target: float) -> float | None:
    """Brings the clip to ``target`` LUFS, less where its peak would pass ``PEAK_DBFS``; its loudness before."""
    y, sr = sf.read(path, dtype="float32")
    if y.size == 0:
        return None
    before = dubmix.lufs(y.T, sr)
    peak = float(np.max(np.abs(y)))
    if not math.isfinite(before) or peak <= 0:
        return None
    gain_db = min(target - before, PEAK_DBFS - 20 * math.log10(peak))
    sf.write(path, y * np.float32(10 ** (gain_db / 20)), sr, subtype=sf.info(path).subtype)
    return before


def hum_db(path: Path) -> float:
    """How far the strongest third-octave band (150 Hz-2.4 kHz) of the pauses stands over its neighbours."""
    from scipy.signal import stft

    y, sr = sf.read(path, dtype="float32")
    if y.ndim > 1:
        y = y.mean(axis=1)
    f, _, z = stft(y, sr, nperseg=4096, noverlap=2048)
    p = np.abs(z) ** 2
    frames = 10 * np.log10(p.sum(axis=0) + 1e-12)
    pauses = frames <= np.percentile(frames, 15)
    edges = 150 * 2 ** (np.arange(13) / 3)
    bands = np.array(
        [10 * np.log10(p[(f >= a) & (f < b)][:, pauses].mean() + 1e-16) for a, b in itertools.pairwise(edges)]
    )
    over = [bands[i] - np.median(np.r_[bands[max(i - 3, 0) : i], bands[i + 1 : i + 4]]) for i in range(len(bands))]
    return float(max(over))


async def _make(
    ctx: Context,
    backend: backends.TtsBackend,
    lang: str,
    text: str,
    description: str,
    exact: bool,
    loudness: float,
) -> dict[str, Any]:
    data = config.data_dir(ctx)
    take = await aio.run_io(_new_take, folder(data))
    try:
        # OmniVoice now and then makes only hiss (seen with whisper), VoxCPM2 a hum under the speech: such a take is
        # made again. Whisper checks only OmniVoice: beside VoxCPM2 it finds no room on a 12 GB card.
        score = None
        for attempt in range(1, TRIES + 1):
            designed = Path(await backend.design(text, lang, description, take / "voice.wav"))
            if backend is OMNIVOICE:
                score = said(text, await _hear(designed))
                if score >= CLEAR:
                    break
                log.warning("design take %d of %d is not clear (%.2f of the text heard)", attempt, TRIES, score)
                continue
            hum = await aio.run_io(hum_db, designed)
            if hum < HUM_DB:
                break
            log.warning(
                "design take %d of %d hums (a band %.1f dB over its neighbours in the pauses)", attempt, TRIES, hum
            )
        await aio.run_io(level, designed, loudness)
        heard = designed
        stressed = lang == "uk" and exact and await _exact_stress(ctx, data, text, designed, take / "speech.wav")
        if stressed:
            heard = take / "speech.wav"
            await aio.run_io(level, heard, loudness)
        info = await aio.run_io(sf.info, heard)
        meta = {
            "path": heard.name,
            "reference": designed.name,
            "duration_s": round(float(info.duration), 2),
            "model": backend.name,
            "language": lang,
            "description": description,
            "text": text,
            "exact_stress": bool(stressed),
            "clear": None if score is None else score >= CLEAR,
            "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        }
        return await aio.run_io(_save, take, meta)
    except BaseException:
        await aio.run_io(shutil.rmtree, take, True)
        raise


def _takes(data: config.DataDir) -> list[dict[str, Any]]:
    root = folder(data)
    if not root.is_dir():
        return []
    takes = sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.name, reverse=True)
    return [t for t in (_read(p) for p in takes[:KEEP]) if t is not None]


@method("voices.design_delete")
def voices_design_delete(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """``{"id"}`` deletes one take, ``{"all": true}`` every take -> ``{"takes": [...]}`` left; kept voices stay."""
    data = config.data_dir(ctx)
    root = folder(data)
    if params.get("all") is True:
        # A take still being made has no take.json yet; it stays.
        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_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:
        shutil.rmtree(p, ignore_errors=True)
    return {"takes": _takes(data)}


@method("voices.design_takes")
def voices_design_takes(ctx: Context, params: dict[str, Any]) -> dict[str, Any]:
    """``{}`` -> ``{"takes": [...]}``, newest first."""
    return {"takes": _takes(config.data_dir(ctx))}