#!/usr/bin/env python3 """Speaker embeddings for common/lib/montage/voiceMatch.mjs. WAV segments in, L2-normalised speaker embeddings out, as JSON. Nothing else: which seconds to embed, the voiced-frames gate, the reference and the score all live in the .mjs caller, so this file stays a thin shell over the model that scripts/diarize-sherpa.py already loads (the same sherpa-onnx SpeakerEmbeddingExtractor, the same TitaNet-small ONNX file). stdout is JSON ONLY; progress goes to stderr. Usage: speaker-embed.py --emb [--threads N] request.json: {"items": [{"id": "...", "wav": "/abs/path.wav"}, ...]} Each wav is 16-bit PCM, mono, 16 kHz (the rate TitaNet is trained at; the caller decodes to it). A wav at another rate is passed to the model with its own rate, which sherpa resamples. Output: {"model": "", "version": "", "dim": n, "items": [{"id", "embedding": [...] | null, "seconds": f, "error"?: "..."}]} `embedding` is rounded to 6 decimals, so the same input prints the same bytes. One thread by default: a CPU reduction split across threads is the one place an ONNX run can differ in its last bits between two runs. """ import argparse, json, os, sys, wave MIN_SECONDS = 0.5 def read_wav(np, path): with wave.open(path, "rb") as w: rate = w.getframerate() width = w.getsampwidth() chans = w.getnchannels() raw = w.readframes(w.getnframes()) if width != 2: raise ValueError(f"{os.path.basename(path)}: {width * 8}-bit wav, want 16-bit PCM") x = np.frombuffer(raw, dtype=" 1: x = x.reshape(-1, chans).mean(axis=1) return x, rate def main(): ap = argparse.ArgumentParser() ap.add_argument("request") ap.add_argument("--emb", required=True) ap.add_argument("--threads", type=int, default=1) args = ap.parse_args() try: import numpy as np import sherpa_onnx except ImportError as e: print(f"speaker-embed: missing dependency: {e}", file=sys.stderr) return 3 with open(args.request, "r", encoding="utf8") as f: req = json.load(f) items = req.get("items") or [] cfg = sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=args.emb, num_threads=args.threads) if not cfg.validate(): print("speaker-embed: invalid model config", file=sys.stderr) return 2 extractor = sherpa_onnx.SpeakerEmbeddingExtractor(cfg) out = [] for k, item in enumerate(items): rec = {"id": item.get("id"), "embedding": None, "seconds": 0.0} try: x, rate = read_wav(np, item["wav"]) rec["seconds"] = round(x.size / rate, 3) if x.size < int(MIN_SECONDS * rate): rec["error"] = "too short" else: stream = extractor.create_stream() stream.accept_waveform(rate, x) stream.input_finished() if not extractor.is_ready(stream): rec["error"] = "too short" else: v = np.asarray(extractor.compute(stream), dtype=np.float64) n = float(np.linalg.norm(v)) if n > 0: rec["embedding"] = [round(float(e), 6) for e in (v / n)] else: rec["error"] = "zero embedding" except Exception as e: # one bad file is that item's error, not the run's rec["error"] = str(e) out.append(rec) if (k + 1) % 10 == 0 or k + 1 == len(items): print(f"speaker-embed: {k + 1}/{len(items)}", file=sys.stderr, flush=True) json.dump( { "model": os.path.basename(args.emb), "version": getattr(sherpa_onnx, "__version__", None), "dim": extractor.dim, "items": out, }, sys.stdout, ) return 0 if __name__ == "__main__": sys.exit(main())