import { test } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import path from "node:path"; import os from "node:os"; import { chmod, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { diarizeOneVideo, voiceprintOneVideo } from "./diarizeOne"; import { defaultSiteSettings } from "../lib/settings"; import type { Paths } from "../lib/paths"; import { hasVoiceprints, type DiarizationRecord } from "../lib/diarization"; import { loadDiarization } from "../lib/diarization-server"; import { loadAudioIntegrity } from "../lib/audioIntegrity-server"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/diarizeOne.test.ts // // The engine is a fake DIARIZE_BIN: it logs its argv, and in --voiceprints-only // mode adds a voiceprint per speaker to the record it is given -- or exits 4 // (diarize-sherpa.py's "ffmpeg failed") when FAKE_EXIT says so. const hasFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0; const FAKE = `#!/usr/bin/env node const fs = require("node:fs"); const argv = process.argv.slice(2); fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify(argv) + "\\n"); if (process.env.FAKE_STDERR) process.stderr.write(process.env.FAKE_STDERR + "\\n"); if (process.env.FAKE_EXIT) process.exit(Number(process.env.FAKE_EXIT)); const at = (f) => argv[argv.indexOf(f) + 1]; const rec = JSON.parse(fs.readFileSync(at("--voiceprints-only"), "utf8")); const speakers = [...new Set(rec.turns.map((t) => t.speaker))]; rec.voiceprints = speakers.map((s) => ({ speaker: s, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" })); rec.voiceprintsAt = "2026-11-11T00:00:00.000Z"; fs.writeFileSync(at("--output"), JSON.stringify(rec) + "\\n"); `; const EXISTING: DiarizationRecord = { videoId: "vid1", generatedAt: "2026-08-07T00:00:00.000Z", speakers: 2, turns: [ { start: 0, end: 4, speaker: 0 }, { start: 4, end: 9, speaker: 1 }, ], engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, }; async function setup(opts: { audio?: string | null } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "diarize-one-")); const bin = path.join(root, "fake-diarize.cjs"); await writeFile(bin, FAKE); await chmod(bin, 0o755); const log = path.join(root, "calls.log"); await writeFile(log, ""); const videoDir = path.join(root, "vid1"); await mkdir(videoDir); await writeFile(path.join(videoDir, "diarization.json"), JSON.stringify(EXISTING) + "\n"); if (opts.audio !== null) await writeFile(path.join(videoDir, "audio.mp3"), opts.audio ?? "not really mp3"); const paths = { diarizeBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths; const settings = { ...defaultSiteSettings().diarization, enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", threshold: 0.9, }; process.env.FAKE_LOG = log; const calls = async () => (await readFile(log, "utf8")).split("\n").filter(Boolean).map((l) => JSON.parse(l) as string[]); return { root, videoDir, paths, settings, calls, cleanup: () => rm(root, { recursive: true, force: true }) }; } test("a fresh sidecar without voiceprints gets them from its own turns — no re-diarization, generatedAt kept", async () => { const t = await setup(); try { const out = await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }); assert.equal(out, "diarized"); const calls = await t.calls(); assert.equal(calls.length, 1); assert.ok(calls[0].includes("--voiceprints-only"), "the voiceprint step, not a diarization"); assert.ok(!calls[0].includes("--seg")); const rec = await loadDiarization(t.videoDir); assert.equal(hasVoiceprints(rec), true); assert.equal(rec?.generatedAt, EXISTING.generatedAt); assert.deepEqual(rec?.turns, EXISTING.turns); // A second pass has nothing to do. assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists"); assert.equal((await t.calls()).length, 1); } finally { await t.cleanup(); } }); test("with the audio gone: no fingerprint is possible, and that is not a failure", async () => { const t = await setup({ audio: null }); try { assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio"); assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists"); assert.equal((await t.calls()).length, 0); assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false); } finally { await t.cleanup(); } }); test("a zero-byte audio is recorded as undecodable and skipped without running the engine", async () => { const t = await setup({ audio: "" }); try { assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable"); assert.equal((await t.calls()).length, 0); const rec = await loadAudioIntegrity(t.videoDir); assert.equal(rec?.verdict, "undecodable"); assert.equal(rec?.by, "speakers"); assert.equal(rec?.size, 0); } finally { await t.cleanup(); } }); test("an engine that cannot decode the audio (exit 4): recorded as undecodable, the sidecar untouched", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => { const t = await setup({ audio: "garbage, not audio" }); process.env.FAKE_EXIT = "4"; try { const before = await readFile(path.join(t.videoDir, "diarization.json"), "utf8"); assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable"); assert.equal(await readFile(path.join(t.videoDir, "diarization.json"), "utf8"), before); assert.equal((await loadAudioIntegrity(t.videoDir))?.verdict, "undecodable"); } finally { delete process.env.FAKE_EXIT; await t.cleanup(); } }); test("an engine failure for any other reason is a plain failure, and no verdict is written", async () => { const t = await setup(); process.env.FAKE_EXIT = "1"; try { assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "failed"); // diarizeOne keeps the diarization: the sidecar is fine, only without voiceprints. assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists"); assert.equal(await loadAudioIntegrity(t.videoDir), null); } finally { delete process.env.FAKE_EXIT; await t.cleanup(); } }); test("the voiceprint step never falls back to a source container: with no audio, no fingerprint is possible", async () => { const t = await setup({ audio: null }); try { await writeFile(path.join(t.videoDir, "source-media.mp4"), "a container of the same recording"); assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio"); assert.equal((await t.calls()).length, 0, "the engine is never given the container"); assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false); } finally { await t.cleanup(); } }); test("an exit-6 refusal is recorded against the file (voiceprintsRefused), turns and generatedAt kept, no voiceprints", async () => { const t = await setup(); process.env.FAKE_EXIT = "6"; process.env.FAKE_STDERR = "diarize-sherpa: refused: the file is 99.000s, the record's audio 10s — not the audio these turns were made from"; try { const logs: string[] = []; assert.equal( await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: (m) => logs.push(m) }), "refused", ); const rec = await loadDiarization(t.videoDir); assert.equal(rec?.generatedAt, EXISTING.generatedAt); assert.deepEqual(rec?.turns, EXISTING.turns); assert.equal(hasVoiceprints(rec), false); assert.equal(rec?.voiceprintsRefused?.file, "audio.mp3"); assert.equal(rec?.voiceprintsRefused?.size, "not really mp3".length); assert.match(rec?.voiceprintsRefused?.reason ?? "", /^the file is 99\.000s/); assert.ok(logs.some((l) => l.includes("no fingerprint possible from this file: the file is 99.000s"))); // Not an integrity verdict: the audio decodes, it is just not these turns'. assert.equal(await loadAudioIntegrity(t.videoDir), null); } finally { delete process.env.FAKE_EXIT; delete process.env.FAKE_STDERR; await t.cleanup(); } });