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.

22.0 KB
Raw Blame
"""OmniVoice worker. Standalone: imports nothing from ``mimvox_engine``.

    python -I omnivoice_worker.py --model-dir <data>/runtime/models/omnivoice
                                  --whisper-dir <data>/runtime/models/whisper [--device cuda|cpu|mps]
                                  [--unload-after S] [--exit-after S] [--prompt-cache N]

Ops (wire format: ``worker_kit.py``):
  load     {}                                         -> {"load_s","device","vram_gb"}
  synth    {"text","lang","ref","out", "steps":32, "speed":1.0, "duration":null, "normalize":true, "ref_text":null,
            "model_lang", "position_temperature", "class_temperature", "guidance_scale"}
                                                      -> {"out","sr","duration_s","gen_s","text"}
  design   {"text","lang","model_lang","instruct","out","steps"}
                                                      -> {"out","sr","duration_s","gen_s","text"}
  warm     {"ref","ref_text"?}                        -> {"elapsed_s"}
  inspect  {"ref","detect"?:true}                     -> {"language","text","elapsed_s"}  (Whisper only, no TTS model)
  release  {}                                         -> {}
  status   {}                                         -> {"loaded","rss_gb","vram_gb"}
  zs_load, zs_convert, zs_warm, zs_release, zs_status: Seed-VC (``zsvc_worker.py``)
Events: {"event":"ready"}, {"event":"unloaded","reason":"idle"}, {"event":"exit","reason":"idle"}. On the CPU an op
also sends {"id","progress":{"alive":true}} at most every 2 s while a model runs (the engine's no-progress watchdog).
"""

import argparse
import collections
import gc
import importlib.util
import json
import os
import re
import sys
import time
from pathlib import Path

HERE = Path(__file__).absolute().parent


def _load_by_path(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


kit = _load_by_path("mimvox_worker_kit", HERE.parent / "worker_kit.py")
INP, OUT = kit.open_channels()  # before torch / transformers: they print, also from C code

ap = argparse.ArgumentParser()
ap.add_argument("--model-dir", required=True)
ap.add_argument("--whisper-dir", default="")
ap.add_argument("--device", default="cuda")
ap.add_argument("--unload-after", type=float, default=0.0)
ap.add_argument("--exit-after", type=float, default=0.0)
ap.add_argument("--prompt-cache", type=int, default=3)
args = ap.parse_args()

os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
os.environ.setdefault("USE_HUB_KERNELS", "0")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")

import numpy as np  # noqa: E402
import soundfile as sf  # noqa: E402
import torch  # noqa: E402

text_norm = _load_by_path("mimvox_omnivoice_text", HERE / "omnivoice_text.py")
whisper_half = _load_by_path("mimvox_whisper_half", HERE.parent / "whisper_half.py")
# MIMVOX_OMNIVOICE_FAST=0 keeps the library's own decoding loop.
fast = (
    _load_by_path("mimvox_omnivoice_fast", HERE / "omnivoice_fast.py")
    if os.environ.get("MIMVOX_OMNIVOICE_FAST", "1") != "0"
    else None
)

# A whole 19 s reference cloned barely better than a 7 s cut (ECAPA 0.86 vs 0.84) but peaked at 6.9 GB VRAM instead
# of 3.9, which next to the RVC worker filled a 12 GB card: longer clips are cut to whole sentences.
REF_MAX_S = float(os.environ.get("MIMVOX_OMNIVOICE_REF_MAX_S", "12"))
REF_CUT_MIN_S, REF_CUT_MAX_S, REF_CUT_TARGET_S = 7.0, REF_MAX_S, 10.0
# fp16 Whisper turbo: 1.6 GB of weights plus decoding; on the CPU otherwise (10-20 s per clip).
WHISPER_NEED_GB = float(os.environ.get("MIMVOX_WHISPER_NEED_GB", "2.6"))
SIDECAR_VERSION = 3
# Measured in fp32: the worker peaked at 7.45 GB (Windows) and 7.1 GB (Linux) with Whisper loaded; the system, the
# engine and the app need about 3.5 GB beside it.
CPU_RAM_NEED_GB = float(os.environ.get("MIMVOX_CPU_RAM_NEED_GB", "11"))
# Measured on an 8 GB laptop: the first voice-clone prompt after loading took the worker from 3.6 to 6.8 GB in 6 s.
CPU_PROMPT_GB = float(os.environ.get("MIMVOX_CPU_PROMPT_GB", "3.2"))

_state = {"model": None, "device": None}
_prompts = collections.OrderedDict()
BEAT_S = 2.0
_beat = {"at": 0.0}


def _log(msg):
    print(f"[omnivoice] {msg}", file=sys.stderr, flush=True)


def _vram_gb():
    if torch.cuda.is_available():
        free, total = torch.cuda.mem_get_info()
        return round((total - free) / 2**30, 2)
    return 0.0


def _rss_gb():
    try:
        if os.name == "nt":
            import ctypes
            from ctypes import wintypes

            class _C(ctypes.Structure):
                _fields_ = [
                    ("cb", wintypes.DWORD),
                    ("PageFaultCount", wintypes.DWORD),
                    ("PeakWorkingSetSize", ctypes.c_size_t),
                    ("WorkingSetSize", ctypes.c_size_t),
                ] + [(f"f{i}", ctypes.c_size_t) for i in range(6)]

            k32, psapi = ctypes.windll.kernel32, ctypes.windll.psapi
            k32.GetCurrentProcess.restype = wintypes.HANDLE
            psapi.GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD]
            c = _C()
            c.cb = ctypes.sizeof(c)
            psapi.GetProcessMemoryInfo(k32.GetCurrentProcess(), ctypes.byref(c), c.cb)
            return round(c.WorkingSetSize / 2**30, 2)
        import resource

        with Path("/proc/self/statm").open() as f:
            return round(int(f.read().split()[1]) * resource.getpagesize() / 2**30, 2)
    except Exception:
        return 0.0


def _device():
    want = args.device
    if want == "cuda" and not torch.cuda.is_available():
        want = "cpu"
    if want == "mps" and not (getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()):
        want = "cpu"
    return want


def _heartbeat(*_args):
    """Progress for the engine's no-progress watchdog: on the CPU a segment may take minutes, with no fixed limit."""
    now = time.monotonic()
    if now - _beat["at"] >= BEAT_S and kit_worker.current is not None:
        _beat["at"] = now
        kit_worker.progress({"alive": True})


_SENTENCE_END = re.compile(r"(?<=[.!?…。!?])\s+")


def _cut_at_sentences():
    """OmniVoice reads text over 30 s in pieces cut at any punctuation, commas too. Pieces end at sentence ends; only a
    sentence over two pieces long is cut inside."""
    try:
        import omnivoice.models.omnivoice as ovm
    except ImportError:
        return
    library = getattr(ovm, "chunk_text_punctuation", None)
    if library is None or getattr(library, "by_sentence", False):
        return

    def by_sentence(text, chunk_len, min_chunk_len=None):
        pieces = []
        for s in _SENTENCE_END.split(text.strip()):
            if pieces and len(pieces[-1]) + 1 + len(s) <= chunk_len:
                pieces[-1] += " " + s
            else:
                pieces.append(s)
        return [p for c in pieces for p in (library(c, chunk_len, min_chunk_len) if len(c) > 2 * chunk_len else [c])]

    by_sentence.by_sentence = True
    ovm.chunk_text_punctuation = by_sentence


def op_load(_req=None):
    if _state["model"] is not None:
        return {"load_s": 0.0, "device": _state["device"], "vram_gb": _vram_gb()}
    _check_ram()
    from omnivoice import OmniVoice

    _cut_at_sentences()
    t0 = time.time()
    dev = _device()
    if dev == "cuda":
        kit.gpu_fence(start=True)
    dtype = torch.float16 if dev in ("cuda", "mps") else torch.float32
    model = OmniVoice.from_pretrained(args.model_dir, device_map=dev if dev != "cuda" else "cuda:0", dtype=dtype)
    _state.update(model=model, device=dev)
    _prompts.clear()
    gc.collect()
    # On the CPU the weights stay in this memory: a trim would only send them to the page file before the first step.
    kit_worker.trim = dev != "cpu"
    if dev != "cpu":
        _trim_working_set()  # the weights passed through host RAM on their way to the GPU
    _log(f"loaded on {dev} in {time.time() - t0:.1f}s, VRAM in use {_vram_gb()} GB")
    return {"load_s": round(time.time() - t0, 2), "device": dev, "vram_gb": _vram_gb()}


def _trim_working_set():
    if os.name == "nt":
        try:
            import ctypes

            k32 = ctypes.windll.kernel32
            k32.GetCurrentProcess.restype = ctypes.c_void_p
            ctypes.windll.psapi.EmptyWorkingSet.argtypes = [ctypes.c_void_p]
            ctypes.windll.psapi.EmptyWorkingSet(k32.GetCurrentProcess())
        except Exception:
            pass


def op_release(_req=None):
    if "mod" in _zs:
        _zs["mod"].OPS["release"]({})
    _state.update(model=None)
    _prompts.clear()
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    _trim_working_set()
    return {}


def _idle_unload():
    if _state["model"] is None:
        return None
    op_release()
    return {"event": "unloaded", "reason": "idle"}


def _sig(path):
    st = Path(path).stat()
    return [Path(path).absolute(), st.st_mtime_ns, st.st_size]


def _load_mono(path):
    x, sr = sf.read(path, dtype="float32", always_2d=True)
    return x.mean(1), sr


def _on_cpu():
    return (_state["device"] or _device()) == "cpu"


def _whisper_device():
    if (_state["device"] or _device()) != "cuda":  # `inspect` runs without the TTS model
        return "cpu"
    free = kit.gpu_free_gb()
    if free >= WHISPER_NEED_GB:
        kit.gpu_fence(start=True)
        return "cuda"
    _log(
        f"only {free:.1f} GB of VRAM free beyond the {kit.vram_reserve_gb():.1f} GB reserve (Whisper needs "
        f"{WHISPER_NEED_GB:.1f}): transcribing the reference on the CPU"
    )
    return "cpu"


def _with_whisper(use):
    """Whisper turbo loaded for this call only; retried on the CPU when the GPU runs out of memory midway."""
    import whisper

    _check_ram()
    dev = _whisper_device()
    for attempt in (dev, "cpu") if dev == "cuda" else ("cpu",):
        wm = None
        try:
            if attempt == "cuda":
                wm = whisper_half.load(whisper, "turbo", args.whisper_dir or None, "cuda")
            else:
                wm = whisper_half.load(whisper, "turbo", args.whisper_dir or None, "cpu", half=False)
            return use(wm, attempt)
        except Exception as exc:
            if attempt != "cuda" or not kit.is_vram_error(exc):
                raise
            _log(f"Whisper ran out of GPU memory ({exc}); transcribing the reference on the CPU")
        finally:
            del wm
            gc.collect()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            if _state["device"] != "cpu" or _state["model"] is None:
                _trim_working_set()  # Whisper's weights passed through host RAM: give those pages back now
    raise AssertionError("unreachable")


def _16k(x, sr):
    import torchaudio

    x16 = torchaudio.functional.resample(torch.from_numpy(x), sr, 16000).numpy() if sr != 16000 else x
    return x16.astype(np.float32)


def _transcribe(x, sr):
    """([(start, end, text)], detected language or None); the language is not forced."""
    x16 = _16k(x, sr)
    res = _with_whisper(lambda wm, dev: wm.transcribe(x16, fp16=dev == "cuda", condition_on_previous_text=False))
    segs = [(float(s["start"]), float(s["end"]), s["text"].strip()) for s in res["segments"] if s["text"].strip()]
    return segs, (str(res.get("language") or "").lower() or None)


def _detect_language(x, sr):
    import whisper

    x16 = _16k(x, sr)

    def detect(wm, _dev):
        audio = whisper.pad_or_trim(torch.from_numpy(x16))
        mel = whisper.log_mel_spectrogram(audio, n_mels=wm.dims.n_mels).to(wm.device)
        if next(wm.parameters()).dtype == torch.float16:
            mel = mel.half()
        _, probs = wm.detect_language(mel)
        return max(probs, key=probs.get) if probs else None

    return _with_whisper(detect)


def _pick_window(segs, total):
    """Whole segments closest to REF_CUT_TARGET_S, preferring statements: a question or exclamation in the reference
    makes every generated sentence sound like one."""
    best, best_score = None, None
    for i in range(len(segs)):
        for j in range(i, len(segs)):
            d = segs[j][1] - segs[i][0]
            if d > REF_CUT_MAX_S:
                break
            if d < REF_CUT_MIN_S:
                continue
            questions = sum(1 for s in segs[i : j + 1] if s[2].rstrip().endswith(("?", "!")))
            score = abs(d - REF_CUT_TARGET_S) + 3.0 * questions
            if best_score is None or score < best_score:
                best, best_score = (i, j), score
    if best is None:
        keep = [s for s in segs if s[1] <= REF_CUT_MAX_S] or segs[:1]
        return 0.0, min(total, keep[-1][1] if keep else REF_CUT_MAX_S), " ".join(s[2] for s in keep)
    i, j = best
    return max(0.0, segs[i][0] - 0.05), min(total, segs[j][1] + 0.15), " ".join(s[2] for s in segs[i : j + 1])


def _reference(ref, ref_text=None):
    """(mono float32, sr, transcript); a clip up to REF_MAX_S with a known ``ref_text`` skips Whisper and sidecar."""
    sig = _sig(ref)
    side = _sidecar(ref)
    x, sr = _load_mono(ref)
    total = len(x) / sr
    if ref_text and total <= REF_MAX_S:
        return x, sr, ref_text
    cached = None
    try:
        with side.open(encoding="utf-8") as fh:
            cached = json.load(fh)
        if cached.get("version") != SIDECAR_VERSION or cached.get("sig") != sig[1:]:
            cached = None
    except (OSError, ValueError):
        cached = None
    if cached is None:
        t0 = time.time()
        _heartbeat()
        segs, language = _transcribe(x, sr)
        if not segs:
            raise kit.OpError("bad_request", "the reference clip has no recognizable speech")
        if total > REF_MAX_S:
            a, b, text = _pick_window(segs, total)
        else:
            a, b, text = 0.0, total, " ".join(s[2] for s in segs)
        cached = {
            "version": SIDECAR_VERSION,
            "sig": sig[1:],
            "start": round(a, 3),
            "end": round(b, 3),
            "text": text,
            "language": language,
        }
        _write_sidecar(side, cached)
        _log(
            f"reference {ref} ({language or '?'}): {a:.2f}-{b:.2f}s of {total:.1f}s chosen in "
            f"{time.time() - t0:.1f}s: {text!r}"
        )
    cut = x[int(cached["start"] * sr) : int(cached["end"] * sr)]
    return cut, sr, cached["text"]


def _sidecar(ref):
    ref = Path(ref)
    return ref.with_name(ref.stem + ".omnivoice.json")


def _write_sidecar(side, cached):
    try:
        tmp = side.with_name(side.name + ".tmp")
        with tmp.open("w", encoding="utf-8") as fh:
            json.dump(cached, fh, ensure_ascii=False, indent=1)
        tmp.replace(side)
    except OSError as exc:
        _log(f"could not cache the reference transcript: {exc}")


def _prompt(ref, ref_text=None):
    key = (tuple(_sig(ref)), ref_text or None)
    if key in _prompts:
        _prompts.move_to_end(key)
        return _prompts[key]
    wav, sr, text = _reference(ref, ref_text)
    kit_worker.check_cancel()
    _check_ram(0.0 if _prompts else CPU_PROMPT_GB)
    prompt = _state["model"].create_voice_clone_prompt((torch.from_numpy(wav), sr), ref_text=text)
    _prompts[key] = prompt
    while len(_prompts) > max(1, args.prompt_cache):
        _prompts.popitem(last=False)
    return prompt


def _check_ram(grow_gb=0.0):
    """On the CPU, before every model pass that may grow the worker by ``grow_gb``. Every step reads all the weights:
    on a computer whose RAM cannot hold the worker, or once a part of them is paged out, each segment waits minutes on
    the disk. A refusal releases the model, as most of that memory is the worker's own; the next request loads it
    again."""
    if not _on_cpu():
        return
    model = _state["model"]
    too_small = kit.ram_too_small(CPU_RAM_NEED_GB)
    msg = too_small
    if not msg and model is not None:
        msg = kit.ram_short([(p.data_ptr(), p.numel() * p.element_size()) for p in model.parameters()])
        if not msg and grow_gb > 0:
            msg = kit.ram_no_room(grow_gb)
    if msg:
        _log(msg)
        if model is not None:
            op_release()
        raise kit.OpError("no_memory", msg, permanent=bool(too_small))


def op_warm(req):
    t0 = time.time()
    _check_ram()
    op_load()
    _prompt(req["ref"], req.get("ref_text"))
    return {"elapsed_s": round(time.time() - t0, 2)}


def op_inspect(req):
    ref = req.get("ref")
    if not ref or not Path(ref).is_file():
        raise kit.OpError("not_found", f"reference clip not found: {ref}")
    _check_ram()
    t0 = time.time()
    _reference(ref)
    side = _sidecar(ref)
    try:
        with side.open(encoding="utf-8") as fh:
            cached = json.load(fh)
    except (OSError, ValueError) as exc:
        raise kit.OpError("internal", f"no sidecar for {ref}: {exc}") from None
    if not cached.get("language") and req.get("detect", True):
        x, sr = _load_mono(ref)
        cached["language"] = _detect_language(x, sr)
        _write_sidecar(side, cached)
        _log(f"reference {ref}: language {cached['language'] or '?'} detected in {time.time() - t0:.1f}s")
    return {"language": cached.get("language"), "text": cached.get("text"), "elapsed_s": round(time.time() - t0, 2)}


def op_synth(req):
    text, out, ref = req.get("text"), req.get("out"), req.get("ref")
    if not isinstance(text, str) or not text.strip() or not out or not ref:
        raise kit.OpError("bad_request", "synth needs 'text', 'ref' and 'out'")
    if not Path(ref).is_file():
        raise kit.OpError("not_found", f"reference clip not found: {ref}")
    lang = str(req.get("lang") or "").lower() or None
    _check_ram()
    op_load()
    prompt = _prompt(ref, req.get("ref_text"))
    if req.get("normalize", True) and lang:
        text = text_norm.normalize(text, lang)
    kit_worker.check_cancel()
    kw = {"num_step": int(req.get("steps") or 32)}
    for knob in ("position_temperature", "class_temperature", "guidance_scale"):
        if req.get(knob) is not None:
            kw[knob] = float(req[knob])
    if req.get("duration"):
        kw["duration"] = float(req["duration"])
    elif req.get("speed") and abs(float(req["speed"]) - 1.0) > 1e-3:
        kw["speed"] = float(req["speed"])
    _check_ram()
    t0 = time.time()
    audio = _generate(text=text, language=req.get("model_lang") or lang, voice_clone_prompt=prompt, **kw)[0]
    return _save(out, audio, t0, text)


def _save(out, audio, t0, text):
    gen_s = time.time() - t0
    audio = np.asarray(audio, dtype=np.float32).reshape(-1)
    if torch.cuda.is_available():
        torch.cuda.empty_cache()  # the RVC worker shares the card
    sr = int(_state["model"].sampling_rate)
    Path(out).absolute().parent.mkdir(parents=True, exist_ok=True)
    sf.write(out, np.clip(audio, -1.0, 1.0), sr, subtype="PCM_16")
    return {"out": out, "sr": sr, "duration_s": round(len(audio) / sr, 3), "gen_s": round(gen_s, 3), "text": text}


def op_design(req):
    """A new voice from ``instruct`` (OmniVoice's own terms, e.g. "female, elderly, low pitch") and no reference."""
    text, out = req.get("text"), req.get("out")
    if not isinstance(text, str) or not text.strip() or not out:
        raise kit.OpError("bad_request", "design needs 'text' and 'out'")
    lang = str(req.get("lang") or "").lower() or None
    instruct = str(req.get("instruct") or "").strip() or None
    if instruct:
        from omnivoice.models.omnivoice import _resolve_instruct

        try:
            instruct = _resolve_instruct(instruct)
        except ValueError as exc:
            raise kit.OpError("bad_request", str(exc)) from None
    _check_ram()
    op_load()
    if lang:
        text = text_norm.normalize(text, lang)
    kit_worker.check_cancel()
    t0 = time.time()
    audio = _generate(
        text=text, language=req.get("model_lang") or lang, instruct=instruct, num_step=int(req.get("steps") or 32)
    )[0]
    return _save(out, audio, t0, text)


def _generate(**kw):
    """``model.generate(**kw)`` through omnivoice_fast when it can run. A non-memory error of the fast path (e.g. an
    omnivoice or transformers version it does not fit) turns it off for the process and falls back to the library."""
    global fast
    model = _state["model"]
    if fast is not None:
        try:
            return fast.generate(model, **kw)
        except fast.Unsupported:
            pass
        except Exception as exc:
            if kit.is_vram_error(exc):
                raise
            _log(f"fast decoding failed ({type(exc).__name__}: {exc}); using the library's decoding from now on")
            fast = None
    return model.generate(**kw)


def op_status(_req=None):
    return {"loaded": _state["model"] is not None, "rss_gb": _rss_gb(), "vram_gb": _vram_gb()}


# Seed-VC is hosted in this process (``zsvc_worker.py`` says why) and loads on its first ``zs_*`` op.

_zs = {}


def _zs_op(name):
    def run(req):
        if "mod" not in _zs:
            if name in ("release", "status"):
                return {"loaded": False} if name == "status" else {}
            spec = importlib.util.spec_from_file_location("mimvox_zsvc_hosted", HERE.parent / "zsvc_worker.py")
            mod = importlib.util.module_from_spec(spec)
            mod.__hosted__ = {
                "kit": kit,
                "worker": kit_worker,
                "argv": ["--seed-vc", req["seed_vc"], "--models", req["models"], "--device", args.device],
            }
            spec.loader.exec_module(mod)
            _zs["mod"] = mod
        return _zs["mod"].OPS[name](req)

    return run


idle = []
if args.unload_after > 0:
    idle.append((args.unload_after, _idle_unload))
if args.exit_after > 0 or kit.IDLE_EXIT_S > 0:
    idle.append((args.exit_after or kit.IDLE_EXIT_S, "exit"))
if _device() == "cpu":
    torch.nn.modules.module.register_module_forward_pre_hook(_heartbeat)
kit_worker = kit.Worker(
    "omnivoice",
    INP,
    OUT,
    {
        "load": op_load,
        "synth": op_synth,
        "design": op_design,
        "warm": op_warm,
        "inspect": op_inspect,
        "release": op_release,
        "status": op_status,
        "ping": lambda _r: {},
        **{f"zs_{name}": _zs_op(name) for name in ("load", "convert", "warm", "release", "status")},
    },
    idle=idle,
)
kit_worker.run()
os._exit(0)