import assert from "node:assert/strict"; import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { cosine, encodeWav16 } from "../montage/voiceMatch.mjs"; import { analyze } from "./clips.mjs"; import { CED_DIR, centroidPieces, resolveTagger, runAudioScan, speakerCentroids, tagWavs, windowLevels } from "./scan.mjs"; import { HOST, SUBJECT, reactionAudio, reactionStream } from "../../testing/clips/reactionStream.mjs"; import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FAKE_TAG = path.join(HERE, "..", "..", "testing", "audio", "fakeAudioTag.mjs"); const FAKE_EMBED = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs"); const tmp = () => mkdtempSync(path.join(os.tmpdir(), "clip-scan-")); const ffmpeg = hasFfmpeg(); test("resolveTagger: env over settings over the repo's .diarize; available is whether the model is there", () => { const d = resolveTagger({ repoRoot: "/repo", env: {} }); assert.deepEqual(d, { python: "/repo/.diarize/env/bin/python", script: "/repo/scripts/audio-tag.py", model: `/repo/.diarize/models/${CED_DIR}/model.int8.onnx`, labels: `/repo/.diarize/models/${CED_DIR}/class_labels_indices.csv`, threads: 1, available: false, }); const s = resolveTagger({ repoRoot: "/repo", env: {}, settings: { diarization: { python: "/venv/python" } } }); assert.equal(s.python, "/venv/python"); const e = resolveTagger({ repoRoot: "/repo", env: { AUDIO_TAG_PYTHON: "node", AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } }); assert.deepEqual([e.python, e.script, e.available], ["node", FAKE_TAG, true]); assert.equal(e.labels, path.join(path.dirname(FAKE_TAG), "class_labels_indices.csv")); }); test("windowLevels: one level per window, loud where the sound is", () => { const x = new Float32Array(16000 * 4); for (let i = 16000 * 2; i < 16000 * 3; i += 1) x[i] = 0.5 * Math.sin(i / 3); const lv = windowLevels(x, { count: 7 }); assert.equal(lv.length, 7); assert.ok(lv[4] > -10 && lv[0] < -100, JSON.stringify(lv)); }); test("centroidPieces: the longest turns that overlap nobody (else the longest at all), the middle of each", () => { const turns = [ { start: 0, end: 10, speaker: 1 }, { start: 9, end: 12, speaker: 0 }, { start: 12, end: 13, speaker: 0 }, { start: 20, end: 40, speaker: 0 }, ]; assert.deepEqual(centroidPieces(turns, 0), [{ start: 26, dur: 8 }]); // Speaker 1's only turn overlaps speaker 0: with nothing clean, the longest at all. assert.deepEqual(centroidPieces(turns, 1), [{ start: 1, dur: 8 }]); const many = Array.from({ length: 30 }, (_, i) => ({ start: i * 10, end: i * 10 + 3 + (i % 3), speaker: 0 })); const picked = centroidPieces(many, 0, 4); // The four longest (5 s: i = 2, 5, 8, 11), in time order, each 0.2 s in from its ends. assert.deepEqual(picked.map((p) => p.start), [20.2, 50.2, 80.2, 110.2]); assert.ok(picked.every((p) => p.dur === 4.6)); }); test("tagWavs + runAudioScan (fake tagger): the laugh is heard where it is, energy everywhere, chunked", { skip: !ffmpeg && "no ffmpeg" }, async () => { const dir = tmp(); try { const wav = path.join(dir, "audio.wav"); writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 120 }))); const tagger = resolveTagger({ repoRoot: dir, env: { AUDIO_TAG_PYTHON: process.execPath, AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } }); const one = await tagWavs([{ id: "a", wav, window: 1, hop: 0.5 }], tagger, path.join(dir, "s")); assert.equal(one.items.get("a")?.scores?.length, 239); const events: Record[] = []; const scan = await runAudioScan({ file: wav, duration: 120, tagger, scratch: path.join(dir, "work"), chunkS: 30, perGroup: 2, onProgress: (e) => events.push(e) }); assert.equal(scan.windows, 239); assert.equal(scan.energy.length, 239); assert.ok(scan.laugh); const at = (t: number) => scan.laugh![Math.round(t / 0.5)]; assert.ok(at(95.5) >= 0.8, `laugh at 95.5: ${at(95.5)}`); assert.ok(at(60) < 0.1 && at(110) < 0.1); assert.equal(scan.model?.file, "fakeAudioTag.mjs"); assert.equal(events.filter((e) => e.event === "decode").length, 4); assert.equal(events.filter((e) => e.event === "tag").length, 2); assert.ok(!existsSync(path.join(dir, "work"))); // The same scan's laughs through the analysis: the host's laugh at 95. const s = reactionStream(); const turns = s.turns.filter((t) => t.start < 120); const a = analyze({ turns, duration: 120, words: s.words.filter((w) => w.end < 120), laughScan: { t0: 0, hop: 0.5, window: 1, scores: scan.laugh } }); assert.equal(a.laughSource, "model"); assert.equal(a.laughs.length, 1); assert.equal(a.laughs[0].speaker, HOST); assert.ok(Math.abs(a.laughs[0].start - 95) <= 1); // No tagger: energy only. const quiet = await runAudioScan({ file: wav, duration: 120, tagger: null, scratch: path.join(dir, "work2"), chunkS: 60 }); assert.equal(quiet.laugh, null); assert.equal(quiet.model, null); assert.deepEqual(quiet.energy, scan.energy); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("speakerCentroids (fake embedder): one centroid per cluster, the two voices apart", { skip: !ffmpeg && "no ffmpeg" }, async () => { const dir = tmp(); try { const wav = path.join(dir, "audio.wav"); writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 200 }))); const s = reactionStream(); const turns = s.turns.filter((t) => t.end <= 200); const engine = { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx", threads: 1 }; const v = await speakerCentroids({ file: wav, turns, engine, scratch: path.join(dir, "v") }); const h = v.speakers[HOST].centroid; const sub = v.speakers[SUBJECT].centroid; assert.ok(h && sub); assert.ok(v.speakers[HOST].pieces >= 2 && v.speakers[SUBJECT].pieces >= 2); assert.ok(cosine(h, sub) < 0.6, `cosine ${cosine(h, sub)}`); assert.ok(!existsSync(path.join(dir, "v"))); } finally { rmSync(dir, { recursive: true, force: true }); } });