commit 8540c28f29cf61e8556f450b9fcc4714fae985fe
parent 2af9d165266be0b29705ec19b982a5152675b2a9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 00:19:34 -0400
common: the laugh scan and the voice centroids -- scripts/audio-tag.py (CED-mini through sherpa-onnx) and lib/clips/scan.mjs (release 35 C1, slice 2)
runAudioScan decodes a recording in chunks (voiceMatch's decodeSpan), keeps
each 1 s window's level (the no-model fallback's energy) and, with the
tagger there, its laugh score (the AudioSet laughter family summed), one
tagger process per group of chunks. speakerCentroids embeds a few clean
turns per diarization cluster with TitaNet (voiceMatch's embedWavs) for the
same-voice merge. The test kit gains fakeAudioTag.mjs (a stand-in for the
shim: it hears the synthetic stream's laugh tone).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 657 insertions(+), 0 deletions(-)
diff --git a/common/lib/clips/scan.d.mts b/common/lib/clips/scan.d.mts
@@ -0,0 +1,61 @@
+export const AUDIO_SCAN_VERSION: 1;
+export const VOICES_VERSION: 1;
+export const CHUNK_S: number;
+export const CHUNKS_PER_GROUP: number;
+export const CED_DIR: string;
+export const PIECES_PER_SPEAKER: number;
+export const PIECE_MIN_S: number;
+export const PIECE_MAX_S: number;
+
+export type Tagger = { python: string; script: string; model: string; labels: string; threads: number; available: boolean };
+export function resolveTagger(o: {
+ repoRoot: string;
+ env?: Record<string, string | undefined>;
+ settings?: unknown;
+ python?: string;
+ script?: string;
+ model?: string;
+ labels?: string;
+ threads?: number;
+}): Tagger;
+export function tagWavs(
+ items: { id: string; wav: string; window?: number; hop?: number }[],
+ engine: { python: string; script: string; model: string; labels: string; threads?: number },
+ scratch: string,
+ opts?: { classes?: readonly number[] },
+): Promise<{ model: string; version: string | null; classes: number[]; items: Map<string, { scores: number[][] | null; seconds: number; error?: string }> }>;
+export function windowLevels(samples: Float32Array, o: { rate?: number; window?: number; hop?: number; count: number }): number[];
+export type AudioScan = {
+ version: 1;
+ window: number;
+ hop: number;
+ t0: number;
+ windows: number;
+ energy: number[];
+ laugh: number[] | null;
+ model: { file: string; sherpaOnnx: string | null; classes: number[] } | null;
+ classes: number[];
+};
+export function runAudioScan(o: {
+ file: string;
+ duration: number;
+ clock?: number;
+ tagger?: Tagger | null;
+ scratch: string;
+ window?: number;
+ hop?: number;
+ chunkS?: number;
+ perGroup?: number;
+ ffmpeg?: string;
+ onProgress?: (e: Record<string, unknown>) => void;
+}): Promise<AudioScan>;
+export function centroidPieces(turns: { start: number; end: number; speaker: number }[], speaker: number, n?: number): { start: number; dur: number }[];
+export function speakerCentroids(o: {
+ 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<string, unknown>) => void;
+}): Promise<{ version: number; model: string; speakers: Record<string, { centroid: number[] | null; pieces: number; kept: number }> }>;
diff --git a/common/lib/clips/scan.mjs b/common/lib/clips/scan.mjs
@@ -0,0 +1,249 @@
+// 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: up to
+// PIECES_PER_SPEAKER of its turns that overlap nobody
+// else, spread over the stream, voiced frames only,
+// embedded with TitaNet-small (voiceMatch's embedWavs) and
+// averaged robustly — what merges one voice split in two.
+//
+// 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 `<repo>/.diarize/models/`. */
+export const CED_DIR = "sherpa-onnx-ced-mini-audio-tagging-2024-04-19";
+export const PIECES_PER_SPEAKER = 12;
+/** 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
+ * `<repo>/.diarize/env/bin/python`), `<repo>/scripts/audio-tag.py`,
+ * `<repo>/.diarize/models/<CED_DIR>/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<string, string | undefined>, 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<string, { scores: number[][] | null, seconds: number, error?: string }> }>}
+ */
+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<typeof resolveTagger>) | null,
+ * scratch: string, window?: number, hop?: number, chunkS?: number, perGroup?: number, ffmpeg?: string,
+ * onProgress?: (e: Record<string, unknown>) => 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: at least PIECE_MIN_S long,
+ * overlapping no other cluster's turn, spread evenly over the stream (sorted
+ * by start, every (len−1)/(n−1)-th), each cut to PIECE_MAX_S from its start.
+ * @param {{ start: number, end: number, speaker: number }[]} turns sorted
+ */
+export function centroidPieces(turns, speaker, n = PIECES_PER_SPEAKER) {
+ const others = turns.filter((t) => t.speaker !== speaker);
+ const clean = turns.filter(
+ (t) => t.speaker === speaker && t.end - t.start >= PIECE_MIN_S && !others.some((o) => o.start < t.end && o.end > t.start),
+ );
+ let picked = clean;
+ if (clean.length > n) {
+ picked = [];
+ for (let k = 0; k < n; k += 1) picked.push(clean[Math.round((k * (clean.length - 1)) / Math.max(1, n - 1))]);
+ }
+ return picked.map((t) => ({ start: t.start, dur: Math.min(PIECE_MAX_S, t.end - t.start) }));
+}
+
+/**
+ * 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<string, unknown>) => void }} o
+ * @returns {Promise<{ version: number, model: string, speakers: Record<string, { centroid: number[] | null, pieces: number, kept: number }> }>}
+ */
+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 items = [];
+ const bySpeaker = new Map();
+ for (const s of speakers) {
+ const pieces = centroidPieces(o.turns, s);
+ 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<string, { centroid: number[] | null, pieces: number, kept: number }>} */
+ 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 };
+}
diff --git a/common/lib/clips/scan.test.ts b/common/lib/clips/scan.test.ts
@@ -0,0 +1,114 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { cosine, encodeWav16 } from "../montage/voiceMatch.mjs";
+import { analyze } from "./clips.mjs";
+import { CED_DIR, centroidPieces, resolveTagger, runAudioScan, speakerCentroids, tagWavs, windowLevels } from "./scan.mjs";
+import { HOST, SUBJECT, reactionAudio, reactionStream } from "../../testing/clips/reactionStream.mjs";
+import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FAKE_TAG = path.join(HERE, "..", "..", "testing", "audio", "fakeAudioTag.mjs");
+const FAKE_EMBED = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs");
+const tmp = () => mkdtempSync(path.join(os.tmpdir(), "clip-scan-"));
+const ffmpeg = hasFfmpeg();
+
+test("resolveTagger: env over settings over the repo's .diarize; available is whether the model is there", () => {
+ const d = resolveTagger({ repoRoot: "/repo", env: {} });
+ assert.deepEqual(d, {
+ python: "/repo/.diarize/env/bin/python",
+ script: "/repo/scripts/audio-tag.py",
+ model: `/repo/.diarize/models/${CED_DIR}/model.int8.onnx`,
+ labels: `/repo/.diarize/models/${CED_DIR}/class_labels_indices.csv`,
+ threads: 1,
+ available: false,
+ });
+ const s = resolveTagger({ repoRoot: "/repo", env: {}, settings: { diarization: { python: "/venv/python" } } });
+ assert.equal(s.python, "/venv/python");
+ const e = resolveTagger({ repoRoot: "/repo", env: { AUDIO_TAG_PYTHON: "node", AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } });
+ assert.deepEqual([e.python, e.script, e.available], ["node", FAKE_TAG, true]);
+ assert.equal(e.labels, path.join(path.dirname(FAKE_TAG), "class_labels_indices.csv"));
+});
+
+test("windowLevels: one level per window, loud where the sound is", () => {
+ const x = new Float32Array(16000 * 4);
+ for (let i = 16000 * 2; i < 16000 * 3; i += 1) x[i] = 0.5 * Math.sin(i / 3);
+ const lv = windowLevels(x, { count: 7 });
+ assert.equal(lv.length, 7);
+ assert.ok(lv[4] > -10 && lv[0] < -100, JSON.stringify(lv));
+});
+
+test("centroidPieces: long turns that overlap nobody, spread over the stream", () => {
+ const turns = [
+ { start: 0, end: 10, speaker: 1 },
+ { start: 9, end: 12, speaker: 0 },
+ { start: 12, end: 13, speaker: 0 },
+ { start: 20, end: 40, speaker: 0 },
+ ];
+ assert.deepEqual(centroidPieces(turns, 0), [{ start: 20, dur: 8 }]);
+ assert.deepEqual(centroidPieces(turns, 1), []);
+ const many = Array.from({ length: 30 }, (_, i) => ({ start: i * 10, end: i * 10 + 3, speaker: 0 }));
+ const picked = centroidPieces(many, 0, 4);
+ assert.deepEqual(picked.map((p) => p.start), [0, 100, 190, 290]);
+});
+
+test("tagWavs + runAudioScan (fake tagger): the laugh is heard where it is, energy everywhere, chunked", { skip: !ffmpeg && "no ffmpeg" }, async () => {
+ const dir = tmp();
+ try {
+ const wav = path.join(dir, "audio.wav");
+ writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 120 })));
+ const tagger = resolveTagger({ repoRoot: dir, env: { AUDIO_TAG_PYTHON: process.execPath, AUDIO_TAG_SCRIPT: FAKE_TAG, AUDIO_TAG_MODEL: FAKE_TAG } });
+ const one = await tagWavs([{ id: "a", wav, window: 1, hop: 0.5 }], tagger, path.join(dir, "s"));
+ assert.equal(one.items.get("a")?.scores?.length, 239);
+ const events: Record<string, unknown>[] = [];
+ const scan = await runAudioScan({ file: wav, duration: 120, tagger, scratch: path.join(dir, "work"), chunkS: 30, perGroup: 2, onProgress: (e) => events.push(e) });
+ assert.equal(scan.windows, 239);
+ assert.equal(scan.energy.length, 239);
+ assert.ok(scan.laugh);
+ const at = (t: number) => scan.laugh![Math.round(t / 0.5)];
+ assert.ok(at(95.5) >= 0.8, `laugh at 95.5: ${at(95.5)}`);
+ assert.ok(at(60) < 0.1 && at(110) < 0.1);
+ assert.equal(scan.model?.file, "fakeAudioTag.mjs");
+ assert.equal(events.filter((e) => e.event === "decode").length, 4);
+ assert.equal(events.filter((e) => e.event === "tag").length, 2);
+ assert.ok(!existsSync(path.join(dir, "work")));
+ // The same scan's laughs through the analysis: the host's laugh at 95.
+ const s = reactionStream();
+ const turns = s.turns.filter((t) => t.start < 120);
+ const a = analyze({ turns, duration: 120, words: s.words.filter((w) => w.end < 120), laughScan: { t0: 0, hop: 0.5, window: 1, scores: scan.laugh } });
+ assert.equal(a.laughSource, "model");
+ assert.equal(a.laughs.length, 1);
+ assert.equal(a.laughs[0].speaker, HOST);
+ assert.ok(Math.abs(a.laughs[0].start - 95) <= 1);
+ // No tagger: energy only.
+ const quiet = await runAudioScan({ file: wav, duration: 120, tagger: null, scratch: path.join(dir, "work2"), chunkS: 60 });
+ assert.equal(quiet.laugh, null);
+ assert.equal(quiet.model, null);
+ assert.deepEqual(quiet.energy, scan.energy);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("speakerCentroids (fake embedder): one centroid per cluster, the two voices apart", { skip: !ffmpeg && "no ffmpeg" }, async () => {
+ const dir = tmp();
+ try {
+ const wav = path.join(dir, "audio.wav");
+ writeFileSync(wav, encodeWav16(reactionAudio({ seconds: 200 })));
+ const s = reactionStream();
+ const turns = s.turns.filter((t) => t.end <= 200);
+ const engine = { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx", threads: 1 };
+ const v = await speakerCentroids({ file: wav, turns, engine, scratch: path.join(dir, "v") });
+ const h = v.speakers[HOST].centroid;
+ const sub = v.speakers[SUBJECT].centroid;
+ assert.ok(h && sub);
+ assert.ok(v.speakers[HOST].pieces >= 2 && v.speakers[SUBJECT].pieces >= 2);
+ assert.ok(cosine(h, sub) < 0.6, `cosine ${cosine(h, sub)}`);
+ assert.ok(!existsSync(path.join(dir, "v")));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/testing/audio/fakeAudioTag.d.mts b/common/testing/audio/fakeAudioTag.d.mts
@@ -0,0 +1,2 @@
+export function toneShare(x: Float32Array, rate: number, hz?: number): number;
+export function fakeProbs(x: Float32Array, rate: number, classes: number[]): number[];
diff --git a/common/testing/audio/fakeAudioTag.mjs b/common/testing/audio/fakeAudioTag.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+// A stand-in for scripts/audio-tag.py (release 35 C1), with its exact command
+// line and JSON — so the laugh scan, its CLI and the app's job run in a test
+// with no python, no sherpa-onnx and no model file.
+//
+// node fakeAudioTag.mjs --model <x> --labels <x> [--threads N] [--classes 16,18,19,20,21] <request.json>
+//
+// It "hears laughter" where a window's sound is mostly the test kit's laugh
+// tone (testing/clips/reactionStream.mjs LAUGH_TONE_HZ, by a Goertzel filter
+// against the window's total energy): 0.8 for the first class (Laughter),
+// 0.05 for the second, 0.01 for the rest; elsewhere 0.01. Deterministic. It
+// is not a sound model. Point AUDIO_TAG_PYTHON at `node` and AUDIO_TAG_SCRIPT
+// at this file (AUDIO_TAG_MODEL at any existing file).
+import { readFileSync } from "node:fs";
+import { pathToFileURL } from "node:url";
+import { LAUGH_TONE_HZ } from "../clips/reactionStream.mjs";
+
+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 };
+}
+
+/** The share of a stretch's energy at `hz` (0..1). */
+export function toneShare(x, rate, hz = LAUGH_TONE_HZ) {
+ if (!x.length) return 0;
+ const w = (2 * Math.PI * hz) / rate;
+ const c = 2 * Math.cos(w);
+ let s1 = 0;
+ let s2 = 0;
+ let total = 0;
+ for (let i = 0; i < x.length; i += 1) {
+ const s0 = x[i] + c * s1 - s2;
+ s2 = s1;
+ s1 = s0;
+ total += x[i] * x[i];
+ }
+ const power = (s1 * s1 + s2 * s2 - c * s1 * s2) / (x.length / 2);
+ return total > 1e-9 ? Math.min(1, power / total) : 0;
+}
+
+export function fakeProbs(x, rate, classes) {
+ const laugh = toneShare(x, rate) > 0.35;
+ return classes.map((_, i) => (laugh ? (i === 0 ? 0.8 : i === 1 ? 0.05 : 0.01) : 0.01));
+}
+
+function main(argv) {
+ let classes = [16, 18, 19, 20, 21];
+ let model = "fake.onnx";
+ const positional = [];
+ for (let i = 0; i < argv.length; i += 1) {
+ const a = argv[i];
+ if (a === "--classes") classes = argv[++i].split(",").filter(Boolean).map(Number);
+ else if (a === "--model") model = argv[++i];
+ else if (a === "--labels" || a === "--threads") i += 1;
+ else positional.push(a);
+ }
+ const req = JSON.parse(readFileSync(positional[0], "utf8"));
+ const items = (req.items ?? []).map((item) => {
+ const rec = { id: item.id, seconds: 0, window: null, hop: null, scores: null };
+ try {
+ const { x, rate } = readWav(item.wav);
+ rec.seconds = Math.round((x.length / rate) * 1000) / 1000;
+ if (item.window == null) rec.scores = [fakeProbs(x, rate, classes)];
+ else {
+ const win = Math.round(item.window * rate);
+ const hop = Math.max(1, Math.round((item.hop ?? item.window) * rate));
+ rec.window = item.window;
+ rec.hop = item.hop ?? item.window;
+ rec.scores = [];
+ for (let a = 0; a + win <= x.length; a += hop) rec.scores.push(fakeProbs(x.subarray(a, a + win), rate, classes));
+ }
+ } catch (e) {
+ rec.error = e instanceof Error ? e.message : String(e);
+ }
+ return rec;
+ });
+ process.stdout.write(JSON.stringify({ model: model.split("/").pop(), version: "fake", classes, names: classes.map(String), items }));
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) main(process.argv.slice(2));
diff --git a/scripts/audio-tag.py b/scripts/audio-tag.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+"""Audio tagging for common/lib/clips/scan.mjs (release 35 C1): the laugh scan.
+
+WAV files in, per-window class probabilities out, as JSON. Nothing else:
+which audio, the windows' clock, the laugh family's sum, the events and the
+cache all live in the .mjs caller, so this file stays a thin shell over
+sherpa-onnx's AudioTagging (CED-mini, AudioSet's 527 classes) — modelled on
+scripts/speaker-embed.py.
+
+stdout is JSON ONLY; progress goes to stderr.
+
+Usage:
+ audio-tag.py --model <model.onnx> --labels <class_labels_indices.csv>
+ [--threads N] [--classes 16,18,19,20,21] <request.json>
+
+request.json: {"items": [{"id": "...", "wav": "/abs/path.wav",
+ "window": 1.0, "hop": 0.5}, ...]}
+ Each wav is 16-bit PCM, mono, 16 kHz (the caller decodes to it). With a
+ `window` (seconds) the wav is scored window by window, every `hop` seconds
+ (default: the window), as many whole windows as fit; without one, the
+ whole wav is one window.
+
+Output: {"model": "<file name>", "version": "<sherpa-onnx>", "classes": [...],
+ "names": [...], "items": [{"id", "seconds", "window", "hop",
+ "scores": [[p, ...], ...] | null, "error"?: "..."}]}
+ `scores` has one row per window, one probability per requested class, in
+ `classes` order, rounded to 4 decimals (the same input prints the same
+ bytes). One thread by default, as speaker-embed.py: a CPU reduction split
+ across threads is where an ONNX run can differ in its last bits.
+"""
+import argparse, csv, json, os, sys, wave
+
+
+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 read_labels(path):
+ names = {}
+ with open(path, "r", encoding="utf8") as f:
+ for row in csv.DictReader(f):
+ names[int(row["index"])] = row["display_name"]
+ return names
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("request")
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--labels", required=True)
+ ap.add_argument("--threads", type=int, default=1)
+ ap.add_argument("--classes", default="16,18,19,20,21")
+ args = ap.parse_args()
+
+ try:
+ import numpy as np
+ import sherpa_onnx
+ except ImportError as e:
+ print(f"audio-tag: missing dependency: {e}", file=sys.stderr)
+ return 3
+
+ classes = [int(c) for c in args.classes.split(",") if c.strip() != ""]
+ names = read_labels(args.labels)
+ with open(args.request, "r", encoding="utf8") as f:
+ req = json.load(f)
+ items = req.get("items") or []
+
+ cfg = sherpa_onnx.AudioTaggingConfig(
+ model=sherpa_onnx.AudioTaggingModelConfig(ced=args.model, num_threads=args.threads),
+ labels=args.labels,
+ top_k=max(len(names), 1),
+ )
+ if not cfg.validate():
+ print("audio-tag: invalid model config", file=sys.stderr)
+ return 2
+ tagger = sherpa_onnx.AudioTagging(cfg)
+
+ def probs(rate, x):
+ stream = tagger.create_stream()
+ stream.accept_waveform(rate, x)
+ by = {e.index: e.prob for e in tagger.compute(stream)}
+ return [round(float(by.get(c, 0.0)), 4) for c in classes]
+
+ out = []
+ done = 0
+ for item in items:
+ rec = {"id": item.get("id"), "seconds": 0.0, "window": None, "hop": None, "scores": None}
+ try:
+ x, rate = read_wav(np, item["wav"])
+ rec["seconds"] = round(x.size / rate, 3)
+ win = item.get("window")
+ if win is None:
+ rec["scores"] = [probs(rate, x)] if x.size else []
+ else:
+ win = float(win)
+ hop = float(item.get("hop") or win)
+ rec["window"] = win
+ rec["hop"] = hop
+ n_win = int(round(win * rate))
+ n_hop = max(1, int(round(hop * rate)))
+ rows = []
+ a = 0
+ while a + n_win <= x.size:
+ rows.append(probs(rate, x[a:a + n_win]))
+ a += n_hop
+ rec["scores"] = rows
+ except Exception as e: # one bad file is that item's error, not the run's
+ rec["error"] = str(e)
+ out.append(rec)
+ done += 1
+ print(f"audio-tag: {done}/{len(items)}", file=sys.stderr, flush=True)
+
+ json.dump(
+ {
+ "model": os.path.basename(args.model),
+ "version": getattr(sherpa_onnx, "__version__", None),
+ "classes": classes,
+ "names": [names.get(c, str(c)) for c in classes],
+ "items": out,
+ },
+ sys.stdout,
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())