commit 250435e9bd20d4f756145560850db1188edd3a6c
parent 000f00623ac2b091372b068270c3190f54f0d295
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 02:58:37 -0500
diarization (review B3): a fingerprint is recorded as complete only when it is real -- hasVoiceprints needs, for every speaker with a turn >= 0.5 s, a centroid of exactly 192 finite numbers by the record's embedding model (null only for a speaker with no turn that long; zero turns is never complete); voiceprints-only refuses (exit 6, nothing written) audio whose duration is not the record's or whose excerpts come back short, and a long-turned speaker with no embedding; voiceprints are cut only from the video's own audio and record voiceprintsFrom {file, bytes, durationSeconds}
(a) common/lib/diarization.ts: hasVoiceprints strict as above;
voiceprintsPossible (no turn long enough = "no fingerprint possible": the
operation reports it present, the snapshot counts it, the cleanup gate
keeps the audio).
(b) scripts/diarize-sherpa.py --voiceprints-only: the probed duration must be
within 1 s of the record's audioSeconds (a record without one is refused);
an excerpt with under 90% of its samples (cut past the end of a truncated
or different file) refuses; a speaker whose turns are long enough and who
still gets no centroid refuses. Exit 6, so diarizeOne does not mistake it
for undecodable audio (4/5).
(c) voiceprintOneVideo takes only pickPreferredAudio over the real audio
files -- never resolveDiarizableMedia's container / saved-video fallback,
whose clock can differ (Rumble: up to 13 s) -- and a video with only those
is "no-audio": no fingerprint possible. The diarization operation is
`partial` only while real audio is there. diarize.mjs records
voiceprintsFrom in both modes.
Tests: hasVoiceprints (all-null from decodable audio, 2-float centroid, NaN,
other model, missing model, short-turn null allowed, zero turns / no long
turn not complete); the script on the stub: duration 85 s off and absent
refused, 0.6 s off accepted, a turn past the end refused, an embedder that
never becomes ready refused (and the full run records nulls); the container
fallback refused in diarizeOne. Every fixture centroid is now 192 floats.
On the real engine (a copy of v6z1o2g): 13 of 13 real centroids,
voiceprintsFrom {audio.mp3, 9912981, 766.101}, hasVoiceprints true.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
15 files changed, 296 insertions(+), 62 deletions(-)
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -27,7 +27,7 @@ import { isTierable } from "../lib/mediaTier";
import { isDriveNotAnswering, onDrive } from "../lib/storageHealth";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
import { getSettings } from "../lib/settings";
-import { hasVoiceprints } from "../lib/diarization";
+import { hasVoiceprints, voiceprintsPossible } from "../lib/diarization";
import { loadDiarization } from "../lib/diarization-server";
import {
loadAvailability,
@@ -1411,7 +1411,9 @@ export async function generateChannelSnapshot(
const diarVoiceprinted = hasVoiceprints(diarRecord);
if (diarRecord) {
if (diarVoiceprinted) speakers.voiceprinted++;
- else if (files.audioFiles.length === 0) speakers.noFingerprintPossible++;
+ else if (files.audioFiles.length === 0 || !voiceprintsPossible(diarRecord)) {
+ speakers.noFingerprintPossible++;
+ }
// The engine's own clock, for the readout's rate: wall time over the
// audio it was given.
if ((diarRecord.durationMs ?? 0) > 0 && (diarRecord.audioSeconds ?? 0) > 0) {
diff --git a/common/controller/cleanAfterCapture.test.ts b/common/controller/cleanAfterCapture.test.ts
@@ -40,7 +40,7 @@ async function settings(diarization: Record<string, unknown>, over: Record<strin
);
}
-const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: [0.6, 0.8], embeddingModel: "emb.onnx" }];
+const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }];
function sidecar(voiceprints: boolean): string {
return JSON.stringify({
diff --git a/common/controller/diarizeOne.test.ts b/common/controller/diarizeOne.test.ts
@@ -28,7 +28,7 @@ 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: [1, 0], embeddingModel: "emb.onnx" }));
+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");
`;
@@ -143,3 +143,15 @@ test("an engine failure for any other reason is a plain failure, and no verdict
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();
+ }
+});
diff --git a/common/controller/diarizeOne.ts b/common/controller/diarizeOne.ts
@@ -250,7 +250,13 @@ export async function voiceprintOneVideo(
const existing = await loadDiarization(opts.videoDir);
if (!existing) return "no-diarization";
if (hasVoiceprints(existing)) return "already-present";
- const media = await resolveDiarizableMedia(opts.videoDir);
+ // THE VIDEO'S OWN AUDIO, NEVER resolveDiarizableMedia's fallback (review B3).
+ // Turns made from audio.<ext> are seconds on that file's clock; a source
+ // container or a saved video of the same recording can run seconds apart
+ // (Rumble: measured up to 13 s), and centroids cut from it would be other
+ // stretches — other voices. Without the audio, no fingerprint is possible.
+ const entries = await readdir(opts.videoDir).catch(() => [] as string[]);
+ const media = pickPreferredAudio(entries.filter(isRealAudioFile));
if (!media) return "no-audio";
if (await isZeroByteAudio(opts.videoDir, media)) {
await recordUnreadableAudio(opts, media, log);
diff --git a/common/lib/diarization.test.ts b/common/lib/diarization.test.ts
@@ -10,7 +10,9 @@ import {
diarizationTarget,
hasVoiceprints,
isDiarizationFresh,
+ VOICEPRINT_DIM,
voiceprintCount,
+ voiceprintsPossible,
type DiarizationRecord,
} from "./diarization";
import {
@@ -131,46 +133,65 @@ test("speech seconds sums turns, and overlapping turns are not clamped", () => {
// ---- voiceprints ------------------------------------------------------------
-const vp = (speaker: number, centroid: number[] | null = [0.6, 0.8]) => ({
+const REAL = Array.from({ length: VOICEPRINT_DIM }, (_, i) => (i === 0 ? 1 : 0));
+const vp = (speaker: number, centroid: number[] | null = REAL, embeddingModel = "titanet.onnx") => ({
speaker,
seconds: 4,
embedded: centroid ? 2 : 0,
centroid,
- embeddingModel: "titanet.onnx",
+ embeddingModel,
});
+const withModel = (over: Partial<DiarizationRecord>) =>
+ record({ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 }, ...over });
-test("hasVoiceprints: complete only when every speaker in the turns has a well-formed entry", () => {
+test("hasVoiceprints: every embeddable speaker has a REAL centroid (192 finite numbers, the record's model)", () => {
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(withModel({ voiceprints: [vp(0)] })), false, "speaker 1 is missing");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1)] })), true);
+ // Both speakers have turns of 4 s and 6 s: a null is a fingerprint not made.
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, null)] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0, null), vp(1, null)] })), false, "all null, from audio that decoded");
+ assert.equal(voiceprintCount(withModel({ voiceprints: [vp(0), vp(1, null)] })), 1);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, [0.6, 0.8])] })), false, "not 192 floats");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL.map((x, i) => (i === 5 ? Number.NaN : x)))] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL, "other.onnx")] })), false, "another embedding model");
assert.equal(
- hasVoiceprints(record({ voiceprints: [vp(0), { speaker: 1, seconds: 1, centroid: [1] } as never] })),
+ hasVoiceprints(withModel({ voiceprints: [vp(0), { speaker: 1, seconds: 1, centroid: REAL } as never] })),
false,
"no embeddingModel",
);
- assert.equal(hasVoiceprints(record({ turns: [], speakers: 0, voiceprints: [] })), true);
+ // A null IS allowed for a speaker with no turn long enough to embed.
+ const blip = withModel({
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 4.3, speaker: 1 },
+ ],
+ voiceprints: [vp(0), vp(1, null)],
+ });
+ assert.equal(hasVoiceprints(blip), true);
+ assert.equal(voiceprintsPossible(blip), true);
+ // Zero turns, or none long enough: nothing was fingerprinted — not complete.
+ assert.equal(hasVoiceprints(withModel({ turns: [], speakers: 0, voiceprints: [] })), false);
+ const short = withModel({ turns: [{ start: 0, end: 0.3, speaker: 0 }], voiceprints: [vp(0, null)] });
+ assert.equal(hasVoiceprints(short), false);
+ assert.equal(voiceprintsPossible(short), false);
});
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);
+ assert.equal(isDiarizationFresh(record({ engine, voiceprints: [vp(0, REAL, "titanet.onnx"), 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)] }));
+ await writeDiarization(dir, withModel({ 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]);
+ assert.deepEqual(loaded?.voiceprints?.[0].centroid, REAL);
} finally {
await rm(dir, { recursive: true, force: true });
}
diff --git a/common/lib/diarization.ts b/common/lib/diarization.ts
@@ -95,6 +95,10 @@ export type DiarizationRecord = {
// for a sidecar that was written with them; later for one that got them from
// the voiceprint step.
voiceprintsAt?: string;
+ // The file the fingerprints were cut from (basename, size, duration). The
+ // voiceprint step only ever uses the video's own extracted audio — never a
+ // source container or a saved video, whose clock can differ (review B3).
+ voiceprintsFrom?: { file: string; bytes?: number; durationSeconds?: number };
};
// A speaker cluster's voice fingerprint. `centroid` is the L2-normalised mean
@@ -115,42 +119,72 @@ export type DiarizationVoiceprint = {
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;
+// The shortest turn the embedder is given (scripts/diarize-sherpa.py
+// EMB_MIN_SEC). A speaker with a turn at least this long CAN be fingerprinted,
+// so a null centroid for one is a fingerprint that was not made.
+export const VOICEPRINT_MIN_SPAN_SEC = 0.5;
+
+function isRealCentroid(c: unknown): c is number[] {
return (
- Array.isArray(p.centroid) &&
- p.centroid.length > 0 &&
- p.centroid.every((x) => typeof x === "number" && Number.isFinite(x))
+ Array.isArray(c) &&
+ c.length === VOICEPRINT_DIM &&
+ c.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.
+// Speakers with at least one turn long enough to embed.
+function embeddableSpeakers(record: Pick<DiarizationRecord, "turns">): Set<number> {
+ const out = new Set<number>();
+ for (const t of record.turns ?? []) {
+ if (t.end - t.start >= VOICEPRINT_MIN_SPAN_SEC) out.add(t.speaker);
+ }
+ return out;
+}
+
+// Could this record's turns be fingerprinted at all? False for a record with no
+// turns, or none long enough to embed — "no fingerprint possible" from these
+// turns, which nothing the lane does will change.
+export function voiceprintsPossible(record: Pick<DiarizationRecord, "turns"> | null): boolean {
+ return !!record && embeddableSpeakers(record).size > 0;
+}
+
+// Has this record's voice capture REALLY been done (review B3)? True only when
+// every speaker its turns name has an entry, and every speaker with a turn of at
+// least VOICEPRINT_MIN_SPAN_SEC has a centroid of exactly VOICEPRINT_DIM finite
+// numbers made by the record's embedding model (null is allowed only for a
+// speaker with no turn that long). A record with no turns, or no speaker long
+// enough to embed, is NOT complete: nothing was fingerprinted, and this is the
+// predicate the cleanup gate keys off — anything short of a real fingerprint
+// keeps the only audio one could still be made from.
export function hasVoiceprints(
- record: Pick<DiarizationRecord, "turns" | "voiceprints"> | null,
+ record: Pick<DiarizationRecord, "turns" | "voiceprints" | "engine"> | 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));
+ if (!(record.turns ?? []).length) return false;
+ const embeddable = embeddableSpeakers(record);
+ if (embeddable.size === 0) return false;
+ const model = record.engine?.embeddingModel;
+ const bySpeaker = new Map<number, DiarizationVoiceprint>();
+ for (const v of record.voiceprints) {
+ if (!v || typeof v !== "object" || !Number.isInteger(v.speaker)) return false;
+ if (typeof v.embeddingModel !== "string" || !v.embeddingModel) return false;
+ if (model && v.embeddingModel !== model) return false;
+ bySpeaker.set(v.speaker, v);
+ }
+ for (const t of record.turns) if (!bySpeaker.has(t.speaker)) return false;
+ for (const [speaker, v] of bySpeaker) {
+ if (embeddable.has(speaker) ? !isRealCentroid(v.centroid) : v.centroid !== null && !isRealCentroid(v.centroid)) {
+ return false;
+ }
+ }
+ return true;
}
// 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;
+ return (record?.voiceprints ?? []).filter((v) => isRealCentroid(v?.centroid)).length;
}
export const DIARIZATION_FILENAME = "diarization.json";
diff --git a/common/lib/operations.test.ts b/common/lib/operations.test.ts
@@ -184,7 +184,7 @@ function sidecar(
...(voiceprints
? {
voiceprints: [
- { speaker: 0, seconds: 4, embedded: 1, centroid: [0.6, 0.8], embeddingModel: "emb-1.onnx" },
+ { speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb-1.onnx" },
],
}
: {}),
@@ -234,10 +234,12 @@ test("partial: fresh turns without voice fingerprints, while the audio is still
await classify({ audio: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
"partial",
);
- // A persisted container is input enough for the voiceprint step too.
+ // A persisted container is NOT: the voiceprint step cuts only the video's
+ // own audio (another file of the recording runs on another clock, review
+ // B3), so with only a container there is no fingerprint to be had.
assert.equal(
await classify({ container: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
- "partial",
+ "present",
);
});
diff --git a/common/lib/operations.ts b/common/lib/operations.ts
@@ -108,6 +108,7 @@ import {
diarizationTarget,
hasVoiceprints,
isDiarizationFresh,
+ voiceprintsPossible,
type DiarizationBackend,
type DiarizationEngineId,
type DiarizationFreshnessTarget,
@@ -708,15 +709,20 @@ const diarization: Operation = {
if (!isDiarizationFresh(record, target as DiarizationFreshnessTarget)) {
return "stale";
}
- if (hasVoiceprints(record) || !settings.diarization.embModel) {
+ if (
+ hasVoiceprints(record) ||
+ !voiceprintsPossible(record) ||
+ !settings.diarization.embModel
+ ) {
return "present";
}
- // Fresh turns WITHOUT voice fingerprints: PARTIAL while the audio is
- // still here (diarizeOneVideo's voiceprint step adds them from the same
- // turns, seconds of work), present once it is gone — no fingerprint is
- // possible then, which the speakers readout lists, and nothing this
- // lane can do about it.
- return (await hasDiarizableInput(videoDir, files)) &&
+ // Fresh turns WITHOUT voice fingerprints: PARTIAL while the video's own
+ // AUDIO is still here (diarizeOneVideo's voiceprint step adds them from
+ // the same turns, seconds of work — and only from that audio, never a
+ // container or a saved video, review B3); present once it is gone — no
+ // fingerprint is possible then, which the speakers readout lists, and
+ // nothing this lane can do about it.
+ return files.audioFiles.length > 0 &&
!(await heldAudioUndecodable(videoDir, files))
? "partial"
: "present";
diff --git a/editor/e2e/cleanup-holds.spec.ts b/editor/e2e/cleanup-holds.spec.ts
@@ -98,7 +98,7 @@ test("the sieve attributes every held byte to exactly one gate, and names the ho
speakers: 1,
turns: [{ start: 0, end: 1, speaker: 0 }],
engine: { engine: "test" },
- voiceprints: [{ speaker: 0, seconds: 1, embedded: 1, centroid: [1, 0], embeddingModel: "t" }],
+ voiceprints: [{ speaker: 0, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "t" }],
}),
);
await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
diff --git a/editor/e2e/diarization.spec.ts b/editor/e2e/diarization.spec.ts
@@ -52,7 +52,7 @@ async function seedDiarization(
...(voiceprints
? {
voiceprints: [
- { speaker: 0, seconds: 10, embedded: 1, centroid: [1, 0], embeddingModel: "null" },
+ { speaker: 0, seconds: 10, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "null" },
],
}
: {}),
diff --git a/editor/e2e/fixtures/bin/fake-diarize.mjs b/editor/e2e/fixtures/bin/fake-diarize.mjs
@@ -65,7 +65,7 @@ const voiceprintsFor = (turns) =>
speaker,
seconds: turns.filter((t) => t.speaker === speaker).reduce((s, t) => s + (t.end - t.start), 0),
embedded: 1,
- centroid: [speaker === 0 ? 1 : 0, speaker === 0 ? 0 : 1],
+ centroid: Array.from({ length: 192 }, (_, i) => (i === speaker ? 1 : 0)),
embeddingModel: emb ? path.basename(emb) : "fake.onnx",
}));
diff --git a/scripts/diarize-sherpa.py b/scripts/diarize-sherpa.py
@@ -304,22 +304,45 @@ def voiceprint_records(turns, vectors):
return out
-def voiceprints_from_samples(np, extractor, samples, sample_rate, turns):
+class VoiceprintRefused(Exception):
+ """The audio does not match the turns it is asked to fingerprint (exit 6):
+ nothing is written, so a fingerprint is never recorded from the wrong
+ stretches of a recording."""
+
+
+# An excerpt that comes back with less than this share of its samples was cut
+# from past the end of the file (or a truncated one): the turns were not made
+# from this audio.
+VP_MIN_FILL = 0.9
+
+
+def check_excerpt(x, a, b, sample_rate, strict):
+ if strict and x.size < VP_MIN_FILL * (b - a) * sample_rate:
+ raise VoiceprintRefused(
+ f"excerpt {a:.2f}-{b:.2f}s decoded {x.size / sample_rate:.2f}s of "
+ f"{b - a:.2f}s — the turns were not made from this file"
+ )
+
+
+def voiceprints_from_samples(np, extractor, samples, sample_rate, turns, strict=False):
"""Voiceprints for a recording whose samples are in memory (the whole-file
- path): each speaker's excerpts sliced out and embedded."""
+ path): each speaker's excerpts sliced out and embedded. `strict` (the
+ voiceprints-only mode) refuses a short excerpt."""
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])
+ x = samples[i:j] if j > i else samples[0:0]
+ check_excerpt(x, a, b, sample_rate, strict)
+ 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 voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns):
+def voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns, strict=True):
"""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."""
@@ -328,6 +351,7 @@ def voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns):
vecs = []
for a, b in spans:
x = decode_window(np, ffmpeg, audio, sample_rate, a, b - a)
+ check_excerpt(x, a, b, sample_rate, strict)
v = embed_samples(np, extractor, sample_rate, x)
if v is not None:
vecs.append(v)
@@ -534,6 +558,21 @@ def run_voiceprints_only(args):
# 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)
+ # THE SAME RECORDING, OR NOTHING (review B3). A record's turns are seconds on
+ # the clock of the file they were made from; another file of the same video
+ # (a re-download, a container, a truncated copy) can run seconds apart, and
+ # centroids cut from it would be other people's voices.
+ recorded = record.get("audioSeconds")
+ if total_sec is not None and (
+ not isinstance(recorded, (int, float)) or abs(total_sec - recorded) > 1.0
+ ):
+ print(
+ f"diarize-sherpa: refused: the file is {total_sec:.3f}s, the record's audio "
+ f"{recorded if recorded is not None else 'unknown'}s — not the audio these "
+ "turns were made from",
+ file=sys.stderr,
+ )
+ return 6
whole = (
total_sec is not None
and total_sec <= args.window_after_minutes * 60.0
@@ -545,7 +584,7 @@ def run_voiceprints_only(args):
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
+ np, extractor, samples, sample_rate, turns, strict=True
)
del samples
elif total_sec is None:
@@ -558,12 +597,28 @@ def run_voiceprints_only(args):
voiceprints = voiceprints_from_file(
np, extractor, args.ffmpeg, args.audio, sample_rate, turns
)
+ except VoiceprintRefused as e:
+ print(f"diarize-sherpa: refused: {e}", file=sys.stderr)
+ return 6
except RuntimeError as e:
print(f"diarize-sherpa: {e}", file=sys.stderr)
return 4
+ # A speaker with a turn long enough to embed MUST come out with a centroid:
+ # a null there is a fingerprint that was not made, and recording it as done
+ # would let the audio go.
+ spans = voiceprint_spans(turns)
+ missing = [v["speaker"] for v in voiceprints if v["centroid"] is None and spans.get(v["speaker"])]
+ if missing:
+ print(
+ f"diarize-sherpa: refused: no embedding for speaker(s) {missing} "
+ "although their turns are long enough",
+ file=sys.stderr,
+ )
+ return 6
print_voiceprint_line(voiceprints, time.time() - t0)
json.dump(
{"voiceprints": voiceprints,
+ "probedSeconds": round(total_sec, 3) if total_sec is not None else None,
"version": getattr(sherpa_onnx, "__version__", None)},
sys.stdout,
)
diff --git a/scripts/diarize-sherpa.test.mjs b/scripts/diarize-sherpa.test.mjs
@@ -128,6 +128,8 @@ test("diarize.mjs records the voiceprints with the embedding model's basename, o
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);
}));
@@ -141,6 +143,7 @@ test("--voiceprints-only adds voiceprints to an existing record from its own tur
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 },
@@ -159,6 +162,10 @@ test("--voiceprints-only adds voiceprints to an existing record from its own tur
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 }, () =>
@@ -211,3 +218,72 @@ test("the real engine (sherpa-onnx + TitaNet-small): two espeak voices, a 192-fl
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));
+ }));
+
diff --git a/scripts/diarize.mjs b/scripts/diarize.mjs
@@ -82,7 +82,7 @@
// See common/lib/diarization.ts, which says so in as many words.
import { spawn } from "node:child_process";
-import { readFile, rename, writeFile } from "node:fs/promises";
+import { readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const HELP = `diarize.mjs [options] <audioFile>
@@ -166,6 +166,17 @@ function recordVoiceprints(raw, embeddingModel) {
return out;
}
+// WHICH FILE the fingerprints were cut from: the cleanup gate and a later
+// voiceprint step can tell one recording's file from another's (review B3).
+async function voiceprintsFrom(file, durationSeconds) {
+ const bytes = await stat(file).then((st) => st.size, () => null);
+ return {
+ file: path.basename(file),
+ ...(bytes !== null ? { bytes } : {}),
+ ...(Number.isFinite(durationSeconds) ? { durationSeconds } : {}),
+ };
+}
+
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.
@@ -222,6 +233,7 @@ async function runVoiceprintsOnly() {
voiceprints,
voiceprintsAt: new Date().toISOString(),
voiceprintsMs: Date.now() - started,
+ voiceprintsFrom: await voiceprintsFrom(audio, raw?.probedSeconds),
};
const target = output ?? voiceprintsOnly;
await writeAtomic(target, JSON.stringify(record) + "\n");
@@ -371,6 +383,9 @@ child.on("close", async (code) => {
},
};
+ if (record.voiceprints) {
+ record.voiceprintsFrom = await voiceprintsFrom(audio, raw.audioSeconds);
+ }
const json = JSON.stringify(record) + "\n";
if (!output) {
process.stdout.write(json);
diff --git a/scripts/fixtures/sherpa-stub/sherpa_onnx.py b/scripts/fixtures/sherpa-stub/sherpa_onnx.py
@@ -96,6 +96,11 @@ class SpeakerEmbeddingExtractor:
return _Stream()
def is_ready(self, stream):
+ # STUB_NOT_READY: an embedder that never has enough (audio that decodes,
+ # and still no fingerprint).
+ import os
+ if os.environ.get("STUB_NOT_READY"):
+ return False
return stream.x.size >= int(0.5 * SR)
def compute(self, stream):