// `umtool speaker-check ` (UI notes 2026-10-30, #15): which of the // project's named voices a clip is -- "Speaker: matches Ember 0.93 / Kirsche // 0.83" on the walk -- with the reference sets it was measured against. // // The scorer is common's (lib/montage/speakerCheck.mjs, over the voice match's // pieces: TitaNet-small through sherpa-onnx, local). This module is umtool's // half, the voice match's (voiceMatch.mjs) again: which seconds of which file // each clip is (planClips), and the reference sets, `/speakers.json`: // // { "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] }, // { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] } // // clips clips of this cut known to be that voice (a confirmed clip; the // walk's "Add to 's voice") // videos recordings of that voice alone (`/`): the first // REFERENCE_SECONDS of speech, in pieces, as the voice match reads them // channels channels whose solo recordings are that voice (the voice // match's heuristic picks them) // // The app's "Check speaker" runs this command as a job (speakerCheckSteps) // through the machine's heavy slot -- light, but a render the operator is // waiting for comes first (render mode). Nothing here calls a model but the // local speaker-embedding one; nothing touches the network. import { existsSync } from "node:fs"; import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_THRESHOLDS, PHRASE_PAD_S, REFERENCE_VIDEOS, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { readSpeakerCheck, runSpeakerCheck, writeSpeakerCheck } from "yt-dlp-transcript-common/lib/montage/speakerCheck.mjs"; 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"; import { planClips, referenceRecordings } from "./voiceMatch.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SPEAKERS_FILE = "speakers.json"; const NAME_RE = /^[^\s/=,][^/=,]{0,47}$/; const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; const VIDEO_RE = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9_.-]+$/i; class CliError extends Error {} /** * The reference sets, checked: `[{ name, clips, videos, channels }]` ([] with * no file). Throws on a file that does not read as one. * @param {unknown} raw */ export function normalizeSpeakers(raw) { const list = raw && typeof raw === "object" && Array.isArray(/** @type {any} */ (raw).speakers) ? /** @type {any} */ (raw).speakers : null; if (!list) throw new Error(`${SPEAKERS_FILE} is { "speakers": [ { "name", "clips"?, "videos"?, "channels"? } ] }`); const seen = new Set(); return list.map((s, i) => { const name = String(s?.name ?? "").trim(); if (!NAME_RE.test(name)) throw new Error(`speaker ${i + 1}: a name of 1–48 characters, no / = or comma (got ${JSON.stringify(s?.name)})`); if (seen.has(name.toLowerCase())) throw new Error(`two speakers are named "${name}"`); seen.add(name.toLowerCase()); const strs = (k, re) => { const v = s?.[k] ?? []; if (!Array.isArray(v)) throw new Error(`${name}: ${k} is a list`); const out = [...new Set(v.map((x) => String(x).trim()).filter(Boolean))]; for (const x of out) if (!re.test(x)) throw new Error(`${name}: ${k} has ${JSON.stringify(x)}`); return out; }; return { name, clips: strs("clips", ID_RE), videos: strs("videos", VIDEO_RE), channels: strs("channels", /^[a-z0-9][a-z0-9._-]*$/i) }; }); } /** The project's reference sets ([] when there is no speakers.json). */ export async function readSpeakers(dir) { let text; try { text = await readFile(path.join(dir, SPEAKERS_FILE), "utf8"); } catch { return []; } return normalizeSpeakers(JSON.parse(text)); } /** Write the reference sets whole (tmp + rename). */ export async function writeSpeakers(dir, speakers) { const list = normalizeSpeakers({ speakers }); const file = path.join(dir, SPEAKERS_FILE); const tmp = tmpPathFor(file); const doc = { speakers: list.map((s) => ({ name: s.name, ...(s.clips.length ? { clips: s.clips } : {}), ...(s.videos.length ? { videos: s.videos } : {}), ...(s.channels.length ? { channels: s.channels } : {}) })) }; await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); return list; } /** * `Name=clip:e01,video:chan/id,channel:slug` (a bare word is a clip id, a * `chan/id` a video) -> a speaker. * @param {string} spec */ export function parseSpeakerSpec(spec) { const i = String(spec).indexOf("="); if (i <= 0) throw new CliError(`--set takes Name=,… (got ${JSON.stringify(spec)})`); const name = spec.slice(0, i).trim(); const s = { name, clips: [], videos: [], channels: [] }; for (const raw of spec.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean)) { const [k, v] = raw.includes(":") ? [raw.slice(0, raw.indexOf(":")), raw.slice(raw.indexOf(":") + 1)] : [raw.includes("/") ? "video" : "clip", raw]; if (k === "clip") s.clips.push(v); else if (k === "video") s.videos.push(v); else if (k === "channel") s.channels.push(v); else throw new CliError(`--set ${name}: "${raw}" is clip:, video:/ or channel:`); } return s; } /** Add one clip of the cut to a voice (made when it is new); a clip is in one voice at a time. */ export async function addClipToSpeaker(dir, name, clipId) { const list = await readSpeakers(dir); const n = String(name ?? "").trim(); let s = list.find((x) => x.name.toLowerCase() === n.toLowerCase()); for (const x of list) x.clips = x.clips.filter((c) => c !== clipId); if (!s) { s = { name: n, clips: [], videos: [], channels: [] }; list.push(s); } s.clips.push(String(clipId)); return writeSpeakers(dir, list); } /** * The scorer's inputs for the project: the planned clips, the keys to check, * the voices with their pieces. */ export async function planSpeakerCheck(dir, manifest, { clipIds = [], channelsDir, speakers }) { const clips = await planClips(dir, manifest, { channelsDir, pad: PHRASE_PAD_S }); const keyOf = new Map(clips.filter((c) => c.id).map((c) => [c.id, c.key])); for (const id of clipIds) if (!keyOf.has(id)) throw new CliError(`no clip ${id} in the cut (or it has its own media)`); const check = clipIds.length ? clipIds.map((id) => /** @type {string} */ (keyOf.get(id))) : clips.filter((c) => c.id).map((c) => c.key); const voices = []; const skipped = []; for (const s of speakers) { const clipKeys = s.clips.map((id) => keyOf.get(id)).filter(Boolean); for (const id of s.clips) if (!keyOf.has(id)) skipped.push({ speaker: s.name, why: `clip ${id} is not in the cut` }); let items = []; let recordings = []; if (s.videos.length || s.channels.length) { const r = await referenceRecordings({ channelsDir, channels: s.channels, videos: s.videos, n: REFERENCE_VIDEOS }); items = r.items.map((it) => ({ key: it.key, file: it.file, start: it.start, dur: it.dur })); recordings = [...new Map(r.items.map((it) => [`${it.slug}/${it.video}`, { channel: it.slug, video: it.video, date: it.date ?? null, title: it.title ?? null }])).values()]; for (const x of r.skipped) skipped.push({ speaker: s.name, why: `${x.channel}/${x.video}: ${x.why}` }); } voices.push({ name: s.name, clipKeys: /** @type {string[]} */ (clipKeys), items, recordings }); } return { clips, check, voices, skipped }; } export const SPEAKER_CHECK_USAGE = [ "usage: umtool speaker-check [--clip …] [--json] [--progress ndjson]", " umtool speaker-check --list | --set 'Name=,/,channel:,…' | --remove Name", "", "Which of the project's named voices each clip is: TitaNet-small (sherpa-onnx, local) on the clip's phrase", `± ${PHRASE_PAD_S} s, voiced frames only, against each voice's robust centroid -> ${""}/speaker-check.json (merged:`, "a check of one clip keeps the others'). The voices are /speakers.json: per name, clips of the cut,", "recordings of that voice alone (/), or channels whose solo recordings it is. A clip that is in a", "voice's set is scored against the rest of it. An aid to the ear: it rules on nothing.", "The engine: VOICE_MATCH_PYTHON / VOICE_MATCH_MODEL, else settings.diarization.python / .embModel, else .diarize/.", ].join("\n"); const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); /** * `umtool speaker-check …` * @param {string[]} args * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, engine?: Record }} [opts] */ export async function speakerCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) { try { const words = []; /** @type {Record} */ const flags = {}; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (["--clip", "--set", "--remove", "--progress"].includes(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); (flags[a] ??= []).push(args[++i]); } else if (["--json", "--list", "--help"].includes(a)) (flags[a] ??= []).push(""); else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); else words.push(a); } if (flags["--help"] || !words.length) { log(SPEAKER_CHECK_USAGE); return flags["--help"] ? 0 : 2; } const r = await resolveProject(words[0], reportsRoot); if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${words[0]}"`); const project = r.project; if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); const ndjson = flags["--progress"]?.at(-1) === "ndjson"; const say = (line) => (ndjson ? err(line) : log(line)); const emit = (ev) => { if (ndjson) log(JSON.stringify({ ev: "speaker-check", ...ev })); }; // The reference sets: edited, or listed. if (flags["--set"] || flags["--remove"]) { let list = await readSpeakers(project.dir); for (const spec of flags["--set"] ?? []) { const s = parseSpeakerSpec(spec); list = [...list.filter((x) => x.name.toLowerCase() !== s.name.toLowerCase()), s]; } for (const name of flags["--remove"] ?? []) list = list.filter((x) => x.name.toLowerCase() !== name.trim().toLowerCase()); await writeSpeakers(project.dir, list); say(`${SPEAKERS_FILE}: ${list.length} voice(s)`); } const speakers = await readSpeakers(project.dir); if (flags["--list"] || flags["--set"] || flags["--remove"]) { if (flags["--json"]) log(JSON.stringify({ project: project.id, speakers }, null, 2)); else for (const s of speakers) log(`${s.name}: ${[...s.clips.map((c) => `clip ${c}`), ...s.videos, ...s.channels.map((c) => `channel ${c}`)].join(", ") || "(nothing yet)"}`); return 0; } if (!speakers.length) { throw new CliError(`no voices to compare with: name them in ${SPEAKERS_FILE} (umtool speaker-check ${project.id} --set 'Name=,/,…'), or the walk's "Add to a voice"`); } 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"); emit({ phase: "plan" }); const plan = await planSpeakerCheck(project.dir, manifest, { clipIds: flags["--clip"] ?? [], channelsDir, speakers }); for (const s of plan.skipped) say(`${s.speaker}: ${s.why}`); say(`${plan.check.length} clip(s) to check against ${plan.voices.map((v) => `${v.name} (${v.clipKeys.length + v.items.length} piece(s))`).join(", ")}`); let settings = null; try { settings = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")); } catch { settings = null; } const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts }); const t0 = Date.now(); const doc = await runSpeakerCheck({ clips: plan.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 })), check: plan.check, speakers: plan.voices, engine, // Beside the project, never /tmp (a RAM tmpfs here); removed at the end. scratch: path.join(/* turbopackIgnore: true */ project.dir, ".speaker-check-work"), thresholds: DEFAULT_THRESHOLDS, onProgress: (e) => emit({ phase: e.event, ...(e.n ? { n: e.n, of: e.of } : {}), ...(e.items ? { items: e.items } : {}) }), }); const { file, doc: merged } = await writeSpeakerCheck(project.dir, doc); emit({ phase: "done", file, seconds: Math.round((Date.now() - t0) / 100) / 10 }); if (flags["--json"]) log(JSON.stringify(merged, null, 1)); else if (!ndjson) { for (const key of plan.check) { const row = /** @type {any} */ (doc.clips[key]); if (!row) continue; log(`${String(row.id ?? "-").padEnd(5)} ${speakerLine(row)}`); } log(`→ ${file}`); } else say(`→ ${file}`); return 0; } catch (e) { err(e instanceof CliError ? `umtool speaker-check: ${e.message}` : `umtool speaker-check: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } } /** "matches Ember 0.93 / Kirsche 0.83", "unsure: Ember 0.51 / Kirsche 0.49", or why it was not scored. */ export function speakerLine(row) { if (!row || !Array.isArray(row.scores) || !row.scores.length) return row?.why ? `not scored — ${row.why}` : "not scored"; const list = row.scores.map((s) => `${s.name} ${Number(s.score).toFixed(2)}`).join(" / "); if (row.label === "matches") return `matches ${list}`; if (row.label === "none") return `matches none of them: ${list}`; return `unsure: ${list}`; } /** The CLI path the app's job runs. */ const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); /** The checkout's heavy-slot CLI (takeRender.mjs's rule), when this umtool sits in the checkout. */ function queueLockScript() { const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs"); return existsSync(/* turbopackIgnore: true */ file) ? file : null; } /** What a check declares to the heavy slot: TitaNet-small and ffmpeg on a few seconds a clip. */ export const SPEAKER_CHECK_ESTIMATE_MB = 800; /** * The walk's "Check speaker": ONE job step on lib/jobs.ts running this * command through the machine's heavy slot (queue-lock --heavy, with its * estimate: admitted beside other jobs by memory, and waiting at the door * while render mode gives a render the machine), nice'd. * @param {{ id: string }} project * @param {{ clip?: string | null, queueLock?: string | null }} [req] */ export function speakerCheckSteps(project, { clip = null, queueLock = queueLockScript() } = {}) { const cmd = ["nice", "-n", "10", process.execPath, umtoolCli(), "speaker-check", project.id, ...(clip ? ["--clip", clip] : []), "--progress", "ndjson"]; return { kind: `speaker-check ${project.id}`, steps: [{ label: clip ? `check ${clip}'s speaker` : "check each clip's speaker", argv: queueLock ? [process.execPath, queueLock, "--heavy", "--estimate", String(SPEAKER_CHECK_ESTIMATE_MB), "--", ...cmd] : cmd, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, ndjson: /** @type {const} */ (true), timeoutMs: 20 * 60 * 1000, }], }; } /** The walk's badge for one clip: its row in speaker-check.json, and the voices it was measured against. */ export async function speakerBadge(dir, manifest, clipId) { const [doc, speakers] = await Promise.all([readSpeakerCheck(dir), readSpeakers(dir).catch(() => [])]); let row = null; if (doc) { row = Object.values(doc.clips).find((r) => /** @type {any} */ (r)?.id === clipId) ?? null; } return { speakers: speakers.map((s) => ({ name: s.name, clips: s.clips, videos: s.videos, channels: s.channels, inReference: s.clips.includes(clipId) })), result: row ? { ...row, line: speakerLine(row), madeAt: doc?.madeAt ?? null } : null, reference: doc ? doc.speakers : null, }; }