Archilyzer · Source

archilyzer

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

commit 78926b667ae9490745719f942a02e905e0e87994
parent df5fbeb2e322fa478a959cdf17129888f7c5139a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 17:55:02 -0400

Merge r34/voice-match: a local speaker score per montage clip (TitaNet-small via the diarization venv; reference = the operator's keeps, else solo uploads), voice-match.json keyed like the deck's rulings, Score the voices on the deck and the Cut tab, umtool voice-match

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

Diffstat:
M.diarize/README.md | 4++++
MENVIRONMENT.md | 3+++
Mcommon/lib/envVars.ts | 3+++
Acommon/lib/montage/voiceMatch.d.mts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/voiceMatch.mjs | 632+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 40++++++++++++++++++++++++++++++++++++++++
Aplans/release-34/voice-match.md | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/speaker-embed.py | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/voice-match/route.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/components/projects/ClipDeckPage.tsx | 11++++++++++-
Mumtool/components/projects/report/CutTab.tsx | 27+++++++++++++++++++++++++++
Aumtool/components/projects/report/VoiceMatchPanel.tsx | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/ClipDeck.tsx | 4++++
Mumtool/docs/cli.md | 1+
Mumtool/docs/report-video.md | 45+++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 35+++++++++++++++++++++++++++++++++++
Aumtool/e2e/voice-match.spec.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/voiceMatch.mjs | 420+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/voiceMatch.test.mjs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 5+++++
Mumtool/report-to-video/package.json | 1+
30 files changed, 2453 insertions(+), 1 deletion(-)

diff --git a/.diarize/README.md b/.diarize/README.md @@ -74,6 +74,10 @@ Absolute paths. `diarize.mjs` records only the BASENAME into the sidecar, becaus the corpus is rsynced between shards and a full path would make records non-portable. +The same `python` and `embModel` run umtool's montage **voice match** +(`umtool voice-match`, `scripts/speaker-embed.py`: WAV segments in, TitaNet +embeddings out), so nothing more needs installing for it. + ## Checking a rebuild reproduces the record on disk Read-only, writes nothing to the corpus. `ObviousRises-rumble/v6z1o2g` is the one diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -106,6 +106,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `DIARIZE_ENGINE_KIND` | `sherpa-onnx` | The diarization engine: `sherpa-onnx` or `sortformer`. | scripts/diarize.mjs | | `DIARIZE_ENGINE_CMD` | the bundled sherpa script | The engine command the wrapper runs. | scripts/diarize.mjs | | `DIARIZE_PYTHON` | `python3` | The python for the default engine. | scripts/diarize.mjs | +| `VOICE_MATCH_PYTHON` | `settings.diarization.python`, else `<repo>/.diarize/env/bin/python` | The program that runs the speaker-embedding script for a montage's voice match: the diarization venv's python. Any program that takes the script's arguments will do; the e2e suite runs the test kit's fake embedder with `node`. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | +| `VOICE_MATCH_SCRIPT` | `<repo>/scripts/speaker-embed.py` | The speaker-embedding script (WAV segments in, L2-normalised embeddings out, JSON). The e2e suite points it at `common/testing/audio/fakeSpeakerEmbed.mjs`. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | +| `VOICE_MATCH_MODEL` | `settings.diarization.embModel`, else `<repo>/.diarize/models/titanet.onnx` | The speaker-embedding ONNX model for the voice match: TitaNet-small, the same file the diarization lane loads. | common/lib/montage/voiceMatch.mjs (`umtool voice-match`) | | `DIARIZE_SEG_MODEL` | — (required) | Segmentation model. The editor passes the settings' value as a flag. | scripts/diarize.mjs | | `DIARIZE_EMB_MODEL` | — (required) | Speaker-embedding model. The editor passes the settings' value as a flag. | scripts/diarize.mjs | | `DIARIZE_THRESHOLD` | `0.5` | Clustering threshold. | scripts/diarize.mjs | diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -142,6 +142,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "DIARIZE_ENGINE_KIND", audience: "runtime", default: "`sherpa-onnx`", readBy: "scripts/diarize.mjs", doc: "The diarization engine: `sherpa-onnx` or `sortformer`." }, { name: "DIARIZE_ENGINE_CMD", audience: "runtime", default: "the bundled sherpa script", readBy: "scripts/diarize.mjs", doc: "The engine command the wrapper runs." }, { name: "DIARIZE_PYTHON", audience: "runtime", default: "`python3`", readBy: "scripts/diarize.mjs", doc: "The python for the default engine." }, + { name: "VOICE_MATCH_PYTHON", audience: "runtime", default: "`settings.diarization.python`, else `<repo>/.diarize/env/bin/python`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The program that runs the speaker-embedding script for a montage's voice match: the diarization venv's python. Any program that takes the script's arguments will do; the e2e suite runs the test kit's fake embedder with `node`." }, + { name: "VOICE_MATCH_SCRIPT", audience: "runtime", default: "`<repo>/scripts/speaker-embed.py`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The speaker-embedding script (WAV segments in, L2-normalised embeddings out, JSON). The e2e suite points it at `common/testing/audio/fakeSpeakerEmbed.mjs`." }, + { name: "VOICE_MATCH_MODEL", audience: "runtime", default: "`settings.diarization.embModel`, else `<repo>/.diarize/models/titanet.onnx`", readBy: "common/lib/montage/voiceMatch.mjs (`umtool voice-match`)", doc: "The speaker-embedding ONNX model for the voice match: TitaNet-small, the same file the diarization lane loads." }, { name: "DIARIZE_SEG_MODEL", audience: "runtime", default: "— (required)", readBy: "scripts/diarize.mjs", doc: "Segmentation model. The editor passes the settings' value as a flag." }, { name: "DIARIZE_EMB_MODEL", audience: "runtime", default: "— (required)", readBy: "scripts/diarize.mjs", doc: "Speaker-embedding model. The editor passes the settings' value as a flag." }, { name: "DIARIZE_THRESHOLD", audience: "runtime", default: "`0.5`", readBy: "scripts/diarize.mjs", doc: "Clustering threshold." }, diff --git a/common/lib/montage/voiceMatch.d.mts b/common/lib/montage/voiceMatch.d.mts @@ -0,0 +1,125 @@ +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>; +export function voiceMatchSummary(doc: VoiceMatchDoc | null): { + madeAt: string; + counts: VoiceMatchDoc["counts"]; + reference: string; +} | null; diff --git a/common/lib/montage/voiceMatch.mjs b/common/lib/montage/voiceMatch.mjs @@ -0,0 +1,632 @@ +// 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; + } +} + +/** + * What a page says about a run: when, the counts, and the reference in words + * ("3 clips ruled keep", "8 solo recordings"). + */ +export function voiceMatchSummary(doc) { + if (!doc) return null; + const ref = doc.reference && typeof doc.reference === "object" ? doc.reference : {}; + const reference = + ref.kind === "rulings" + ? `${Number(ref.kept) || 0} clip${ref.kept === 1 ? "" : "s"} ruled keep` + : `${Array.isArray(ref.recordings) ? ref.recordings.length : 0} solo recording${Array.isArray(ref.recordings) && ref.recordings.length === 1 ? "" : "s"}`; + // Counted from the rows when the file does not carry them (a hand-made or + // older file): a page never trusts a field to be there. + const rows = Object.values(doc.clips ?? {}); + const n = (label) => rows.filter((r) => r && r.label === label).length; + const c = doc.counts && typeof doc.counts === "object" ? doc.counts : {}; + const counts = { + clips: Number.isFinite(c.clips) ? c.clips : rows.length, + scored: Number.isFinite(c.scored) ? c.scored : rows.filter((r) => r && Number.isFinite(r.score)).length, + likely: Number.isFinite(c.likely) ? c.likely : n("likely"), + unsure: Number.isFinite(c.unsure) ? c.unsure : n("unsure"), + unlikely: Number.isFinite(c.unlikely) ? c.unlikely : n("unlikely"), + }; + return { madeAt: typeof doc.madeAt === "string" ? doc.madeAt : "", counts, reference }; +} + +/** Written whole: tmp + rename. */ +export async function writeVoiceMatch(dir, doc) { + const file = path.join(dir, VOICE_MATCH_FILE); + const tmp = `${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 @@ -38,6 +38,7 @@ "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs", "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs", "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.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 { pathToFileURL } from "node:url"; + +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] && pathToFileURL(process.argv[1]).href === import.meta.url; +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/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool scores who is speaking in each montage clip.** A montage's clip deck and its Cut tab have **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every Cut-tab row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him — and the deck puts the doubtful clips first with their scores. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool. - **Rule a montage's clips by ear, and the render leaves out the ones that aren't him.** A report video made of one phrase said many times has a clip deck (the Cut tab's **Clips — n to rule**, at `/projects/<id>/clips`): one card per instance, its cut playing from the cached window (**Wider** plays the whole clip), the quote with the phrase marked, the date and source, the clip's note, and — when a speaker score is beside the manifest — that score. Swipe or press → **Keep**, ← **Cut**, ↓ **Not him** (a co-host, a guest, a clip played), ↑ **Read aloud** (a post or a quote read out); **e** keeps it with a wider phrase, **s** skips, space replays, **z** undoes; a reason chip or a few words go with the ruling. The deck walks the unruled clips, the doubtful ones first, the ruled ones, or all, and works at phone width with the buttons under the thumb. The rulings are `montage-rulings.json` beside the manifest, kept by the moment in the source rather than the clip's number, so seeding the montage again keeps them. A render, and a take, leaves out every clip ruled cut, not him or read aloud (of the cut and of the wall), cuts a clip to its wider phrase, and numbers the kept clips 1 to N; the build log names each clip left out and why. Without a rulings file a render is exactly as before; `--no-rulings` builds every clip. The end of the deck counts the rulings, shows the next render's clips, and **Re-render the take** makes the picked take (or the one whole-cut take) again. A seed's `edits.json` is offered once as **Import earlier rulings**. From a terminal: `umtool rulings <project>` (show, `import`, `set`, `clear`). Nothing calls a model. Needs a restart of umtool. - **Find the next montage phrase in umtool, with no model.** Tools → **Phrases** (`/tools/phrases`) searches several phrases at once across the channels you pick: type plain words (a caption's commas, hyphens and a plural are allowed for) or a regular expression, choose a channel to cut from where it holds the same stream and a pattern to leave out, and press **Search**. It runs as a job with its progress and a Stop. For each phrase you see how many times it was said (a stream and its clip upload counted once), a bar per year, how many are on Rumble and how many elsewhere, how many have a speaker change in the captions, and ten moments spread over the years, each with **Play** and **Transcript** (the lines around it); several phrases are ranked side by side. **Create montage** makes a report-video project from that search, exactly as the new-project form's phrase seed would, and opens it. A catchphrase report's `candidates.json` under the reports folder shows as suggestions. The page remembers your last search. The same search from a terminal: `umtool phrases "<phrase>" … --channels a,b --prefer c`. A second search over the same channels reads a cache and takes seconds instead of most of a minute. Needs a restart of umtool. - **Report videos cut clips from Rumble windows on the right second.** Some downloaded windows (Rumble's) keep their source's clock, so their picture starts a second or two in, and every cut from one landed that much late — in the slow-news montage, one clip's "slow news week" fell into the pause after it. The build now reads where such a window's picture starts and cuts on its own clock (and says so in the build log). In a montage with even loudness, a clip or wall tile that measures near-silent is taken for a phrase looked for in the wrong place: it is found again by the sound — the speech nearest where it was expected — recorded, said in the log, and never boosted from silence. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10560,3 +10560,43 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `CHANNEL_SLUG_RE` (`/^[A-Za-z0-9][A-Za-z0-9._-]*$/`): mixed-case channel dirs (HasanAbiVODs3) were refused before. - Suggestions: `UMTOOL_PHRASE_CANDIDATES` (`:`-separated paths) else every `<REPORTS_ROOT>/<dir>/candidates.json` with `scanned: [{key, regex, instances?, spark?}]` (the catchphrase report's shape). + +## Release 34 lane N2: the voice match (verified 2026-10-18, branch `r34/voice-match`) + +- **`<project>/voice-match.json`** `{version: 1, model: "titanet-small", engine {file, sherpaOnnx, dim 192, + sampleRate 16000}, madeAt, thresholds {likely 0.42, unlikely 0.3}, gate {…}, reference {kind "rulings" | "recordings", + kept, dropped[], trim 0.15, + rulings/embedded | recordings[{channel, video, date, title}]/pieces/seconds 60/ + pieceSeconds 10, skipped?}, counts {clips, scored, likely, unsure, unlikely}, span, clips: {<clipMomentKey>: {score + 0..1 | null, label | null, speechSeconds, best?, id?, via "words"|"cues"|"cut", fallback?, inReference?, why?, + from? "instances"}}}`. Keyed by N1's `clipMomentKey`. One writer: `writeVoiceMatch` (tmp + rename), whole file per + run. `readVoiceMatch` accepts any `{version: 1, clips: {}}`; `voiceMatchSummary` recounts from the rows when a file + has no `counts` (N1's deck fixture writes one without). +- **The pipeline** (`common/lib/montage/voiceMatch.mjs`, plain ESM + .d.mts, export `./lib/montage/voiceMatch.mjs`): + ffmpeg decodes the span at 16 kHz mono (`-ss` before `-i`); the gate keeps 20 ms frames ≥ max(−50 dBFS, p90 − 22 dB), + bridges pauses ≤ 0.12 s, drops runs < 0.1 s; under 0.8 s voiced → unscored ("too little speech"); a phrase span under + 1.5 s voiced is decoded again from the clip's cut ± 1 s and the one with more speech wins (`fallback: true`). The + voiced samples go to `scripts/speaker-embed.py` as 16-bit wavs (one process, one thread, embeddings rounded to 6 dp: + two runs of the slow-news project are identical but for `madeAt`). Score = cosine to the robust centroid (mean, drop + items < median − 0.15, mean again), clamped 0..1; `best` = max over kept items; a rulings reference is leave-one-out. +- **The span** (`umtool/lib/report/voiceMatch.mjs` `clipSpan`): the phrase (`montage.match` / `onscreen.title`) + located with report-to-video/montage.mjs `locatePhrase` in whisper.cpp token words (`transcript.json`) else the cues, + within the cut ± 0.5 s, padded ± 1 s; else the cut ± 1 s. The file is `sources.mjs` `resolveLocalSource` (raw cache, + corpus window, saved video, audio — audio admitted), on its own clock (`clockOffset` = build-video's `startOffset` + rule). report-to-video exports `./montage` for it. +- **Reference recordings** when < 3 keeps (or `--reference recordings`): every video of the project's clip channels + (`--reference-channel` overrides) with a whole source on disk (`saved-video.json`, `source-media.*`, `audio.*`) whose + `transcript.cues.json` passes `soloRecordingWhy` (source `vtt`, no `>>` in any cue, not `isLivestream`, title not + matching `COHOST_TITLE_RE`, duration ≥ 90 s); `pickReferenceRecordings` takes 8 spread evenly by upload date; each + gives 6 × 10 s pieces from its first cue's start. On slow-news: 8 the-quartering uploads 2017–2026; the trim dropped + all six pieces of 3 of them (15 of 48) — their first minute is not (only) him; 33 kept. +- **Measured on slow-news** (copy, 2026-10-18; 73 clips + the instance list): 35–38 s wall, 310 MB max RSS, nice'd. + The two clips ruled another speaker: `ynWQxASVthg@3127.54` (the dropped s04, scored from `instances.json`) 0.241, + `v70yc82@3597.60` (s56, was #58) 0.005. Solo uploads (s01–s12, s26, s27, s29, s31, s60) 0.432–0.765. With a + simulated rulings reference (14 solo keeps) the same two: 0.185 and unlikely. Phrase ± 1 s separates better than the + cut ± 1 s (ynWQ 0.241 vs 0.338) and better than ± 1.5 s (0.337). +- **Job**: `/api/report/voice-match` POST `{project, reference?}` → `voiceMatchSteps` → one lib/jobs.ts step `nice -n + 10 node umtool/bin/umtool.mjs voice-match <id> --reference <mode> --progress ndjson` (events `{ev: "voice-match", + phase: plan|decode|embed|done}`); no heavy slot. Scratch is `<project>/.voice-match-work` (never /tmp), removed by the + run and by the next. Engine: `VOICE_MATCH_PYTHON` / `_SCRIPT` / `_MODEL` (ENVIRONMENT.md), else + `settings.diarization.python` / `.embModel` (read from `SETTINGS_FILE` or `<repo>/settings.json`), else `.diarize/`. + The e2e runs `common/testing/audio/fakeSpeakerEmbed.mjs` with node. diff --git a/plans/release-34/voice-match.md b/plans/release-34/voice-match.md @@ -0,0 +1,154 @@ +# Release 34 lane N2 — `r34/voice-match`: who is speaking, per montage clip (as shipped) + +An aid to the operator's ear for the co-host hazard: a local speaker-similarity score per montage clip, so the clip +deck (N1) puts the doubtful ones first. Deterministic for a given model and input; no network; no LLM; nothing rules. +Rulings followed: the UI works with no model you talk to (a button on the deck and the Cut tab; every CLI step has +it); the verification is still a person listening; records state rulings; synthetic fixtures only; no corpus writes +(the real run read the corpus windows from a copy of the project, read-only). + +## What + +1. **`scripts/speaker-embed.py`** — WAV segments in, L2-normalised TitaNet-small embeddings out (JSON), through the + sherpa-onnx `SpeakerEmbeddingExtractor` diarize-sherpa.py already loads; one thread, 6 decimals. +2. **`common/lib/montage/voiceMatch.mjs`** (+ .d.mts): decode a span at 16 kHz mono (ffmpeg, the window's own clock); + the voiced-frames gate (energy relative to the span's loud frames: the phrase, not the gap after it); a fallback + span when the phrase holds under 1.5 s of speech; one embedding process per run; score = cosine to a robust + reference centroid (0..1) and the best reference item; labels likely ≥ 0.42 > unsure ≥ 0.30 > unlikely; the solo- + recording heuristic (`soloRecordingWhy`, `pickReferenceRecordings`); `readVoiceMatch` / `writeVoiceMatch` / + `voiceMatchSummary`. Test kit: `testing/audio/syntheticVoice.mjs` (two voices TitaNet separates: ~0.98 within, + ~0.63 across) and `testing/audio/fakeSpeakerEmbed.mjs` (the script's contract, no python or model). +3. **`umtool voice-match <project>`** (`umtool/lib/report/voiceMatch.mjs`): each clip's phrase ± 1 s found as the + montage render finds it (whisper words, then cues), else the cut ± 1 s; the file the render cuts from + (sources.mjs); the reference = the clips ruled keep in `montage-rulings.json` (≥ 3, leave-one-out) else solo + recordings on disk (`--reference`, `--reference-video`, `--reference-channel`); `--instances` scores a phrase scan's + instances not in the manifest; `--dry`, `--json`, `--span`, `--pad`, `--likely/--unlikely`, `--out`. Keys are N1's + `clipMomentKey`. report-to-video exports `./montage`. +4. **The UI**: `/api/report/voice-match` (one nice'd lib/jobs.ts job running the CLI; GET summary / job; cancel); + `VoiceMatchPanel` — **Score the voices** with a reference picker — on the clip deck's head (`voicePanel`, additive + to N1's ClipDeck) and on the Cut tab, whose rows show `voice 0.43 · unsure`. +5. **Docs**: umtool/docs/report-video.md "Who is speaking: the voice match", cli.md row, CHANGELOG bullet, + ENVIRONMENT.md (`VOICE_MATCH_PYTHON` / `_SCRIPT` / `_MODEL`), `.diarize/README.md` note, FACTS section, test kit + README rows. + +## Commits + +| sha | what | +|---|---| +| `595130ff` | common: voice match lib, speaker-embed.py, test kit, unit tests | +| `a268ea2e` | umtool: `umtool voice-match`, the job route, the panel, the Cut-tab chip | +| `8500888c` | umtool: e2e `voice-match.spec.ts` + fixture (`voice-fixture`, fake engine env) | +| `4b13d8a4` | docs + ENVIRONMENT.md declarations; scratch beside the project | +| `dcbd270b` | the fake embedder's main check without a cwd-derived path (next-build-trace) | +| `a0635a20` | merge main (N1): clipMomentKey keys, deck panel, lenient summary | +| (this) | plans: record + FACTS; docs mention the deck | + +## Gates (all through the shared lock, from the worktree root) + +- tsc (all packages): clean before each code commit and after the merge. +- common: **4606 (main) → 4617 (4615 pass, 0 fail, 2 skipped)**: +11 voiceMatch (one, the real-TitaNet test, skips + without `VOICE_MATCH_PYTHON` + `VOICE_MATCH_MODEL`; run with them: 11/11). +- test:scripts: **1160 (main after N1) → 1163 (1159 pass, 0 fail, 4 skipped)**: +3 voiceMatch.test.mjs. +- umtool `test`: 45/45 (none of mine in its globs). +- `archilyzer docs env --check`, `docs files --check`, `docs cli --check`: clean (ENVIRONMENT.md regenerated). +- e2e umtool, single specs: `voice-match.spec.ts` 2/2 (18.8 s); `takes.spec.ts` + `projects.spec.ts` 30/30; after + the merge `voice-match.spec.ts` (3 tests now, incl. the deck) + `clip-deck.spec.ts` 5/5 (first run: the deck's 2 + failed on my summary reading a hand-made file with no `counts`; fixed with `voiceMatchSummary`). + +## The real run (a copy of the slow-news project, corpus read-only) + +Engine the primary's `.diarize` venv + TitaNet; reference: recordings (no rulings file yet) — 8 the-quartering +uploads 2017–2026, 48 pieces, 33 kept (all of 3 uploads' first minutes trimmed). 75 of 80 scored (73 clips + 7 +instances; 5 instances have no window on disk), 35–38 s, 310 MB. Two runs identical but for `madeAt`. + +- Distribution: 0–0.1: 3 · 0.2–0.3: 1 · 0.3–0.42: 4 · 0.42–0.5: 1 · 0.5–0.6: 3 · 0.6–0.7: 21 · 0.7–0.8: 36 · + 0.8–0.9: 6. Median 0.71. +- **The two ruled another speaker: `ynWQxASVthg@3127.54` (old #4, dropped from the manifest, scored from + instances.json) 0.241 unlikely; `v70yc82@3597.60` (s56, old #58) 0.005 unlikely.** Solo uploads all likely + (0.432 s05 … 0.765). m69i-maW88g@454 (him reading a tweet, ruled out by the operator) 0.527 likely — a voice match + cannot tell read-aloud, which is the deck's verdict to make. +- Also unlikely: s39 (0.071), s40 (0.000); unsure: s44 0.319, s45 0.392, s46 0.398, s66 0.405 — for the ear. + +### Score table + +| clip | source moment | score | best | label | speech s | span | +|---|---|---|---|---|---|---| +| s01 | `the-quartering/f8GaZP7tL-8@2.91` | 0.676 | 0.623 | likely | 2.34 | cues | +| s02 | `the-quartering/qU1ioyPGsqc@871.82` | 0.662 | 0.650 | likely | 2.58 | cues | +| s03 | `the-quartering/O_7BC0kNCGs@659.58` | 0.765 | 0.709 | likely | 2.42 | cues | +| s04 | `the-quartering/6-VGIqjM3gI@12.36` | 0.763 | 0.756 | likely | 2.82 | cues | +| s05 | `the-quartering/Ov35xvnPgOs@84.10` | 0.432 | 0.454 | likely | 2.46 | cues | +| s06 | `the-quartering/QncOdQy3jCw@609.18` | 0.637 | 0.707 | likely | 2.06 | cues | +| s07 | `the-quartering/orJMUSV76Po@364.88` | 0.712 | 0.725 | likely | 2.14 | cues | +| s08 | `the-quartering/wFBfJahTWUs@27.36` | 0.732 | 0.725 | likely | 2.24 | cues | +| s09 | `the-quartering/ko1wAJKPtdg@162.96` | 0.716 | 0.696 | likely | 2.62 | cues | +| s10 | `the-quartering/icnzB70f_bE@51.12` | 0.732 | 0.698 | likely | 2.72 | cues | +| s11 | `the-quartering/NjtQ8Dyqnwk@4.96` | 0.749 | 0.739 | likely | 2.34 | cues | +| s12 | `the-quartering/y5MocPVTv9A@49.36` | 0.715 | 0.719 | likely | 2.66 | cues | +| s13 | `the-quartering-rumble/vhyhaz@66.64` | 0.744 | 0.722 | likely | 2.46 | words | +| s14 | `the-quartering-rumble/vpdtvn@649.04` | 0.643 | 0.759 | likely | 2.84 | words | +| s15 | `the-quartering-rumble/vpdt0v@11.62` | 0.787 | 0.752 | likely | 2.24 | words | +| s16 | `cornbreadman/38e650fa36b36b1c344b73f68654ec511da706ae@1606.00` | 0.709 | 0.707 | likely | 1.9 | cues | +| s17 | `the-quartering-rumble/v14d52c@3.92` | 0.663 | 0.662 | likely | 2.52 | words | +| s18 | `the-quartering-rumble/v1d1qso@1239.06` | 0.723 | 0.729 | likely | 2.2 | words | +| s19 | `the-quartering-rumble/v1i1sgy@4664.56` | 0.762 | 0.762 | likely | 2.14 | words | +| s20 | `the-quartering-rumble/v28xqot@178.98` | 0.703 | 0.679 | likely | 2.2 | words | +| s21 | `the-quartering-rumble/v2bc8kr@4223.52` | 0.682 | 0.645 | likely | 2.42 | words | +| s22 | `the-quartering-rumble/v2car0l@526.84` | 0.790 | 0.744 | likely | 2.72 | words | +| s23 | `the-quartering-rumble/v2cjwi9@2132.96` | 0.750 | 0.758 | likely | 2.24 | words | +| s24 | `the-quartering-rumble/v2cjwi9@2560.16` | 0.662 | 0.693 | likely | 2.84 | words | +| s25 | `cornbreadman/695d11f47b1f7286d46ce420a3d742217e7378d9@1305.52` | 0.654 | 0.645 | likely | 2.3 | cues | +| s26 | `the-quartering/g8BAomXSTaQ@488.16` | 0.737 | 0.684 | likely | 2.46 | cues | +| s27 | `the-quartering/dXhMvZA5ef8@8.28` | 0.668 | 0.685 | likely | 2.38 | cues | +| s28 | `cornbreadman/316031cdedff41b62278f3577b3fee9a1de6de5a@3796.08` | 0.724 | 0.717 | likely | 2.86 | cues | +| s29 | `the-quartering/JkgzGFb0Ju8@4.56` | 0.745 | 0.736 | likely | 2.54 | cues | +| s30 | `cornbreadman/9251b6222d97900140dd5d670e76eeeae888c2b3@2402.32` | 0.638 | 0.650 | likely | 2 | cues | +| s31 | `the-quartering/2z0R2352Ysw@334.86` | 0.560 | 0.597 | likely | 2.2 | cues | +| s32 | `the-quartering-rumble/v32pn0y@5335.80` | 0.736 | 0.772 | likely | 2.22 | words | +| s33 | `the-quartering-rumble/v3lp5dz@2513.90` | 0.710 | 0.673 | likely | 2.2 | words | +| s34 | `the-quartering-rumble/v3pwxwa@3810.00` | 0.813 | 0.754 | likely | 3.54 | words | +| s35 | `cornbreadman/08f1f447c258b92ad639e865efc7629cfef91073@2989.84` | 0.761 | 0.746 | likely | 2.54 | cues | +| s36 | `the-quartering-rumble/v4aaixo@2732.16` | 0.601 | 0.650 | likely | 3.48 | words (fallback) | +| s37 | `the-quartering-rumble/v4aqir9@3463.84` | 0.723 | 0.738 | likely | 2.6 | words | +| s38 | `the-quartering-rumble/v4dl2pq@6331.00` | 0.756 | 0.749 | likely | 2.8 | words (fallback) | +| s39 | `the-quartering-rumble/v4sw6ck@3218.08` | 0.071 | 0.151 | unlikely | 5.26 | cut | +| s40 | `the-quartering-rumble/v4wsyvo@5195.52` | 0.000 | 0.000 | unlikely | 2.18 | words | +| s41 | `the-quartering-rumble/v518ptn@1175.00` | 0.593 | 0.579 | likely | 2.42 | words | +| s42 | `the-quartering-rumble/v5fakjf@554.54` | 0.670 | 0.644 | likely | 2.26 | words | +| s43 | `the-quartering-rumble/v5fakjf@2132.16` | 0.667 | 0.646 | likely | 2.58 | words | +| s44 | `the-quartering-rumble/v5jl6o5@8651.64` | 0.319 | 0.367 | unsure | 2.36 | words | +| s45 | `the-quartering-rumble/v64wgr1@53.46` | 0.392 | 0.435 | unsure | 2.76 | words | +| s46 | `the-quartering-rumble/v64wgr1@3516.58` | 0.398 | 0.429 | unsure | 5.48 | words (fallback) | +| s47 | `the-quartering-rumble/v69py5m@55.00` | 0.804 | 0.786 | likely | 2.56 | words | +| s48 | `the-quartering-rumble/v6r8iru@2329.98` | 0.694 | 0.680 | likely | 2.18 | words | +| s49 | `the-quartering-rumble/v6r8iru@5847.82` | 0.686 | 0.658 | likely | 2.16 | words | +| s50 | `the-quartering-rumble/v6sqr91@96.48` | 0.769 | 0.691 | likely | 1.66 | words | +| s51 | `the-quartering-rumble/v6ss2d5@1091.68` | 0.729 | 0.705 | likely | 2.2 | words | +| s52 | `the-quartering-rumble/v6ss2d5@1099.84` | 0.639 | 0.647 | likely | 2.18 | words | +| s53 | `the-quartering-rumble/v6yjkwk@3351.24` | 0.668 | 0.672 | likely | 1.76 | words | +| s54 | `the-quartering-rumble/v6zrrlq@3297.76` | 0.767 | 0.754 | likely | 2.1 | words | +| s55 | `the-quartering-rumble/v70yc82@3528.48` | 0.760 | 0.718 | likely | 2.36 | words | +| s56 | `the-quartering-rumble/v70yc82@3597.60` | 0.005 | 0.069 | unlikely | 3.42 | words | +| s57 | `the-quartering-rumble/v7857kg@3469.54` | 0.708 | 0.731 | likely | 2.66 | words | +| s58 | `the-quartering-rumble/v786x5i@1045.16` | 0.804 | 0.799 | likely | 2.66 | words | +| s59 | `the-quartering-rumble/v79j3r8@474.00` | 0.821 | 0.785 | likely | 2 | words | +| s60 | `the-quartering/GuRHjN2e1kE@769.48` | 0.602 | 0.635 | likely | 2.28 | cues | +| s61 | `the-quartering-rumble/v79jnqy@7134.08` | 0.751 | 0.736 | likely | 1.96 | words | +| s62 | `the-quartering-rumble/v79sihy@3833.64` | 0.744 | 0.759 | likely | 2.5 | words | +| s63 | `the-quartering-rumble/v7arhpy@7288.00` | 0.708 | 0.699 | likely | 1.64 | cues | +| s64 | `the-quartering-rumble/v7arhpy@7304.32` | 0.611 | 0.652 | likely | 1.72 | cues | +| s65 | `the-quartering-rumble/v7cofng@455.92` | 0.775 | 0.796 | likely | 2.08 | cues | +| s66 | `the-quartering-rumble/v7d5pl6@2260.24` | 0.405 | 0.467 | unsure | 2.64 | cues | +| s67 | `the-quartering-rumble/v7dcdd6@2606.64` | 0.806 | 0.795 | likely | 2.38 | cues | +| s68 | `the-quartering-rumble/v7fsm4y@351.04` | 0.605 | 0.610 | likely | 1.66 | cues | +| s69 | `the-quartering-rumble/v7fucc4@293.20` | 0.731 | 0.721 | likely | 2.56 | cues | +| s70 | `the-quartering-rumble/v7fucc4@357.52` | 0.804 | 0.831 | likely | 7.2 | cues (fallback) | +| s71 | `the-quartering-rumble/v7fw0t0@2590.72` | 0.618 | 0.657 | likely | 1.46 | cues (fallback) | +| s72 | `the-quartering-rumble/v7gh5pq@2728.64` | 0.725 | 0.760 | likely | 2.64 | cues | +| s73 | `the-quartering-rumble/v7gh5pq@4851.12` | 0.714 | 0.756 | likely | 2.66 | cues | +| — | `the-quartering/ynWQxASVthg@3127.54` | 0.241 | 0.288 | unlikely | 2.18 | cues | +| — | `the-quartering/m69i-maW88g@454.26` | 0.527 | 0.617 | likely | 1.82 | cues | +| — | `the-quartering-rumble/v2ljh5d@488.72` | | | no local window | 0 | words | +| — | `the-quartering-rumble/v2lpc5x@6.72` | | | no local window | 0 | words | +| — | `the-quartering-rumble/v2mqmp1@3.96` | | | no local window | 0 | words | +| — | `the-quartering-rumble/v2zfc20@335.60` | | | no local window | 0 | words | +| — | `the-quartering-rumble/v475edo@2987.00` | | | no local window | 0 | words | 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()) diff --git a/umtool/app/api/report/voice-match/route.ts b/umtool/app/api/report/voice-match/route.ts @@ -0,0 +1,64 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readVoiceMatch } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { voiceMatchSteps } from "@/lib/report/voiceMatch.mjs"; + +export const dynamic = "force-dynamic"; + +// WHO IS SPEAKING, PER MONTAGE CLIP (release 34) -- the Cut tab's "Score the +// voices", as ONE job on the app's runner (lib/jobs.ts: one at a time, a log, +// the NDJSON events, Cancel). The job runs the CLI (`umtool voice-match`), so +// the button and a terminal do the same thing. Local and light (TitaNet-small +// on a few seconds a clip, nice'd): no heavy slot, no network, no LLM. +// +// GET ?job=<id>[&since=&sinceEvent=] that job +// GET ?project=<id> the project's voice-match.json summary, and the job running, if any +// POST { project, reference?: "auto" | "rulings" | "recordings" } +// ?cancel=<job> stop it; nothing is written until the run is done +export async function GET(request: Request) { + const url = new URL(request.url); + const headers = { "cache-control": "no-store" }; + const id = url.searchParams.get("job"); + if (id) { + const job = getJob(id); + if (!job) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const project = await projectRef(String(url.searchParams.get("project") ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const doc = await readVoiceMatch(project.dir); + const running = runningJob(); + return Response.json( + { + voiceMatch: doc ? { madeAt: doc.madeAt, counts: doc.counts, reference: doc.reference, thresholds: doc.thresholds } : null, + running: running && running.project === project.id && running.kind.startsWith("voice-match ") ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const { cancelJob } = await import("@/lib/jobs"); + return Response.json({ cancelled: cancelJob(cancel) }); + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "voices are scored for a report video" }, { status: 400 }); + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + const plan = voiceMatchSteps(project, { reference: typeof body.reference === "string" ? body.reference : undefined }); + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -54,6 +54,8 @@ // the clip deck's montage rulings (release 34) // umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] // [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass) +// umtool voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json] +// a speaker-similarity score per montage clip -> <project>/voice-match.json import process from "node:process"; import { PROJECT_KINDS, @@ -726,6 +728,8 @@ function usage() { " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]", " how often each phrase was said, by year, in one pass (the phrase finder's search)", + " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", + " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json", " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", @@ -766,6 +770,8 @@ const COMMANDS = { rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // The phrase finder (release 34): lib/phrase-finder/cli.mjs. phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))), + // Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs. + "voice-match": async () => process.exit(await (await import("../lib/report/voiceMatch.mjs")).voiceMatchCommand(argv.slice(argv.indexOf("voice-match") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx @@ -5,6 +5,8 @@ import { pieceHrefOfProject } from "@/lib/pieces/article"; import type { ProjectRef } from "@/lib/project-types"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import ClipDeck from "./review/ClipDeck"; +import VoiceMatchPanel from "./report/VoiceMatchPanel"; +import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; // `/projects/<project>/clips` -- THE CLIP DECK (release 34 N1): a montage's // every instance, one card at a time, its cut playing, ruled by ear: keep, cut, @@ -39,7 +41,14 @@ export default async function ClipDeckPage({ project, show }: { project: Project : "unruled"; return ( <BenchFrame kind="clips" top={top}> - <ClipDeck project={project.id} view={view} initialShow={initialShow} back={back} takesHref={takesHref(project.id)} /> + <ClipDeck + project={project.id} + view={view} + initialShow={initialShow} + back={back} + takesHref={takesHref(project.id)} + voicePanel={<VoiceMatchPanel project={project.id} summary={voiceMatchSummary(await readVoiceMatch(project.dir))} reload />} + /> </BenchFrame> ); } diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -14,6 +14,9 @@ import FetchUnfetchedButton from "../FetchUnfetchedButton"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; +import VoiceMatchPanel from "./VoiceMatchPanel"; +import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. @@ -63,6 +66,13 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return montage.filter((e) => !doc.rulings[keys.get(e.id) ?? ""]).length; }) : 0; + // Who is speaking, per clip (release 34): voice-match.json, keyed by the + // source moment (clipMomentKey, the rulings' key), so a re-seed keeps its scores. + const voices = await readVoiceMatch(project.dir); + const voiceOf = (e: Record<string, unknown>) => { + const key = voices ? (clipMomentKey({ ...e, type: "clip" }, m) as string | null) : null; + return key ? voices!.clips[key] ?? null : null; + }; // ---- what a clip's "mix" link opens --------------------------------------- // @@ -157,6 +167,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor Make takes </Link> )} + {clips.length > 0 && ( + <VoiceMatchPanel + project={project.id} + summary={voiceMatchSummary(voices)} + /> + )} </div> {/* --- the timeline --------------------------------------------- */} @@ -244,6 +260,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </Pill> )} {e.segment && <Pill>segment built</Pill>} + {(() => { + const v = voiceOf(e); + if (!v) return null; + return ( + <span data-voice={v.label ?? "unscored"} data-voice-score={v.score ?? ""}> + <Pill tone={v.label === "unlikely" ? TONE.blocking : v.label === "unsure" ? TONE.open : TONE.info}> + {typeof v.score !== "number" ? `voice: ${v.why ?? "not scored"}` : `voice ${v.score.toFixed(2)} · ${v.label}`} + </Pill> + </span> + ); + })()} {!e.hasCues && ( <Pill tone={TONE.blocking}>no cues</Pill> )} diff --git a/umtool/components/projects/report/VoiceMatchPanel.tsx b/umtool/components/projects/report/VoiceMatchPanel.tsx @@ -0,0 +1,159 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import { JobProgress } from "@/components/ui/job-progress"; + +// --------------------------------------------------------------------------- +// "Score the voices" (release 34): who is speaking, per montage clip. +// +// One job (`umtool voice-match <project>`, lib/report/voiceMatch.mjs): each +// clip's phrase, voiced frames only, against the host's voice — the clips +// ruled keep when there are three, else solo recordings on disk. Local +// (TitaNet-small through sherpa-onnx) and light: no network, no LLM. +// +// It is an aid to the ear and says so: the score sorts and flags; the ruling +// is still a person listening. The rows below show each clip's score once a +// run has written voice-match.json. +// --------------------------------------------------------------------------- + +type JobView = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[]; events: Record<string, unknown>[] }; + +export type VoiceMatchSummary = { + madeAt: string; + counts: { clips: number; scored: number; likely: number; unsure: number; unlikely: number }; + reference: string; +}; + +const REFERENCES = [ + ["auto", "keeps, else solo recordings"], + ["rulings", "the clips ruled keep"], + ["recordings", "solo recordings on disk"], +] as const; + +export default function VoiceMatchPanel({ + project, + summary, + reload = false, +}: { + project: string; + summary: VoiceMatchSummary | null; + /** Reload the page when the run is done (the clip deck keeps its cards in state). */ + reload?: boolean; +}) { + const router = useRouter(); + const [reference, setReference] = useState<string>("auto"); + const [job, setJob] = useState<JobView | null>(null); + const [error, setError] = useState<string | null>(null); + const alive = useRef(true); + useEffect(() => () => void (alive.current = false), []); + + async function watch(id: string) { + for (;;) { + await new Promise((r) => setTimeout(r, 1000)); + if (!alive.current) return; + const r = await fetch(`/api/report/voice-match?job=${encodeURIComponent(id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as (JobView & { error?: string | null }) | null; + if (!r.ok || !j || !j.state) { + setError(j?.error ?? "the job is gone"); + return; + } + setJob(j); + if (j.state !== "running") { + if (j.state === "done") { + if (reload) window.location.reload(); + else router.refresh(); + } + return; + } + } + } + + async function start() { + setError(null); + const r = await fetch("/api/report/voice-match", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, reference }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string }; + if (!r.ok || !j.job) { + setError(j.error ?? `HTTP ${r.status}`); + return; + } + setJob(j.job); + void watch(j.job.id); + } + + const running = job?.state === "running"; + const last = [...(job?.events ?? [])].reverse().find((e) => e.ev === "voice-match") as { phase?: string; n?: number; of?: number } | undefined; + return ( + <div data-voice-match-panel="" className="flex flex-col items-start gap-1"> + <div className="flex flex-wrap items-center gap-2"> + <button + type="button" + data-action="voice-match" + data-state={running ? "busy" : job?.state ?? "idle"} + disabled={running} + onClick={() => void start()} + className={buttonVariants({ size: "sm" })} + > + {running ? "Scoring the voices…" : summary ? "Score the voices again" : "Score the voices"} + </button> + <label className="flex items-center gap-1 text-[11px] text-text-2"> + reference + <select + data-voice-reference="" + value={reference} + disabled={running} + onChange={(e) => setReference(e.target.value)} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-1 py-0.5 text-[11px]" + > + {REFERENCES.map(([v, label]) => ( + <option key={v} value={v}> + {label} + </option> + ))} + </select> + </label> + </div> + {summary && ( + <span data-voice-summary="" className="num text-[11px] text-[var(--color-dim)]"> + voices: {summary.counts.likely} likely · {summary.counts.unsure} unsure · {summary.counts.unlikely} unlikely of{" "} + {summary.counts.scored} scored · against {summary.reference} + {summary.madeAt ? ` · ${summary.madeAt.slice(0, 16).replace("T", " ")}` : ""} + </span> + )} + {job && ( + <JobProgress + data-voice-job={job.id} + label="score the voices" + state={job.state} + status={ + job.state === "running" + ? last?.phase === "decode" && last.n + ? `reading clip ${last.n} of ${last.of}` + : last?.phase === "embed" + ? "embedding" + : "planning" + : `${job.state}${job.error ? ` — ${job.error}` : ""}` + } + log={job.state === "failed" ? job.log.slice(-12) : undefined} + logLabel="voice-match log" + onCancel={ + running + ? () => void fetch(`/api/report/voice-match?cancel=${encodeURIComponent(job.id)}`, { method: "POST" }) + : undefined + } + /> + )} + {error && ( + <p data-voice-error="" role="alert" className="text-[12px] text-reject-text"> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx @@ -111,12 +111,15 @@ export default function ClipDeck({ initialShow, back, takesHref, + voicePanel = null, }: { project: string; view: ClipDeckView; initialShow: ClipDeckShow; back: string; takesHref: string; + /** Release 34 N2's "Score the voices" (VoiceMatchPanel), shown in the head. */ + voicePanel?: React.ReactNode; }) { const cards = view.cards; const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]); @@ -449,6 +452,7 @@ export default function ClipDeck({ voice match: {view.voiceMatch.count} clips scored{view.voiceMatch.model ? ` · ${view.voiceMatch.model}` : ""} </p> )} + {voicePanel} </div> ); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -44,6 +44,7 @@ Inbox cannot disagree about what is wrong with one. | `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | +| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | A project argument is an exact id, a directory, or a **unique** basename. Two projects answering to one name is reported, never resolved by picking one. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -860,6 +860,51 @@ the picked take (or the one whole-cut take) again with them. A seed's `edits.json` (its `exclude` and `match` lists) is offered once as **Import earlier rulings**. The same writer is `umtool rulings` ([cli.md](cli.md)). +### Who is speaking: the voice match + +A montage of one phrase is also a montage of everyone who said it near the host: +a co-host's "slow news day", a guest's answer, a post read aloud. **Score the +voices** on the clip deck or the Cut tab (or `umtool voice-match <project>`) scores every clip's +voice against the host's, locally, and writes `voice-match.json` beside the +manifest; each row then shows `voice 0.43 · unsure`. It is an aid to the ear: +the audition deck puts the doubtful clips first and the ruling is still yours. +Nothing here is a model you talk to, and nothing leaves the machine. + +- **What is scored:** the clip's phrase ± 1 s — found the way the montage + render finds it (whisper's word timings, else the captions) — read from the + file the render would cut from, voiced frames only. When the phrase's + seconds hold under 1.5 s of speech (word timing on a pause, a window whose + sound runs late) the clip's cut ± 1 s is scored instead (`fallback: true`). +- **The host's voice (the reference):** the clips you ruled **keep** in the + audition deck (`montage-rulings.json`), once there are three — each of them + scored against the others. Before that, solo recordings found on disk: the + first 60 s of speech of up to 8 uploads of the project's channels with their + sound or video on disk, spread over the years, each a captioned upload (only + captions mark a speaker change) with no `>>` in its captions, not a + livestream, and no second voice in its title ("with", "ft.", "interview", + "debate", "podcast", …). Ten-second pieces far from the rest (a clip played in + the video, an intro) are dropped before the reference is made. The reference + picker (auto / the clips ruled keep / solo recordings) beside the button, or + `--reference`, chooses; `--reference-video <channel>/<id>` names the + recordings yourself. +- **The labels:** `likely` at 0.42 or over, `unlikely` under 0.30, `unsure` + between (cosine similarity to the reference, 0–1). Measured on the slow-news + montage: the solo uploads all came out likely, the two lines the operator + ruled another speaker came out at 0.24 and 0.005. `--likely` / `--unlikely` + move them for a run. +- **The engine:** TitaNet-small through sherpa-onnx, the diarization lane's own + venv and model (`settings.diarization.python` / `.embModel`, else + `.diarize/`), one process for the whole project, nice'd; the 73-clip + slow-news project takes about 35 s and 300 MB. `VOICE_MATCH_PYTHON`, + `VOICE_MATCH_SCRIPT` and `VOICE_MATCH_MODEL` override it. + +`voice-match.json`: `{version: 1, model: "titanet-small", reference: {kind: +"rulings" | "recordings", …how it was built}, thresholds, counts, clips: { +"<channel>/<video>@<cutStart>": {score, label, speechSeconds, best, id, via, +fallback?, inReference?, why?}}}` — keyed by the source moment, as the +rulings are, so a re-seed keeps it. A clip with no window on disk, or no +speech in it, has `score: null` and says why. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1036,6 +1036,41 @@ writeProject( ]), ); +// THE VOICE-MATCH FIXTURE (release 34): who is speaking, per clip. Four clips +// of one "voice" (a 150 Hz tone with its octave) and one of another (a +// 1.1 kHz tone), each window already in the corpus under its own channel so no +// other spec's fetch can touch it; three of the first four are ruled `keep` in +// montage-rulings.json, so the reference is the keeps. The app's job runs the +// test kit's fake embedder (VOICE_MATCH_PYTHON / VOICE_MATCH_SCRIPT in +// playwright.config.ts), which tells the two spectra apart. +{ + const chan = "voicechan"; + const voices = { host: "0.3*sin(2*PI*150*t)+0.15*sin(2*PI*300*t)", guest: "0.3*sin(2*PI*1100*t)+0.1*sin(2*PI*2300*t)" }; + const clips = [["v01", "voice1", "host"], ["v02", "voice2", "guest"], ["v03", "voice3", "host"], ["v04", "voice4", "host"], ["v05", "voice5", "host"]]; + const timeline = []; + for (const [id, vid, who] of clips) { + const dir = path.join(CHANNELS, chan, "data", vid); + mkdirSync(path.join(dir, "clips"), { recursive: true }); + writeFileSync( + path.join(dir, "transcript.cues.json"), + JSON.stringify({ title: `Voice ${vid}`, uploadDate: "20250101", channel: "Voice Channel", webpageUrl: `https://example.invalid/watch?v=${vid}`, duration: 20, cues: [{ start: 2, end: 4.5, text: "slow news day" }] }, null, 1), + ); + ff([ + "-f", "lavfi", "-i", "color=c=gray:size=160x90:rate=15:duration=6", + "-f", "lavfi", "-i", `aevalsrc=${voices[who]}:s=48000:d=6`, + "-map", "0:v", "-map", "1:a", "-t", "6", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", + path.join(dir, "clips", "0.00-6.00.mp4"), + ]); + timeline.push({ type: "clip", id, channel: chan, video: vid, start: 0.5, end: 5.5, cutStart: 2, cutEnd: 4.5, cite: 2, section: 0, lock: true, quote: "slow news day", montage: { match: "slow news day" } }); + } + const dir = writeProject("voice-fixture", manifest("voice-fixture", "The Voice Fixture", { siteOrigin: "https://archive.example", channelSlug: chan }, timeline)); + writeFileSync( + path.join(dir, "montage-rulings.json"), + JSON.stringify({ version: 1, rulings: Object.fromEntries(["voice1", "voice3", "voice4"].map((v) => [`${chan}/${v}@2.00`, { verdict: "keep", reason: "", at: "2026-10-18T00:00:00.000Z" }])) }, null, 1), + ); +} + // A RECORD THAT STORES ITS MEDIA URL (release 32 R6): an Odysee record whose // metadata.info.json names its one CDN format, so "Cut from the stored media // URL" is offered beside its fetch (lib/clips/stored.ts). Its own channel and a diff --git a/umtool/e2e/voice-match.spec.ts b/umtool/e2e/voice-match.spec.ts @@ -0,0 +1,70 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Who is speaking, per montage clip (release 34): the Cut tab's "Score the +// voices" runs `umtool voice-match` as a job and every row then carries its +// score. The engine is the test kit's fake embedder (playwright.config.ts), so +// nothing here needs python or a model. +// +// voice-fixture WRITES voice-match.json. Five clips with their windows in +// the corpus: four of one voice (three ruled keep), one of +// another (v02) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PROJECT = "reports/voice-fixture"; +const FILE = path.join(HERE, "..", ".e2e-song", "reports", "voice-fixture", "voice-match.json"); + +test("Score the voices: a job writes voice-match.json and each clip row shows its score", async ({ page }) => { + await page.goto(urls.section(PROJECT, "cut")); + const panel = page.locator("[data-voice-match-panel]"); + await expect(panel).toBeVisible(); + await expect(page.locator("[data-voice-summary]")).toHaveCount(0); + await expect(page.locator("[data-entry] [data-voice]")).toHaveCount(0); + + await panel.locator("[data-voice-reference]").selectOption("auto"); + await panel.getByRole("button", { name: "Score the voices" }).click(); + await expect(page.locator("[data-voice-summary]")).toContainText("4 likely · 0 unsure · 1 unlikely of 5 scored", { timeout: 60_000 }); + await expect(page.locator("[data-voice-summary]")).toContainText("against 3 clips ruled keep"); + + await expect(page.locator("[data-entry='v02'] [data-voice]")).toHaveAttribute("data-voice", "unlikely"); + await expect(page.locator("[data-entry='v01'] [data-voice]")).toHaveAttribute("data-voice", "likely"); + await expect(page.locator("[data-entry='v05'] [data-voice]")).toContainText(/voice \d\.\d\d · likely/); + + // The file, in the shape the audition deck reads: keyed by the source moment. + const doc = JSON.parse(readFileSync(FILE, "utf8")); + expect(doc.version).toBe(1); + expect(doc.model).toBe("titanet-small"); + expect(doc.reference.kind).toBe("rulings"); + expect(Object.keys(doc.clips).sort()).toEqual(["voicechan/voice1@2.00", "voicechan/voice2@2.00", "voicechan/voice3@2.00", "voicechan/voice4@2.00", "voicechan/voice5@2.00"]); + const guest = doc.clips["voicechan/voice2@2.00"]; + expect(guest.label).toBe("unlikely"); + expect(guest.id).toBe("v02"); + expect(typeof guest.score).toBe("number"); + expect(guest.speechSeconds).toBeGreaterThan(1); + + // Run again: the button says so, and the same input scores the same. + await expect(panel.getByRole("button", { name: "Score the voices again" })).toBeVisible(); +}); + +test("the clip deck carries Score the voices, and its cards show the scores voice-match.json holds", async ({ page }) => { + // After the test above: voice-match.json is there. + await page.goto(urls.clipDeckHref(PROJECT, { show: "all" })); + const panel = page.locator("[data-voice-match-panel]"); + await expect(panel).toBeVisible(); + await expect(panel.locator("[data-voice-summary]")).toContainText("1 unlikely of 5 scored"); + await expect(panel.getByRole("button", { name: "Score the voices again" })).toBeVisible(); + // The deck puts the doubtful clip first, with its score (lane N1 reads the file). + await expect(page.locator("[data-card-voice]").first()).toHaveAttribute("data-card-voice", "unlikely"); +}); + +test("the route refuses what is not a report video, and a project that does not exist", async ({ request }) => { + expect((await request.post("/api/report/voice-match", { data: { project: "reports/no-such-project" } })).status()).toBe(404); + expect((await request.post("/api/report/voice-match", { data: "nope", headers: { "content-type": "application/json" } })).status()).toBe(400); + const r = await request.get(`/api/report/voice-match?project=${encodeURIComponent(PROJECT)}`); + expect(r.status()).toBe(200); +}); diff --git a/umtool/lib/report/voiceMatch.mjs b/umtool/lib/report/voiceMatch.mjs @@ -0,0 +1,420 @@ +// `umtool voice-match <project>` (release 34): who is speaking, per montage +// clip — a local speaker-similarity score written to <project>/voice-match.json. +// +// The scoring is common's (yt-dlp-transcript-common/lib/montage/voiceMatch.mjs: +// the voiced-frames gate, TitaNet-small through sherpa-onnx, the reference +// centroid). This module is umtool's half: WHICH seconds of WHICH file each +// clip is, and which recordings are the host's voice. +// +// - A clip's seconds are its phrase ± PHRASE_PAD_S: the phrase found the way +// the montage render finds it (whisper.cpp's word offsets in the corpus's +// transcript.json first, then the cues by character position — report-to- +// video/montage.mjs `locatePhrase`), else its cut (cutStart–cutEnd) ± the +// pad. Read from the file the render would cut from (report-to-video/ +// sources.mjs: the project's raw cache, the corpus's clip windows, a saved +// source, the sound), on that file's own clock (`clockOffset`). +// - The reference: the clips ruled `keep` in montage-rulings.json (lane N1) +// when there are at least REFERENCE_MIN_RULINGS, else solo recordings of +// the host found on disk (`referenceRecordings`). `--reference` forces one. +// +// The app's Cut tab runs this same command as a job (voiceMatchSteps), so a +// button and a terminal do one thing. Nothing here calls a model but the +// local speaker-embedding one; nothing touches the network. +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { + PHRASE_PAD_S, + REFERENCE_MIN_RULINGS, + REFERENCE_PIECE_S, + REFERENCE_SECONDS, + REFERENCE_VIDEOS, + DEFAULT_THRESHOLDS, + VOICE_MATCH_FILE, + clockOffset, + pickReferenceRecordings, + resolveEngine, + runVoiceMatch, + soloRecordingWhy, + writeVoiceMatch, +} from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources"; +import { clipPhrase, locatePhrase, whisperWords } from "umtool-report-to-video/montage"; +import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { REPO_ROOT } from "../paths.mjs"; +import { UMTOOL_DIR } from "./driver.mjs"; + +export { VOICE_MATCH_FILE }; +/** Lane N1's file: `{version: 1, rulings: {<key>: {verdict, …}}}`. */ +export const RULINGS_FILE = "montage-rulings.json"; +export const REFERENCE_MODES = Object.freeze(["auto", "rulings", "recordings"]); + +export const VOICE_MATCH_USAGE = [ + "usage: umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …]", + " [--reference-channel <slug> …] [--instances FILE] [--span phrase|cut]", + " [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]", + "", + "A speaker-similarity score per montage clip against the host's voice, written to", + `<project>/${VOICE_MATCH_FILE}: TitaNet-small (sherpa-onnx, local) on each clip's phrase ± ${PHRASE_PAD_S} s,`, + "voiced frames only. An aid to the ear: the audition deck sorts the doubtful ones first; it rules on nothing.", + `The reference: the clips ruled keep in ${RULINGS_FILE} (at least ${REFERENCE_MIN_RULINGS}), else solo recordings on`, + `disk — captioned uploads with no ">>" speaker change and no second voice in the title, the first`, + `${REFERENCE_SECONDS} s of speech of up to ${REFERENCE_VIDEOS}, spread over the years (or --reference-video).`, + "--instances FILE also scores a phrase scan's instances that are not in the manifest (a calibration).", + "The engine: VOICE_MATCH_PYTHON / VOICE_MATCH_MODEL, else settings.diarization.python / .embModel, else .diarize/.", +].join("\n"); + +class CliError extends Error {} + +function parse(args) { + const valued = new Set(["--reference", "--reference-video", "--reference-channel", "--instances", "--span", "--pad", "--likely", "--unlikely", "--out", "--progress", "--videos"]); + /** @type {Record<string, string[]>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + (flags[a] ??= []).push(args[++i]); + } else (flags[a] ??= []).push(""); + } else positional.push(a); + } + return { flags, positional, one: (n) => flags[n]?.[flags[n].length - 1], has: (n) => n in flags, all: (n) => flags[n] ?? [] }; +} + +const num = (x) => typeof x === "number" && Number.isFinite(x); +const readJson = (file) => readFile(file, "utf8").then(JSON.parse, () => null); + +/** The `keep` keys of montage-rulings.json, in the file's order; [] without one. */ +export async function keepRulings(dir) { + const doc = await readJson(path.join(dir, RULINGS_FILE)); + const rulings = doc && typeof doc === "object" && doc.rulings && typeof doc.rulings === "object" ? doc.rulings : {}; + return Object.entries(rulings).filter(([, r]) => r && r.verdict === "keep").map(([k]) => k); +} + +/** A corpus video's whisper words and cues, read once each. */ +function transcriptReader(channelsDir) { + const cache = new Map(); + return (slug, video) => { + const key = `${slug}/${video}`; + if (!cache.has(key)) { + cache.set(key, (async () => { + const dir = await resolveVideoDir(channelsDir, slug, video).catch(() => path.join(channelsDir, slug, "data", video)); + const [words, cues] = await Promise.all([ + readJson(path.join(dir, "transcript.json")).then((d) => (d ? whisperWords(d) : null)), + readJson(path.join(dir, "transcript.cues.json")).then((d) => (Array.isArray(d?.cues) ? d.cues : [])), + ]); + return { words, cues }; + })()); + } + return cache.get(key); + }; +} + +/** + * The seconds one clip is scored on, in SOURCE time: the phrase ± the pad + * (`via` "words" | "cues"), else the cut ± the pad (`via` "cut"). + */ +export async function clipSpan(entry, slug, transcripts, { span = "phrase", pad = PHRASE_PAD_S } = {}) { + const hasCut = num(entry.cutStart) && num(entry.cutEnd); + const cut = hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end }; + const phrase = clipPhrase(entry); + if (span === "phrase" && phrase) { + const near = (cut.start + cut.end) / 2; + const range = { from: cut.start - 0.5, to: cut.end + 0.5, near }; + const t = await transcripts(slug, entry.video); + const byWords = t.words ? locatePhrase(phrase, t.words, range) : null; + const found = byWords ?? locatePhrase(phrase, t.cues, range); + if (found) { + return { + from: Math.max(0, found.start - pad), to: found.end + pad, via: byWords ? "words" : "cues", + cut: { from: Math.max(0, cut.start - pad), to: cut.end + pad }, + }; + } + } + return { from: Math.max(0, cut.start - pad), to: cut.end + pad, via: "cut", cut: null }; +} + +/** A clip-like entry for one phrase-scan instance (umtool's seed shape). */ +const instanceEntry = (i) => ({ + type: "clip", channel: i.slug, video: i.videoId, start: Math.max(0, i.start - 2.5), end: i.end + 2.5, + cutStart: Math.round(i.start * 100) / 100, cutEnd: Math.round(i.end * 100) / 100, montage: { match: i.match }, +}); + +/** + * Every clip of the manifest (and of `instances`, when given) as the span the + * common run decodes: the file, the seconds in it, or `missing`. + */ +export async function planClips(dir, manifest, { channelsDir, rawDir = path.join(dir, "out", "clips-raw"), instances = [], span = "phrase", pad = PHRASE_PAD_S } = {}) { + const transcripts = transcriptReader(channelsDir); + const prov = manifest?.provenance ?? {}; + const rows = []; + const seen = new Set(); + const add = async (entry, id) => { + const slug = entry.channel ?? prov.channelSlug; + // The clip deck's key (lane N1's clipMomentKey): the source moment, so the + // deck finds each score under the key it files its rulings by. + const key = clipMomentKey(entry, manifest); + if (!slug || !entry.video || !key) return; + if (seen.has(key)) return; + seen.add(key); + const s = await clipSpan(entry, slug, transcripts, { span, pad }); + const base = { key, ...(id ? { id } : {}), channel: slug, video: entry.video, from: s.from, to: s.to, via: s.via }; + let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + let from = s.from; + let to = s.to; + if (!hit && num(entry.cutStart) && num(entry.cutEnd)) { + // A window that holds the cut but not its pad: the cut alone. + hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + if (hit) { + from = Math.max(entry.cutStart, hit.windowStart); + to = Math.min(entry.cutEnd, hit.windowEnd); + } + } + if (!hit) { + rows.push({ ...base, file: null, start: 0, dur: 0, missing: "no local window" }); + return; + } + const off = await clockOffset(hit.path); + const at = (t) => Math.max(0, t - hit.windowStart - off); + // The cut ± the pad, clamped to the window: what is decoded when the phrase + // span has too little speech in it. + const fb = s.cut && from === s.from ? { a: Math.max(s.cut.from, hit.windowStart), b: Math.min(s.cut.to, hit.windowEnd) } : null; + rows.push({ + ...base, file: hit.path, source: hit.kind, start: at(from), dur: to - from, + ...(fb && fb.b - fb.a > 0 ? { fallback: { start: at(fb.a), dur: fb.b - fb.a } } : {}), + }); + }; + for (const e of manifest?.timeline ?? []) { + if (e?.type === "clip" && !e.src) await add(e, e.id); + } + for (const i of instances) { + if (i && typeof i === "object" && i.slug && i.videoId && num(i.start) && num(i.end)) await add(instanceEntry(i), null); + } + return rows; +} + +const SOURCE_NAME = /^(?:saved-video\.json|source-media\.[a-z0-9]+|audio\.(?:mp3|m4a|opus))$/; + +/** + * Solo recordings of the host on disk, as reference pieces. Candidates: every + * video of `channels` with a whole source on disk (a saved video, a + * source-media file, its sound) whose transcript passes `soloRecordingWhy`; + * `pickReferenceRecordings` spreads `n` over the years. Each gives the first + * REFERENCE_SECONDS from its first cue, in REFERENCE_PIECE_S pieces. Or the + * named `videos` (`<channel>/<id>`), whatever their transcript says. + */ +export async function referenceRecordings({ channelsDir, channels, videos = [], n = REFERENCE_VIDEOS, exclude = new Set() }) { + /** @type {{ slug: string, videoId: string, date: string | null, title: string | null, first: number }[]} */ + let picked = []; + const skipped = []; + if (videos.length) { + for (const v of videos) { + const [slug, videoId] = String(v).split("/"); + if (!slug || !videoId) throw new CliError(`--reference-video ${v}: <channel>/<id>`); + const dir = await resolveVideoDir(channelsDir, slug, videoId).catch(() => path.join(channelsDir, slug, "data", videoId)); + const doc = await readJson(path.join(dir, "transcript.cues.json")); + picked.push({ slug, videoId, date: doc?.uploadDate ?? null, title: doc?.title ?? null, first: Number(doc?.cues?.[0]?.start ?? 0) || 0 }); + } + } else { + const candidates = []; + for (const slug of channels) { + const dataDir = path.join(channelsDir, slug, "data"); + const ids = await readdir(dataDir).catch(() => []); + for (const id of ids) { + if (exclude.has(`${slug}/${id}`)) continue; + const names = await readdir(path.join(dataDir, id)).catch(() => []); + if (!names.some((x) => SOURCE_NAME.test(x))) continue; + const doc = await readJson(path.join(dataDir, id, "transcript.cues.json")); + if (soloRecordingWhy(doc) !== null) continue; + candidates.push({ slug, videoId: String(doc.id ?? id), dirId: id, date: doc.uploadDate ?? null, title: doc.title ?? null, first: Number(doc.cues[0]?.start ?? 0) || 0 }); + } + } + picked = pickReferenceRecordings(candidates, n); + } + const items = []; + for (const r of picked) { + const from = Math.max(0, r.first); + const hit = await resolveLocalSource( + { video: r.videoId, slug: r.slug, from, to: from + REFERENCE_SECONDS }, + { channelsDir, audio: true, probe: ffprobeSource }, + ); + if (!hit) { + skipped.push({ channel: r.slug, video: r.videoId, why: "no local source covers it" }); + continue; + } + const off = await clockOffset(hit.path); + for (let k = 0; k * REFERENCE_PIECE_S < REFERENCE_SECONDS; k += 1) { + items.push({ + key: `${r.slug}/${r.videoId}#${k}`, slug: r.slug, video: r.videoId, date: r.date, title: r.title, + file: hit.path, start: Math.max(0, from + k * REFERENCE_PIECE_S - hit.windowStart - off), dur: REFERENCE_PIECE_S, + }); + } + } + return { items, skipped }; +} + +async function pickProject(arg, root) { + if (!arg) throw new CliError("which project? pass an id, a name, or a directory"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + return r.project; +} + +const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); + +/** + * `umtool voice-match …` + * @param {string[]} args everything after `voice-match` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, engine?: Record<string, unknown> }} [opts] + */ +export async function voiceMatchCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) { + try { + const p = parse(args); + if (p.has("--help") || !p.positional.length) { + log(VOICE_MATCH_USAGE); + return p.has("--help") ? 0 : 2; + } + const project = await pickProject(p.positional[0], reportsRoot); + const ndjson = p.one("--progress") === "ndjson"; + if (p.has("--progress") && !ndjson) throw new CliError("--progress takes ndjson"); + const say = (line) => (ndjson ? err(line) : log(line)); + const emit = (ev) => { + if (ndjson) log(JSON.stringify({ ev: "voice-match", ...ev })); + }; + const mode = p.one("--reference") ?? "auto"; + if (!REFERENCE_MODES.includes(mode)) throw new CliError(`--reference ${mode}: one of ${REFERENCE_MODES.join(", ")}`); + const span = p.one("--span") ?? "phrase"; + if (span !== "phrase" && span !== "cut") throw new CliError("--span phrase|cut"); + const pad = p.has("--pad") ? Number(p.one("--pad")) : PHRASE_PAD_S; + if (!Number.isFinite(pad) || pad < 0 || pad > 5) throw new CliError("--pad takes 0..5 seconds"); + const thresholds = { ...DEFAULT_THRESHOLDS }; + for (const k of /** @type {const} */ (["likely", "unlikely"])) { + if (p.has(`--${k}`)) { + const v = Number(p.one(`--${k}`)); + if (!Number.isFinite(v) || v < 0 || v > 1) throw new CliError(`--${k} takes 0..1`); + thresholds[k] = v; + } + } + if (thresholds.unlikely > thresholds.likely) throw new CliError("--unlikely is at most --likely"); + + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDir) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from"); + const instances = p.has("--instances") ? await readJson(path.resolve(/** @type {string} */ (p.one("--instances")))) : []; + if (!Array.isArray(instances)) throw new CliError("--instances: a JSON array of phrase-scan instances"); + + emit({ phase: "plan" }); + const clips = await planClips(project.dir, manifest, { channelsDir, instances, span, pad }); + const keeps = (await keepRulings(project.dir)).filter((k) => clips.some((c) => c.key === k && c.file)); + const useRulings = mode === "rulings" || (mode === "auto" && keeps.length >= REFERENCE_MIN_RULINGS); + if (mode === "rulings" && keeps.length < 2) throw new CliError(`--reference rulings: ${keeps.length} clip(s) ruled keep with a window; at least 2`); + /** @type {import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs").ReferenceSpec} */ + let reference; + let skipped = []; + if (useRulings) { + reference = { kind: "rulings", keys: keeps }; + say(`reference: ${keeps.length} clip(s) ruled keep`); + } else { + const channels = [...new Set([...clips.map((c) => c.channel), manifest.provenance?.channelSlug].filter(Boolean))]; + const extra = p.all("--reference-channel"); + const r = await referenceRecordings({ + channelsDir, + channels: extra.length ? extra : channels, + videos: p.all("--reference-video"), + n: p.has("--videos") ? Math.max(1, Number(p.one("--videos")) || REFERENCE_VIDEOS) : REFERENCE_VIDEOS, + }); + skipped = r.skipped; + if (!r.items.length) throw new CliError("no reference: no clip ruled keep and no solo recording on disk (--reference-video <channel>/<id>)"); + reference = { kind: "recordings", items: r.items }; + say(`reference: ${new Set(r.items.map((i) => `${i.slug}/${i.video}`)).size} recording(s), ${r.items.length} piece(s)`); + } + const missing = clips.filter((c) => !c.file).length; + say(`${clips.length} clip(s) to score${missing ? `, ${missing} with no local window` : ""}`); + if (p.has("--dry")) { + const plan = { clips, reference, skipped }; + log(p.has("--json") ? JSON.stringify(plan, null, 1) : clips.map((c) => `${c.id ?? "-"} ${c.key} ${c.via} ${c.file ? `${path.basename(c.file)} +${c.start.toFixed(2)} ${c.dur.toFixed(2)}s` : c.missing}`).join("\n")); + return 0; + } + + let settings = null; + try { + settings = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")); + } catch { + settings = null; + } + const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts }); + // Beside the project, never /tmp (a RAM tmpfs on the box this runs on): + // a few MB of 16 kHz wavs, removed when the run ends (and by the next run, + // when one was cancelled). + const scratch = path.join(/* turbopackIgnore: true */ project.dir, ".voice-match-work"); + const t0 = Date.now(); + const doc = await runVoiceMatch({ + clips: clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })), + pad, + reference, + engine, + scratch, + thresholds, + onProgress: (e) => emit({ phase: e.event, ...(e.n ? { n: e.n, of: e.of } : {}), ...(e.items ? { items: e.items } : {}) }), + }); + if (skipped.length) doc.reference.skipped = skipped; + doc.span = span; + for (const c of clips) { + const row = doc.clips[c.key]; + if (!row) continue; + row.via = c.via; + if (!c.id) row.from = "instances"; + } + const out = p.has("--out") ? path.resolve(/** @type {string} */ (p.one("--out"))) : null; + const file = out + ? (await import("node:fs/promises")).writeFile(out, `${JSON.stringify(doc, null, 1)}\n`).then(() => out) + : writeVoiceMatch(project.dir, doc); + const written = await file; + emit({ phase: "done", file: written, counts: doc.counts, seconds: Math.round((Date.now() - t0) / 100) / 10 }); + if (p.has("--json")) log(JSON.stringify(doc, null, 1)); + else if (!ndjson) { + for (const c of clips) { + const r = doc.clips[c.key]; + log(`${(c.id ?? "-").padEnd(4)} ${c.key.padEnd(56)} ${r.score == null ? " - " : r.score.toFixed(3)} ${String(r.label ?? r.why ?? "").padEnd(9)} ${Number(r.speechSeconds).toFixed(1)}s`); + } + log(`${doc.counts.likely} likely · ${doc.counts.unsure} unsure · ${doc.counts.unlikely} unlikely of ${doc.counts.scored} scored → ${written}`); + } else say(`${doc.counts.likely} likely · ${doc.counts.unsure} unsure · ${doc.counts.unlikely} unlikely → ${written}`); + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool voice-match: ${e.message}` : `umtool voice-match: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} + +/** The CLI path the app's job runs. */ +const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + +/** + * The Cut tab's "Score the voices": ONE job step on lib/jobs.ts running this + * command, nice'd (it is light — TitaNet-small on a few seconds a clip — so it + * does not take the heavy slot). + * @param {{ id: string }} project + * @param {{ reference?: string }} [req] + */ +export function voiceMatchSteps(project, req = {}) { + const mode = typeof req.reference === "string" && REFERENCE_MODES.includes(req.reference) ? req.reference : "auto"; + return { + kind: `voice-match ${project.id}`, + steps: [{ + label: "score each clip's voice", + argv: ["nice", "-n", "10", "node", umtoolCli(), "voice-match", project.id, "--reference", mode, "--progress", "ndjson"], + cwd: UMTOOL_DIR, + env: {}, + ndjson: /** @type {const} */ (true), + timeoutMs: 15 * 60 * 1000, + }], + }; +} diff --git a/umtool/lib/report/voiceMatch.test.mjs b/umtool/lib/report/voiceMatch.test.mjs @@ -0,0 +1,163 @@ +// `umtool voice-match` (release 34 N2): the plan (which seconds of which file), +// the reference (keeps, else solo recordings on disk), the CLI end to end over a +// synthetic corpus with the test kit's fake embedder, and the app's job step. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; +import { keepRulings, planClips, referenceRecordings, voiceMatchCommand, voiceMatchSteps } from "./voiceMatch.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FAKE = path.resolve(HERE, "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx" }; +const KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +/** A wav of `x`, encoded by ffmpeg to an audio-only AAC file at `out`. */ +async function encode(x, out) { + const wav = `${out}.wav`; + await writeFile(wav, encodeWav16(x)); + execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "aac", "-b:a", "96k", out]); + await rm(wav); +} + +const cuesDoc = (id, cues, extra = {}) => ({ id, title: `Upload ${id}`, uploadDate: "20200101", duration: 200, source: "vtt", isLivestream: false, platform: "youtube", cues, ...extra }); + +/** + * A corpus and a project: three solo uploads of VOICE_A with their sound on + * disk (the reference), and clips whose windows say "slow news day" in + * VOICE_A (s01, s03, s04) or VOICE_B (s02, the guest). + */ +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), "voice-match-")); + const chans = path.join(root, "channels"); + const data = (id) => path.join(chans, "chan", "data", id); + for (const [i, date] of ["20190101", "20210101", "20230101"].entries()) { + const id = `solo${i}`; + await mkdir(data(id), { recursive: true }); + await writeFile(path.join(data(id), "transcript.cues.json"), JSON.stringify(cuesDoc(id, [{ start: 2, end: 5, text: "what is going on everyone" }], { uploadDate: date }))); + await encode(withSilence(syntheticVoice({ ...VOICE_A, seconds: 66, phase: i * 0.9 }), { before: 2 }), path.join(data(id), "audio.m4a")); + } + // An upload that is NOT a reference: a ">>" speaker change. + await mkdir(data("duo"), { recursive: true }); + await writeFile(path.join(data("duo"), "transcript.cues.json"), JSON.stringify(cuesDoc("duo", [{ start: 2, end: 5, text: ">> and you" }]))); + await encode(syntheticVoice({ ...VOICE_B, seconds: 70 }), path.join(data("duo"), "audio.m4a")); + + const clips = [ + ["s01", "host1", VOICE_A, 1.7], + ["s02", "guest1", VOICE_B, 0.4], + ["s03", "host2", VOICE_A, 3.1], + ["s04", "host3", VOICE_A, 4.6], + ]; + const timeline = []; + for (const [id, video, voice, phase] of clips) { + // The window is source seconds 100–108; the phrase is said at 102.5–104. + await mkdir(path.join(data(video), "clips"), { recursive: true }); + await writeFile(path.join(data(video), "transcript.cues.json"), JSON.stringify(cuesDoc(video, [{ start: 102.5, end: 104, text: "slow news day" }]))); + const sound = withSilence(syntheticVoice({ ...voice, seconds: 2.5, phase }), { before: 2, after: 3.5 }); + await encode(sound, path.join(data(video), "clips", "100.00-108.00.mp4")); + timeline.push({ type: "clip", id, channel: "chan", video, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, montage: { match: "slow news day" } }); + } + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "montage"); + await mkdir(dir, { recursive: true }); + const manifest = { schemaVersion: 1, slug: "montage", title: "Montage", kind: KIND, provenance: { channelsDir: "../../channels", channelSlug: "chan" }, render: {}, timeline }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 1)); + return { root, chans, dir, reportsRoot, manifest }; +} + +const quiet = () => { + const out = []; + return { out, log: (s) => out.push(s), err: (s) => out.push(s) }; +}; + +test("voice-match: the plan, the reference recordings, and the CLI over a synthetic corpus", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => { + const f = await fixture(); + try { + // The plan: the phrase found in the cues, ± 1 s, on the window's clock. + const plan = await planClips(f.dir, f.manifest, { channelsDir: f.chans }); + assert.equal(plan.length, 4); + const s01 = plan.find((c) => c.id === "s01"); + assert.equal(s01.key, "chan/host1@102.50"); + assert.equal(s01.via, "cues"); + assert.ok(Math.abs(s01.start - 1.5) < 0.05 && Math.abs(s01.dur - 3.5) < 0.05, `+${s01.start} ${s01.dur}s`); + assert.ok(s01.fallback, "the cut ± the pad is the fallback"); + + // The reference: the three solo uploads, not the one with a ">>". + const ref = await referenceRecordings({ channelsDir: f.chans, channels: ["chan"] }); + assert.deepEqual([...new Set(ref.items.map((i) => i.video))], ["solo0", "solo1", "solo2"]); + assert.equal(ref.items.length, 18, "six 10 s pieces each"); + assert.ok(Math.abs(ref.items[0].start - 2) < 0.05, "from the first cue"); + + // The CLI end to end. + const q = quiet(); + const code = await voiceMatchCommand(["montage", "--json"], { reportsRoot: f.reportsRoot, ...q, engine: ENGINE }); + assert.equal(code, 0, q.out.join("\n")); + const doc = JSON.parse(await readFile(path.join(f.dir, "voice-match.json"), "utf8")); + assert.equal(doc.version, 1); + assert.equal(doc.model, "titanet-small"); + assert.equal(doc.reference.kind, "recordings"); + assert.equal(doc.reference.recordings.length, 3); + assert.equal(doc.clips["chan/host1@102.50"].label, "likely"); + assert.equal(doc.clips["chan/guest1@102.50"].label, "unlikely"); + assert.equal(doc.clips["chan/host1@102.50"].id, "s01"); + assert.ok(doc.clips["chan/host1@102.50"].speechSeconds <= 2.6, "the pad's silence is not speech"); + + // Three keeps: the reference is the ruled clips, each scored against the others. + await writeFile( + path.join(f.dir, "montage-rulings.json"), + JSON.stringify({ version: 1, rulings: Object.fromEntries(["host1", "host2", "host3"].map((v) => [`chan/${v}@102.50`, { verdict: "keep", reason: "", at: "2026-10-18T00:00:00Z" }])) }), + ); + assert.deepEqual(await keepRulings(f.dir), ["chan/host1@102.50", "chan/host2@102.50", "chan/host3@102.50"]); + assert.equal(await voiceMatchCommand(["montage"], { reportsRoot: f.reportsRoot, ...quiet(), engine: ENGINE }), 0); + const ruled = JSON.parse(await readFile(path.join(f.dir, "voice-match.json"), "utf8")); + assert.equal(ruled.reference.kind, "rulings"); + assert.equal(ruled.clips["chan/host2@102.50"].inReference, true); + assert.equal(ruled.clips["chan/guest1@102.50"].label, "unlikely"); + + // --dry plans and writes nothing new. + const dry = quiet(); + assert.equal(await voiceMatchCommand(["montage", "--dry", "--reference", "recordings"], { reportsRoot: f.reportsRoot, ...dry, engine: ENGINE }), 0); + assert.match(dry.out.join("\n"), /s02 {2}chan\/guest1@102\.50 {2}cues {2}100\.00-108\.00\.mp4/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("voice-match: refusals in words", async () => { + const q = quiet(); + assert.equal(await voiceMatchCommand(["no-such-project"], { reportsRoot: path.join(tmpdir(), "nowhere-voice"), ...q }), 2); + assert.match(q.out.join("\n"), /no project matches/); + const help = quiet(); + assert.equal(await voiceMatchCommand(["--help"], { ...help }), 0); + assert.match(help.out.join("\n"), /usage: umtool voice-match/); +}); + +test("voiceMatchSteps: one nice'd job step running the CLI, NDJSON", () => { + const plan = voiceMatchSteps({ id: "montage" }, { reference: "recordings" }); + assert.equal(plan.kind, "voice-match montage"); + assert.equal(plan.steps.length, 1); + const [s] = plan.steps; + assert.deepEqual(s.argv.slice(0, 4), ["nice", "-n", "10", "node"]); + assert.match(s.argv[4], /umtool[\\/]bin[\\/]umtool\.mjs$/); + assert.deepEqual(s.argv.slice(5), ["voice-match", "montage", "--reference", "recordings", "--progress", "ndjson"]); + assert.equal(s.ndjson, true); + assert.equal(voiceMatchSteps({ id: "m" }, { reference: "bogus" }).steps[0].argv.includes("auto"), true); +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -176,6 +176,11 @@ export default defineConfig({ // would otherwise enumerate every fixture article's corpus and add cards // other specs count. refresh.spec runs the check itself, through its route. `UMTOOL_REFRESH_CHECK=0 ` + + // The voice match's engine (release 34): the test kit's fake embedder, + // run by this node, in the place of scripts/speaker-embed.py and the + // TitaNet venv -- the same command line and JSON, no python, no model. + `VOICE_MATCH_PYTHON=${process.execPath} ` + + `VOICE_MATCH_SCRIPT=${path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs")} VOICE_MATCH_MODEL=fake.onnx ` + APP_SERVER, port: PORT, reuseExistingServer: false, diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -28,6 +28,7 @@ "./factcheck": "./factcheck.mjs", "./frames-cut": "./frames-cut.mjs", "./ledger-totals": "./ledger-totals.mjs", + "./montage": "./montage.mjs", "./montage-styles": "./montage-styles.mjs", "./montage-rulings": "./montage-rulings.mjs", "./lint": "./lint.mjs",