Archilyzer · Source

archilyzer

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

commit 7124bdeb5ce697fd6c3ff1c3fe73aa5feacf5db2
parent e72332a6bed5402e55a3feb97e1b0c15392426e5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 02:27:42 -0500

umtool, common: the speaker check on the walk -- "Speaker: matches Ember 0.93 / Kirsche 0.83" with its reference sets, and Check speaker as a job through the heavy slot (UI notes #15)

- a scorer existed: the release-34 voice match (TitaNet-small through sherpa-onnx, local), against ONE voice. This builds the several-voices check on its pieces, unchanged
- common/lib/montage/speakerCheck.mjs: each clip against every named voice's robust centroid, one embedding process for all, best first; matches (>= 0.42 and 0.05 ahead), none (all < 0.30), unsure; a voice's own clip scored against the rest of it; <project>/speaker-check.json merged per clip
- the voices are <project>/speakers.json: per name, clips of the cut, recordings of that voice alone, or channels whose solo recordings it is
- `umtool speaker-check <p> [--clip <id> …] [--json]`, `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'`, `--remove`, `--list`
- the walk: the clip bench's verdict bar shows the badge with the reference sets; Check speaker (POST /api/report/speaker-check) runs the CLI as one job through queue-lock --heavy --estimate 800, nice'd; Add to a voice puts the clip in a voice's set
- no model is installed and no weights are fetched: the engine is the voice match's (VOICE_MATCH_PYTHON / _MODEL, or the diarization lane's); the tests run the test kit's fake embedder
- tests: speakerCheck.test.ts, ui-ops.test.mjs (speakers.json, the job's argv, the CLI over a synthetic corpus, the badge); docs: report-video.md, cli.md

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

Diffstat:
Acommon/lib/montage/speakerCheck.mjs | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/speakerCheck.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Aumtool/app/api/report/speaker-check/route.ts | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 5+++++
Mumtool/components/projects/ClipBench.tsx | 3+++
Aumtool/components/projects/SpeakerBadge.tsx | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 1+
Mumtool/docs/report-video.md | 26++++++++++++++++++++++++++
Aumtool/lib/report/speakerCheck.mjs | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/ui-ops.test.mjs | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 972 insertions(+), 0 deletions(-)

diff --git a/common/lib/montage/speakerCheck.mjs b/common/lib/montage/speakerCheck.mjs @@ -0,0 +1,206 @@ +// THE SPEAKER CHECK (UI notes 2026-10-30, #15): which of SEVERAL named voices +// a clip is -- "Speaker: matches Ember 0.93 / Kirsche 0.83" -- where the voice +// match (voiceMatch.mjs, release 34) scores every clip against ONE voice, the +// host's. Panel shows (Side Scrollers, Kirsche) were attributed this way by +// hand in scratch projects; this is the same arithmetic as a project's own +// file. +// +// The pieces are voiceMatch.mjs's, unchanged: a span decoded at 16 kHz mono on +// the window's own clock, the voiced-frames gate (a fallback span when the +// phrase holds too little speech), ONE embedding process for every clip and +// every reference piece (TitaNet-small through sherpa-onnx, or the test kit's +// fake embedder), a robust centroid per voice, the cosine to it. Each named +// reference set ("speaker") is clips of the cut, or reference pieces of +// recordings; a clip that is itself in a speaker's set is scored against the +// rest of that set (leave-one-out). Deterministic for a given model and input; +// no network; nothing rules -- the verification is still a person listening. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + DEFAULT_THRESHOLDS, + FALLBACK_SPEECH_S, + MIN_SPEECH_S, + SAMPLE_RATE, + VOICE_MATCH_MODEL, + decodeSpan, + embedWavs, + encodeWav16, + robustCentroid, + scoreAgainst, + voicedSamples, +} from "./voiceMatch.mjs"; + +export const SPEAKER_CHECK_FILE = "speaker-check.json"; +export const SPEAKER_CHECK_VERSION = 1; +/** A best voice this far ahead of the next is a match; closer is unsure. */ +export const SPEAKER_MARGIN = 0.05; + +const round = (x, n = 3) => Math.round(x * 10 ** n) / 10 ** n; + +/** + * A clip's verdict from its scores (best first): `matches` (the best at or + * over `likely` and SPEAKER_MARGIN ahead of the next), `none` (every voice + * under `unlikely`: someone the reference sets do not hold), else `unsure`. + * @param {{ name: string, score: number }[]} scores + */ +export function speakerVerdict(scores, t = DEFAULT_THRESHOLDS) { + const [a, b] = scores; + if (!a) return { label: /** @type {const} */ ("unsure"), best: null, margin: null }; + const margin = b ? round(a.score - b.score) : null; + if (a.score < t.unlikely) return { label: /** @type {const} */ ("none"), best: a.name, margin }; + if (a.score >= t.likely && (margin === null || margin >= SPEAKER_MARGIN)) return { label: /** @type {const} */ ("matches"), best: a.name, margin }; + return { label: /** @type {const} */ ("unsure"), best: a.name, margin }; +} + +/** + * Score `clips` against every named voice in `speakers`. + * + * @param {{ + * clips: Array<{ key: string, id?: string | null, file: string | null, start: number, dur: number, fallback?: { start: number, dur: number } | null, missing?: string }>, + * check?: string[], the keys to score (default every clip); the rest are only reference + * speakers: Array<{ name: string, clipKeys?: string[], items?: Array<{ key: string, file: string, start: number, dur: number, label?: string }>, recordings?: unknown[] }>, + * engine: { python: string, script: string, model: string, threads?: number }, + * scratch: string, + * thresholds?: { likely: number, unlikely: number }, + * ffmpeg?: string, + * now?: () => Date, + * onProgress?: (e: { event: string, n?: number, of?: number, items?: number }) => void, + * }} o + */ +export async function runSpeakerCheck(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 }); + const check = new Set(o.check ?? o.clips.map((c) => c.key)); + const refClipKeys = new Set(o.speakers.flatMap((s) => s.clipKeys ?? [])); + + /** @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 (id, 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(id, { seconds: 0, wav: null, why: `decode failed: ${e instanceof Error ? e.message : String(e)}` }); + return; + } + if (v.seconds < MIN_SPEECH_S) { + prepared.set(id, { 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(id, { seconds: v.seconds, wav, fallback: usedFallback }); + }; + const wanted = o.clips.filter((c) => check.has(c.key) || refClipKeys.has(c.key)); + let k = 0; + for (const c of wanted) { + 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: wanted.length }); + } + for (const s of o.speakers) for (const r of s.items ?? []) await prepare(`ref:${s.name}:${r.key}`, r.file, r.start, r.dur); + + 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; + + // Each voice: its pieces, the outliers out. + const voices = o.speakers.map((s) => { + const all = [ + ...(s.clipKeys ?? []).map((key) => ({ key: `clip:${key}`, clipKey: key, vector: vec(`clip:${key}`) })), + ...(s.items ?? []).map((r) => ({ key: `ref:${s.name}:${r.key}`, clipKey: null, vector: vec(`ref:${s.name}:${r.key}`) })), + ].filter((r) => r.vector); + const robust = robustCentroid(all.map((r) => /** @type {number[]} */ (r.vector))); + const kept = robust.kept.map((i) => all[i]); + return { + name: s.name, + kept, + doc: { + name: s.name, + clips: [...(s.clipKeys ?? [])], + recordings: s.recordings ?? [], + pieces: (s.clipKeys?.length ?? 0) + (s.items?.length ?? 0), + embedded: all.length, + kept: kept.length, + dropped: robust.dropped.map((i) => all[i].clipKey ?? all[i].key.replace(/^ref:[^:]*:/, "")), + }, + }; + }); + + /** @type {Record<string, Record<string, unknown>>} */ + const clips = {}; + for (const c of o.clips) { + if (!check.has(c.key)) continue; + const p = prepared.get(`clip:${c.key}`); + const v = vec(`clip:${c.key}`); + /** @type {Record<string, unknown>} */ + const row = { speechSeconds: round(p?.seconds ?? 0, 2), scores: [] }; + if (c.id) row.id = c.id; + if (p?.fallback) row.fallback = true; + if (!c.file) row.why = 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 { + const scores = []; + for (const voice of voices) { + const s = scoreAgainst(v, voice.kept.map((r) => ({ key: r.key, vector: /** @type {number[]} */ (r.vector) })), { selfKey: `clip:${c.key}` }); + if (s.score == null) continue; + scores.push({ name: voice.name, score: s.score, best: s.best, ...(voice.kept.some((r) => r.clipKey === c.key) ? { inReference: true } : {}) }); + } + scores.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)); + row.scores = scores; + if (!scores.length) row.why = "no reference voice has pieces to compare with"; + else Object.assign(row, speakerVerdict(scores, t)); + } + clips[c.key] = row; + } + await rm(scratch, { recursive: true, force: true }); + return { + version: SPEAKER_CHECK_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, margin: SPEAKER_MARGIN }, + speakers: voices.map((v) => v.doc), + clips, + }; +} + +/** `<project>/speaker-check.json`, or null. */ +export async function readSpeakerCheck(dir) { + try { + const doc = JSON.parse(await readFile(path.join(dir, SPEAKER_CHECK_FILE), "utf8")); + return doc && doc.version === SPEAKER_CHECK_VERSION && doc.clips && typeof doc.clips === "object" ? doc : null; + } catch { + return null; + } +} + +/** + * Written whole (tmp + rename), MERGED into the file there: a check of one + * clip keeps the other clips' rows -- when they were scored against the same + * voices (by name and pieces); a change of the reference sets starts over. + */ +export async function writeSpeakerCheck(dir, doc) { + const file = path.join(dir, SPEAKER_CHECK_FILE); + const prev = await readSpeakerCheck(dir); + const sig = (d) => JSON.stringify((d?.speakers ?? []).map((s) => [s.name, s.clips, s.recordings])); + const merged = prev && sig(prev) === sig(doc) ? { ...doc, clips: { ...prev.clips, ...doc.clips } } : doc; + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`); + await rename(tmp, file); + return { file, doc: merged }; +} diff --git a/common/lib/montage/speakerCheck.test.ts b/common/lib/montage/speakerCheck.test.ts @@ -0,0 +1,75 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { encodeWav16 } from "./voiceMatch.mjs"; +import { SPEAKER_CHECK_FILE, readSpeakerCheck, runSpeakerCheck, speakerVerdict, writeSpeakerCheck } from "./speakerCheck.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice } from "../../testing/audio/syntheticVoice.mjs"; +import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; + +// The speaker check (UI notes 2026-10-30, #15): which of several named voices +// a clip is. Two synthetic voices the test kit's fake embedder tells apart; +// no python, no model. + +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(), "speaker-check-")); +const wav = (dir: string, name: string, x: Float32Array) => { + const f = path.join(dir, name); + writeFileSync(f, encodeWav16(x)); + return f; +}; + +test("speakerVerdict: matches when the best is over the bar and ahead by the margin; none under the floor; else unsure", () => { + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.93 }, { name: "Kirsche", score: 0.83 }]), { label: "matches", best: "Ember", margin: 0.1 }); + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.62 }, { name: "Kirsche", score: 0.6 }]), { label: "unsure", best: "Ember", margin: 0.02 }); + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.2 }]), { label: "none", best: "Ember", margin: null }); + assert.deepEqual(speakerVerdict([]), { label: "unsure", best: null, margin: null }); +}); + +test("runSpeakerCheck: each clip against every named voice, best first; a voice's own clip is scored against the rest of it", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { + const dir = tmp(); + try { + const a = [0.4, 1.1, 2.2].map((ph, i) => wav(dir, `a${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: ph }))); + const b = [0.7, 1.9].map((ph, i) => wav(dir, `b${i}.wav`, syntheticVoice({ ...VOICE_B, seconds: 2.5, phase: ph }))); + const probe = wav(dir, "probe.wav", syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: 3.3 })); + const clip = (key: string, file: string) => ({ key, id: key, file, start: 0, dur: 2.5 }); + const doc = await runSpeakerCheck({ + clips: [clip("a0", a[0]), clip("a1", a[1]), clip("p", probe)], + check: ["p", "a0"], + speakers: [ + { name: "Host", clipKeys: ["a0", "a1"], items: [{ key: "r2", file: a[2], start: 0, dur: 2.5 }] }, + { name: "Guest", items: b.map((f, i) => ({ key: `g${i}`, file: f, start: 0, dur: 2.5 })) }, + ], + engine: FAKE_ENGINE, + scratch: path.join(dir, "scratch"), + now: () => new Date("2026-11-02T10:00:00Z"), + }); + const p = doc.clips.p as { scores: { name: string; score: number }[]; label: string; best: string }; + assert.deepEqual(p.scores.map((s) => s.name), ["Host", "Guest"]); + assert.equal(p.label, "matches"); + assert.equal(p.best, "Host"); + assert.ok(p.scores[0].score > p.scores[1].score + 0.05, JSON.stringify(p.scores)); + // a0 is in Host's set: scored against a1 and r2, and says so. + const a0 = doc.clips.a0 as { scores: { name: string; inReference?: boolean }[]; label: string }; + assert.equal(a0.scores[0].name, "Host"); + assert.equal(a0.scores[0].inReference, true); + assert.equal("a1" in doc.clips, false, "a reference clip not asked for is not a row"); + assert.deepEqual(doc.speakers.map((s: { name: string; pieces: number; kept: number }) => [s.name, s.pieces, s.kept]), [["Host", 3, 3], ["Guest", 2, 2]]); + // The file merges a later check of one clip into the rows there. + await writeSpeakerCheck(dir, doc); + const again = { ...doc, clips: { p: { ...p, label: "unsure" } } }; + const { doc: merged } = await writeSpeakerCheck(dir, again); + assert.deepEqual(Object.keys(merged.clips).sort(), ["a0", "p"]); + assert.equal((await readSpeakerCheck(dir))?.clips.p && (merged.clips.p as { label: string }).label, "unsure"); + // New reference sets start the file over. + const { doc: fresh } = await writeSpeakerCheck(dir, { ...again, speakers: [{ ...doc.speakers[0], name: "Renamed" }] }); + assert.deepEqual(Object.keys(fresh.clips), ["p"]); + assert.ok(SPEAKER_CHECK_FILE.endsWith(".json")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/common/package.json b/common/package.json @@ -47,6 +47,7 @@ "./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/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs", "./lib/ports.mjs": "./lib/ports.mjs", "./lib/renderPriority.mjs": "./lib/renderPriority.mjs", "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs", diff --git a/umtool/app/api/report/speaker-check/route.ts b/umtool/app/api/report/speaker-check/route.ts @@ -0,0 +1,84 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { addClipToSpeaker, speakerBadge, speakerCheckSteps } from "@/lib/report/speakerCheck.mjs"; + +export const dynamic = "force-dynamic"; + +// THE SPEAKER CHECK ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches +// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against +// (lib/report/speakerCheck.mjs; the voices are <project>/speakers.json). +// "Check speaker" is ONE job on the app's runner (lib/jobs.ts: a log, the +// NDJSON events, Cancel) running `umtool speaker-check <p> --clip <id>` +// through the machine's heavy slot (queue-lock --heavy with its estimate: +// beside other jobs by memory, after a render the operator is waiting for). +// Local: TitaNet-small; no network, no LLM. +// +// GET ?project=<id>&clip=<id> the clip's row, the voices, and the check running, if any +// GET ?job=<id>[&since=&sinceEvent=] that job +// POST { project, clip } check that clip's speaker (a job) +// POST { project, clip, addTo: "<name>" } put the clip in that voice's reference set (made when new) +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + 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 clip = String(url.searchParams.get("clip") ?? ""); + const m = await readManifest(project.dir); + const running = runningJob(); + try { + return Response.json( + { + ...(await speakerBadge(project.dir, m ?? {}, clip)), + running: running && running.project === project.id && running.kind.startsWith("speaker-check ") ? jobView(running) : null, + }, + { headers }, + ); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} + +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 refused = refuseCaller(request, "/api/report/speaker-check"); + if (refused) return refused; + 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: "speakers are checked for a report video" }, { status: 400 }); + const clip = typeof body.clip === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(body.clip) ? body.clip : null; + if (!clip) return Response.json({ error: "which clip?" }, { status: 400 }); + if (typeof body.addTo === "string") { + try { + const speakers = await addClipToSpeaker(project.dir, body.addTo, clip); + return Response.json({ ok: true, speakers }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { 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 = speakerCheckSteps(project, { clip }); + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers }); + } 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 @@ -15,6 +15,7 @@ // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) +// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) // umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them @@ -777,6 +778,8 @@ function usage() { " umtool check [<project>] [--json] exit 1 on anything blocking", " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage", " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", + " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", + " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy", " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it", " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a", @@ -1000,6 +1003,8 @@ const COMMANDS = { trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), + // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. + "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), // The project's link policy (UI notes #10): lib/report/linksCli.mjs. "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))), // A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs. diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -19,6 +19,7 @@ import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { cn } from "@/lib/utils"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import SpeakerBadge from "./SpeakerBadge"; import CopyCitation from "./bench/CopyCitation"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport"; import EdgeStrip from "./bench/EdgeStrip"; @@ -2725,6 +2726,8 @@ export default function ClipBench({ > {verdictLabel(clip)} </span> + {/* Which named voice it is (UI notes #15): the speaker check's row, and Check speaker. */} + <SpeakerBadge project={data.project} clip={clip.id} /> </VerdictBar> ); diff --git a/umtool/components/projects/SpeakerBadge.tsx b/umtool/components/projects/SpeakerBadge.tsx @@ -0,0 +1,158 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// THE SPEAKER BADGE ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches +// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against, +// and "Check speaker", which queues `umtool speaker-check <p> --clip <id>` as +// a job through the machine's heavy slot (POST /api/report/speaker-check). The +// voices are the project's speakers.json; "Add to a voice" puts this clip in +// one. An aid to the ear: the verdict is still the walk's. + +type Score = { name: string; score: number; best: number | null; inReference?: boolean }; +type Badge = { + speakers: { name: string; clips: string[]; videos: string[]; channels: string[]; inReference: boolean }[]; + result: null | { scores: Score[]; label?: "matches" | "unsure" | "none"; best?: string; margin?: number | null; why?: string; line: string; madeAt: string | null; speechSeconds?: number }; + reference: null | { name: string; pieces: number; kept: number; clips: string[]; recordings: { channel: string; video: string }[] }[]; + running: null | { id: string; state: string }; + error?: string; +}; +type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[] }; + +export default function SpeakerBadge({ project, clip }: { project: string; clip: string }) { + const [badge, setBadge] = useState<Badge | null>(null); + const [job, setJob] = useState<JobPoll | null>(null); + const [err, setErr] = useState<string | null>(null); + const [voice, setVoice] = useState(""); + const timer = useRef<ReturnType<typeof setTimeout> | null>(null); + + const load = useCallback(async () => { + const r = await fetch(`/api/report/speaker-check?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as Badge | null; + if (!r.ok || !j) { + setErr(j?.error ?? `HTTP ${r.status}`); + return; + } + setBadge(j); + }, [project, clip]); + + useEffect(() => { + void load(); + return () => { + if (timer.current) clearTimeout(timer.current); + }; + }, [load]); + + const follow = useCallback( + (id: string) => { + const tick = async () => { + const r = await fetch(`/api/report/speaker-check?job=${encodeURIComponent(id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as JobPoll | null; + if (!j) return; + setJob(j); + if (j.state === "running") timer.current = setTimeout(() => void tick(), 1000); + else void load(); + }; + void tick(); + }, + [load], + ); + + const check = async () => { + setErr(null); + const r = await fetch("/api/report/speaker-check", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip }), + }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string }; error?: string }; + if (!r.ok || !j.job) { + setErr(j.error ?? `HTTP ${r.status}`); + return; + } + follow(j.job.id); + }; + + const addTo = async () => { + const name = voice.trim(); + if (!name) return; + setErr(null); + const r = await fetch("/api/report/speaker-check", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip, addTo: name }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string }; + if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`); + setVoice(""); + void load(); + }; + + if (!badge) return err ? <span data-speaker-badge="error" className="text-[11.5px] text-doubt-text">{err}</span> : null; + const res = badge.result; + const running = job?.state === "running" || (!!badge.running && !job); + const label = res?.label ?? (res ? "unscored" : "unchecked"); + const tone = label === "matches" ? "text-[var(--color-good)]" : label === "none" ? "text-[var(--color-dirty)]" : "text-text-2"; + const mine = badge.speakers.find((s) => s.inReference); + const refWords = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length, kept: 0, clips: s.clips, recordings: [] }))) + .map((s) => `${s.name}: ${s.pieces} piece${s.pieces === 1 ? "" : "s"}${s.kept ? ` (${s.kept} kept)` : ""}`) + .join(" · "); + + return ( + <span data-speaker-badge={label} className="inline-flex flex-wrap items-center gap-2 text-[12px]"> + <span data-speaker-line="" className={tone} title={refWords ? `measured against: ${refWords}` : undefined}> + Speaker: {res ? res.line : badge.speakers.length ? "not checked" : "no voices named"} + </span> + {res && ( + <span data-speaker-reference="" className="text-[11px] text-muted"> + against {refWords || "—"} + {res.madeAt ? ` · ${res.madeAt.slice(0, 16).replace("T", " ")}` : ""} + </span> + )} + {mine && <span className="text-[11px] text-muted">this clip is in {mine.name}&rsquo;s voice</span>} + <button + type="button" + data-speaker-check="" + disabled={running || !badge.speakers.length} + onClick={() => void check()} + className={buttonVariants({ variant: "quiet", size: "md" })} + title={ + badge.speakers.length + ? "scores this clip's voice against each named voice (TitaNet-small, local) as a job through the heavy slot" + : "name the voices first: Add to a voice, or umtool speaker-check <p> --set 'Name=…'" + } + > + {running ? "Checking…" : "Check speaker"} + </button> + <span className="inline-flex items-center gap-1"> + <input + data-speaker-voice="" + list={`voices-${clip}`} + value={voice} + onChange={(e) => setVoice(e.target.value)} + placeholder="voice name" + className="w-[8.5rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px]" + /> + <datalist id={`voices-${clip}`}> + {badge.speakers.map((s) => ( + <option key={s.name} value={s.name} /> + ))} + </datalist> + <button type="button" data-speaker-add="" disabled={!voice.trim()} onClick={() => void addTo()} className={buttonVariants({ variant: "quiet", size: "md" })} title="this clip is that voice: it joins the voice's reference set (speakers.json)"> + Add to a voice + </button> + </span> + {job?.state === "failed" && ( + <span data-speaker-error="" className="text-[11.5px] text-doubt-text"> + {job.error ?? job.log.at(-1) ?? "the check failed"} + </span> + )} + {err && ( + <span data-speaker-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </span> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -67,6 +67,7 @@ Inbox cannot disagree about what is wrong with one. | `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | | `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)) | +| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1551,6 +1551,32 @@ 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. +### The speaker check on the walk: which of several voices + +The voice match scores every clip against one voice, the host's. A panel show needs more: which of +**several named voices** a clip is. `umtool speaker-check <project> [--clip <id> …]` scores each clip +the same way (TitaNet-small through sherpa-onnx, local; the phrase ± 1 s, voiced frames only) against +each voice in `<project>/speakers.json` — + +```json +{ "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] }, + { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] } +``` + +— a voice's **clips** of this cut, **videos** of that voice alone (the first 60 s of speech, in +pieces), or **channels** whose solo recordings it is (the voice match's heuristic). A clip in a voice's +set is scored against the rest of it. The answer is `<project>/speaker-check.json` (a check of one clip +keeps the others' rows; new reference sets start it over): per clip, every voice's score best first, +and `matches` (the best ≥ 0.42 and 0.05 ahead of the next), `none` (every one under 0.30: a voice the +sets do not hold) or `unsure`. + +On the clip bench's walk the verdict bar says **Speaker: matches Ember 0.93 / Kirsche 0.83**, with the +reference sets it was measured against; **Check speaker** queues the check of that clip as a job +through the machine's heavy slot (`queue-lock --heavy --estimate 800`: beside other jobs by memory, +after a render in render mode), and **Add to a voice** puts the clip in a voice's set (made when new). +From a terminal: `umtool speaker-check <p> --set 'Ember=e01,e07' --set 'Kirsche=kirsche/abc123,channel:kirsche'`, +`--remove <name>`, `--list`. An aid to the ear: it rules on nothing. + ## Highlights: the clip finder A long recording cut down to its best moments — a stream, a podcast, a host diff --git a/umtool/lib/report/speakerCheck.mjs b/umtool/lib/report/speakerCheck.mjs @@ -0,0 +1,321 @@ +// `umtool speaker-check <project>` (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, `<project>/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 <name>'s voice") +// videos recordings of that voice alone (`<channel>/<id>`): 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"; + +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 = `${file}.${process.pid}.tmp`; + 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=<clip id | channel/id | channel:slug>,… (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:<id>, video:<channel>/<id> or channel:<slug>`); + } + 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 <project> [--clip <id> …] [--json] [--progress ndjson]", + " umtool speaker-check <project> --list | --set 'Name=<clip id>,<channel>/<id>,channel:<slug>,…' | --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 -> ${"<project>"}/speaker-check.json (merged:`, + "a check of one clip keeps the others'). The voices are <project>/speakers.json: per name, clips of the cut,", + "recordings of that voice alone (<channel>/<id>), 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<string, unknown> }} [opts] + */ +export async function speakerCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) { + try { + const words = []; + /** @type {Record<string, string[]>} */ + 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=<clip id>,<channel>/<id>,…'), 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, + }; +} diff --git a/umtool/lib/report/ui-ops.test.mjs b/umtool/lib/report/ui-ops.test.mjs @@ -308,3 +308,95 @@ test("takeEta: the median rate of the same kind, times the length; none of its k assert.match(String(win?.note), /no past fresh take of a window — from the project's other renders/); assert.equal(takeEta([], { seconds: 60 }), null); }); + +// ---- #15 the speaker check ------------------------------------------------ + +const { execFileSync } = await import("node:child_process"); +const { fileURLToPath } = await import("node:url"); +const { encodeWav16 } = await import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"); +const { VOICE_A, VOICE_B, syntheticVoice, withSilence } = await import("yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"); +const { PROJECT_KINDS } = await import("../projects/kinds.mjs"); +const sc = await import("./speakerCheck.mjs"); + +const FAKE_EMBED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +test("speakers.json: names checked, a spec parsed, a clip added to one voice at a time", async () => { + assert.deepEqual(sc.normalizeSpeakers({ speakers: [{ name: " Ember ", clips: ["e01", "e01"], videos: ["ember/abc"] }] }), [{ name: "Ember", clips: ["e01"], videos: ["ember/abc"], channels: [] }]); + assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "a/b" }] }), /no \/ = or comma/); + assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "X" }, { name: "x" }] }), /two speakers are named "x"/); + assert.throws(() => sc.normalizeSpeakers({}), /speakers\.json is/); + assert.deepEqual(sc.parseSpeakerSpec("Kirsche=k01,kirsche/v9,channel:kirsche"), { name: "Kirsche", clips: ["k01"], videos: ["kirsche/v9"], channels: ["kirsche"] }); + const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-speakers-")); + try { + assert.deepEqual(await sc.readSpeakers(dir), []); + await sc.addClipToSpeaker(dir, "Ember", "e01"); + await sc.addClipToSpeaker(dir, "Kirsche", "k01"); + await sc.addClipToSpeaker(dir, "Kirsche", "e01"); + assert.deepEqual((await sc.readSpeakers(dir)).map((s) => [s.name, s.clips]), [["Ember", []], ["Kirsche", ["k01", "e01"]]]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("Check speaker is one job through the heavy slot, with its estimate", () => { + const plan = sc.speakerCheckSteps({ id: "reports/x" }, { clip: "k04", queueLock: "/repo/scripts/queue-lock.mjs" }); + assert.equal(plan.kind, "speaker-check reports/x"); + const argv = plan.steps[0].argv; + assert.deepEqual(argv.slice(1, 5), ["/repo/scripts/queue-lock.mjs", "--heavy", "--estimate", "800"]); + assert.deepEqual(argv.slice(argv.indexOf("speaker-check")), ["speaker-check", "reports/x", "--clip", "k04", "--progress", "ndjson"]); + assert.equal(sc.speakerCheckSteps({ id: "p" }, { queueLock: null }).steps[0].argv[0], "nice"); +}); + +test("umtool speaker-check: each clip against the named voices, over a synthetic corpus; the walk's badge reads the row", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => { + const root = await mkdtemp(path.join(tmpdir(), "ui-ops-speaker-")); + try { + const chans = path.join(root, "channels"); + const encode = async (x, out) => { + await writeFile(`${out}.wav`, encodeWav16(x)); + execFileSync("ffmpeg", ["-v", "error", "-y", "-i", `${out}.wav`, "-c:a", "aac", "-b:a", "96k", out]); + await rm(`${out}.wav`); + }; + const timeline = []; + for (const [id, voice, phase] of [["k01", VOICE_A, 0.3], ["k02", VOICE_A, 1.6], ["k03", VOICE_B, 0.8], ["k04", VOICE_A, 2.9]]) { + const d = path.join(chans, "chan", "data", `v${id}`); + await mkdir(path.join(d, "clips"), { recursive: true }); + await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify({ id: `v${id}`, cues: [{ start: 102.5, end: 104, text: "slow news day" }] })); + await encode(withSilence(syntheticVoice({ ...voice, seconds: 2.5, phase }), { before: 2, after: 3.5 }), path.join(d, "clips", "100.00-108.00.mp4")); + timeline.push({ type: "clip", id, channel: "chan", video: `v${id}`, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, quote: "slow news day" }); + } + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "cut"); + await mkdir(dir, { recursive: true }); + const manifest = { schemaVersion: 1, slug: "cut", title: "Cut", kind: PROJECT_KINDS.find((k) => k.makesTakes).id, provenance: { channelsDir: "../../channels", channelSlug: "chan" }, render: {}, timeline }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)); + const out = []; + const io = { reportsRoot, log: (s) => out.push(s), err: (s) => out.push(s), engine: { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx" } }; + // No voices yet: refused, saying how to name them. + assert.equal(await sc.speakerCheckCommand(["cut"], io), 2); + assert.match(out.join("\n"), /no voices to compare with: name them in speakers\.json/); + assert.equal(await sc.speakerCheckCommand(["cut", "--set", "Host=k01,k02", "--set", "Guest=k03"], io), 0); + out.length = 0; + assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "k04"], io), 0, out.join("\n")); + assert.match(out.join("\n"), /k04 {3}matches Host \d\.\d\d \/ Guest 0\.\d\d/); + const doc = JSON.parse(await readFile(path.join(dir, "speaker-check.json"), "utf8")); + assert.deepEqual(Object.keys(doc.clips), ["chan/vk04@102.50"]); + const badge = await sc.speakerBadge(dir, manifest, "k04"); + assert.equal(badge.result?.label, "matches"); + assert.match(badge.result?.line ?? "", /^matches Host \d\.\d\d \/ Guest 0\.\d\d$/); + assert.deepEqual(badge.reference?.map((s) => [s.name, s.pieces]), [["Host", 2], ["Guest", 1]]); + assert.deepEqual(badge.speakers.map((s) => s.name), ["Host", "Guest"]); + // A clip with no row yet. + assert.equal((await sc.speakerBadge(dir, manifest, "k02")).result, null); + assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "nope"], io), 2); + } finally { + await rm(root, { recursive: true, force: true }); + } +});