Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 0c5940b96ba0cdd8dfe36216753568a1be5dad0a
parent e95542d23879ea9346d38f7444b2a0cb8aea6945
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 16:50:21 -0400

common: voice match — a local speaker-similarity score per montage clip (TitaNet-small through sherpa-onnx)

lib/montage/voiceMatch.mjs: decode a clip's phrase span at 16 kHz mono (ffmpeg, the window's own
clock), keep the voiced frames (an energy gate relative to the span's loud frames), embed through
scripts/speaker-embed.py (the model diarize-sherpa.py loads; one thread, 6 decimals), score cosine
to a robust reference centroid (clamped 0..1) and the best reference item; label likely/unsure/
unlikely. The reference is the keeps (leave-one-out) or solo recordings (soloRecordingWhy,
pickReferenceRecordings). voice-match.json read/write. Test kit: syntheticVoice (two voices
TitaNet separates) and fakeSpeakerEmbed (the script's contract with no python or model).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/lib/montage/voiceMatch.d.mts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/voiceMatch.mjs | 606+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/voiceMatch.test.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/testing/README.md | 2++
Acommon/testing/audio/fakeSpeakerEmbed.d.mts | 1+
Acommon/testing/audio/fakeSpeakerEmbed.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/audio/syntheticVoice.d.mts | 5+++++
Acommon/testing/audio/syntheticVoice.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/speaker-embed.py | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 1207 insertions(+), 0 deletions(-)

diff --git a/common/lib/montage/voiceMatch.d.mts b/common/lib/montage/voiceMatch.d.mts @@ -0,0 +1,120 @@ +export const VOICE_MATCH_FILE: string; +export const VOICE_MATCH_VERSION: 1; +export const VOICE_MATCH_MODEL: string; +export const SAMPLE_RATE: number; +export const PHRASE_PAD_S: number; +export const FRAME_S: number; +export const GATE_FLOOR_DB: number; +export const GATE_REL_DB: number; +export const GATE_BRIDGE_S: number; +export const GATE_MIN_RUN_S: number; +export const MIN_SPEECH_S: number; +export const FALLBACK_SPEECH_S: number; +export const REFERENCE_MIN_RULINGS: number; +export const REFERENCE_VIDEOS: number; +export const REFERENCE_SECONDS: number; +export const REFERENCE_PIECE_S: number; +export const REFERENCE_TRIM: number; +export const COHOST_TITLE_RE: RegExp; + +export type VoiceLabel = "likely" | "unsure" | "unlikely"; +export type Thresholds = { likely: number; unlikely: number }; +export const DEFAULT_THRESHOLDS: Readonly<Thresholds>; + +export function voiceMatchKey(channel: string, video: string, cutStart: number): string; +export function labelFor(score: number | null, t?: Thresholds): VoiceLabel | null; + +export type GateOpts = { frameS?: number; floorDb?: number; relDb?: number; bridgeS?: number; minRunS?: number }; +export function frameLevels(samples: Float32Array, rate?: number, frameS?: number): number[]; +export function voicedRuns(samples: Float32Array, rate?: number, opts?: GateOpts): { runs: [number, number][]; threshold: number; frameSamples: number }; +export function voicedSamples(samples: Float32Array, rate?: number, opts?: GateOpts): { samples: Float32Array; seconds: number; runs: [number, number][] }; + +export function decodeSpan(file: string, start: number, dur: number, opts?: { ffmpeg?: string; rate?: number }): Promise<Float32Array>; +export function clockOffset(file: string, opts?: { ffprobe?: string }): Promise<number>; +export function encodeWav16(samples: Float32Array, rate?: number): Buffer; +export function decodeWav16(buf: Buffer): { samples: Float32Array; rate: number }; + +export type Engine = { python: string; script: string; model: string; threads: number }; +export function resolveEngine(o: { + repoRoot: string; + env?: Record<string, string | undefined>; + settings?: unknown; + python?: string; + script?: string; + model?: string; + threads?: number; +}): Engine; +export function embedWavs( + items: { id: string; wav: string }[], + engine: { python: string; script: string; model: string; threads?: number }, + scratch: string, +): Promise<{ model: string; version: string | null; dim: number; items: Map<string, { embedding: number[] | null; seconds: number; error?: string }> }>; + +export function dot(a: number[], b: number[]): number; +export function normalize(v: number[]): number[]; +export function cosine(a: number[], b: number[]): number; +export function centroid(vectors: number[][]): number[] | null; +export function robustCentroid(vectors: number[][], opts?: { trim?: number }): { centroid: number[] | null; kept: number[]; dropped: number[] }; +export function scoreAgainst( + v: number[], + refItems: { key: string; vector: number[] }[], + opts?: { selfKey?: string | null }, +): { score: number | null; best: number | null }; + +export function soloRecordingWhy(doc: unknown): string | null; +export function pickReferenceRecordings<C extends { date?: string | null; videoId: string }>(candidates: C[], n?: number): C[]; + +export type SpanItem = { + key: string; + id?: string; + file: string; + start: number; + dur: number; + label?: string; + fallback?: { start: number; dur: number } | null; +}; +export type MissingItem = { key: string; id?: string; file: null; start: number; dur: number; missing: string }; +export type ReferenceSpec = + | { kind: "rulings"; keys: string[] } + | { kind: "recordings"; items: (SpanItem & { slug: string; video: string; date?: string | null; title?: string | null })[] }; + +/** One clip's row in voice-match.json. */ +export type VoiceMatchClip = { + score: number | null; + label: VoiceLabel | null; + speechSeconds: number; + best?: number | null; + id?: string; + why?: string; + fallback?: true; + inReference?: true; + via?: "words" | "cues" | "cut"; + from?: "instances"; +}; +export type VoiceMatchDoc = { + version: 1; + model: string; + engine: { file: string; sherpaOnnx: string | null; dim: number; sampleRate: number }; + madeAt: string; + thresholds: Thresholds; + gate: Record<string, number>; + reference: Record<string, unknown> & { kind: "rulings" | "recordings"; kept: number; dropped: string[] }; + counts: { clips: number; scored: number; likely: number; unsure: number; unlikely: number }; + span?: "phrase" | "cut"; + clips: Record<string, VoiceMatchClip>; +}; + +export function runVoiceMatch(o: { + clips: (SpanItem | MissingItem)[]; + reference: ReferenceSpec; + engine: { python: string; script: string; model: string; threads?: number }; + scratch: string; + thresholds?: Thresholds; + ffmpeg?: string; + pad?: number; + onProgress?: (e: Record<string, unknown>) => void; + now?: () => Date; +}): Promise<VoiceMatchDoc>; + +export function readVoiceMatch(dir: string): Promise<VoiceMatchDoc | null>; +export function writeVoiceMatch(dir: string, doc: VoiceMatchDoc): Promise<string>; diff --git a/common/lib/montage/voiceMatch.mjs b/common/lib/montage/voiceMatch.mjs @@ -0,0 +1,606 @@ +// 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"; + +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<Float32Array>} + */ +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<number>} + */ +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 `<repo>/.diarize/env/bin/python` and + * `<repo>/.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<string, string | undefined>, 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<string, { embedding: number[] | null, seconds: number, error?: string }> }>} + */ +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<SpanItem, "file"> & { 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<string, unknown>) => 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<string, { seconds: number, wav: string | null, why?: string, fallback?: boolean }>} */ + 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<string, unknown>} */ + 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<string, Record<string, unknown>>} */ + const clips = {}; + for (const c of o.clips) { + const p = prepared.get(`clip:${c.key}`); + const v = vec(`clip:${c.key}`); + /** @type {Record<string, unknown>} */ + 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 --------------------------------------------------------------------- + +/** `<project>/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; + } +} + +/** Written whole: tmp + rename. */ +export async function writeVoiceMatch(dir, doc) { + const file = path.join(dir, VOICE_MATCH_FILE); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); + await rename(tmp, file); + return file; +} diff --git a/common/lib/montage/voiceMatch.test.ts b/common/lib/montage/voiceMatch.test.ts @@ -0,0 +1,228 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + DEFAULT_THRESHOLDS, + REFERENCE_SECONDS, + SAMPLE_RATE, + decodeWav16, + embedWavs, + encodeWav16, + labelFor, + pickReferenceRecordings, + readVoiceMatch, + resolveEngine, + robustCentroid, + runVoiceMatch, + scoreAgainst, + soloRecordingWhy, + voiceMatchKey, + voicedSamples, + writeVoiceMatch, + cosine, +} from "./voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "../../testing/audio/syntheticVoice.mjs"; +import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FAKE = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const FAKE_ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx", threads: 1 }; +const tmp = () => mkdtempSync(path.join(os.tmpdir(), "voice-match-")); + +test("voiceMatchKey: the source moment to two decimals, the shape montage-rulings.json uses", () => { + assert.equal(voiceMatchKey("the-chan", "abc123", 3127.5), "the-chan/abc123@3127.50"); + assert.equal(voiceMatchKey("c", "v", 2.909), "c/v@2.91"); +}); + +test("labelFor: likely at or over the bar, unlikely under the floor, unsure between", () => { + const t = { likely: 0.42, unlikely: 0.3 }; + assert.equal(labelFor(0.42, t), "likely"); + assert.equal(labelFor(0.419, t), "unsure"); + assert.equal(labelFor(0.3, t), "unsure"); + assert.equal(labelFor(0.299, t), "unlikely"); + assert.equal(labelFor(null, t), null); + assert.deepEqual({ ...DEFAULT_THRESHOLDS }, t); +}); + +test("voicedSamples: the voiced-frames gate keeps the phrase and ignores trailing silence and a low hiss", () => { + const voice = syntheticVoice({ ...VOICE_A, seconds: 1.2 }); + const padded = withSilence(voice, { before: 0.3, after: 2 }); + // A hiss 60 dB under the voice where the silence was: still not voice. + let seed = 7; + for (let i = 0; i < padded.length; i += 1) { + seed = (seed * 1103515245 + 12345) % 2147483648; + padded[i] += ((seed / 2147483648) * 2 - 1) * 0.0003; + } + const v = voicedSamples(padded); + assert.ok(v.seconds > 0.8 && v.seconds <= 1.25, `voiced ${v.seconds}s of a 1.2 s phrase`); + const lastFrame = v.runs[v.runs.length - 1][1]; + assert.ok(lastFrame * 0.02 <= 0.3 + 1.2 + 0.05, "nothing after the phrase is kept"); + // Digital silence alone is no speech at all. + assert.equal(voicedSamples(new Float32Array(SAMPLE_RATE * 2)).seconds, 0); +}); + +test("encodeWav16 / decodeWav16 round-trip to 16-bit precision", () => { + const x = syntheticVoice({ ...VOICE_B, seconds: 0.25 }); + const back = decodeWav16(encodeWav16(x)); + assert.equal(back.rate, SAMPLE_RATE); + assert.equal(back.samples.length, x.length); + for (let i = 0; i < x.length; i += 97) assert.ok(Math.abs(back.samples[i] - x[i]) < 1e-4); +}); + +test("robustCentroid drops the item far from the rest; scoreAgainst leaves the clip's own reference item out", () => { + const near = (k: number) => [1, 0.1 * k, 0, 0]; + const vecs = [near(0), near(1), near(2), near(3), [0, 0, 1, 0]]; + const r = robustCentroid(vecs); + assert.deepEqual(r.dropped, [4]); + assert.equal(r.kept.length, 4); + const ref = r.kept.map((i) => ({ key: `k${i}`, vector: vecs[i] })); + const self = scoreAgainst(vecs[0], ref, { selfKey: "k0" }); + const withSelf = scoreAgainst(vecs[0], ref); + assert.ok(self.score! < withSelf.score!, "leave-one-out scores lower than scoring against itself"); + assert.ok(self.best! < 1); + assert.equal(scoreAgainst([0, 0, 1, 0], ref).score, 0, "a voice opposite the reference clamps to 0"); +}); + +test("soloRecordingWhy: captions, no >>, an upload, no second voice in the title, long enough", () => { + const ok = { source: "vtt", isLivestream: false, title: "Some Headline About Things", duration: 600, cues: [{ text: "hello there" }] }; + assert.equal(soloRecordingWhy(ok), null); + assert.equal(soloRecordingWhy({ ...ok, source: "whisper" }), "not captions"); + assert.equal(soloRecordingWhy({ ...ok, isLivestream: true }), "a livestream"); + assert.equal(soloRecordingWhy({ ...ok, title: "A Chat With Somebody" }), "a second voice in the title"); + assert.equal(soloRecordingWhy({ ...ok, title: "Big Interview" }), "a second voice in the title"); + assert.equal(soloRecordingWhy({ ...ok, title: "Kotaku & Vice Collude" }), null, "an ampersand joins two subjects, not two voices"); + assert.equal(soloRecordingWhy({ ...ok, duration: REFERENCE_SECONDS }), "too short"); + assert.equal(soloRecordingWhy({ ...ok, cues: [{ text: "so" }, { text: ">> and you" }] }), "a speaker change in the captions"); + assert.equal(soloRecordingWhy(null), "no transcript"); +}); + +test("pickReferenceRecordings spreads over the dates, oldest first, deterministically", () => { + const c = Array.from({ length: 20 }, (_, i) => ({ videoId: `v${String(i).padStart(2, "0")}`, date: `20${String(10 + i).padStart(2, "0")}0101` })); + const shuffled = [...c].reverse(); + const a = pickReferenceRecordings(shuffled, 5); + assert.deepEqual(a.map((x) => x.videoId), ["v00", "v05", "v10", "v14", "v19"]); + assert.deepEqual(pickReferenceRecordings(c, 5), a); + assert.equal(pickReferenceRecordings(c.slice(0, 3), 8).length, 3); +}); + +test("resolveEngine: explicit, then env, then the diarization lane's settings, then .diarize/", () => { + const repoRoot = "/repo"; + const base = resolveEngine({ repoRoot, env: {} }); + assert.equal(base.python, "/repo/.diarize/env/bin/python"); + assert.equal(base.model, "/repo/.diarize/models/titanet.onnx"); + assert.equal(base.script, "/repo/scripts/speaker-embed.py"); + const fromSettings = resolveEngine({ repoRoot, env: {}, settings: { diarization: { python: "/v/py", embModel: "/m/t.onnx" } } }); + assert.deepEqual([fromSettings.python, fromSettings.model], ["/v/py", "/m/t.onnx"]); + const fromEnv = resolveEngine({ repoRoot, env: { VOICE_MATCH_PYTHON: "node", VOICE_MATCH_SCRIPT: "/f.mjs" }, settings: { diarization: { python: "/v/py" } } }); + assert.deepEqual([fromEnv.python, fromEnv.script], ["node", "/f.mjs"]); +}); + +// ---- the whole run, through ffmpeg and the fake embedder -------------------------- + +function writeVoiceWav(dir: string, name: string, x: Float32Array) { + const f = path.join(dir, name); + writeFileSync(f, encodeWav16(x)); + return f; +} + +test("runVoiceMatch: two synthetic voices separate; the score is the same for the same input; a silent span is unscored", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { + const dir = tmp(); + try { + // The "host": four reference pieces and two clips, each a different take. + const ref = [0.4, 1.1, 2.2, 3.3].map((ph, i) => writeVoiceWav(dir, `ref${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 3, phase: ph }))); + const hostClip = writeVoiceWav(dir, "host.wav", withSilence(syntheticVoice({ ...VOICE_A, seconds: 2, phase: 4.4 }), { after: 3 })); + const guestClip = writeVoiceWav(dir, "guest.wav", syntheticVoice({ ...VOICE_B, seconds: 2.5, phase: 0.9 })); + const silent = writeVoiceWav(dir, "silent.wav", new Float32Array(SAMPLE_RATE * 3)); + // Its phrase span is silent; its cut (the fallback) is not. + const late = writeVoiceWav(dir, "late.wav", withSilence(syntheticVoice({ ...VOICE_A, seconds: 2, phase: 5.1 }), { before: 3 })); + const clips = [ + { key: "c/host@1.00", id: "s01", file: hostClip, start: 0, dur: 5 }, + { key: "c/guest@2.00", id: "s02", file: guestClip, start: 0, dur: 2.5 }, + { key: "c/silent@3.00", id: "s03", file: silent, start: 0, dur: 3 }, + { key: "c/late@4.00", id: "s04", file: late, start: 0, dur: 2.5, fallback: { start: 0, dur: 5 } }, + { key: "c/gone@5.00", id: "s05", file: null, start: 0, dur: 0, missing: "no local window" }, + ]; + const reference = { + kind: "recordings" as const, + items: ref.map((file, i) => ({ key: `c/ref#${i}`, slug: "c", video: "ref", file, start: 0, dur: 3 })), + }; + const now = () => new Date("2026-10-18T00:00:00Z"); + const run = () => runVoiceMatch({ clips, reference, engine: FAKE_ENGINE, scratch: path.join(dir, "scratch"), now }); + const doc = await run(); + const host = doc.clips["c/host@1.00"]; + const guest = doc.clips["c/guest@2.00"]; + assert.equal(host.label, "likely"); + assert.equal(guest.label, "unlikely"); + assert.ok(host.score! - guest.score! > 0.5, `host ${host.score} vs guest ${guest.score}`); + assert.ok(host.speechSeconds <= 2.05, "the trailing silence is not speech"); + assert.equal(doc.clips["c/silent@3.00"].score, null); + assert.equal(doc.clips["c/silent@3.00"].why, "too little speech"); + assert.equal(doc.clips["c/late@4.00"].fallback, true); + assert.equal(doc.clips["c/late@4.00"].label, "likely"); + assert.equal(doc.clips["c/gone@5.00"].why, "no local window"); + assert.equal(doc.reference.kind, "recordings"); + assert.deepEqual(doc.counts, { clips: 5, scored: 3, likely: 2, unsure: 0, unlikely: 1 }); + // Deterministic: the same input is the same document. + assert.deepEqual(await run(), doc); + // And the file round-trips. + await writeVoiceMatch(dir, doc); + assert.deepEqual(await readVoiceMatch(dir), doc); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("runVoiceMatch: a rulings reference scores each kept clip against the OTHER keeps", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { + const dir = tmp(); + try { + const takes = [0.2, 1.4, 2.6, 3.8].map((ph, i) => writeVoiceWav(dir, `k${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: ph }))); + const guest = writeVoiceWav(dir, "g.wav", syntheticVoice({ ...VOICE_B, seconds: 2.5 })); + const clips = [...takes.map((file, i) => ({ key: `c/v${i}@1.00`, id: `s0${i}`, file, start: 0, dur: 2.5 })), { key: "c/g@1.00", id: "s09", file: guest, start: 0, dur: 2.5 }]; + const doc = await runVoiceMatch({ + clips, + reference: { kind: "rulings", keys: ["c/v0@1.00", "c/v1@1.00", "c/v2@1.00"] }, + engine: FAKE_ENGINE, + scratch: path.join(dir, "scratch"), + }); + assert.equal(doc.reference.kind, "rulings"); + assert.equal(doc.clips["c/v0@1.00"].inReference, true); + assert.ok(doc.clips["c/v0@1.00"].score! < 1, "not scored against itself"); + assert.equal(doc.clips["c/v3@1.00"].label, "likely"); + assert.equal(doc.clips["c/g@1.00"].label, "unlikely"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +// ---- the real model, when this machine has it --------------------------------------- +// +// VOICE_MATCH_PYTHON + VOICE_MATCH_MODEL (the diarization lane's venv and +// TitaNet file). Skipped elsewhere: CI and a fresh clone have neither. +const REAL = (() => { + const python = process.env.VOICE_MATCH_PYTHON; + const model = process.env.VOICE_MATCH_MODEL; + if (!python || !model || !existsSync(python) || !existsSync(model)) return null; + return { python, model, script: path.join(HERE, "..", "..", "..", "scripts", "speaker-embed.py"), threads: 1 }; +})(); + +test("speaker-embed.py (TitaNet-small): two synthetic voices separate, and one input embeds to the same numbers twice", { skip: !REAL && "set VOICE_MATCH_PYTHON and VOICE_MATCH_MODEL to run it" }, async () => { + const dir = tmp(); + try { + const items = [ + ["a1", VOICE_A, 0.3], ["a2", VOICE_A, 2.1], ["b1", VOICE_B, 0.3], ["b2", VOICE_B, 2.1], + ].map(([id, v, ph]) => ({ id: id as string, wav: writeVoiceWav(dir, `${id}.wav`, syntheticVoice({ ...(v as typeof VOICE_A), seconds: 3, phase: ph as number })) })); + const r1 = await embedWavs(items, REAL!, path.join(dir, "s1")); + const r2 = await embedWavs(items, REAL!, path.join(dir, "s2")); + const e = (id: string) => r1.items.get(id)!.embedding!; + assert.equal(r1.dim, 192); + assert.deepEqual(r2.items.get("a1")!.embedding, e("a1")); + const within = Math.min(cosine(e("a1"), e("a2")), cosine(e("b1"), e("b2"))); + const across = Math.max(cosine(e("a1"), e("b1")), cosine(e("a2"), e("b2"))); + assert.ok(within - across > 0.2, `within ${within.toFixed(3)} vs across ${across.toFixed(3)}`); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/common/package.json b/common/package.json @@ -36,6 +36,7 @@ "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs", + "./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs", "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", "./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs", diff --git a/common/testing/README.md b/common/testing/README.md @@ -27,6 +27,8 @@ transcript, channel or person goes in these fixtures, ever. | `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | +| `audio/syntheticVoice.mjs` | Release 34 N2: synthetic "voices" for the speaker-similarity tests — `syntheticVoice({f0, formants, seconds, phase})` (additive harmonics shaped by formant resonances, a syllable envelope and a vibrato; `phase` makes another take of the same voice), `withSilence`, and `VOICE_A` / `VOICE_B`, two voices TitaNet-small tells apart (cosine ~0.98 within a voice, ~0.63 across, measured). | +| `audio/fakeSpeakerEmbed.mjs` | Release 34 N2: a stand-in for `scripts/speaker-embed.py` with its command line and JSON (`node fakeSpeakerEmbed.mjs --emb <x> <request.json>`): the "embedding" is the long-term spectrum (32 log-spaced Goertzel bands, dB, mean-removed, L2-normalised) — deterministic, and it separates `VOICE_A` from `VOICE_B`. Not a speaker model: set `VOICE_MATCH_PYTHON` to `node` and `VOICE_MATCH_SCRIPT` to it for a run with no python or model. | | `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). | | `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | diff --git a/common/testing/audio/fakeSpeakerEmbed.d.mts b/common/testing/audio/fakeSpeakerEmbed.d.mts @@ -0,0 +1 @@ +export function fakeEmbedding(x: Float32Array, rate: number): number[] | null; diff --git a/common/testing/audio/fakeSpeakerEmbed.mjs b/common/testing/audio/fakeSpeakerEmbed.mjs @@ -0,0 +1,82 @@ +#!/usr/bin/env node +// A stand-in for scripts/speaker-embed.py (release 34 N2), with its exact +// command line and JSON — so the voice-match pipeline, its CLI and the app's +// job run in a test with no python, no sherpa-onnx and no model file. +// +// node fakeSpeakerEmbed.mjs --emb <anything> [--threads N] <request.json> +// +// The "embedding" is the clip's long-term spectrum: the energy at 32 +// log-spaced frequencies (60 Hz–4 kHz, Goertzel over 32 ms frames), in dB, +// mean-removed and L2-normalised. Deterministic, and it tells two voices of +// different pitch and colour apart (syntheticVoice.mjs's VOICE_A and VOICE_B) +// — which is all a test of the plumbing needs. It is not a speaker model. +// Point VOICE_MATCH_PYTHON at `node` and VOICE_MATCH_SCRIPT at this file. +import { readFileSync } from "node:fs"; +import path from "node:path"; + +const BANDS = 32; +const FRAME = 512; + +function readWav(file) { + const buf = readFileSync(file); + let at = 12; + let rate = 16000; + while (at + 8 <= buf.length) { + const id = buf.toString("ascii", at, at + 4); + const size = buf.readUInt32LE(at + 4); + if (id === "fmt ") rate = buf.readUInt32LE(at + 12); + if (id === "data") { + const n = Math.floor(Math.min(size, buf.length - at - 8) / 2); + const x = new Float32Array(n); + for (let i = 0; i < n; i += 1) x[i] = buf.readInt16LE(at + 8 + i * 2) / 32768; + return { x, rate }; + } + at += 8 + size + (size % 2); + } + return { x: new Float32Array(0), rate }; +} + +export function fakeEmbedding(x, rate) { + const freqs = Array.from({ length: BANDS }, (_, i) => 60 * (4000 / 60) ** (i / (BANDS - 1))); + const acc = new Array(BANDS).fill(0); + let frames = 0; + for (let a = 0; a + FRAME <= x.length; a += FRAME / 2) { + frames += 1; + freqs.forEach((f, b) => { + const w = (2 * Math.PI * f) / rate; + const c = 2 * Math.cos(w); + let s1 = 0; + let s2 = 0; + for (let i = 0; i < FRAME; i += 1) { + const win = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1)); + const s0 = x[a + i] * win + c * s1 - s2; + s2 = s1; + s1 = s0; + } + acc[b] += s1 * s1 + s2 * s2 - c * s1 * s2; + }); + } + if (!frames) return null; + const db = acc.map((e) => 10 * Math.log10(e / frames + 1e-9)); + const mean = db.reduce((s, v) => s + v, 0) / BANDS; + const v = db.map((d) => d - mean); + const n = Math.sqrt(v.reduce((s, e) => s + e * e, 0)); + return n > 0 ? v.map((e) => Math.round((e / n) * 1e6) / 1e6) : null; +} + +const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname); +if (isMain) { + const args = process.argv.slice(2); + const req = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--"))).pop(); + const { items = [] } = JSON.parse(readFileSync(req, "utf8")); + const out = items.map((it) => { + try { + const { x, rate } = readWav(it.wav); + const e = x.length >= rate * 0.5 ? fakeEmbedding(x, rate) : null; + return { id: it.id, embedding: e, seconds: Math.round((x.length / rate) * 1000) / 1000, ...(e ? {} : { error: "too short" }) }; + } catch (e) { + return { id: it.id, embedding: null, seconds: 0, error: String(e) }; + } + }); + process.stdout.write(JSON.stringify({ model: "fake-spectrum", version: null, dim: BANDS, items: out })); +} diff --git a/common/testing/audio/syntheticVoice.d.mts b/common/testing/audio/syntheticVoice.d.mts @@ -0,0 +1,5 @@ +export type VoiceSpec = { f0: number; formants: [number, number][] }; +export const VOICE_A: Readonly<VoiceSpec>; +export const VOICE_B: Readonly<VoiceSpec>; +export function syntheticVoice(o: VoiceSpec & { seconds?: number; rate?: number; syllableHz?: number; phase?: number; level?: number }): Float32Array; +export function withSilence(samples: Float32Array, o?: { before?: number; after?: number; rate?: number }): Float32Array; diff --git a/common/testing/audio/syntheticVoice.mjs b/common/testing/audio/syntheticVoice.mjs @@ -0,0 +1,52 @@ +// Synthetic "voices" for the speaker-similarity tests (release 34 N2): additive +// harmonic speech-like sound, deterministic for its parameters. Two voices +// differ the way two people do to a speaker-embedding model — pitch and the +// resonances of the vocal tract — and nothing in them is a recording. +// +// syntheticVoice({ f0, formants, seconds, rate, syllableHz, phase }) +// f0 fundamental in Hz (a low voice ~100, a high one ~220) +// formants [[centreHz, bandwidthHz], …] — each harmonic's gain is the +// sum of these resonances (a vowel colour) +// syllableHz the on/off rate of the syllable envelope (default 4) +// phase shifts the syllables and the vibrato, so two takes of ONE +// voice are different sound with the same colour +// withSilence(samples, { before, after, rate }) pads with digital silence. +// VOICE_A / VOICE_B: two voices a model should tell apart. +export const VOICE_A = Object.freeze({ f0: 105, formants: [[700, 130], [1220, 160], [2600, 250]] }); +export const VOICE_B = Object.freeze({ f0: 215, formants: [[380, 90], [2250, 220], [3050, 300]] }); + +export function syntheticVoice({ f0, formants, seconds = 2, rate = 16000, syllableHz = 4, phase = 0, level = 0.3 }) { + const n = Math.round(seconds * rate); + const out = new Float32Array(n); + const top = Math.min(4000, rate / 2 - 200); + const gains = []; + for (let k = 1; k * f0 * 1.06 < top; k += 1) { + const f = k * f0; + let g = 0; + for (const [c, b] of formants) g += 1 / (1 + ((f - c) / b) ** 2); + gains.push(g / k ** 0.5); + } + let ph = 0; + for (let i = 0; i < n; i += 1) { + const t = i / rate; + // A slow vibrato and a falling-rising intonation: pitch is never a constant. + const pitch = f0 * (1 + 0.03 * Math.sin(2 * Math.PI * 5.5 * t + phase) + 0.06 * Math.sin(2 * Math.PI * 0.4 * t + phase * 0.7)); + ph += (2 * Math.PI * pitch) / rate; + let s = 0; + for (let k = 0; k < gains.length; k += 1) s += gains[k] * Math.sin((k + 1) * ph); + const env = 0.5 - 0.5 * Math.cos(2 * Math.PI * syllableHz * t + phase); + out[i] = s * env; + } + let peak = 0; + for (const x of out) peak = Math.max(peak, Math.abs(x)); + if (peak > 0) for (let i = 0; i < n; i += 1) out[i] = (out[i] / peak) * level; + return out; +} + +export function withSilence(samples, { before = 0, after = 0, rate = 16000 } = {}) { + const a = Math.round(before * rate); + const b = Math.round(after * rate); + const out = new Float32Array(a + samples.length + b); + out.set(samples, a); + return out; +} diff --git a/scripts/speaker-embed.py b/scripts/speaker-embed.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Speaker embeddings for common/lib/montage/voiceMatch.mjs. + +WAV segments in, L2-normalised speaker embeddings out, as JSON. Nothing else: +which seconds to embed, the voiced-frames gate, the reference and the score +all live in the .mjs caller, so this file stays a thin shell over the model +that scripts/diarize-sherpa.py already loads (the same sherpa-onnx +SpeakerEmbeddingExtractor, the same TitaNet-small ONNX file). + +stdout is JSON ONLY; progress goes to stderr. + +Usage: + speaker-embed.py --emb <model.onnx> [--threads N] <request.json> + +request.json: {"items": [{"id": "...", "wav": "/abs/path.wav"}, ...]} + Each wav is 16-bit PCM, mono, 16 kHz (the rate TitaNet is trained at; the + caller decodes to it). A wav at another rate is passed to the model with its + own rate, which sherpa resamples. + +Output: {"model": "<file name>", "version": "<sherpa-onnx>", "dim": n, + "items": [{"id", "embedding": [...] | null, "seconds": f, + "error"?: "..."}]} + `embedding` is rounded to 6 decimals, so the same input prints the same + bytes. One thread by default: a CPU reduction split across threads is the + one place an ONNX run can differ in its last bits between two runs. +""" +import argparse, json, os, sys, wave + +MIN_SECONDS = 0.5 + + +def read_wav(np, path): + with wave.open(path, "rb") as w: + rate = w.getframerate() + width = w.getsampwidth() + chans = w.getnchannels() + raw = w.readframes(w.getnframes()) + if width != 2: + raise ValueError(f"{os.path.basename(path)}: {width * 8}-bit wav, want 16-bit PCM") + x = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0 + if chans > 1: + x = x.reshape(-1, chans).mean(axis=1) + return x, rate + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("request") + ap.add_argument("--emb", required=True) + ap.add_argument("--threads", type=int, default=1) + args = ap.parse_args() + + try: + import numpy as np + import sherpa_onnx + except ImportError as e: + print(f"speaker-embed: missing dependency: {e}", file=sys.stderr) + return 3 + + with open(args.request, "r", encoding="utf8") as f: + req = json.load(f) + items = req.get("items") or [] + + cfg = sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=args.emb, num_threads=args.threads) + if not cfg.validate(): + print("speaker-embed: invalid model config", file=sys.stderr) + return 2 + extractor = sherpa_onnx.SpeakerEmbeddingExtractor(cfg) + + out = [] + for k, item in enumerate(items): + rec = {"id": item.get("id"), "embedding": None, "seconds": 0.0} + try: + x, rate = read_wav(np, item["wav"]) + rec["seconds"] = round(x.size / rate, 3) + if x.size < int(MIN_SECONDS * rate): + rec["error"] = "too short" + else: + stream = extractor.create_stream() + stream.accept_waveform(rate, x) + stream.input_finished() + if not extractor.is_ready(stream): + rec["error"] = "too short" + else: + v = np.asarray(extractor.compute(stream), dtype=np.float64) + n = float(np.linalg.norm(v)) + if n > 0: + rec["embedding"] = [round(float(e), 6) for e in (v / n)] + else: + rec["error"] = "zero embedding" + except Exception as e: # one bad file is that item's error, not the run's + rec["error"] = str(e) + out.append(rec) + if (k + 1) % 10 == 0 or k + 1 == len(items): + print(f"speaker-embed: {k + 1}/{len(items)}", file=sys.stderr, flush=True) + + json.dump( + { + "model": os.path.basename(args.emb), + "version": getattr(sherpa_onnx, "__version__", None), + "dim": extractor.dim, + "items": out, + }, + sys.stdout, + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main())