// 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, PYTHONDONTWRITEBYTECODE: "1" }; 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.deepEqual(Object.keys(rec.voiceprintsFrom).sort(), ["bytes", "durationSeconds", "file"]); assert.equal(rec.voiceprintsFrom.file, "a.wav"); 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", audioSeconds: whole.audioSeconds, 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); } // Which file they were cut from. assert.equal(after.voiceprintsFrom.file, "a.wav"); assert.equal(after.voiceprintsFrom.bytes, readFileSync(wav).length); assert.ok(Math.abs(after.voiceprintsFrom.durationSeconds - 14) < 0.01); })); 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); } })); // ---- review B3: refuse rather than record a fingerprint from the wrong audio -- function vpOnly(dir, wav, record, extraEnv = {}) { const rec = path.join(dir, "diarization.json"); const body = JSON.stringify(record) + "\n"; writeFileSync(rec, body); const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], { env: { ...env, ...extraEnv }, encoding: "utf8", }); return { status: r.status, stderr: r.stderr, untouched: readFileSync(rec, "utf8") === body }; } const base = (over) => ({ videoId: "v1", generatedAt: "x", audioSeconds: 14, speakers: 2, turns: [ { start: 0, end: 4, speaker: 0 }, { start: 4.5, end: 8, speaker: 1 }, ], engine: { engine: "sherpa-onnx" }, ...over, }); test("voiceprints-only refuses a file whose duration is not the record's (> 1 s apart), or a record with none", { skip }, () => withDir((dir) => { const wav = path.join(dir, "a.wav"); writeWav(wav, PLAN); const off = vpOnly(dir, wav, base({ audioSeconds: 99 })); assert.equal(off.status, 6); assert.ok(off.untouched); assert.match(off.stderr, /not the audio these turns were made from/); const none = vpOnly(dir, wav, base({ audioSeconds: undefined })); assert.equal(none.status, 6); assert.ok(none.untouched); assert.equal(vpOnly(dir, wav, base({ audioSeconds: 14.6 })).status, 0, "under a second apart is the same file"); })); test("voiceprints-only refuses when an excerpt comes back short (a turn past the file's end)", { skip }, () => withDir((dir) => { const wav = path.join(dir, "a.wav"); writeWav(wav, PLAN); const r = vpOnly(dir, wav, base({ turns: [{ start: 0, end: 4, speaker: 0 }, { start: 12, end: 18, speaker: 1 }] })); assert.equal(r.status, 6); assert.ok(r.untouched); assert.match(r.stderr, /were not made from this file/); })); test("voiceprints-only refuses when a speaker with long turns gets no embedding, though the audio decodes", { skip }, () => withDir((dir) => { const wav = path.join(dir, "a.wav"); writeWav(wav, PLAN); const r = vpOnly(dir, wav, base(), { STUB_NOT_READY: "1" }); assert.equal(r.status, 6); assert.ok(r.untouched); assert.match(r.stderr, /no embedding for speaker/); // The full diarization still writes the record — with null centroids, which // the cleanup gate (hasVoiceprints) reads as NOT fingerprinted. const out = engine(["--seg", "s", "--emb", "e", wav].concat([])); assert.ok(out.voiceprints.length > 0); const notReady = JSON.parse( execFileSync("python3", [SCRIPT, "--seg", "s", "--emb", "e", wav], { env: { ...env, STUB_NOT_READY: "1" }, stdio: ["ignore", "pipe", "pipe"] }).toString(), ); assert.ok(notReady.voiceprints.every((v) => v.centroid === null)); })); test("a voiceprint step that succeeds drops a refusal recorded against an earlier file", { skip }, () => withDir((dir) => { const wav = path.join(dir, "a.wav"); writeWav(wav, PLAN); const r = vpOnly(dir, wav, base({ voiceprintsRefused: { file: "audio.mp3", size: 1, mtime: 1, reason: "old", at: "x" } })); assert.equal(r.status, 0); const after = JSON.parse(readFileSync(path.join(dir, "diarization.json"), "utf8")); assert.equal("voiceprintsRefused" in after, false); assert.equal(after.voiceprints.length, 2); }));