// Who is speaking, per montage clip: a local speaker-similarity score. // // An aid to the operator's ear, never a replacement for it. A montage cuts the // same phrase out of hundreds of recordings, and some of those lines are a // co-host's, a guest's, or a post read aloud — the co-host hazard. This scores // each clip's voice against a REFERENCE for the host's voice, so the audition // deck can put the doubtful ones first. It rules on nothing. // // The pipeline, per clip: // 1. decode the seconds that say the phrase (the caller names them: the // phrase ± PHRASE_PAD_S, in the fetched window) at 16 kHz mono via ffmpeg; // 2. keep only the VOICED frames (`voicedSamples`: an energy gate relative to // the span's own loud frames), so the silence or the gap after the phrase // does not dilute the voice; // 3. embed them with TitaNet-small through sherpa-onnx (scripts/speaker-embed.py, // the model scripts/diarize-sherpa.py already loads); // 4. score: cosine similarity to the reference's centroid (`score`, clamped to // 0..1), and the best match over the reference's items (`best`). // // THE REFERENCE is built per project and recorded in the output: // - "rulings": the clips the operator ruled `keep` in montage-rulings.json, // when there are at least REFERENCE_MIN_RULINGS of them. A clip in the // reference is scored against the others (leave-one-out), never itself. // - "recordings": otherwise, solo recordings of the host (`soloRecordingWhy`, // `pickReferenceRecordings`): the first REFERENCE_SECONDS of speech of up to // REFERENCE_VIDEOS uploads, in REFERENCE_PIECE_S pieces. // Either way the centroid is ROBUST (`robustCentroid`): items far below the // median similarity to the first centroid are dropped and the centroid made // again, so one mis-ruled clip or one guest segment does not move it. // // Deterministic for a given model and input: the decode is ffmpeg's, the gate // is arithmetic, the model runs on one thread and prints 6 decimals, and every // number here is rounded before it is written. No network; no LLM. // // Plain ESM with a .d.mts beside it, so umtool's CLI runs it with bare node. import { spawn } from "node:child_process"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "../atomicFile.mjs"; export const VOICE_MATCH_FILE = "voice-match.json"; export const VOICE_MATCH_VERSION = 1; export const VOICE_MATCH_MODEL = "titanet-small"; export const SAMPLE_RATE = 16000; /** The seconds either side of the phrase that are decoded. */ export const PHRASE_PAD_S = 1; // ---- the voiced-frames gate ------------------------------------------------------- /** One analysis frame. */ export const FRAME_S = 0.02; /** A frame quieter than this is never voice, however quiet the span is. */ export const GATE_FLOOR_DB = -50; /** …nor one this far under the span's loud frames (its 90th percentile). */ export const GATE_REL_DB = 22; /** A pause between two voiced runs shorter than this is kept (a word's own gaps). */ export const GATE_BRIDGE_S = 0.12; /** A voiced run shorter than this is a click, not speech. */ export const GATE_MIN_RUN_S = 0.1; /** Less voiced speech than this is not scored: the embedding says nothing. */ export const MIN_SPEECH_S = 0.8; /** * A phrase span with less voiced speech than this is decoded again from the * clip's `fallback` span (its cut ± the pad), and the one with more speech is * scored: a phrase whose word timing lands on a pause (or a window whose sound * runs late) is not a reason to score nothing. */ export const FALLBACK_SPEECH_S = 1.5; // ---- the reference ---------------------------------------------------------------- export const REFERENCE_MIN_RULINGS = 3; export const REFERENCE_VIDEOS = 8; export const REFERENCE_SECONDS = 60; export const REFERENCE_PIECE_S = 10; /** A reference item this far under the median similarity is dropped. */ export const REFERENCE_TRIM = 0.15; /** A title naming a second voice: a guest, a co-host, a call-in, a debate. */ export const COHOST_TITLE_RE = /\b(?:w\/|with|ft\.?|feat\.?|featuring|guests?|interviews?|debates?|panel|podcast|co-?hosts?|call[- ]?ins?|q\s*&\s*a|vs\.?|versus|reacts? with|sits? down|joins?)\b|\s[+x]\s/i; // ---- the labels ------------------------------------------------------------------- /** * Calibrated on the slow-news montage (plans/release-34/voice-match.md): the * two clips the operator ruled another speaker scored under `unlikely`, the * solo uploads over `likely`. `unsure` is the band between, where the ear * decides. */ export const DEFAULT_THRESHOLDS = Object.freeze({ likely: 0.42, unlikely: 0.3 }); const round = (x, d = 3) => (Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : null); /** * The key a clip's verdicts are filed under, shared with montage-rulings.json * (lane N1): the SOURCE moment, not the clip id, so a re-seed that renumbers the * ids keeps every score. * @param {string} channel @param {string} video @param {number} cutStart */ export function voiceMatchKey(channel, video, cutStart) { return `${channel}/${video}@${Number(cutStart).toFixed(2)}`; } /** @param {number | null} score @param {{likely: number, unlikely: number}} [t] */ export function labelFor(score, t = DEFAULT_THRESHOLDS) { if (!Number.isFinite(score)) return null; if (score >= t.likely) return "likely"; if (score < t.unlikely) return "unlikely"; return "unsure"; } // ---- the gate --------------------------------------------------------------------- /** Per-frame RMS level in dBFS (−120 for digital silence). */ export function frameLevels(samples, rate = SAMPLE_RATE, frameS = FRAME_S) { const n = Math.max(1, Math.round(rate * frameS)); const out = []; for (let a = 0; a + n <= samples.length; a += n) { let s = 0; for (let i = a; i < a + n; i += 1) s += samples[i] * samples[i]; const rms = Math.sqrt(s / n); out.push(rms > 1e-6 ? 20 * Math.log10(rms) : -120); } return out; } function percentile(values, p) { if (!values.length) return -120; const v = [...values].sort((a, b) => a - b); return v[Math.min(v.length - 1, Math.max(0, Math.floor(p * (v.length - 1))))]; } /** * The voiced stretches of a span, as [startFrame, endFrame) runs: frames at or * over max(GATE_FLOOR_DB, p90 − GATE_REL_DB), pauses under GATE_BRIDGE_S * bridged, runs under GATE_MIN_RUN_S dropped. * @returns {{ runs: [number, number][], threshold: number, frameSamples: number }} */ export function voicedRuns(samples, rate = SAMPLE_RATE, opts = {}) { const frameS = opts.frameS ?? FRAME_S; const levels = frameLevels(samples, rate, frameS); const threshold = Math.max(opts.floorDb ?? GATE_FLOOR_DB, percentile(levels, 0.9) - (opts.relDb ?? GATE_REL_DB)); const bridge = Math.round((opts.bridgeS ?? GATE_BRIDGE_S) / frameS); const minRun = Math.round((opts.minRunS ?? GATE_MIN_RUN_S) / frameS); /** @type {[number, number][]} */ let runs = []; let open = -1; levels.forEach((db, i) => { if (db >= threshold) { if (open < 0) open = i; } else if (open >= 0) { runs.push([open, i]); open = -1; } }); if (open >= 0) runs.push([open, levels.length]); const merged = []; for (const r of runs) { const last = merged[merged.length - 1]; if (last && r[0] - last[1] <= bridge) last[1] = r[1]; else merged.push([r[0], r[1]]); } runs = merged.filter(([a, b]) => b - a >= minRun); return { runs, threshold, frameSamples: Math.max(1, Math.round(rate * frameS)) }; } /** * The span's voiced samples, joined: what is embedded. * @param {Float32Array} samples * @returns {{ samples: Float32Array, seconds: number, runs: [number, number][] }} seconds = voiced seconds */ export function voicedSamples(samples, rate = SAMPLE_RATE, opts = {}) { const { runs, frameSamples } = voicedRuns(samples, rate, opts); const total = runs.reduce((n, [a, b]) => n + (b - a) * frameSamples, 0); const out = new Float32Array(total); let at = 0; for (const [a, b] of runs) { out.set(samples.subarray(a * frameSamples, b * frameSamples), at); at += (b - a) * frameSamples; } return { samples: out, seconds: total / rate, runs }; } // ---- audio in and out ------------------------------------------------------------- function run(cmd, args, { input = null, maxBytes = 1 << 28 } = {}) { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: [input ? "pipe" : "ignore", "pipe", "pipe"] }); const out = []; let bytes = 0; let err = ""; child.stdout.on("data", (b) => { bytes += b.length; if (bytes <= maxBytes) out.push(b); }); child.stderr.on("data", (b) => { err += b; if (err.length > 20000) err = err.slice(-20000); }); child.on("error", reject); child.on("close", (code) => { if (code === 0) resolve({ stdout: Buffer.concat(out), stderr: err }); else reject(Object.assign(new Error(`${path.basename(cmd)} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`), { code, stderr: err })); }); if (input) child.stdin.end(input); }); } /** * [start, start + dur] of `file` as 16 kHz mono float samples. `-ss` before * `-i`: an input seek, so a late span costs what an early one does. * @returns {Promise} */ export async function decodeSpan(file, start, dur, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", rate = SAMPLE_RATE } = {}) { const { stdout } = await run(ffmpeg, [ "-v", "error", "-nostdin", "-ss", Math.max(0, start).toFixed(3), "-t", Math.max(0, dur).toFixed(3), "-i", file, "-vn", "-ac", "1", "-ar", String(rate), "-f", "f32le", "-", ]); const n = Math.floor(stdout.length / 4); const out = new Float32Array(n); for (let i = 0; i < n; i += 1) out[i] = stdout.readFloatLE(i * 4); return out; } /** * Where a file's time ZERO is, the rule report-to-video's build uses * (build-video.mjs `startOffset`, release 33 M3d): a window whose PICTURE starts * late (a video stream with start_time > 0.05 s) holds the source's * `from + start_time + X` at `-ss X`. Anything else: 0. * @returns {Promise} */ export async function clockOffset(file, { ffprobe = process.env.FFPROBE_BIN ?? "ffprobe" } = {}) { let doc; try { const { stdout } = await run(ffprobe, ["-v", "error", "-show_entries", "format=start_time:stream=codec_type,start_time", "-of", "json", file]); doc = JSON.parse(String(stdout)); } catch { return 0; } const video = (doc.streams ?? []).find((s) => s.codec_type === "video"); const v = Number(video?.start_time); const f = Number(doc.format?.start_time); return Number.isFinite(v) && v > 0.05 && Number.isFinite(f) && f > 0 ? f : 0; } /** 16-bit PCM mono WAV bytes. */ export function encodeWav16(samples, rate = SAMPLE_RATE) { const data = Buffer.alloc(samples.length * 2); for (let i = 0; i < samples.length; i += 1) { const s = Math.max(-1, Math.min(1, samples[i])); data.writeInt16LE(Math.round(s < 0 ? s * 32768 : s * 32767), i * 2); } const h = Buffer.alloc(44); h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVE", 8); h.write("fmt ", 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22); h.writeUInt32LE(rate, 24); h.writeUInt32LE(rate * 2, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40); return Buffer.concat([h, data]); } /** A 16-bit PCM WAV's samples (mono, or channels averaged). */ export function decodeWav16(buf) { let at = 12; let rate = SAMPLE_RATE; let chans = 1; while (at + 8 <= buf.length) { const id = buf.toString("ascii", at, at + 4); const size = buf.readUInt32LE(at + 4); if (id === "fmt ") { chans = buf.readUInt16LE(at + 10); rate = buf.readUInt32LE(at + 12); } else if (id === "data") { const n = Math.floor(Math.min(size, buf.length - at - 8) / (2 * chans)); const out = new Float32Array(n); for (let i = 0; i < n; i += 1) { let s = 0; for (let c = 0; c < chans; c += 1) s += buf.readInt16LE(at + 8 + (i * chans + c) * 2); out[i] = s / chans / 32768; } return { samples: out, rate }; } at += 8 + size + (size % 2); } return { samples: new Float32Array(0), rate }; } // ---- the engine ------------------------------------------------------------------- /** * Which python, script and model embed. In order: the explicit `opts`, then * VOICE_MATCH_PYTHON / VOICE_MATCH_SCRIPT / VOICE_MATCH_MODEL, then the * diarization lane's own (`settings.diarization.python` / `.embModel` — the * same venv and TitaNet file), then `/.diarize/env/bin/python` and * `/.diarize/models/titanet.onnx`. `VOICE_MATCH_PYTHON` may name any * program that takes the script's arguments (the test kit's fake embedder is * run by `node`). * @param {{ repoRoot: string, env?: Record, settings?: any, * python?: string, script?: string, model?: string, threads?: number }} o */ export function resolveEngine(o) { const env = o.env ?? process.env; const d = o.settings?.diarization ?? {}; const python = o.python || env.VOICE_MATCH_PYTHON || (typeof d.python === "string" && d.python) || path.join(o.repoRoot, ".diarize", "env", "bin", "python"); const script = o.script || env.VOICE_MATCH_SCRIPT || path.join(o.repoRoot, "scripts", "speaker-embed.py"); const model = o.model || env.VOICE_MATCH_MODEL || (typeof d.embModel === "string" && d.embModel) || path.join(o.repoRoot, ".diarize", "models", "titanet.onnx"); return { python, script, model, threads: o.threads ?? 1 }; } /** * Embed WAV files: one process for the whole batch (the model loads once). * @param {{ id: string, wav: string }[]} items * @param {{ python: string, script: string, model: string, threads?: number }} engine * @param {string} scratch a directory for the request file * @returns {Promise<{ model: string, version: string | null, dim: number, items: Map }>} */ export async function embedWavs(items, engine, scratch) { await mkdir(scratch, { recursive: true }); const req = path.join(scratch, "embed-request.json"); await writeFile(req, JSON.stringify({ items })); const { stdout } = await run(engine.python, [engine.script, "--emb", engine.model, "--threads", String(engine.threads ?? 1), req]); const doc = JSON.parse(String(stdout)); const byId = new Map(); for (const it of doc.items ?? []) byId.set(String(it.id), { embedding: Array.isArray(it.embedding) ? it.embedding : null, seconds: it.seconds ?? 0, ...(it.error ? { error: String(it.error) } : {}) }); return { model: String(doc.model ?? path.basename(engine.model)), version: doc.version ?? null, dim: Number(doc.dim ?? 0), items: byId }; } // ---- the arithmetic --------------------------------------------------------------- export function dot(a, b) { let s = 0; for (let i = 0; i < a.length; i += 1) s += a[i] * b[i]; return s; } export function normalize(v) { const n = Math.sqrt(dot(v, v)); return n > 0 ? v.map((x) => x / n) : v.map(() => 0); } export const cosine = (a, b) => dot(normalize(a), normalize(b)); export function centroid(vectors) { if (!vectors.length) return null; const out = new Array(vectors[0].length).fill(0); for (const v of vectors) for (let i = 0; i < out.length; i += 1) out[i] += v[i]; return normalize(out); } function median(values) { const v = [...values].sort((a, b) => a - b); if (!v.length) return 0; const m = Math.floor(v.length / 2); return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; } /** * The centroid with the outliers out: the mean, then every item more than * `trim` under the median similarity to it dropped, then the mean of the rest. * @param {number[][]} vectors * @returns {{ centroid: number[] | null, kept: number[], dropped: number[] }} indices into `vectors` */ export function robustCentroid(vectors, { trim = REFERENCE_TRIM } = {}) { const first = centroid(vectors); if (!first) return { centroid: null, kept: [], dropped: [] }; if (vectors.length < 3) return { centroid: first, kept: vectors.map((_, i) => i), dropped: [] }; const sims = vectors.map((v) => dot(normalize(v), first)); const floor = median(sims) - trim; const kept = []; const dropped = []; sims.forEach((s, i) => (s >= floor ? kept : dropped).push(i)); return { centroid: centroid(kept.map((i) => vectors[i])), kept, dropped }; } /** * One clip against the reference: cosine to the centroid (clamped to 0..1) and * the best single reference item. `selfKey` leaves the clip's own reference * item out, centroid included (leave-one-out). * @param {number[]} v * @param {{ key: string, vector: number[] }[]} refItems the KEPT reference items */ export function scoreAgainst(v, refItems, { selfKey = null } = {}) { const others = refItems.filter((r) => r.key !== selfKey); const c = centroid(others.map((r) => r.vector)); if (!c) return { score: null, best: null }; const u = normalize(v); const best = Math.max(...others.map((r) => dot(u, normalize(r.vector)))); return { score: round(Math.max(0, Math.min(1, dot(u, c)))), best: round(Math.max(0, Math.min(1, best))) }; } // ---- reference recordings --------------------------------------------------------- /** * Why a recording is NOT a solo recording of the channel's host, or null when * it is one. The heuristic (documented in plans/release-34/voice-match.md): * - its transcript is captions (`source: "vtt"`): only captions mark a speaker * change (`>>`), so a whisper/parakeet transcript is no evidence either way; * - no cue carries `>>`; * - not a livestream (streams carry chat read aloud, call-ins and guests); * - no title word naming a second voice (COHOST_TITLE_RE); * - at least REFERENCE_SECONDS + 30 s long. * @param {{ source?: string, cues?: {text?: string}[], isLivestream?: boolean, title?: string, duration?: number }} doc a transcript.cues.json */ export function soloRecordingWhy(doc) { if (!doc || typeof doc !== "object") return "no transcript"; if (doc.source !== "vtt") return "not captions"; if (doc.isLivestream === true) return "a livestream"; if (COHOST_TITLE_RE.test(String(doc.title ?? ""))) return "a second voice in the title"; if (!(Number(doc.duration) >= REFERENCE_SECONDS + 30)) return "too short"; const cues = Array.isArray(doc.cues) ? doc.cues : []; if (!cues.length) return "no cues"; if (cues.some((c) => String(c?.text ?? "").includes(">>"))) return "a speaker change in the captions"; return null; } /** * Up to `n` of the candidates, spread evenly over their upload dates (a voice * and a microphone change over years; a montage spans them), oldest first. * Deterministic: sorted by date then id, then every (len−1)/(n−1)-th. * @template {{ date?: string | null, videoId: string }} C * @param {C[]} candidates * @returns {C[]} */ export function pickReferenceRecordings(candidates, n = REFERENCE_VIDEOS) { const sorted = [...candidates].sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")) || a.videoId.localeCompare(b.videoId)); if (sorted.length <= n) return sorted; if (n <= 1) return sorted.slice(0, Math.max(0, n)); const out = []; const seen = new Set(); for (let k = 0; k < n; k += 1) { const i = Math.round((k * (sorted.length - 1)) / (n - 1)); if (!seen.has(i)) { seen.add(i); out.push(sorted[i]); } } return out; } // ---- the run ---------------------------------------------------------------------- /** * @typedef {{ key: string, id?: string, file: string, start: number, dur: number, label?: string, fallback?: { start: number, dur: number } | null }} SpanItem * `start`/`dur` in the FILE's seconds (the caller has applied the window's * offset and clock); `fallback` the span decoded instead when this one has * under FALLBACK_SPEECH_S of speech (the clip's cut ± the pad). * @typedef {{ kind: "rulings", keys: string[] } | { kind: "recordings", items: (SpanItem & { slug: string, video: string, date?: string | null, title?: string | null })[] }} ReferenceSpec */ /** * Score every clip. Clips whose window is missing are passed with `file: null` * and come back unscored, with why. * @param {{ clips: (SpanItem | (Omit & { file: null, missing: string }))[], * reference: ReferenceSpec, engine: { python: string, script: string, model: string, threads?: number }, * scratch: string, thresholds?: { likely: number, unlikely: number }, ffmpeg?: string, * onProgress?: (e: Record) => void, now?: () => Date }} o */ export async function runVoiceMatch(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 }); // 1-2: decode + gate, clips and reference recordings alike. /** @type {Map} */ const prepared = new Map(); const voiced = async (file, start, dur) => voicedSamples(await decodeSpan(file, start, dur, { ffmpeg: o.ffmpeg })); const prepare = async (key, 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(key, { seconds: 0, wav: null, why: `decode failed: ${e instanceof Error ? e.message : String(e)}` }); return; } if (v.seconds < MIN_SPEECH_S) { prepared.set(key, { 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(key, { seconds: v.seconds, wav, fallback: usedFallback }); }; let k = 0; for (const c of o.clips) { 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: o.clips.length, key: c.key }); } const recs = o.reference.kind === "recordings" ? o.reference.items : []; for (const r of recs) await prepare(`ref:${r.key}`, r.file, r.start, r.dur); // 3: embed, one process. 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; // 4: the reference. /** @type {{ key: string, vector: number[], label?: string }[]} */ let refAll = []; /** @type {Record} */ let refDoc; if (o.reference.kind === "rulings") { refAll = o.reference.keys.map((key) => ({ key, vector: vec(`clip:${key}`) })).filter((r) => r.vector); refDoc = { kind: "rulings", rulings: o.reference.keys.length, embedded: refAll.length }; } else { refAll = recs.map((r) => ({ key: r.key, vector: vec(`ref:${r.key}`), label: r.label })).filter((r) => r.vector); refDoc = { kind: "recordings", seconds: REFERENCE_SECONDS, pieceSeconds: REFERENCE_PIECE_S, recordings: [...new Map(recs.map((r) => [`${r.slug}/${r.video}`, { channel: r.slug, video: r.video, date: r.date ?? null, title: r.title ?? null }])).values()], pieces: recs.length, embedded: refAll.length, }; } const robust = robustCentroid(refAll.map((r) => r.vector)); const refKept = robust.kept.map((i) => refAll[i]); refDoc.kept = refKept.length; refDoc.dropped = robust.dropped.map((i) => refAll[i].key); refDoc.trim = REFERENCE_TRIM; // The clips. /** @type {Record>} */ const clips = {}; for (const c of o.clips) { const p = prepared.get(`clip:${c.key}`); const v = vec(`clip:${c.key}`); /** @type {Record} */ const row = { score: null, label: null, speechSeconds: round(p?.seconds ?? 0, 2) }; if (c.id) row.id = c.id; if (p?.fallback) row.fallback = true; if (!c.file) row.why = /** @type {any} */ (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 if (refKept.length < (o.reference.kind === "rulings" ? 2 : 1)) row.why = "no reference"; else { const self = o.reference.kind === "rulings" ? c.key : null; const s = scoreAgainst(v, refKept, { selfKey: self }); row.score = s.score; row.best = s.best; row.label = labelFor(s.score, t); if (self && o.reference.kind === "rulings" && o.reference.keys.includes(c.key)) row.inReference = true; } clips[c.key] = row; } await rm(scratch, { recursive: true, force: true }); const scored = Object.values(clips).filter((c) => c.score != null); return { version: VOICE_MATCH_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 }, gate: { frameSeconds: FRAME_S, floorDb: GATE_FLOOR_DB, relDb: GATE_REL_DB, bridgeSeconds: GATE_BRIDGE_S, minSpeechSeconds: MIN_SPEECH_S, fallbackSpeechSeconds: FALLBACK_SPEECH_S, phrasePadSeconds: o.pad ?? PHRASE_PAD_S }, reference: refDoc, counts: { clips: o.clips.length, scored: scored.length, likely: scored.filter((c) => c.label === "likely").length, unsure: scored.filter((c) => c.label === "unsure").length, unlikely: scored.filter((c) => c.label === "unlikely").length, }, clips, }; } // ---- the file --------------------------------------------------------------------- /** `/voice-match.json`, or null when there is none (or it is not one). */ export async function readVoiceMatch(dir) { try { const doc = JSON.parse(await readFile(path.join(dir, VOICE_MATCH_FILE), "utf8")); return doc && doc.version === VOICE_MATCH_VERSION && doc.clips && typeof doc.clips === "object" ? doc : null; } catch { return null; } } /** * What a page says about a run: when, the counts, and the reference in words * ("3 clips ruled keep", "8 solo recordings"). */ export function voiceMatchSummary(doc) { if (!doc) return null; const ref = doc.reference && typeof doc.reference === "object" ? doc.reference : {}; const reference = ref.kind === "rulings" ? `${Number(ref.kept) || 0} clip${ref.kept === 1 ? "" : "s"} ruled keep` : `${Array.isArray(ref.recordings) ? ref.recordings.length : 0} solo recording${Array.isArray(ref.recordings) && ref.recordings.length === 1 ? "" : "s"}`; // Counted from the rows when the file does not carry them (a hand-made or // older file): a page never trusts a field to be there. const rows = Object.values(doc.clips ?? {}); const n = (label) => rows.filter((r) => r && r.label === label).length; const c = doc.counts && typeof doc.counts === "object" ? doc.counts : {}; const counts = { clips: Number.isFinite(c.clips) ? c.clips : rows.length, scored: Number.isFinite(c.scored) ? c.scored : rows.filter((r) => r && Number.isFinite(r.score)).length, likely: Number.isFinite(c.likely) ? c.likely : n("likely"), unsure: Number.isFinite(c.unsure) ? c.unsure : n("unsure"), unlikely: Number.isFinite(c.unlikely) ? c.unlikely : n("unlikely"), }; return { madeAt: typeof doc.madeAt === "string" ? doc.madeAt : "", counts, reference }; } /** Written whole: tmp + rename. */ export async function writeVoiceMatch(dir, doc) { const file = path.join(dir, VOICE_MATCH_FILE); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; }