// `umtool voice-match ` (release 34): who is speaking, per montage // clip — a local speaker-similarity score written to /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: {: {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 [--reference auto|rulings|recordings] [--reference-video / …]", " [--reference-channel …] [--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", `/${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} */ 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, render: manifest?.render ?? null }); 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, render: manifest?.render ?? null }); 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` (`/`), 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}: /`); 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 }, // A reference recording, not a cut's clip: no render. { channelsDir, audio: true, probe: ffprobeSource, render: null }, ); 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 }} [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 /)"); 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, }], }; }