// THE SPEAKER CHECK (UI notes 2026-10-30, #15): which of SEVERAL named voices // a clip is -- "Speaker: matches Ember 0.93 / Kirsche 0.83" -- where the voice // match (voiceMatch.mjs, release 34) scores every clip against ONE voice, the // host's. Panel shows (Side Scrollers, Kirsche) were attributed this way by // hand in scratch projects; this is the same arithmetic as a project's own // file. // // The pieces are voiceMatch.mjs's, unchanged: a span decoded at 16 kHz mono on // the window's own clock, the voiced-frames gate (a fallback span when the // phrase holds too little speech), ONE embedding process for every clip and // every reference piece (TitaNet-small through sherpa-onnx, or the test kit's // fake embedder), a robust centroid per voice, the cosine to it. Each named // reference set ("speaker") is clips of the cut, or reference pieces of // recordings; a clip that is itself in a speaker's set is scored against the // rest of that set (leave-one-out). Deterministic for a given model and input; // no network; nothing rules -- the verification is still a person listening. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_THRESHOLDS, FALLBACK_SPEECH_S, MIN_SPEECH_S, SAMPLE_RATE, VOICE_MATCH_MODEL, decodeSpan, embedWavs, encodeWav16, robustCentroid, scoreAgainst, voicedSamples, } from "./voiceMatch.mjs"; import { tmpPathFor } from "../atomicFile.mjs"; export const SPEAKER_CHECK_FILE = "speaker-check.json"; export const SPEAKER_CHECK_VERSION = 1; /** A best voice this far ahead of the next is a match; closer is unsure. */ export const SPEAKER_MARGIN = 0.05; const round = (x, n = 3) => Math.round(x * 10 ** n) / 10 ** n; /** * A clip's verdict from its scores (best first): `matches` (the best at or * over `likely` and SPEAKER_MARGIN ahead of the next), `none` (every voice * under `unlikely`: someone the reference sets do not hold), else `unsure`. * @param {{ name: string, score: number }[]} scores */ export function speakerVerdict(scores, t = DEFAULT_THRESHOLDS) { const [a, b] = scores; if (!a) return { label: /** @type {const} */ ("unsure"), best: null, margin: null }; const margin = b ? round(a.score - b.score) : null; if (a.score < t.unlikely) return { label: /** @type {const} */ ("none"), best: a.name, margin }; if (a.score >= t.likely && (margin === null || margin >= SPEAKER_MARGIN)) return { label: /** @type {const} */ ("matches"), best: a.name, margin }; return { label: /** @type {const} */ ("unsure"), best: a.name, margin }; } /** * Score `clips` against every named voice in `speakers`. * * @param {{ * clips: Array<{ key: string, id?: string | null, file: string | null, start: number, dur: number, fallback?: { start: number, dur: number } | null, missing?: string }>, * check?: string[], the keys to score (default every clip); the rest are only reference * speakers: Array<{ name: string, clipKeys?: string[], items?: Array<{ key: string, file: string, start: number, dur: number, label?: string }>, recordings?: unknown[] }>, * engine: { python: string, script: string, model: string, threads?: number }, * scratch: string, * thresholds?: { likely: number, unlikely: number }, * ffmpeg?: string, * now?: () => Date, * onProgress?: (e: { event: string, n?: number, of?: number, items?: number }) => void, * }} o */ export async function runSpeakerCheck(o) { const t = o.thresholds ?? DEFAULT_THRESHOLDS; const emit = o.onProgress ?? (() => {}); const scratch = o.scratch; await rm(scratch, { recursive: true, force: true }); await mkdir(scratch, { recursive: true }); const check = new Set(o.check ?? o.clips.map((c) => c.key)); const refClipKeys = new Set(o.speakers.flatMap((s) => s.clipKeys ?? [])); /** @type {Map} */ const prepared = new Map(); const voiced = async (file, start, dur) => voicedSamples(await decodeSpan(file, start, dur, { ffmpeg: o.ffmpeg })); const prepare = async (id, file, start, dur, fallback = null) => { let v; let usedFallback = false; try { v = await voiced(file, start, dur); if (fallback && v.seconds < FALLBACK_SPEECH_S) { const w = await voiced(file, fallback.start, fallback.dur); if (w.seconds > v.seconds) { v = w; usedFallback = true; } } } catch (e) { prepared.set(id, { seconds: 0, wav: null, why: `decode failed: ${e instanceof Error ? e.message : String(e)}` }); return; } if (v.seconds < MIN_SPEECH_S) { prepared.set(id, { seconds: v.seconds, wav: null, why: "too little speech", fallback: usedFallback }); return; } const wav = path.join(scratch, `${prepared.size.toString().padStart(4, "0")}.wav`); await writeFile(wav, encodeWav16(v.samples)); prepared.set(id, { seconds: v.seconds, wav, fallback: usedFallback }); }; const wanted = o.clips.filter((c) => check.has(c.key) || refClipKeys.has(c.key)); let k = 0; for (const c of wanted) { k += 1; if (c.file) await prepare(`clip:${c.key}`, c.file, c.start, c.dur, c.fallback ?? null); emit({ event: "decode", n: k, of: wanted.length }); } for (const s of o.speakers) for (const r of s.items ?? []) await prepare(`ref:${s.name}:${r.key}`, r.file, r.start, r.dur); const batch = [...prepared].filter(([, p]) => p.wav).map(([id, p]) => ({ id, wav: /** @type {string} */ (p.wav) })); emit({ event: "embed", items: batch.length }); const emb = batch.length ? await embedWavs(batch, o.engine, scratch) : { model: path.basename(o.engine.model), version: null, dim: 0, items: new Map() }; const vec = (id) => emb.items.get(id)?.embedding ?? null; // Each voice: its pieces, the outliers out. const voices = o.speakers.map((s) => { const all = [ ...(s.clipKeys ?? []).map((key) => ({ key: `clip:${key}`, clipKey: key, vector: vec(`clip:${key}`) })), ...(s.items ?? []).map((r) => ({ key: `ref:${s.name}:${r.key}`, clipKey: null, vector: vec(`ref:${s.name}:${r.key}`) })), ].filter((r) => r.vector); const robust = robustCentroid(all.map((r) => /** @type {number[]} */ (r.vector))); const kept = robust.kept.map((i) => all[i]); return { name: s.name, kept, doc: { name: s.name, clips: [...(s.clipKeys ?? [])], recordings: s.recordings ?? [], pieces: (s.clipKeys?.length ?? 0) + (s.items?.length ?? 0), embedded: all.length, kept: kept.length, dropped: robust.dropped.map((i) => all[i].clipKey ?? all[i].key.replace(/^ref:[^:]*:/, "")), }, }; }); /** @type {Record>} */ const clips = {}; for (const c of o.clips) { if (!check.has(c.key)) continue; const p = prepared.get(`clip:${c.key}`); const v = vec(`clip:${c.key}`); /** @type {Record} */ const row = { speechSeconds: round(p?.seconds ?? 0, 2), scores: [] }; if (c.id) row.id = c.id; if (p?.fallback) row.fallback = true; if (!c.file) row.why = c.missing ?? "no window"; else if (!p?.wav) row.why = p?.why ?? "not decoded"; else if (!v) row.why = emb.items.get(`clip:${c.key}`)?.error ?? "not embedded"; else { const scores = []; for (const voice of voices) { const s = scoreAgainst(v, voice.kept.map((r) => ({ key: r.key, vector: /** @type {number[]} */ (r.vector) })), { selfKey: `clip:${c.key}` }); if (s.score == null) continue; scores.push({ name: voice.name, score: s.score, best: s.best, ...(voice.kept.some((r) => r.clipKey === c.key) ? { inReference: true } : {}) }); } scores.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)); row.scores = scores; if (!scores.length) row.why = "no reference voice has pieces to compare with"; else Object.assign(row, speakerVerdict(scores, t)); } clips[c.key] = row; } await rm(scratch, { recursive: true, force: true }); return { version: SPEAKER_CHECK_VERSION, model: VOICE_MATCH_MODEL, engine: { file: emb.model, sherpaOnnx: emb.version, dim: emb.dim, sampleRate: SAMPLE_RATE }, madeAt: (o.now ? o.now() : new Date()).toISOString(), thresholds: { likely: t.likely, unlikely: t.unlikely, margin: SPEAKER_MARGIN }, speakers: voices.map((v) => v.doc), clips, }; } /** `/speaker-check.json`, or null. */ export async function readSpeakerCheck(dir) { try { const doc = JSON.parse(await readFile(path.join(dir, SPEAKER_CHECK_FILE), "utf8")); return doc && doc.version === SPEAKER_CHECK_VERSION && doc.clips && typeof doc.clips === "object" ? doc : null; } catch { return null; } } /** * Written whole (tmp + rename), MERGED into the file there: a check of one * clip keeps the other clips' rows -- when they were scored against the same * voices (by name and pieces); a change of the reference sets starts over. */ export async function writeSpeakerCheck(dir, doc) { const file = path.join(dir, SPEAKER_CHECK_FILE); const prev = await readSpeakerCheck(dir); const sig = (d) => JSON.stringify((d?.speakers ?? []).map((s) => [s.name, s.clips, s.recordings])); const merged = prev && sig(prev) === sig(doc) ? { ...doc, clips: { ...prev.clips, ...doc.clips } } : doc; const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`); await rename(tmp, file); return { file, doc: merged }; }