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.

8.3 KB
Raw Blame
"""Text language identification with fastText's ``lid.176.ftz`` (176 languages), read with numpy: fastText itself has no
wheels for this Python, and building it needs a C++ compiler. Setup downloads the model into ``<runtime>/models/lid``;
without it ``detect`` returns None and callers keep their own guess."""

from __future__ import annotations

import math
import struct
import threading
from pathlib import Path
from typing import Any, BinaryIO

import numpy as np

from . import config

FILE = Path("lid") / "lid.176.ftz"
_MAGIC = 793712314
_KSUB = 256
_EOS = "</s>"
_SPACES = frozenset(" \n\r\t\v\f\0")

_path: list[Path | None] = [None]
_model: list[_Model | bool | None] = [False]
_lock = threading.Lock()


def configure(runtime: dict[str, Any]) -> None:
    root = config.runtime_root(runtime)
    _path[0] = root / "models" / FILE if root else None
    _model[0] = False


def _read(f: BinaryIO, fmt: str) -> Any:
    size = struct.calcsize(fmt)
    out = struct.unpack("<" + fmt, f.read(size))
    return out[0] if len(out) == 1 else out


def _fnv(data: bytes) -> int:
    h = 2166136261
    for b in data:
        h = ((h ^ (b if b < 128 else b | 0xFFFFFF00)) * 16777619) & 0xFFFFFFFF
    return h


class _PQ:
    def __init__(self, f: BinaryIO) -> None:
        self.dim, self.nsubq, self.dsub, self.lastdsub = _read(f, "iiii")
        self.centroids = np.frombuffer(f.read(4 * self.dim * _KSUB), dtype="<f4")

    def decode(self, codes: np.ndarray) -> np.ndarray:
        """Rows of ``codes`` (n, nsubq) back to vectors (n, dim)."""
        parts = []
        for m in range(self.nsubq):
            d = self.lastdsub if m == self.nsubq - 1 else self.dsub
            start = m * _KSUB * self.dsub
            table = self.centroids[start : start + _KSUB * d].reshape(_KSUB, d)
            parts.append(table[codes[:, m]])
        return np.concatenate(parts, axis=1)


def _matrix(f: BinaryIO) -> np.ndarray:
    quant = _read(f, "?")
    if not quant:
        m, n = _read(f, "qq")
        return np.frombuffer(f.read(4 * m * n), dtype="<f4").reshape(m, n)
    qnorm = _read(f, "?")
    m, n = _read(f, "qq")
    codesize = _read(f, "i")
    codes = np.frombuffer(f.read(codesize), dtype=np.uint8)
    pq = _PQ(f)
    rows = pq.decode(codes.reshape(m, pq.nsubq).astype(np.int64))
    if qnorm:
        norm_codes = np.frombuffer(f.read(m), dtype=np.uint8)
        npq = _PQ(f)
        rows = rows * npq.decode(norm_codes.reshape(m, 1).astype(np.int64))
    return rows.astype(np.float32)


class _Model:
    def __init__(self, path: Path) -> None:
        with path.open("rb") as f:
            magic, _version = _read(f, "ii")
            if magic != _MAGIC:
                raise ValueError(f"{path} is not a fastText model")
            (
                self.dim,
                _ws,
                _epoch,
                _min_count,
                _neg,
                self.word_ngrams,
                self.loss,
                _model,
                self.bucket,
                self.minn,
                self.maxn,
                _lr_rate,
            ) = _read(f, "12i")
            _read(f, "d")
            size, self.nwords, _nlabels = _read(f, "iii")
            _read(f, "q")
            prune_size = _read(f, "q")
            words: list[str] = []
            counts: list[int] = []
            for _ in range(size):
                raw = bytearray()
                while (ch := f.read(1)) != b"\0":
                    raw += ch
                counts.append(_read(f, "q"))
                _read(f, "b")
                words.append(raw.decode("utf-8", errors="replace"))
            self.prune = dict(_read(f, "ii") for _ in range(prune_size)) if prune_size > 0 else None
            self.pruned_all = prune_size == 0
            self.input = _matrix(f)
            self.output = _matrix(f)
        self.ids = {w: i for i, w in enumerate(words[: self.nwords])}
        self.labels = [w.removeprefix("__label__") for w in words[self.nwords :]]
        if self.loss != 1:
            raise ValueError("only hierarchical-softmax models are read")
        self._tree(counts[self.nwords :])

    def _tree(self, counts: list[int]) -> None:
        """The Huffman tree fastText builds over the labels (sorted by count, most frequent first)."""
        osz = len(counts)
        n = 2 * osz - 1
        self.left, self.right = [-1] * n, [-1] * n
        count = [float(c) for c in counts] + [1e15] * (osz - 1)
        leaf, node = osz - 1, osz
        for i in range(osz, n):
            pick = []
            for _ in range(2):
                if leaf >= 0 and count[leaf] < count[node]:
                    pick.append(leaf)
                    leaf -= 1
                else:
                    pick.append(node)
                    node += 1
            self.left[i], self.right[i] = pick
            count[i] = count[pick[0]] + count[pick[1]]
        self.osz, self.root = osz, n - 1

    def _hash_id(self, h: int) -> int | None:
        if self.pruned_all:
            return None
        if self.prune is not None:
            if h not in self.prune:
                return None
            h = self.prune[h]
        return self.nwords + h

    def _subwords(self, word: str) -> list[int]:
        data = ("<" + word + ">").encode("utf-8")
        out = []
        for i in range(len(data)):
            if data[i] & 0xC0 == 0x80:
                continue
            j, n = i, 1
            while j < len(data) and n <= self.maxn:
                j += 1
                while j < len(data) and data[j] & 0xC0 == 0x80:
                    j += 1
                if n >= self.minn and not (n == 1 and (i == 0 or j == len(data))):
                    hid = self._hash_id(_fnv(data[i:j]) % self.bucket)
                    if hid is not None:
                        out.append(hid)
                n += 1
        return out

    def _line(self, text: str) -> list[int]:
        tokens = [*"".join(" " if ch in _SPACES else ch for ch in text).split(), _EOS]
        ids: list[int] = []
        hashes: list[int] = []
        for tok in tokens:
            wid = self.ids.get(tok)
            if wid is None:
                if tok != _EOS:
                    ids += self._subwords(tok)
            else:
                ids.append(wid)
                if self.maxn > 0 and tok != _EOS:
                    ids += self._subwords(tok)
            hashes.append(_fnv(tok.encode("utf-8")))
        for i in range(len(hashes)):
            h = hashes[i]
            for j in range(i + 1, min(len(hashes), i + self.word_ngrams)):
                h = (h * 116049371 + hashes[j]) & 0xFFFFFFFFFFFFFFFF
                hid = self._hash_id(h % self.bucket)
                if hid is not None:
                    ids.append(hid)
        return ids

    def predict(self, text: str, k: int = 1) -> list[tuple[str, float]]:
        ids = self._line(text)
        if not ids:
            return []
        hidden = self.input[ids].mean(axis=0)
        found: list[tuple[float, int]] = []

        def walk(node: int, score: float) -> None:
            if self.left[node] == -1:
                found.append((score, node))
                return
            f = 1.0 / (1.0 + math.exp(-float(self.output[node - self.osz] @ hidden)))
            walk(self.left[node], score + math.log(1.0 - f + 1e-5))
            walk(self.right[node], score + math.log(f + 1e-5))

        walk(self.root, 0.0)
        found.sort(reverse=True)
        return [(self.labels[node], math.exp(score)) for score, node in found[:k]]


def _loaded() -> _Model | None:
    with _lock:
        if _model[0] is False:
            path = _path[0]
            try:
                _model[0] = _Model(path) if path and path.is_file() else None
            except (OSError, ValueError, struct.error):
                _model[0] = None
        return _model[0] or None


def detect(text: str, among: frozenset[str] | set[str] | None = None, sure: float = 0.5) -> str | None:
    """The language code fastText gives the text (``among`` those, when given) with at least ``sure`` probability; None
    without the model, for too little text or when it is not sure."""
    model = _loaded()
    line = " ".join((text or "").split())
    if model is None or sum(ch.isalpha() for ch in line) < 8:
        return None
    for code, prob in model.predict(line, k=5):
        if among is not None and code not in among:
            continue
        return code if prob >= sure else None
    return None