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.

3.5 KB
Raw Blame
"""Text-to-speech backends: the first registered backend that speaks a language and is ``available()`` wins."""

from __future__ import annotations

import abc
from dataclasses import dataclass
from pathlib import Path
from typing import Any


@dataclass(frozen=True)
class SynthParams:
    out_path: str | Path
    temperature: float = 0.8
    quality: str = "best"
    duration_factor: float = 1.0  # 1 / speed: below 1 is faster
    first: bool = False
    reference_text: str | None = None


class TtsBackend(abc.ABC):
    """One text-to-speech model. All methods are called on the engine's event loop."""

    name: str = "?"
    label: str = "?"
    languages: frozenset[str] = frozenset()
    designs: bool = False

    @abc.abstractmethod
    async def synthesize(self, text: str, lang: str, reference: str, params: SynthParams) -> str:
        """Write a WAV to ``params.out_path`` and return its path; ``EngineError("not_ready")`` when not loaded."""

    async def design(self, text: str, lang: str, description: str, out_path: str | Path) -> str:
        """Speak ``text`` in a new voice made from ``description``, with no reference clip; returns the WAV path."""
        from ..registry import EngineError

        raise EngineError("bad_request", f"{self.label} cannot make a voice from a description")

    def status(self) -> str:
        return "ready"

    def status_message(self) -> str | None:
        """Why the backend cannot speak, where ``status()`` alone does not say it."""
        return None

    def available(self) -> bool:
        """While installed and not failed, so its languages fall through to another backend otherwise."""
        return True

    async def load(self, runtime: dict[str, Any]) -> None:  # noqa: B027 - optional hook, a no-op by default
        """Called at start-up and after a training gives the GPU back."""

    async def release(self) -> None:  # noqa: B027
        """Free the GPU and host RAM before a training takes the GPU."""

    async def close(self) -> None:  # noqa: B027
        """Stop any process the backend started and await its exit."""

    def count_tokens(self, text: str) -> int:
        return max(1, len(text) // 3)

    def is_warm(self, reference: str) -> bool:
        return False

    def forget_reference(self) -> None:  # noqa: B027
        """Callable from any thread."""


_BACKENDS: list[TtsBackend] = []


def register(backend: TtsBackend) -> None:
    _BACKENDS.append(backend)


def all_backends() -> list[TtsBackend]:
    if not _BACKENDS:
        _builtin()
    return list(_BACKENDS)


def by_name(name: str) -> TtsBackend | None:
    return next((b for b in all_backends() if b.name == name), None)


def selectable() -> list[TtsBackend]:
    """The voice-cloning models a request may name in ``model`` (HolosTTS is chosen by ``exact_stress`` instead)."""
    return [b for b in all_backends() if b.name != "holos" and b.status() != "missing"]


def for_language(lang: str, skip: tuple[str, ...] = ()) -> TtsBackend | None:
    lang = (lang or "").lower()
    for b in all_backends():
        if b.name not in skip and lang in b.languages and b.available():
            return b
    return None


def languages() -> set[str]:
    """What the installed models speak."""
    out: set[str] = set()
    for b in all_backends():
        if b.status() != "missing":
            out |= set(b.languages)
    return out


def _builtin() -> None:
    from .clone import CHATTERBOX, VOXCPM
    from .holos import HOLOS
    from .omnivoice import OMNIVOICE

    register(HOLOS)
    register(OMNIVOICE)
    register(VOXCPM)
    register(CHATTERBOX)