// The clip finder's two scans of a recording's sound (release 35 C1): laughs // and voices. The I/O half of common/lib/clips — the arithmetic is clips.mjs. // // runAudioScan the sound in SCAN_WINDOW_S windows every SCAN_HOP_S: // each window's level (dBFS, always — the no-model // fallback's energy) and, when the tagger is there, its // laugh score (CED-mini through scripts/audio-tag.py, the // AudioSet laughter family summed). Decoded in chunks with // ffmpeg (voiceMatch's decodeSpan), so a 3-hour stream // never sits in memory; one tagger process per group of // chunks (the model loads once per group). // speakerCentroids a voice centroid per diarization cluster: its longest // turns that overlap nobody (24 for the two clusters with // the most seconds, 6 for each other), voiced frames only, // embedded with TitaNet-small (voiceMatch's embedWavs) and // averaged robustly — what merges one voice split in two. // embedSpans spans embedded as they are: each laugh's voice, scored // against the host's and the subject's centroids. // // Deterministic for a given model and input; no network; no LLM. // // Plain ESM with a .d.mts beside it. import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; import { mkdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { decodeSpan, embedWavs, encodeWav16, frameLevels, robustCentroid, voicedSamples, SAMPLE_RATE, MIN_SPEECH_S } from "../montage/voiceMatch.mjs"; import { LAUGH_CLASSES, SCAN_HOP_S, SCAN_WINDOW_S, laughScore } from "./clips.mjs"; export const AUDIO_SCAN_VERSION = 1; export const VOICES_VERSION = 1; /** The seconds decoded at a time. */ export const CHUNK_S = 300; /** Chunks per tagger process. */ export const CHUNKS_PER_GROUP = 4; /** The default model directory under `/.diarize/models/`. */ export const CED_DIR = "sherpa-onnx-ced-mini-audio-tagging-2024-04-19"; /** Pieces for the two clusters with the most seconds (the voices that matter), and for each of the rest. */ export const PIECES_MAIN = 24; export const PIECES_PER_SPEAKER = 6; /** A turn shorter than this is not used for a voice centroid. */ export const PIECE_MIN_S = 2; /** A piece is at most this long. */ export const PIECE_MAX_S = 8; const round = (x, d = 3) => (Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : null); function run(cmd, args) { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); const out = []; let err = ""; child.stdout.on("data", (b) => 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(new Error(`${path.basename(cmd)} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`)); }); }); } /** * Which python, script and model tag. In order: the explicit `opts`, then * AUDIO_TAG_PYTHON / AUDIO_TAG_SCRIPT / AUDIO_TAG_MODEL / AUDIO_TAG_LABELS, * then the diarization venv (`settings.diarization.python`, else * `/.diarize/env/bin/python`), `/scripts/audio-tag.py`, * `/.diarize/models//model.int8.onnx` and the * class_labels_indices.csv beside the model. `available` is whether the * model file is there (the scan runs without it: energy only). * @param {{ repoRoot: string, env?: Record, settings?: any, * python?: string, script?: string, model?: string, labels?: string, threads?: number }} o */ export function resolveTagger(o) { const env = o.env ?? process.env; const d = o.settings?.diarization ?? {}; const python = o.python || env.AUDIO_TAG_PYTHON || (typeof d.python === "string" && d.python) || path.join(o.repoRoot, ".diarize", "env", "bin", "python"); const script = o.script || env.AUDIO_TAG_SCRIPT || path.join(o.repoRoot, "scripts", "audio-tag.py"); const model = o.model || env.AUDIO_TAG_MODEL || path.join(o.repoRoot, ".diarize", "models", CED_DIR, "model.int8.onnx"); const labels = o.labels || env.AUDIO_TAG_LABELS || path.join(path.dirname(model), "class_labels_indices.csv"); return { python, script, model, labels, threads: o.threads ?? 1, available: existsSync(model) }; } /** * Tag WAV files: one process for the batch. * @param {{ id: string, wav: string, window?: number, hop?: number }[]} items * @param {{ python: string, script: string, model: string, labels: string, threads?: number }} engine * @param {string} scratch * @returns {Promise<{ model: string, version: string | null, classes: number[], items: Map }>} */ export async function tagWavs(items, engine, scratch, { classes = LAUGH_CLASSES } = {}) { await mkdir(scratch, { recursive: true }); const req = path.join(scratch, "tag-request.json"); await writeFile(req, JSON.stringify({ items })); const { stdout } = await run(engine.python, [engine.script, "--model", engine.model, "--labels", engine.labels, "--threads", String(engine.threads ?? 1), "--classes", classes.join(","), req]); const doc = JSON.parse(String(stdout)); const byId = new Map(); for (const it of doc.items ?? []) byId.set(String(it.id), { scores: Array.isArray(it.scores) ? it.scores : null, seconds: Number(it.seconds) || 0, ...(it.error ? { error: String(it.error) } : {}) }); return { model: String(doc.model ?? path.basename(engine.model)), version: doc.version ?? null, classes: Array.isArray(doc.classes) ? doc.classes : [...classes], items: byId }; } /** Each window's RMS level in dBFS (1 dp): the mean power of its 20 ms frames. */ export function windowLevels(samples, { rate = SAMPLE_RATE, window = SCAN_WINDOW_S, hop = SCAN_HOP_S, count }) { const frames = frameLevels(samples, rate, 0.02); const per = Math.round(window / 0.02); const step = Math.round(hop / 0.02); const out = []; for (let i = 0; i < count; i += 1) { const a = i * step; let p = 0; let n = 0; for (let f = a; f < Math.min(frames.length, a + per); f += 1) { p += 10 ** (frames[f] / 10); n += 1; } out.push(n ? round(10 * Math.log10(p / n + 1e-12), 1) : -120); } return out; } /** * The sound of [0, duration) of `file` (FILE seconds; `clock` is added to * every time, the file's offset on the source's clock), in windows. Returns * `{ version, window, hop, t0, windows, energy, laugh, model, classes }`: * `laugh` null when no tagger ran (`tagger` null or not available). * @param {{ file: string, duration: number, clock?: number, tagger?: (ReturnType) | null, * scratch: string, window?: number, hop?: number, chunkS?: number, perGroup?: number, ffmpeg?: string, * onProgress?: (e: Record) => void }} o */ export async function runAudioScan(o) { const window = o.window ?? SCAN_WINDOW_S; const hop = o.hop ?? SCAN_HOP_S; const chunkS = o.chunkS ?? CHUNK_S; const perGroup = Math.max(1, o.perGroup ?? CHUNKS_PER_GROUP); const emit = o.onProgress ?? (() => {}); const tagger = o.tagger && o.tagger.available ? o.tagger : null; const total = Math.max(0, Math.floor((o.duration - window) / hop + 1e-9) + 1); const perChunk = Math.max(1, Math.round(chunkS / hop)); const chunks = Math.ceil(total / perChunk); await rm(o.scratch, { recursive: true, force: true }); await mkdir(o.scratch, { recursive: true }); const energy = new Array(total).fill(-120); const laugh = tagger ? new Array(total).fill(0) : null; let model = null; let pending = []; const flush = async () => { if (!pending.length || !tagger) return; const got = await tagWavs(pending.map((p) => ({ id: p.id, wav: p.wav, window, hop })), tagger, o.scratch); model = { file: got.model, sherpaOnnx: got.version, classes: got.classes }; for (const p of pending) { const it = got.items.get(p.id); if (it?.error) throw new Error(`audio-tag: chunk ${p.id}: ${it.error}`); const rows = it?.scores ?? []; for (let k = 0; k < Math.min(rows.length, p.count); k += 1) /** @type {number[]} */ (laugh)[p.i0 + k] = round(laughScore(rows[k]), 3); await rm(p.wav, { force: true }); } emit({ event: "tag", chunks: pending.length }); pending = []; }; for (let c = 0; c < chunks; c += 1) { const i0 = c * perChunk; const i1 = Math.min(total, i0 + perChunk); const start = i0 * hop; const dur = (i1 - i0 - 1) * hop + window; const samples = await decodeSpan(o.file, start, dur, { ffmpeg: o.ffmpeg }); const count = i1 - i0; const lv = windowLevels(samples, { window, hop, count }); for (let k = 0; k < count; k += 1) energy[i0 + k] = lv[k]; if (tagger) { const wav = path.join(o.scratch, `chunk-${String(c).padStart(5, "0")}.wav`); await writeFile(wav, encodeWav16(samples)); pending.push({ id: `c${c}`, wav, i0, count }); if (pending.length >= perGroup) await flush(); } emit({ event: "decode", n: c + 1, of: chunks }); } await flush(); await rm(o.scratch, { recursive: true, force: true }); return { version: AUDIO_SCAN_VERSION, window, hop, t0: round(o.clock ?? 0, 3), windows: total, energy, laugh, model, classes: [...LAUGH_CLASSES], }; } /** * Up to `n` of a cluster's turns for its voice: the LONGEST of those at least * PIECE_MIN_S long that overlap no other cluster's turn (when none is clean, * the longest at all), each the middle PIECE_MAX_S of the turn (0.2 s in from * either end), in time order. * @param {{ start: number, end: number, speaker: number }[]} turns sorted */ export function centroidPieces(turns, speaker, n = PIECES_PER_SPEAKER) { const own = turns.filter((t) => t.speaker === speaker && t.end - t.start >= PIECE_MIN_S); const others = turns.filter((t) => t.speaker !== speaker); const clean = own.filter((t) => !others.some((o) => o.start < t.end && o.end > t.start)); const pool = clean.length ? clean : own; const picked = [...pool].sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start).slice(0, n).sort((a, b) => a.start - b.start); return picked.map((t) => { const d = Math.min(PIECE_MAX_S, t.end - t.start - 0.4); return { start: round((t.start + t.end) / 2 - d / 2, 3), dur: round(d, 3) }; }); } /** * Embed spans of the sound as they are (no gate): a laugh's voice. * @param {{ file: string, clock?: number, spans: { key: string, start: number, dur: number }[], * engine: { python: string, script: string, model: string, threads?: number }, scratch: string, ffmpeg?: string }} o * @returns {Promise>} key → embedding (5 dp); a span that would not embed is left out */ export async function embedSpans(o) { const out = new Map(); if (!o.spans.length) return out; await rm(o.scratch, { recursive: true, force: true }); await mkdir(o.scratch, { recursive: true }); const items = []; for (const [k, sp] of o.spans.entries()) { const x = await decodeSpan(o.file, Math.max(0, sp.start - (o.clock ?? 0)), sp.dur, { ffmpeg: o.ffmpeg }); if (x.length < SAMPLE_RATE * 0.5) continue; const wav = path.join(o.scratch, `span-${k}.wav`); await writeFile(wav, encodeWav16(x)); items.push({ id: sp.key, wav }); } const emb = items.length ? await embedWavs(items, o.engine, o.scratch) : { items: new Map() }; for (const it of items) { const v = emb.items.get(it.id)?.embedding; if (Array.isArray(v)) out.set(it.id, v.map((x) => round(x, 5))); } await rm(o.scratch, { recursive: true, force: true }); return out; } /** * A voice centroid per cluster (null when none of its pieces had speech). * @param {{ file: string, clock?: number, turns: { start: number, end: number, speaker: number }[], * engine: { python: string, script: string, model: string, threads?: number }, scratch: string, ffmpeg?: string, * onProgress?: (e: Record) => void }} o * @returns {Promise<{ version: number, model: string, speakers: Record }>} */ export async function speakerCentroids(o) { const emit = o.onProgress ?? (() => {}); const clock = o.clock ?? 0; await rm(o.scratch, { recursive: true, force: true }); await mkdir(o.scratch, { recursive: true }); const speakers = [...new Set(o.turns.map((t) => t.speaker))].sort((a, b) => a - b); const seconds = new Map(); for (const t of o.turns) seconds.set(t.speaker, (seconds.get(t.speaker) ?? 0) + t.end - t.start); const main = new Set([...speakers].sort((a, b) => (seconds.get(b) ?? 0) - (seconds.get(a) ?? 0) || a - b).slice(0, 2)); const items = []; const bySpeaker = new Map(); for (const s of speakers) { const pieces = centroidPieces(o.turns, s, main.has(s) ? PIECES_MAIN : PIECES_PER_SPEAKER); bySpeaker.set(s, []); for (const [k, p] of pieces.entries()) { const v = voicedSamples(await decodeSpan(o.file, Math.max(0, p.start - clock), p.dur, { ffmpeg: o.ffmpeg })); if (v.seconds < MIN_SPEECH_S) continue; const id = `s${s}-${k}`; const wav = path.join(o.scratch, `${id}.wav`); await writeFile(wav, encodeWav16(v.samples)); items.push({ id, wav }); bySpeaker.get(s).push(id); } emit({ event: "voice", speaker: s, pieces: bySpeaker.get(s).length }); } const emb = items.length ? await embedWavs(items, o.engine, o.scratch) : { model: path.basename(o.engine.model), items: new Map() }; /** @type {Record} */ const out = {}; for (const s of speakers) { const vecs = bySpeaker.get(s).map((id) => emb.items.get(id)?.embedding).filter(Array.isArray); const r = robustCentroid(vecs); out[s] = { centroid: r.centroid ? r.centroid.map((x) => round(x, 5)) : null, pieces: bySpeaker.get(s).length, kept: r.kept.length }; } await rm(o.scratch, { recursive: true, force: true }); return { version: VOICES_VERSION, model: emb.model, speakers: out }; }