commit c89f420248fc7c563a923ea256a40df4fad7ad75
parent 786e448915e81c1eade741a0928dd3c19762fc2f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 00:02:28 -0500
diarization: keep the voice fingerprints -- one TitaNet centroid per final speaker lands in diarization.json as `voiceprints` (speaker, seconds, embedded, centroid[192] at 4 decimals, embeddingModel), outside the freshness identity as `windowing` is; hasVoiceprints() is the predicate a cleanup gate can key on
scripts/diarize-sherpa.py computed per-cluster embeddings for the windowed path
and threw them away; the whole-file path never made any. Both now print one
voiceprint per FINAL speaker, computed after the turns are final and never fed
back into them: the speaker's 8 longest turns (each cut to 10 s) embedded and
averaged with voiceMatch's robustCentroid rule (trim 0.15 under the median).
Windowed: the robust mean of the local centroids that clustered into the final
speaker. A speaker with nothing embeddable is recorded with centroid null.
--voiceprints-only <record> (diarize.mjs and the .py) adds them to an EXISTING
record from its own turns -- no segmentation, no clustering; turns, engine and
generatedAt kept byte-for-byte (attribution-diarized's freshness names
generatedAt). A file the whole-file path would take is decoded whole so its
voiceprints equal a fresh run's; longer files seek per excerpt.
Measured on a copy of ObviousRises-rumble/v6z1o2g (766 s): turns byte-identical
to the 2026-08-07 sidecar (51 turns, 13 speakers); 13 of 13 voiceprints;
2,485 -> 22,085 bytes; the voiceprint pass 3.7 s beside 158 s of engine; the
voiceprints-only pass 5.7 s and cos 1.0000 against the full run on all 13.
Tests: scripts/diarize-sherpa.test.mjs on a sherpa_onnx stub (tones as voices,
system python + numpy) -- whole file, windowed, the wrapper, voiceprints-only,
zero-byte audio; and the real engine on two espeak-ng voices when
DIARIZE_PYTHON / DIARIZE_SEG_MODEL / DIARIZE_EMB_MODEL name it (passed here).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
6 files changed, 846 insertions(+), 15 deletions(-)
diff --git a/common/lib/diarization.test.ts b/common/lib/diarization.test.ts
@@ -7,6 +7,10 @@ import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import {
DIARIZATION_FILENAME,
diarizationSpeechSeconds,
+ diarizationTarget,
+ hasVoiceprints,
+ isDiarizationFresh,
+ voiceprintCount,
type DiarizationRecord,
} from "./diarization";
import {
@@ -124,3 +128,50 @@ test("speech seconds sums turns, and overlapping turns are not clamped", () => {
});
assert.equal(diarizationSpeechSeconds(overlapping), 12);
});
+
+// ---- voiceprints ------------------------------------------------------------
+
+const vp = (speaker: number, centroid: number[] | null = [0.6, 0.8]) => ({
+ speaker,
+ seconds: 4,
+ embedded: centroid ? 2 : 0,
+ centroid,
+ embeddingModel: "titanet.onnx",
+});
+
+test("hasVoiceprints: complete only when every speaker in the turns has a well-formed entry", () => {
+ assert.equal(hasVoiceprints(null), false);
+ assert.equal(hasVoiceprints(record()), false, "a sidecar from before voiceprints has none");
+ assert.equal(hasVoiceprints(record({ voiceprints: [vp(0)] })), false, "speaker 1 is missing");
+ assert.equal(hasVoiceprints(record({ voiceprints: [vp(0), vp(1)] })), true);
+ // A null centroid is a recorded "too short to embed": the capture ran.
+ assert.equal(hasVoiceprints(record({ voiceprints: [vp(0), vp(1, null)] })), true);
+ assert.equal(voiceprintCount(record({ voiceprints: [vp(0), vp(1, null)] })), 1);
+ // Malformed reads as absent, so the cleanup gate keeps the audio.
+ assert.equal(hasVoiceprints(record({ voiceprints: [vp(0), vp(1, [Number.NaN])] })), false);
+ assert.equal(
+ hasVoiceprints(record({ voiceprints: [vp(0), { speaker: 1, seconds: 1, centroid: [1] } as never] })),
+ false,
+ "no embeddingModel",
+ );
+ assert.equal(hasVoiceprints(record({ turns: [], speakers: 0, voiceprints: [] })), true);
+});
+
+test("voiceprints are outside the freshness identity: a sidecar without them is not stale", () => {
+ const target = diarizationTarget({ segModel: "/m/model.onnx", embModel: "/m/titanet.onnx", threshold: 0.9 });
+ const engine = { engine: "sherpa-onnx", segmentationModel: "model.onnx", embeddingModel: "titanet.onnx", threshold: 0.9 };
+ assert.equal(isDiarizationFresh(record({ engine }), target), true);
+ assert.equal(isDiarizationFresh(record({ engine, voiceprints: [vp(0), vp(1)], voiceprintsAt: "2026-11-11T00:00:00.000Z" }), target), true);
+});
+
+test("a sidecar with voiceprints round-trips through the writer and the coercer", async () => {
+ const dir = await tmpDir();
+ try {
+ await writeDiarization(dir, record({ voiceprints: [vp(0), vp(1)] }));
+ const loaded = await loadDiarization(dir);
+ assert.equal(hasVoiceprints(loaded), true);
+ assert.deepEqual(loaded?.voiceprints?.[0].centroid, [0.6, 0.8]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/diarization.ts b/common/lib/diarization.ts
@@ -78,8 +78,81 @@ export type DiarizationRecord = {
windowSeconds: number;
overlapSeconds: number;
};
+ // One voice fingerprint per speaker cluster: the TitaNet embedding the
+ // diarizer clustered with, kept rather than discarded (scripts/
+ // diarize-sherpa.py). It is the ONE part of a diarization that cannot be
+ // recomputed once the audio is gone, so the cleanup gate waits for it
+ // (hasVoiceprints) before deleting the audio.
+ //
+ // OUTSIDE `engine` AND OUTSIDE THE FRESHNESS IDENTITY, exactly as `windowing`
+ // is: a sidecar written before voiceprints existed is not stale — its turns
+ // are what the engine produces today — it is only without them, and the
+ // voiceprint step (diarizeOne's voiceprintOneVideo) adds them from the same
+ // turns without re-clustering and without touching `generatedAt` (which
+ // attribution-diarized's freshness names).
+ voiceprints?: DiarizationVoiceprint[];
+ // ISO 8601, when the voiceprints were computed. Equal to (about) generatedAt
+ // for a sidecar that was written with them; later for one that got them from
+ // the voiceprint step.
+ voiceprintsAt?: string;
+};
+
+// A speaker cluster's voice fingerprint. `centroid` is the L2-normalised mean
+// TitaNet-small embedding (VOICEPRINT_DIM floats, rounded to 4 decimals) of the
+// speaker's longest turns, outliers trimmed as voiceMatch's robustCentroid does;
+// null when none of the speaker's turns were long enough to embed — a recorded
+// "nothing to fingerprint", not a missing one.
+export type DiarizationVoiceprint = {
+ speaker: number;
+ // Talk time of this cluster in the record's turns.
+ seconds: number;
+ // How many excerpts the centroid was made from (0 with a null centroid).
+ embedded?: number;
+ centroid: number[] | null;
+ // Basename of the embedding model, so a comparison never mixes models.
+ embeddingModel: string;
};
+export const VOICEPRINT_DIM = 192;
+
+function isVoiceprint(v: unknown): v is DiarizationVoiceprint {
+ const p = v as Partial<DiarizationVoiceprint> | null;
+ if (!p || typeof p !== "object") return false;
+ if (!Number.isInteger(p.speaker)) return false;
+ if (typeof p.embeddingModel !== "string") return false;
+ if (p.centroid === null) return true;
+ return (
+ Array.isArray(p.centroid) &&
+ p.centroid.length > 0 &&
+ p.centroid.every((x) => typeof x === "number" && Number.isFinite(x))
+ );
+}
+
+// Has this record's voice capture been done? True when `voiceprints` holds a
+// well-formed entry for EVERY speaker its turns name (a null centroid counts:
+// the capture ran and that cluster had nothing long enough to embed). A record
+// with no turns at all is trivially complete. This is the predicate the
+// cleanup gate keys off (diarization.requireVoiceprints), so anything short of
+// complete reads as false: a partial array must not be what lets the sweep
+// delete the only audio a missing fingerprint could still be made from.
+export function hasVoiceprints(
+ record: Pick<DiarizationRecord, "turns" | "voiceprints"> | null,
+): boolean {
+ if (!record || !Array.isArray(record.voiceprints)) return false;
+ if (!record.voiceprints.every(isVoiceprint)) return false;
+ const covered = new Set(record.voiceprints.map((v) => v.speaker));
+ return (record.turns ?? []).every((t) => covered.has(t.speaker));
+}
+
+// How many clusters carry an actual centroid.
+export function voiceprintCount(
+ record: Pick<DiarizationRecord, "voiceprints"> | null,
+): number {
+ return (record?.voiceprints ?? []).filter(
+ (v) => isVoiceprint(v) && v.centroid !== null,
+ ).length;
+}
+
export const DIARIZATION_FILENAME = "diarization.json";
// The engine id scripts/diarize.mjs records when it runs its own default
diff --git a/scripts/diarize-sherpa.py b/scripts/diarize-sherpa.py
@@ -43,9 +43,25 @@ Usage:
[--threads N] [--ffmpeg PATH] [--ffprobe PATH]
[--window-minutes M] [--window-after-minutes M]
<audioFile>
+ diarize-sherpa.py --voiceprints-only <diarization.json> --emb <model.onnx>
+ [--threads N] [--ffmpeg PATH] <audioFile>
Output: {"turns":[{"start":s,"end":s,"speaker":i}], "audioSeconds":f,
- "version":"...", "sampleRate":n, "windowing":{...}|null}
+ "version":"...", "sampleRate":n, "windowing":{...}|null,
+ "voiceprints":[{"speaker":i,"seconds":f,"embedded":n,
+ "centroid":[192 floats]|null}]}
+ --voiceprints-only prints {"voiceprints":[...], "version":"..."} for the
+ turns of an EXISTING record: no segmentation, no clustering, the turns are
+ not touched.
+
+VOICEPRINTS, AND WHY THEY ARE KEPT
+----------------------------------
+A voiceprint is one TitaNet embedding per FINAL speaker: the robust mean of
+that speaker's longest turns (see speaker_voiceprints). It is the one thing a
+diarization cannot recompute once the audio is deleted, and the cleanup sweep
+deletes the audio, so it is captured here, while the samples are in memory.
+It is computed AFTER the turns are final and never feeds back into them: the
+turns a file produced before voiceprints existed are the turns it produces now.
"""
import argparse, json, subprocess, sys, time
@@ -60,6 +76,18 @@ EMB_MIN_SEC = 0.5
# does not leave a visible split that the same audio processed whole would not
# have had.
MERGE_GAP_SEC = 0.5
+# A voiceprint embeds a speaker's VP_MAX_SEGMENTS longest turns, each capped at
+# VP_MAX_SEC, and drops the ones more than VP_TRIM under the median similarity to
+# the first mean before taking the mean again -- the same robust centroid as
+# common/lib/montage/voiceMatch.mjs's robustCentroid (REFERENCE_TRIM 0.15), so a
+# voiceprint and a voice-match reference mean the same thing.
+VP_MAX_SEGMENTS = 8
+VP_MAX_SEC = 10.0
+VP_TRIM = 0.15
+# 4 decimals: a cosine between two rounded unit vectors moves by < 1e-3, far
+# under any threshold that reads them (0.30 / 0.42), and a 192-float centroid
+# stays ~1.5 KB on disk.
+VP_DECIMALS = 4
def decode_whole_file(np, ffmpeg, audio, sample_rate):
@@ -195,10 +223,116 @@ def speaker_centroid(np, extractor, samples, sample_rate, segments):
if norm > 0:
vecs.append(v / norm)
if not vecs:
- return None
+ return None, 0
mean = np.mean(np.stack(vecs), axis=0)
norm = float(np.linalg.norm(mean))
- return mean / norm if norm > 0 else None
+ return (mean / norm if norm > 0 else None), len(vecs)
+
+
+def unit(np, v):
+ n = float(np.linalg.norm(v))
+ return v / n if n > 0 else None
+
+
+def robust_centroid(np, vecs, trim=VP_TRIM):
+ """voiceMatch.mjs's robustCentroid: the mean, then every vector more than
+ `trim` under the median similarity to it dropped, then the mean of the rest.
+ Fewer than three vectors are simply averaged (no median worth trusting)."""
+ if not vecs:
+ return None
+ first = unit(np, np.mean(np.stack(vecs), axis=0))
+ if first is None or len(vecs) < 3:
+ return first
+ sims = [float(np.dot(v, first)) for v in vecs]
+ floor = float(np.median(sims)) - trim
+ kept = [v for v, s in zip(vecs, sims) if s >= floor]
+ return unit(np, np.mean(np.stack(kept), axis=0)) if kept else first
+
+
+def embed_samples(np, extractor, sample_rate, x):
+ """One L2-normalized embedding of a stretch of samples, or None."""
+ if x.size < int(EMB_MIN_SEC * sample_rate):
+ return None
+ stream = extractor.create_stream()
+ stream.accept_waveform(sample_rate, x)
+ stream.input_finished()
+ if not extractor.is_ready(stream):
+ return None
+ return unit(np, np.asarray(extractor.compute(stream), dtype=np.float32))
+
+
+def voiceprint_spans(turns):
+ """{speaker: [(start, end)]}: the excerpts a voiceprint embeds. A speaker's
+ longest turns, each cut to VP_MAX_SEC from its start; spans under
+ EMB_MIN_SEC are not worth an embedding and are left out here."""
+ by_speaker = {}
+ for t in turns:
+ by_speaker.setdefault(int(t["speaker"]), []).append((float(t["start"]), float(t["end"])))
+ out = {}
+ for spk, spans in by_speaker.items():
+ picked = sorted(spans, key=lambda s: (s[0] - s[1], s[0]))[:VP_MAX_SEGMENTS]
+ out[spk] = [(a, min(b, a + VP_MAX_SEC)) for a, b in picked
+ if min(b, a + VP_MAX_SEC) - a >= EMB_MIN_SEC]
+ return out
+
+
+def speaker_seconds(turns):
+ """{speaker: talk seconds}, from the FINAL turns."""
+ out = {}
+ for t in turns:
+ spk = int(t["speaker"])
+ out[spk] = out.get(spk, 0.0) + max(0.0, float(t["end"]) - float(t["start"]))
+ return out
+
+
+def voiceprint_records(turns, vectors):
+ """The `voiceprints` array: one entry per speaker in `turns`, in speaker
+ order. `vectors` is {speaker: (unit vector or None, excerpts embedded)}; a
+ speaker with nothing embeddable gets centroid null -- present and honest,
+ so "no voiceprint for this one" is a recorded fact, not a missing field."""
+ secs = speaker_seconds(turns)
+ out = []
+ for spk in sorted(secs):
+ vec, n = vectors.get(spk, (None, 0))
+ out.append({
+ "speaker": spk,
+ "seconds": round(secs[spk], 3),
+ "embedded": int(n),
+ "centroid": None if vec is None
+ else [round(float(e), VP_DECIMALS) for e in vec],
+ })
+ return out
+
+
+def voiceprints_from_samples(np, extractor, samples, sample_rate, turns):
+ """Voiceprints for a recording whose samples are in memory (the whole-file
+ path): each speaker's excerpts sliced out and embedded."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ i, j = int(a * sample_rate), min(int(b * sample_rate), samples.size)
+ v = embed_samples(np, extractor, sample_rate, samples[i:j])
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
+
+
+def voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns):
+ """Voiceprints for an EXISTING record's turns, decoding only the excerpts
+ (an input seek per excerpt, as the windowed path does), so a nine-hour file
+ costs a few hundred seconds of audio, not nine hours of memory."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ x = decode_window(np, ffmpeg, audio, sample_rate, a, b - a)
+ v = embed_samples(np, extractor, sample_rate, x)
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
def merge_and_renumber(turns):
@@ -246,7 +380,7 @@ def merge_and_renumber(turns):
merged.append({"start": cur_start, "end": cur_end, "speaker": speaker})
merged.sort(key=lambda t: (t["start"], t["end"], t["speaker"]))
- return merged
+ return merged, order
def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
@@ -268,6 +402,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
kept = [] # {"start","end","key"} in ABSOLUTE seconds
centroids = [] # parallel to keys
keys = [] # (window index, local speaker)
+ embedded = {} # key -> excerpts its centroid was made from
decoded_sec = 0.0
for wi, (ws, dur, own_s, own_e) in enumerate(windows):
@@ -296,11 +431,12 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
# every turn belongs to the neighbouring window would otherwise add a
# cluster that names nothing.
for spk, spk_segs in owned_by_speaker.items():
- c = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
+ c, n = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
if c is None:
continue
centroids.append(c)
keys.append((wi, spk))
+ embedded[(wi, spk)] = n
elapsed = time.time() - t0
print(
@@ -312,7 +448,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
del samples, result, segs
if not kept:
- return [], decoded_sec, len(windows)
+ return [], [], decoded_sec, len(windows)
# Cross-window identity. Same clusterer and same threshold as within a
# window, so "these two are the same person" means the same thing at both
@@ -338,13 +474,107 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
t["speaker"] = global_of[t["key"]]
del t["key"]
- return merge_and_renumber(kept), decoded_sec, len(windows)
+ merged, order = merge_and_renumber(kept)
+
+ # ONE voiceprint per FINAL speaker: the robust mean of the local centroids
+ # that clustered into it. Those centroids are what decided the identity
+ # across seams, so they are the voiceprint of exactly that identity. A
+ # spare (a local speaker with no usable centroid) has none.
+ by_label = {}
+ for key, c in zip(keys, centroids):
+ by_label.setdefault(global_of[key], []).append((c, embedded.get(key, 0)))
+ vectors = {}
+ for label, final in order.items():
+ members = by_label.get(label, [])
+ vectors[final] = (
+ robust_centroid(np, [c for c, _ in members]),
+ sum(n for _, n in members),
+ )
+ return merged, vectors, decoded_sec, len(windows)
+
+
+def print_voiceprint_line(voiceprints, elapsed):
+ # Not "window i/n": common/jobs/progressParsers.ts reads those lines as a bar.
+ have = sum(1 for v in voiceprints if v["centroid"] is not None)
+ print(
+ f"diarize-sherpa: voiceprints for {have} of {len(voiceprints)} speaker(s) "
+ f"in {elapsed:.1f}s",
+ file=sys.stderr, flush=True,
+ )
+
+
+def run_voiceprints_only(args):
+ """Voiceprints for an existing record's turns. No segmentation model, no
+ clustering: the turns are read, never changed."""
+ try:
+ import numpy as np
+ import sherpa_onnx
+ except ImportError as e:
+ print(f"diarize-sherpa: missing dependency: {e}", file=sys.stderr)
+ return 3
+ try:
+ with open(args.voiceprints_only, "r", encoding="utf8") as f:
+ record = json.load(f)
+ turns = record["turns"]
+ except Exception as e:
+ print(f"diarize-sherpa: cannot read turns from {args.voiceprints_only}: {e}",
+ file=sys.stderr)
+ return 2
+ cfg = sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ if not cfg.validate():
+ print("diarize-sherpa: invalid embedding model config", file=sys.stderr)
+ return 2
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(cfg)
+ t0 = time.time()
+ sample_rate = 16000
+ # A file the whole-file path would have taken is decoded whole here too, so
+ # its voiceprints are the very numbers a fresh diarization would record (an
+ # mp3 input seek is not sample-exact, and a short turn's embedding moves
+ # with a few ms of offset). Longer files seek per excerpt, as windowing does.
+ total_sec = probe_duration(args.ffprobe, args.audio)
+ whole = (
+ total_sec is not None
+ and total_sec <= args.window_after_minutes * 60.0
+ )
+ try:
+ if whole:
+ samples = decode_whole_file(np, args.ffmpeg, args.audio, sample_rate)
+ if samples is None or samples.size == 0:
+ print("diarize-sherpa: decoded zero samples", file=sys.stderr)
+ return 5 if samples is not None else 4
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sample_rate, turns
+ )
+ del samples
+ elif total_sec is None:
+ # ffprobe cannot read it: neither can ffmpeg, and seeking into it
+ # would only produce silence to embed.
+ print("diarize-sherpa: cannot measure the audio (unreadable?)",
+ file=sys.stderr)
+ return 4
+ else:
+ voiceprints = voiceprints_from_file(
+ np, extractor, args.ffmpeg, args.audio, sample_rate, turns
+ )
+ except RuntimeError as e:
+ print(f"diarize-sherpa: {e}", file=sys.stderr)
+ return 4
+ print_voiceprint_line(voiceprints, time.time() - t0)
+ json.dump(
+ {"voiceprints": voiceprints,
+ "version": getattr(sherpa_onnx, "__version__", None)},
+ sys.stdout,
+ )
+ return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("audio")
- ap.add_argument("--seg", required=True)
+ ap.add_argument("--seg")
+ ap.add_argument("--voiceprints-only", metavar="DIARIZATION_JSON")
ap.add_argument("--emb", required=True)
ap.add_argument("--threshold", type=float, default=0.5)
ap.add_argument("--threads", type=int, default=4)
@@ -363,6 +593,11 @@ def main():
ap.add_argument("--window-overlap-seconds", type=float, default=30.0)
args = ap.parse_args()
+ if args.voiceprints_only:
+ return run_voiceprints_only(args)
+ if not args.seg:
+ ap.error("--seg is required")
+
try:
import numpy as np
import sherpa_onnx
@@ -409,7 +644,7 @@ def main():
# to separate them.
t0 = time.time()
try:
- turns, audio_seconds, window_count = run_windowed(
+ turns, vectors, audio_seconds, window_count = run_windowed(
np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec
)
except RuntimeError as e:
@@ -448,6 +683,19 @@ def main():
for s in result
]
windowing = None
+ # After the turns are final and outside the engine timing above, so
+ # `elapsed` keeps meaning what plans/ recorded it as.
+ t1 = time.time()
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(
+ sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ )
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sd.sample_rate, turns
+ )
+ vp_elapsed = time.time() - t1
+ del samples
if windowed:
turns = [
@@ -455,6 +703,8 @@ def main():
"speaker": int(t["speaker"])}
for t in turns
]
+ voiceprints = voiceprint_records(turns, vectors)
+ vp_elapsed = 0.0
speakers = len({t["speaker"] for t in turns})
print(
@@ -463,6 +713,8 @@ def main():
file=sys.stderr, flush=True,
)
+ print_voiceprint_line(voiceprints, vp_elapsed)
+
json.dump(
{
"turns": turns,
@@ -470,6 +722,7 @@ def main():
"sampleRate": sd.sample_rate,
"version": getattr(sherpa_onnx, "__version__", None),
"windowing": windowing,
+ "voiceprints": voiceprints,
},
sys.stdout,
)
diff --git a/scripts/diarize-sherpa.test.mjs b/scripts/diarize-sherpa.test.mjs
@@ -0,0 +1,213 @@
+// scripts/diarize-sherpa.py's voiceprints, through scripts/diarize.mjs.
+//
+// Two engines run these tests. The STUB (scripts/fixtures/sherpa-stub, on the
+// system python with numpy) is the default: a "voice" is a pure tone, so the
+// test can say who speaks when, and every number is exact. The REAL engine
+// (sherpa-onnx + TitaNet-small) runs the last test when DIARIZE_PYTHON,
+// DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL name it, on two espeak-ng voices.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const HERE = import.meta.dirname;
+const SCRIPT = path.join(HERE, "diarize-sherpa.py");
+const WRAPPER = path.join(HERE, "diarize.mjs");
+const STUB = path.join(HERE, "fixtures", "sherpa-stub");
+
+function has(cmd, args) {
+ return spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
+}
+const hasFfmpeg = has("ffmpeg", ["-version"]) && has("ffprobe", ["-version"]);
+const hasNumpy = has("python3", ["-c", "import numpy"]);
+const skip = !(hasFfmpeg && hasNumpy) && "needs ffmpeg, ffprobe and python3 with numpy";
+
+const SR = 16000;
+// [start, end, hz]: who is speaking when. 300 Hz and 1000 Hz are two voices;
+// the 2000 Hz blip is a third whose only turn is too short to embed.
+const PLAN = [
+ [0, 4, 300],
+ [4.5, 8, 1000],
+ [8.5, 11, 300],
+ [11.5, 13, 1000],
+ [13.5, 13.75, 2000],
+];
+
+function writeWav(file, plan, total = 14) {
+ const n = Math.round(total * SR);
+ const pcm = Buffer.alloc(n * 2);
+ for (const [a, b, hz] of plan) {
+ for (let i = Math.round(a * SR); i < Math.round(b * SR); i += 1) {
+ pcm.writeInt16LE(Math.round(0.5 * 32767 * Math.sin((2 * Math.PI * hz * i) / SR)), i * 2);
+ }
+ }
+ const h = Buffer.alloc(44);
+ h.write("RIFF", 0);
+ h.writeUInt32LE(36 + pcm.length, 4);
+ h.write("WAVEfmt ", 8);
+ h.writeUInt32LE(16, 16);
+ h.writeUInt16LE(1, 20);
+ h.writeUInt16LE(1, 22);
+ h.writeUInt32LE(SR, 24);
+ h.writeUInt32LE(SR * 2, 28);
+ h.writeUInt16LE(2, 32);
+ h.writeUInt16LE(16, 34);
+ h.write("data", 36);
+ h.writeUInt32LE(pcm.length, 40);
+ writeFileSync(file, Buffer.concat([h, pcm]));
+}
+
+const env = { ...process.env, PYTHONPATH: STUB };
+
+function engine(args) {
+ return JSON.parse(execFileSync("python3", [SCRIPT, ...args], { env, stdio: ["ignore", "pipe", "pipe"] }).toString());
+}
+
+const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
+
+function withDir(fn) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "diarize-sherpa-test-"));
+ try {
+ return fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test("whole file: one voiceprint per speaker, unit length, voices apart; a too-short speaker is recorded with a null centroid", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = engine(["--seg", "seg.onnx", "--emb", "emb.onnx", wav]);
+ // The turns are the engine's own, untouched by the voiceprint pass.
+ assert.deepEqual(
+ out.turns.map((t) => [t.start, t.end, t.speaker]),
+ [[0, 4, 0], [4.5, 8, 1], [8.5, 11, 0], [11.5, 13, 1], [13.5, 13.75, 2]],
+ );
+ assert.equal(out.windowing, null);
+ assert.deepEqual(out.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded]), [[0, 6.5, 2], [1, 5, 2], [2, 0.25, 0]]);
+ const [a, b, c] = out.voiceprints;
+ assert.equal(a.centroid.length, 192);
+ assert.ok(Math.abs(dot(a.centroid, a.centroid) - 1) < 1e-3);
+ assert.ok(dot(a.centroid, b.centroid) < 0.2, "two voices are apart");
+ assert.equal(c.centroid, null);
+ // Rounded to 4 decimals, so the same input prints the same bytes.
+ assert.ok(a.centroid.every((x) => Math.round(x * 1e4) / 1e4 === x));
+ }));
+
+test("windowed: one voiceprint per FINAL cluster, and it is the same voice as the whole-file one", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN.slice(0, 4));
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const win = engine(["--seg", "s", "--emb", "e", "--window-minutes", "0.1", "--window-after-minutes", "0", "--window-overlap-seconds", "1", wav]);
+ assert.equal(win.windowing.windows, 3);
+ const speakers = [...new Set(win.turns.map((t) => t.speaker))].sort();
+ assert.deepEqual(speakers, [0, 1]);
+ assert.deepEqual(win.voiceprints.map((v) => v.speaker), [0, 1]);
+ for (const v of win.voiceprints) {
+ assert.ok(v.embedded >= 2, `speaker ${v.speaker} was embedded from more than one window's turns`);
+ const same = whole.voiceprints.find((w) => w.speaker === v.speaker);
+ assert.ok(dot(v.centroid, same.centroid) > 0.99, `speaker ${v.speaker} matches its whole-file voiceprint`);
+ }
+ assert.equal(
+ win.voiceprints.find((v) => v.speaker === 0).seconds,
+ whole.voiceprints.find((v) => v.speaker === 0).seconds,
+ );
+ }));
+
+test("diarize.mjs records the voiceprints with the embedding model's basename, outside `engine`", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", "python3", "--seg", "/m/seg.onnx", "--emb", "/m/titanet.onnx", "--threshold", "0.9", "--output", out, "--video-id", "v1", wav], { env, stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ assert.equal(rec.voiceprints.length, 3);
+ assert.ok(rec.voiceprints.every((v) => v.embeddingModel === "titanet.onnx"));
+ assert.equal(typeof rec.voiceprintsAt, "string");
+ assert.equal(rec.engine.embeddingModel, "titanet.onnx");
+ assert.equal("voiceprints" in rec.engine, false);
+ }));
+
+test("--voiceprints-only adds voiceprints to an existing record from its own turns, keeping turns and generatedAt", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const rec = path.join(dir, "diarization.json");
+ const before = {
+ videoId: "v1",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ speakers: 3,
+ turns: whole.turns,
+ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 },
+ };
+ writeFileSync(rec, JSON.stringify(before) + "\n");
+ execFileSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/titanet.onnx", wav], { env, stdio: "ignore" });
+ const after = JSON.parse(readFileSync(rec, "utf8"));
+ assert.equal(after.generatedAt, before.generatedAt);
+ assert.deepEqual(after.turns, before.turns);
+ assert.deepEqual(after.engine, before.engine);
+ assert.deepEqual(
+ after.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded, v.embeddingModel]),
+ [[0, 6.5, 2, "titanet.onnx"], [1, 5, 2, "titanet.onnx"], [2, 0.25, 0, "titanet.onnx"]],
+ );
+ // Decoded per excerpt rather than whole, and the same voice either way.
+ for (const v of after.voiceprints.filter((x) => x.centroid)) {
+ assert.ok(dot(v.centroid, whole.voiceprints[v.speaker].centroid) > 0.999);
+ }
+ }));
+
+test("--voiceprints-only on a zero-byte audio fails and leaves the record exactly as it was", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "empty.mp3");
+ writeFileSync(wav, "");
+ const rec = path.join(dir, "diarization.json");
+ const body = JSON.stringify({ videoId: "v1", generatedAt: "x", speakers: 1, turns: [{ start: 0, end: 3, speaker: 0 }], engine: { engine: "sherpa-onnx" } }) + "\n";
+ writeFileSync(rec, body);
+ const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], { env, stdio: "ignore" });
+ assert.notEqual(r.status, 0);
+ assert.equal(readFileSync(rec, "utf8"), body);
+ }));
+
+const REAL = (() => {
+ const python = process.env.DIARIZE_PYTHON;
+ const seg = process.env.DIARIZE_SEG_MODEL;
+ const emb = process.env.DIARIZE_EMB_MODEL;
+ if (!python || !seg || !emb || ![python, seg, emb].every(existsSync)) return null;
+ if (!has("espeak-ng", ["--version"]) || !hasFfmpeg) return null;
+ return { python, seg, emb };
+})();
+
+test("the real engine (sherpa-onnx + TitaNet-small): two espeak voices, a 192-float voiceprint per speaker", { skip: !REAL && "set DIARIZE_PYTHON, DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL (and install espeak-ng) to run it" }, () =>
+ withDir((dir) => {
+ const parts = [
+ ["en-us", "The quick brown fox jumps over the lazy dog while the band plays on into the night."],
+ ["en+f4", "Nobody expected the committee to vote that way, but here we are again this morning."],
+ ["en-us", "Then the fox came back and asked whether anyone had seen his other shoe, which was red."],
+ ];
+ const files = parts.map(([voice, text], i) => {
+ const f = path.join(dir, `p${i}.wav`);
+ execFileSync("espeak-ng", ["-v", voice, "-s", "150", "-w", f, text]);
+ return f;
+ });
+ const list = path.join(dir, "list.txt");
+ writeFileSync(list, files.map((f) => `file '${f}'`).join("\n"));
+ const wav = path.join(dir, "talk.wav");
+ execFileSync("ffmpeg", ["-v", "error", "-f", "concat", "-safe", "0", "-i", list, "-ar", "16000", "-ac", "1", wav]);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", REAL.python, "--seg", REAL.seg, "--emb", REAL.emb, "--threshold", "0.9", "--output", out, "--video-id", "real", wav], { stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ const speakers = new Set(rec.turns.map((t) => t.speaker));
+ assert.ok(speakers.size >= 1);
+ assert.equal(rec.voiceprints.length, speakers.size);
+ const real = rec.voiceprints.filter((v) => v.centroid);
+ assert.ok(real.length >= 1);
+ for (const v of real) {
+ assert.equal(v.centroid.length, 192);
+ assert.ok(Math.abs(dot(v.centroid, v.centroid) - 1) < 1e-2);
+ }
+ }));
diff --git a/scripts/diarize.mjs b/scripts/diarize.mjs
@@ -58,8 +58,20 @@
// (DIARIZE_WINDOW_MINUTES, 45)
// --window-after-minutes <m> only window files longer than this
// (DIARIZE_WINDOW_AFTER_MINUTES, 90)
+// --voiceprints-only <record.json>
+// add voiceprints to an EXISTING record from its own
+// turns (sherpa's embedder; no segmentation, no
+// clustering) and write it to --output (default: back
+// over <record.json>). Turns, generatedAt and engine are
+// kept byte-for-byte; only voiceprints/voiceprintsAt land.
// -h, --help
//
+// VOICEPRINTS: the sherpa engine prints one TitaNet centroid per final speaker
+// (scripts/diarize-sherpa.py), and they land on the record as `voiceprints`,
+// each carrying the embedding model's basename. Like `windowing` they are
+// OUTSIDE `engine` and outside the freshness identity: a sidecar written before
+// they existed is not stale, it is merely without them (hasVoiceprints).
+//
// WINDOWING IS RECORDED BUT IS NOT PART OF THE FRESHNESS IDENTITY. It lands on
// the record as a top-level `windowing` field, deliberately OUTSIDE `engine` —
// isDiarizationFresh compares engine/models/threshold, and the target it
@@ -70,7 +82,7 @@
// See common/lib/diarization.ts, which says so in as many words.
import { spawn } from "node:child_process";
-import { rename, writeFile } from "node:fs/promises";
+import { readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
const HELP = `diarize.mjs [options] <audioFile>
@@ -126,6 +138,104 @@ const windowAfterMinutes = arg(
process.env.DIARIZE_WINDOW_AFTER_MINUTES ?? "90",
);
+const voiceprintsOnly = arg("--voiceprints-only", "");
+
+// The engine's voiceprints as the record stores them. Anything malformed is
+// dropped rather than written: a voiceprint is read by cosine, and a wrong
+// length or a NaN would make every comparison against it quietly meaningless.
+function recordVoiceprints(raw, embeddingModel) {
+ if (!Array.isArray(raw)) return undefined;
+ const out = [];
+ for (const v of raw) {
+ const speaker = Number(v?.speaker);
+ if (!Number.isInteger(speaker)) continue;
+ const centroid =
+ Array.isArray(v.centroid) &&
+ v.centroid.length > 0 &&
+ v.centroid.every((x) => Number.isFinite(x))
+ ? v.centroid.map(Number)
+ : null;
+ out.push({
+ speaker,
+ seconds: Number.isFinite(v.seconds) ? v.seconds : 0,
+ embedded: Number.isInteger(v.embedded) ? v.embedded : 0,
+ centroid,
+ embeddingModel,
+ });
+ }
+ return out;
+}
+
+async function writeAtomic(file, json) {
+ // Atomic: a half-written sidecar must never be what convinces the cleanup
+ // sweep it is safe to delete the only copy of the audio.
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, json);
+ await rename(tmp, file);
+}
+
+async function runVoiceprintsOnly() {
+ if (!emb) fail("missing --emb (or DIARIZE_EMB_MODEL)");
+ let existing;
+ try {
+ existing = JSON.parse(await readFile(voiceprintsOnly, "utf8"));
+ } catch (e) {
+ fail(`cannot read ${voiceprintsOnly}: ${e.message}`);
+ }
+ if (!Array.isArray(existing?.turns)) fail(`${voiceprintsOnly} has no \`turns\``);
+ const started = Date.now();
+ const child = spawn(
+ python,
+ [
+ path.join(import.meta.dirname, "diarize-sherpa.py"),
+ "--voiceprints-only", voiceprintsOnly,
+ "--emb", emb,
+ "--threads", String(threads),
+ "--ffmpeg", ffmpeg,
+ "--ffprobe", ffprobe,
+ "--window-after-minutes", String(windowAfterMinutes),
+ audio,
+ ],
+ { stdio: ["ignore", "pipe", "inherit"] },
+ );
+ let out = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (d) => (out += d));
+ const code = await new Promise((resolve) => {
+ child.on("error", (err) => fail(`failed to run ${python}: ${err.message}`, 3));
+ child.on("close", resolve);
+ });
+ if (code !== 0) fail(`engine exited ${code}`, code ?? 1);
+ let raw;
+ try {
+ raw = JSON.parse(out);
+ } catch {
+ fail("engine produced no parseable JSON on stdout");
+ }
+ const voiceprints = recordVoiceprints(raw?.voiceprints, path.basename(emb));
+ if (!voiceprints) fail("engine output has no `voiceprints` array");
+ // Everything already on the record stays as it was -- generatedAt above
+ // all: attribution-diarized's freshness names it, so touching it would make
+ // every name already put to these clusters stale for no change in them.
+ const record = {
+ ...existing,
+ voiceprints,
+ voiceprintsAt: new Date().toISOString(),
+ voiceprintsMs: Date.now() - started,
+ };
+ const target = output ?? voiceprintsOnly;
+ await writeAtomic(target, JSON.stringify(record) + "\n");
+ const have = voiceprints.filter((v) => v.centroid).length;
+ process.stderr.write(
+ `diarize: voiceprints for ${have} of ${voiceprints.length} speaker(s) -> ${target}\n`,
+ );
+}
+
+if (voiceprintsOnly) {
+ await runVoiceprintsOnly();
+ process.exit(0);
+}
+
const engineCmd = arg("--engine", process.env.DIARIZE_ENGINE_CMD ?? "");
const engineKind = arg(
"--engine-kind",
@@ -227,6 +337,14 @@ child.on("close", async (code) => {
: {}),
speakers: new Set(turns.map((t) => t.speaker)).size,
turns,
+ // Outside `engine`, like `windowing`. Only the sherpa engine embeds; a
+ // sortformer or `--engine` record has none, and says so by omission.
+ ...(() => {
+ const vp = usingSortformer
+ ? undefined
+ : recordVoiceprints(raw.voiceprints, emb ? path.basename(emb) : "");
+ return vp ? { voiceprints: vp, voiceprintsAt: new Date().toISOString() } : {};
+ })(),
// Provenance is per-engine, and the fields a given engine CANNOT have are
// left off rather than written empty. Recording sherpa's threshold on a
// sortformer record would be a lie that isDiarizationFresh then acts on: it
@@ -258,11 +376,7 @@ child.on("close", async (code) => {
process.stdout.write(json);
return;
}
- // Atomic: a half-written sidecar must never be what convinces the cleanup
- // sweep it is safe to delete the only copy of the audio.
- const tmp = `${output}.tmp-${process.pid}`;
- await writeFile(tmp, json);
- await rename(tmp, output);
+ await writeAtomic(output, json);
process.stderr.write(
`diarize: ${record.turns.length} turns, ${record.speakers} speakers -> ${output}\n`,
);
diff --git a/scripts/fixtures/sherpa-stub/sherpa_onnx.py b/scripts/fixtures/sherpa-stub/sherpa_onnx.py
@@ -0,0 +1,127 @@
+"""A stand-in for sherpa_onnx, for scripts/diarize-sherpa.test.mjs.
+
+Same surface as the calls scripts/diarize-sherpa.py makes, none of the models:
+a "voice" is a pure tone, so a test can say who is speaking when by writing a
+wav. Segmentation labels each voiced 0.25 s frame by its dominant frequency;
+an embedding is a smooth bump on a 192-bin frequency axis, so two tones of one
+pitch embed alike and two pitches embed apart; clustering is greedy cosine.
+The real engine is tested by the same file when DIARIZE_PYTHON /
+DIARIZE_SEG_MODEL / DIARIZE_EMB_MODEL name it.
+"""
+import numpy as np
+
+__version__ = "stub-1"
+SR = 16000
+FRAME = 0.25
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ self.__dict__.update(kw)
+
+ def validate(self):
+ return True
+
+
+OfflineSpeakerDiarizationConfig = _Cfg
+OfflineSpeakerSegmentationModelConfig = _Cfg
+OfflineSpeakerSegmentationPyannoteModelConfig = _Cfg
+SpeakerEmbeddingExtractorConfig = _Cfg
+FastClusteringConfig = _Cfg
+
+
+def _pitch(x):
+ if x.size == 0:
+ return 0.0
+ spec = np.abs(np.fft.rfft(x * np.hanning(x.size)))
+ return float(np.argmax(spec)) * SR / x.size
+
+
+class _Seg:
+ def __init__(self, start, end, speaker):
+ self.start, self.end, self.speaker = start, end, speaker
+
+
+class _Result(list):
+ def sort_by_start_time(self):
+ return _Result(sorted(self, key=lambda s: s.start))
+
+
+class OfflineSpeakerDiarization:
+ sample_rate = SR
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def process(self, samples):
+ n = int(FRAME * SR)
+ labels = {}
+ segs = []
+ cur = None
+ for i in range(0, samples.size - n + 1, n):
+ x = samples[i:i + n]
+ if float(np.sqrt(np.mean(x * x))) < 0.01:
+ cur = None
+ continue
+ # Pitch to the nearest 100 Hz is the "speaker".
+ key = int(round(_pitch(x) / 100.0))
+ spk = labels.setdefault(key, len(labels))
+ t = i / SR
+ if cur is not None and cur.speaker == spk and abs(cur.end - t) < 1e-6:
+ cur.end = t + FRAME
+ else:
+ cur = _Seg(t, t + FRAME, spk)
+ segs.append(cur)
+ return _Result(segs)
+
+
+class _Stream:
+ def __init__(self):
+ self.x = np.zeros(0, dtype=np.float32)
+
+ def accept_waveform(self, sr, x):
+ self.x = np.concatenate([self.x, np.asarray(x, dtype=np.float32)])
+
+ def input_finished(self):
+ pass
+
+
+class SpeakerEmbeddingExtractor:
+ dim = 192
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def create_stream(self):
+ return _Stream()
+
+ def is_ready(self, stream):
+ return stream.x.size >= int(0.5 * SR)
+
+ def compute(self, stream):
+ f = _pitch(stream.x)
+ axis = np.arange(self.dim, dtype=np.float64)
+ centre = min(self.dim - 1, f / 20.0)
+ v = np.exp(-((axis - centre) ** 2) / 18.0) + 0.01
+ return list(v)
+
+
+class FastClustering:
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def __call__(self, arr):
+ cents = []
+ out = []
+ for v in np.asarray(arr, dtype=np.float64):
+ v = v / np.linalg.norm(v)
+ best = -1
+ for k, c in enumerate(cents):
+ if float(np.dot(v, c)) > 0.5:
+ best = k
+ break
+ if best < 0:
+ cents.append(v)
+ best = len(cents) - 1
+ out.append(best)
+ return out