Routyo / routyo.py
jsbeaudry's picture
Run on cactus-compute (the new Cactus package); cactus-needle still works where cached
41943ea verified
Raw History Blame Contribute Delete
8.29 kB
"""Routyo: which language is spoken, Haitian Creole (ht), English (en), French (fr) or Spanish (es)?
python routyo.py clip.wav # whole clip, all four languages
python routyo.py clip.wav --pair ht,en # only Kreyòl against English (as an interpreter asks)
python routyo.py clip.wav --first 1.5 # decide from the first 1.5 s of speech
python routyo.py clip.wav --words # add the word check (4 short forced decodes, more accurate)
from routyo import Routyo
r = Routyo() # finds the files next to this script
r.rates(samples_16k) # [{"language": "ht", "rate": 0.97}, ...]
Needs: numpy, soundfile, huggingface_hub, the Cactus engine (pip install cactus-compute; tested with 4.1.0; the
older cactus-needle package works too where its engine is still cached), and soxr only if your audio is not 16 kHz.
Encoders: the stock Whistle (Cactus-Compute/whistle, downloaded on first use) and the Kreyòl-tuned Whistle in this
repo (whistle-kreyol.cact). Both give 512 numbers per 80 ms (the engine's embed call); Routyo joins them (1,024).
"""
import argparse
import ctypes
import json
import os
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
RATE = 16000
LABELS = ("ht", "en", "fr", "es")
NAMES = {"ht": "Haitian Creole", "en": "English", "fr": "French", "es": "Spanish"}
def load_audio(path):
import soundfile as sf
x, rate = sf.read(path, dtype="float32", always_2d=True)
x = x.mean(1)
if rate != RATE:
import soxr
x = soxr.resample(x, rate, RATE)
return np.ascontiguousarray(x, np.float32)
def onset(samples, seconds):
"""The window that starts 0.1 s before the first speech (as a phone's voice detector hands it over)."""
n = len(samples) // 320
if n == 0:
return 0, len(samples)
rms = np.sqrt((samples[:n * 320].reshape(n, 320) ** 2).mean(1) + 1e-12)
db = 20 * np.log10(rms)
start = max(int(np.argmax(db > db.max() - 30)) * 320 - 1600, 0)
return start, min(start + int(seconds * RATE), len(samples))
def whistle_module():
"""The Cactus engine's Whistle module: cactus-compute (4.x) first, else the older cactus-needle (3.x)."""
try:
from cactus.agent import whistle
except ImportError:
from needle.agent import whistle
return whistle
class Encoder:
"""Whistle encoder frames through the Cactus engine (its embed call): 512 floats per 80 ms."""
def __init__(self, weights):
W = whistle_module()
self.model = W.Whistle(weights)
if hasattr(self.model, "embed"): # cactus-compute: thread-safe embed on the model itself
self._raw = None
return
self.lib = W._lib() # cactus-needle: call the engine directly
self._raw = self.lib.needle_embed
self._raw.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_float), ctypes.c_int,
ctypes.POINTER(ctypes.c_float), ctypes.c_int]
self._raw.restype = ctypes.c_int
self.out = (ctypes.c_float * (512 * 400))()
def frames(self, samples):
x = np.ascontiguousarray(samples, np.float32)
if self._raw is None:
return np.asarray(self.model.embed(x), np.float32).reshape(-1, 512)
self.model._bind() # the engine holds one model at a time: load this one if another was used since
p = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
need = self._raw(None, p, len(x), None, 0)
if need <= 0:
raise RuntimeError(self.lib.needle_last_error().decode("utf-8", "replace"))
if need > len(self.out):
self.out = (ctypes.c_float * need)()
self._raw(None, p, len(x), self.out, need)
return np.frombuffer(self.out, np.float32, need).reshape(-1, 512).copy()
class _Head:
"""One head: standardise, per-frame layers (ReLU), attentive mean + std beside the plain mean + std, linear."""
def __init__(self, z):
self.mu, self.sigma = z["mu"], z["sigma"]
self.temperature = float(z["temperature"])
self.layers = []
while f"c{len(self.layers)}" in z:
i = len(self.layers)
self.layers.append((z[f"c{i}"], z[f"cb{i}"]))
self.aw, self.ab, self.av, self.w, self.b = z["aw"], z["ab"], z["av"], z["w"], z["b"]
def log_probs(self, frames):
x = (np.asarray(frames, np.float32) - self.mu) / self.sigma
h = x
for k, b in self.layers:
if k.shape[0] == 1:
h = h @ k[0]
else:
pad = k.shape[0] // 2
hp = np.pad(h, ((pad, k.shape[0] - 1 - pad), (0, 0)))
h = sum(hp[j:j + len(h)] @ k[j] for j in range(k.shape[0]))
h = np.maximum(h + b, 0)
e = np.tanh(h @ self.aw + self.ab) @ self.av
a = np.exp(e - e.max())
a /= a.sum()
m = (h * a[:, None]).sum(0)
s = np.sqrt((((h - m) ** 2) * a[:, None]).sum(0) + 1e-5)
z = np.concatenate([m, s, x.mean(0), x.std(0)]) @ self.w + self.b
z = z / self.temperature
return z - np.logaddexp.reduce(z)
class Routyo:
def __init__(self, folder=HERE, stock=None):
if stock is None:
from huggingface_hub import hf_hub_download
stock = hf_hub_download("Cactus-Compute/whistle", "whistle.cact")
self.stock = Encoder(stock)
self.kreyol = Encoder(os.path.join(folder, "whistle-kreyol.cact"))
z = np.load(os.path.join(folder, "routyo.npz"), allow_pickle=False)
self.heads = [_Head({k[len(f"m{i}_"):]: z[k] for k in z.files if k.startswith(f"m{i}_")})
for i in range(int(z["members"]))]
self.check = json.load(open(os.path.join(folder, "word_check.json")))
self._decoders = None
def log_probs(self, samples):
"""Sound only: the three heads' log-probabilities averaged (order: ht, en, fr, es)."""
frames = np.concatenate([self.stock.frames(samples), self.kreyol.frames(samples)], 1)
lp = np.mean([h.log_probs(frames) for h in self.heads], 0)
return lp - np.logaddexp.reduce(lp)
def word_probs(self, samples):
"""Mean word probability when Whistle transcribes the audio forced to each language."""
W = whistle_module()
if self._decoders is None:
self._decoders = {"kreyol": W.Whistle(self.kreyol.model.weights), "stock": W.Whistle(self.stock.model.weights)}
out = []
for lang in LABELS:
res = self._decoders[self.check["engines"][lang]].transcribe(samples, language=lang, word_timestamps=True)
words = res.get("words") or []
out.append(float(np.mean([w["probability"] for w in words])) if words else 0.0)
return np.array(out)
def rates(self, samples, pair=None, words=False, first=None):
x = np.ascontiguousarray(samples, np.float32)
if first:
a, b = onset(x, first)
x = x[a:b]
s = self.log_probs(x)
if words:
c = self.check
s = (s + c["beta"] * self.word_probs(x) + np.array([c["offsets"][k] for k in LABELS])) / c["temperature"]
if pair:
s = np.where([k in pair for k in LABELS], s, -np.inf)
p = np.exp(s - s.max())
p /= p.sum()
return [{"language": LABELS[k], "name": NAMES[LABELS[k]], "rate": round(float(p[k]), 4)}
for k in np.argsort(-p) if not pair or LABELS[k] in pair]
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("audio", nargs="+")
ap.add_argument("--pair", default=None, help="two languages, e.g. ht,en")
ap.add_argument("--first", type=float, default=None, help="decide from the first N seconds of speech")
ap.add_argument("--words", action="store_true", help="add the word check")
args = ap.parse_args()
r = Routyo()
pair = tuple(args.pair.split(",")) if args.pair else None
for path in args.audio:
out = r.rates(load_audio(path), pair=pair, words=args.words, first=args.first)
print(json.dumps({"file": os.path.basename(path), "rates": out}, ensure_ascii=False))
if __name__ == "__main__":
main()