import assert from "node:assert/strict"; import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { DEFAULT_THRESHOLDS, REFERENCE_SECONDS, SAMPLE_RATE, decodeWav16, embedWavs, encodeWav16, labelFor, pickReferenceRecordings, readVoiceMatch, resolveEngine, robustCentroid, runVoiceMatch, scoreAgainst, soloRecordingWhy, voiceMatchKey, voicedSamples, writeVoiceMatch, cosine, } from "./voiceMatch.mjs"; import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "../../testing/audio/syntheticVoice.mjs"; import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FAKE = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs"); const FAKE_ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx", threads: 1 }; const tmp = () => mkdtempSync(path.join(os.tmpdir(), "voice-match-")); test("voiceMatchKey: the source moment to two decimals, the shape montage-rulings.json uses", () => { assert.equal(voiceMatchKey("the-chan", "abc123", 3127.5), "the-chan/abc123@3127.50"); assert.equal(voiceMatchKey("c", "v", 2.909), "c/v@2.91"); }); test("labelFor: likely at or over the bar, unlikely under the floor, unsure between", () => { const t = { likely: 0.42, unlikely: 0.3 }; assert.equal(labelFor(0.42, t), "likely"); assert.equal(labelFor(0.419, t), "unsure"); assert.equal(labelFor(0.3, t), "unsure"); assert.equal(labelFor(0.299, t), "unlikely"); assert.equal(labelFor(null, t), null); assert.deepEqual({ ...DEFAULT_THRESHOLDS }, t); }); test("voicedSamples: the voiced-frames gate keeps the phrase and ignores trailing silence and a low hiss", () => { const voice = syntheticVoice({ ...VOICE_A, seconds: 1.2 }); const padded = withSilence(voice, { before: 0.3, after: 2 }); // A hiss 60 dB under the voice where the silence was: still not voice. let seed = 7; for (let i = 0; i < padded.length; i += 1) { seed = (seed * 1103515245 + 12345) % 2147483648; padded[i] += ((seed / 2147483648) * 2 - 1) * 0.0003; } const v = voicedSamples(padded); assert.ok(v.seconds > 0.8 && v.seconds <= 1.25, `voiced ${v.seconds}s of a 1.2 s phrase`); const lastFrame = v.runs[v.runs.length - 1][1]; assert.ok(lastFrame * 0.02 <= 0.3 + 1.2 + 0.05, "nothing after the phrase is kept"); // Digital silence alone is no speech at all. assert.equal(voicedSamples(new Float32Array(SAMPLE_RATE * 2)).seconds, 0); }); test("encodeWav16 / decodeWav16 round-trip to 16-bit precision", () => { const x = syntheticVoice({ ...VOICE_B, seconds: 0.25 }); const back = decodeWav16(encodeWav16(x)); assert.equal(back.rate, SAMPLE_RATE); assert.equal(back.samples.length, x.length); for (let i = 0; i < x.length; i += 97) assert.ok(Math.abs(back.samples[i] - x[i]) < 1e-4); }); test("robustCentroid drops the item far from the rest; scoreAgainst leaves the clip's own reference item out", () => { const near = (k: number) => [1, 0.1 * k, 0, 0]; const vecs = [near(0), near(1), near(2), near(3), [0, 0, 1, 0]]; const r = robustCentroid(vecs); assert.deepEqual(r.dropped, [4]); assert.equal(r.kept.length, 4); const ref = r.kept.map((i) => ({ key: `k${i}`, vector: vecs[i] })); const self = scoreAgainst(vecs[0], ref, { selfKey: "k0" }); const withSelf = scoreAgainst(vecs[0], ref); assert.ok(self.score! < withSelf.score!, "leave-one-out scores lower than scoring against itself"); assert.ok(self.best! < 1); assert.equal(scoreAgainst([0, 0, 1, 0], ref).score, 0, "a voice opposite the reference clamps to 0"); }); test("soloRecordingWhy: captions, no >>, an upload, no second voice in the title, long enough", () => { const ok = { source: "vtt", isLivestream: false, title: "Some Headline About Things", duration: 600, cues: [{ text: "hello there" }] }; assert.equal(soloRecordingWhy(ok), null); assert.equal(soloRecordingWhy({ ...ok, source: "whisper" }), "not captions"); assert.equal(soloRecordingWhy({ ...ok, isLivestream: true }), "a livestream"); assert.equal(soloRecordingWhy({ ...ok, title: "A Chat With Somebody" }), "a second voice in the title"); assert.equal(soloRecordingWhy({ ...ok, title: "Big Interview" }), "a second voice in the title"); assert.equal(soloRecordingWhy({ ...ok, title: "Kotaku & Vice Collude" }), null, "an ampersand joins two subjects, not two voices"); assert.equal(soloRecordingWhy({ ...ok, duration: REFERENCE_SECONDS }), "too short"); assert.equal(soloRecordingWhy({ ...ok, cues: [{ text: "so" }, { text: ">> and you" }] }), "a speaker change in the captions"); assert.equal(soloRecordingWhy(null), "no transcript"); }); test("pickReferenceRecordings spreads over the dates, oldest first, deterministically", () => { const c = Array.from({ length: 20 }, (_, i) => ({ videoId: `v${String(i).padStart(2, "0")}`, date: `20${String(10 + i).padStart(2, "0")}0101` })); const shuffled = [...c].reverse(); const a = pickReferenceRecordings(shuffled, 5); assert.deepEqual(a.map((x) => x.videoId), ["v00", "v05", "v10", "v14", "v19"]); assert.deepEqual(pickReferenceRecordings(c, 5), a); assert.equal(pickReferenceRecordings(c.slice(0, 3), 8).length, 3); }); test("resolveEngine: explicit, then env, then the diarization lane's settings, then .diarize/", () => { const repoRoot = "/repo"; const base = resolveEngine({ repoRoot, env: {} }); assert.equal(base.python, "/repo/.diarize/env/bin/python"); assert.equal(base.model, "/repo/.diarize/models/titanet.onnx"); assert.equal(base.script, "/repo/scripts/speaker-embed.py"); const fromSettings = resolveEngine({ repoRoot, env: {}, settings: { diarization: { python: "/v/py", embModel: "/m/t.onnx" } } }); assert.deepEqual([fromSettings.python, fromSettings.model], ["/v/py", "/m/t.onnx"]); const fromEnv = resolveEngine({ repoRoot, env: { VOICE_MATCH_PYTHON: "node", VOICE_MATCH_SCRIPT: "/f.mjs" }, settings: { diarization: { python: "/v/py" } } }); assert.deepEqual([fromEnv.python, fromEnv.script], ["node", "/f.mjs"]); }); // ---- the whole run, through ffmpeg and the fake embedder -------------------------- function writeVoiceWav(dir: string, name: string, x: Float32Array) { const f = path.join(dir, name); writeFileSync(f, encodeWav16(x)); return f; } test("runVoiceMatch: two synthetic voices separate; the score is the same for the same input; a silent span is unscored", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { const dir = tmp(); try { // The "host": four reference pieces and two clips, each a different take. const ref = [0.4, 1.1, 2.2, 3.3].map((ph, i) => writeVoiceWav(dir, `ref${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 3, phase: ph }))); const hostClip = writeVoiceWav(dir, "host.wav", withSilence(syntheticVoice({ ...VOICE_A, seconds: 2, phase: 4.4 }), { after: 3 })); const guestClip = writeVoiceWav(dir, "guest.wav", syntheticVoice({ ...VOICE_B, seconds: 2.5, phase: 0.9 })); const silent = writeVoiceWav(dir, "silent.wav", new Float32Array(SAMPLE_RATE * 3)); // Its phrase span is silent; its cut (the fallback) is not. const late = writeVoiceWav(dir, "late.wav", withSilence(syntheticVoice({ ...VOICE_A, seconds: 2, phase: 5.1 }), { before: 3 })); const clips = [ { key: "c/host@1.00", id: "s01", file: hostClip, start: 0, dur: 5 }, { key: "c/guest@2.00", id: "s02", file: guestClip, start: 0, dur: 2.5 }, { key: "c/silent@3.00", id: "s03", file: silent, start: 0, dur: 3 }, { key: "c/late@4.00", id: "s04", file: late, start: 0, dur: 2.5, fallback: { start: 0, dur: 5 } }, { key: "c/gone@5.00", id: "s05", file: null, start: 0, dur: 0, missing: "no local window" }, ]; const reference = { kind: "recordings" as const, items: ref.map((file, i) => ({ key: `c/ref#${i}`, slug: "c", video: "ref", file, start: 0, dur: 3 })), }; const now = () => new Date("2026-10-18T00:00:00Z"); const run = () => runVoiceMatch({ clips, reference, engine: FAKE_ENGINE, scratch: path.join(dir, "scratch"), now }); const doc = await run(); const host = doc.clips["c/host@1.00"]; const guest = doc.clips["c/guest@2.00"]; assert.equal(host.label, "likely"); assert.equal(guest.label, "unlikely"); assert.ok(host.score! - guest.score! > 0.5, `host ${host.score} vs guest ${guest.score}`); assert.ok(host.speechSeconds <= 2.05, "the trailing silence is not speech"); assert.equal(doc.clips["c/silent@3.00"].score, null); assert.equal(doc.clips["c/silent@3.00"].why, "too little speech"); assert.equal(doc.clips["c/late@4.00"].fallback, true); assert.equal(doc.clips["c/late@4.00"].label, "likely"); assert.equal(doc.clips["c/gone@5.00"].why, "no local window"); assert.equal(doc.reference.kind, "recordings"); assert.deepEqual(doc.counts, { clips: 5, scored: 3, likely: 2, unsure: 0, unlikely: 1 }); // Deterministic: the same input is the same document. assert.deepEqual(await run(), doc); // And the file round-trips. await writeVoiceMatch(dir, doc); assert.deepEqual(await readVoiceMatch(dir), doc); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("runVoiceMatch: a rulings reference scores each kept clip against the OTHER keeps", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { const dir = tmp(); try { const takes = [0.2, 1.4, 2.6, 3.8].map((ph, i) => writeVoiceWav(dir, `k${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: ph }))); const guest = writeVoiceWav(dir, "g.wav", syntheticVoice({ ...VOICE_B, seconds: 2.5 })); const clips = [...takes.map((file, i) => ({ key: `c/v${i}@1.00`, id: `s0${i}`, file, start: 0, dur: 2.5 })), { key: "c/g@1.00", id: "s09", file: guest, start: 0, dur: 2.5 }]; const doc = await runVoiceMatch({ clips, reference: { kind: "rulings", keys: ["c/v0@1.00", "c/v1@1.00", "c/v2@1.00"] }, engine: FAKE_ENGINE, scratch: path.join(dir, "scratch"), }); assert.equal(doc.reference.kind, "rulings"); assert.equal(doc.clips["c/v0@1.00"].inReference, true); assert.ok(doc.clips["c/v0@1.00"].score! < 1, "not scored against itself"); assert.equal(doc.clips["c/v3@1.00"].label, "likely"); assert.equal(doc.clips["c/g@1.00"].label, "unlikely"); } finally { rmSync(dir, { recursive: true, force: true }); } }); // ---- the real model, when this machine has it --------------------------------------- // // VOICE_MATCH_PYTHON + VOICE_MATCH_MODEL (the diarization lane's venv and // TitaNet file). Skipped elsewhere: CI and a fresh clone have neither. const REAL = (() => { const python = process.env.VOICE_MATCH_PYTHON; const model = process.env.VOICE_MATCH_MODEL; if (!python || !model || !existsSync(python) || !existsSync(model)) return null; return { python, model, script: path.join(HERE, "..", "..", "..", "scripts", "speaker-embed.py"), threads: 1 }; })(); test("speaker-embed.py (TitaNet-small): two synthetic voices separate, and one input embeds to the same numbers twice", { skip: !REAL && "set VOICE_MATCH_PYTHON and VOICE_MATCH_MODEL to run it" }, async () => { const dir = tmp(); try { const items = [ ["a1", VOICE_A, 0.3], ["a2", VOICE_A, 2.1], ["b1", VOICE_B, 0.3], ["b2", VOICE_B, 2.1], ].map(([id, v, ph]) => ({ id: id as string, wav: writeVoiceWav(dir, `${id}.wav`, syntheticVoice({ ...(v as typeof VOICE_A), seconds: 3, phase: ph as number })) })); const r1 = await embedWavs(items, REAL!, path.join(dir, "s1")); const r2 = await embedWavs(items, REAL!, path.join(dir, "s2")); const e = (id: string) => r1.items.get(id)!.embedding!; assert.equal(r1.dim, 192); assert.deepEqual(r2.items.get("a1")!.embedding, e("a1")); const within = Math.min(cosine(e("a1"), e("a2")), cosine(e("b1"), e("b2"))); const across = Math.max(cosine(e("a1"), e("b1")), cosine(e("a2"), e("b2"))); assert.ok(within - across > 0.2, `within ${within.toFixed(3)} vs across ${across.toFixed(3)}`); } finally { rmSync(dir, { recursive: true, force: true }); } });