Archilyzer · Source

archilyzer

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

commit 4664fa246c860d26c74b0bf08c2e6c8837a53724
parent 0c5940b96ba0cdd8dfe36216753568a1be5dad0a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 16:50:29 -0400

umtool: voice-match — `umtool voice-match <project>`, the Cut tab's "Score the voices" job, and a voice chip per clip

lib/report/voiceMatch.mjs: each clip's phrase ± 1 s (whisper words, then cues, as the montage
render finds it; else the cut), from the file the render cuts from (sources.mjs), the cut ± 1 s as
the fallback when the phrase span has under 1.5 s of speech; the reference: the clips ruled keep in
montage-rulings.json (≥ 3), else solo uploads on disk spread over the years (--reference-video to
name them); --instances scores a phrase scan's dropped instances (a calibration). Writes
<project>/voice-match.json. /api/report/voice-match runs it as one nice'd job; the Cut tab shows
the summary and "voice 0.43 · unsure" on each row. report-to-video exports ./montage.

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

Diffstat:
Aumtool/app/api/report/voice-match/route.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/components/projects/report/CutTab.tsx | 35+++++++++++++++++++++++++++++++++++
Aumtool/components/projects/report/VoiceMatchPanel.tsx | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/voiceMatch.mjs | 417+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/voiceMatch.test.mjs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
7 files changed, 832 insertions(+), 0 deletions(-)

diff --git a/umtool/app/api/report/voice-match/route.ts b/umtool/app/api/report/voice-match/route.ts @@ -0,0 +1,64 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readVoiceMatch } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { voiceMatchSteps } from "@/lib/report/voiceMatch.mjs"; + +export const dynamic = "force-dynamic"; + +// WHO IS SPEAKING, PER MONTAGE CLIP (release 34) -- the Cut tab's "Score the +// voices", as ONE job on the app's runner (lib/jobs.ts: one at a time, a log, +// the NDJSON events, Cancel). The job runs the CLI (`umtool voice-match`), so +// the button and a terminal do the same thing. Local and light (TitaNet-small +// on a few seconds a clip, nice'd): no heavy slot, no network, no LLM. +// +// GET ?job=<id>[&since=&sinceEvent=] that job +// GET ?project=<id> the project's voice-match.json summary, and the job running, if any +// POST { project, reference?: "auto" | "rulings" | "recordings" } +// ?cancel=<job> stop it; nothing is written until the run is done +export async function GET(request: Request) { + const url = new URL(request.url); + const headers = { "cache-control": "no-store" }; + const id = url.searchParams.get("job"); + if (id) { + const job = getJob(id); + if (!job) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const project = await projectRef(String(url.searchParams.get("project") ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const doc = await readVoiceMatch(project.dir); + const running = runningJob(); + return Response.json( + { + voiceMatch: doc ? { madeAt: doc.madeAt, counts: doc.counts, reference: doc.reference, thresholds: doc.thresholds } : null, + running: running && running.project === project.id && running.kind.startsWith("voice-match ") ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const { cancelJob } = await import("@/lib/jobs"); + return Response.json({ cancelled: cancelJob(cancel) }); + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "voices are scored for a report video" }, { status: 400 }); + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + const plan = voiceMatchSteps(project, { reference: typeof body.reference === "string" ? body.reference : undefined }); + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -50,6 +50,8 @@ // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] // [--at S --dur S | --full] [--force] | --id <id> --rebuild make one take // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] +// umtool voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json] +// a speaker-similarity score per montage clip -> <project>/voice-match.json import process from "node:process"; import { PROJECT_KINDS, @@ -718,6 +720,8 @@ function usage() { " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]", " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", + " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", + " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json", " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", @@ -754,6 +758,8 @@ const COMMANDS = { // The take maker (release 33): lib/report/takeCli.mjs. take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), + // Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs. + "voice-match": async () => process.exit(await (await import("../lib/report/voiceMatch.mjs")).voiceMatchCommand(argv.slice(argv.indexOf("voice-match") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -13,6 +13,8 @@ import FetchUnfetchedButton from "../FetchUnfetchedButton"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; +import VoiceMatchPanel from "./VoiceMatchPanel"; +import { readVoiceMatch, voiceMatchKey } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. @@ -53,6 +55,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; const showAll = search.all === "1"; const takes = await listTakes(project.dir); + // Who is speaking, per clip (release 34): voice-match.json, keyed by the + // source moment (channel/video@cutStart), so a re-seed keeps its scores. + const voices = await readVoiceMatch(project.dir); + const voiceOf = (e: { channel?: string | null; video?: string; cutStart?: number; start: number }) => + voices && e.channel && e.video ? voices.clips[voiceMatchKey(e.channel, e.video, e.cutStart ?? e.start)] ?? null : null; // ---- what a clip's "mix" link opens --------------------------------------- // @@ -137,6 +144,23 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor Make takes </Link> )} + {clips.length > 0 && ( + <VoiceMatchPanel + project={project.id} + summary={ + voices + ? { + madeAt: voices.madeAt, + counts: voices.counts, + reference: + voices.reference.kind === "rulings" + ? `${voices.reference.kept} clips ruled keep` + : `${(voices.reference.recordings as unknown[] | undefined)?.length ?? 0} solo recordings`, + } + : null + } + /> + )} </div> {/* --- the timeline --------------------------------------------- */} @@ -224,6 +248,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </Pill> )} {e.segment && <Pill>segment built</Pill>} + {(() => { + const v = voiceOf(e); + if (!v) return null; + return ( + <span data-voice={v.label ?? "unscored"} data-voice-score={v.score ?? ""}> + <Pill tone={v.label === "unlikely" ? TONE.blocking : v.label === "unsure" ? TONE.open : TONE.info}> + {v.score == null ? `voice: ${v.why ?? "not scored"}` : `voice ${v.score.toFixed(2)} · ${v.label}`} + </Pill> + </span> + ); + })()} {!e.hasCues && ( <Pill tone={TONE.blocking}>no cues</Pill> )} diff --git a/umtool/components/projects/report/VoiceMatchPanel.tsx b/umtool/components/projects/report/VoiceMatchPanel.tsx @@ -0,0 +1,146 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import { JobProgress } from "@/components/ui/job-progress"; + +// --------------------------------------------------------------------------- +// "Score the voices" (release 34): who is speaking, per montage clip. +// +// One job (`umtool voice-match <project>`, lib/report/voiceMatch.mjs): each +// clip's phrase, voiced frames only, against the host's voice — the clips +// ruled keep when there are three, else solo recordings on disk. Local +// (TitaNet-small through sherpa-onnx) and light: no network, no LLM. +// +// It is an aid to the ear and says so: the score sorts and flags; the ruling +// is still a person listening. The rows below show each clip's score once a +// run has written voice-match.json. +// --------------------------------------------------------------------------- + +type JobView = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[]; events: Record<string, unknown>[] }; + +export type VoiceMatchSummary = { + madeAt: string; + counts: { clips: number; scored: number; likely: number; unsure: number; unlikely: number }; + reference: string; +}; + +const REFERENCES = [ + ["auto", "keeps, else solo recordings"], + ["rulings", "the clips ruled keep"], + ["recordings", "solo recordings on disk"], +] as const; + +export default function VoiceMatchPanel({ project, summary }: { project: string; summary: VoiceMatchSummary | null }) { + const router = useRouter(); + const [reference, setReference] = useState<string>("auto"); + const [job, setJob] = useState<JobView | null>(null); + const [error, setError] = useState<string | null>(null); + const alive = useRef(true); + useEffect(() => () => void (alive.current = false), []); + + async function watch(id: string) { + for (;;) { + await new Promise((r) => setTimeout(r, 1000)); + if (!alive.current) return; + const r = await fetch(`/api/report/voice-match?job=${encodeURIComponent(id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as (JobView & { error?: string | null }) | null; + if (!r.ok || !j || !j.state) { + setError(j?.error ?? "the job is gone"); + return; + } + setJob(j); + if (j.state !== "running") { + if (j.state === "done") router.refresh(); + return; + } + } + } + + async function start() { + setError(null); + const r = await fetch("/api/report/voice-match", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, reference }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string }; + if (!r.ok || !j.job) { + setError(j.error ?? `HTTP ${r.status}`); + return; + } + setJob(j.job); + void watch(j.job.id); + } + + const running = job?.state === "running"; + const last = [...(job?.events ?? [])].reverse().find((e) => e.ev === "voice-match") as { phase?: string; n?: number; of?: number } | undefined; + return ( + <div data-voice-match="" className="flex flex-col items-start gap-1"> + <div className="flex flex-wrap items-center gap-2"> + <button + type="button" + data-action="voice-match" + data-state={running ? "busy" : job?.state ?? "idle"} + disabled={running} + onClick={() => void start()} + className={buttonVariants({ size: "sm" })} + > + {running ? "Scoring the voices…" : summary ? "Score the voices again" : "Score the voices"} + </button> + <label className="flex items-center gap-1 text-[11px] text-text-2"> + reference + <select + data-voice-reference="" + value={reference} + disabled={running} + onChange={(e) => setReference(e.target.value)} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-1 py-0.5 text-[11px]" + > + {REFERENCES.map(([v, label]) => ( + <option key={v} value={v}> + {label} + </option> + ))} + </select> + </label> + </div> + {summary && ( + <span data-voice-summary="" className="num text-[11px] text-[var(--color-dim)]"> + voices: {summary.counts.likely} likely · {summary.counts.unsure} unsure · {summary.counts.unlikely} unlikely of{" "} + {summary.counts.scored} scored · against {summary.reference} · {summary.madeAt.slice(0, 16).replace("T", " ")} + </span> + )} + {job && ( + <JobProgress + data-voice-job={job.id} + label="score the voices" + state={job.state} + status={ + job.state === "running" + ? last?.phase === "decode" && last.n + ? `reading clip ${last.n} of ${last.of}` + : last?.phase === "embed" + ? "embedding" + : "planning" + : `${job.state}${job.error ? ` — ${job.error}` : ""}` + } + log={job.state === "failed" ? job.log.slice(-12) : undefined} + logLabel="voice-match log" + onCancel={ + running + ? () => void fetch(`/api/report/voice-match?cancel=${encodeURIComponent(job.id)}`, { method: "POST" }) + : undefined + } + /> + )} + {error && ( + <p data-voice-error="" role="alert" className="text-[12px] text-reject-text"> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/lib/report/voiceMatch.mjs b/umtool/lib/report/voiceMatch.mjs @@ -0,0 +1,417 @@ +// `umtool voice-match <project>` (release 34): who is speaking, per montage +// clip — a local speaker-similarity score written to <project>/voice-match.json. +// +// The scoring is common's (yt-dlp-transcript-common/lib/montage/voiceMatch.mjs: +// the voiced-frames gate, TitaNet-small through sherpa-onnx, the reference +// centroid). This module is umtool's half: WHICH seconds of WHICH file each +// clip is, and which recordings are the host's voice. +// +// - A clip's seconds are its phrase ± PHRASE_PAD_S: the phrase found the way +// the montage render finds it (whisper.cpp's word offsets in the corpus's +// transcript.json first, then the cues by character position — report-to- +// video/montage.mjs `locatePhrase`), else its cut (cutStart–cutEnd) ± the +// pad. Read from the file the render would cut from (report-to-video/ +// sources.mjs: the project's raw cache, the corpus's clip windows, a saved +// source, the sound), on that file's own clock (`clockOffset`). +// - The reference: the clips ruled `keep` in montage-rulings.json (lane N1) +// when there are at least REFERENCE_MIN_RULINGS, else solo recordings of +// the host found on disk (`referenceRecordings`). `--reference` forces one. +// +// The app's Cut tab runs this same command as a job (voiceMatchSteps), so a +// button and a terminal do one thing. Nothing here calls a model but the +// local speaker-embedding one; nothing touches the network. +import { readdir, readFile } from "node:fs/promises"; +import os from "node:os"; +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, + voiceMatchKey, + 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 { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { REPO_ROOT } from "../paths.mjs"; +import { UMTOOL_DIR } from "./driver.mjs"; + +export { VOICE_MATCH_FILE }; +/** Lane N1's file: `{version: 1, rulings: {<key>: {verdict, …}}}`. */ +export const RULINGS_FILE = "montage-rulings.json"; +export const REFERENCE_MODES = Object.freeze(["auto", "rulings", "recordings"]); + +export const VOICE_MATCH_USAGE = [ + "usage: umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …]", + " [--reference-channel <slug> …] [--instances FILE] [--span phrase|cut]", + " [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]", + "", + "A speaker-similarity score per montage clip against the host's voice, written to", + `<project>/${VOICE_MATCH_FILE}: TitaNet-small (sherpa-onnx, local) on each clip's phrase ± ${PHRASE_PAD_S} s,`, + "voiced frames only. An aid to the ear: the audition deck sorts the doubtful ones first; it rules on nothing.", + `The reference: the clips ruled keep in ${RULINGS_FILE} (at least ${REFERENCE_MIN_RULINGS}), else solo recordings on`, + `disk — captioned uploads with no ">>" speaker change and no second voice in the title, the first`, + `${REFERENCE_SECONDS} s of speech of up to ${REFERENCE_VIDEOS}, spread over the years (or --reference-video).`, + "--instances FILE also scores a phrase scan's instances that are not in the manifest (a calibration).", + "The engine: VOICE_MATCH_PYTHON / VOICE_MATCH_MODEL, else settings.diarization.python / .embModel, else .diarize/.", +].join("\n"); + +class CliError extends Error {} + +function parse(args) { + const valued = new Set(["--reference", "--reference-video", "--reference-channel", "--instances", "--span", "--pad", "--likely", "--unlikely", "--out", "--progress", "--videos"]); + /** @type {Record<string, string[]>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + (flags[a] ??= []).push(args[++i]); + } else (flags[a] ??= []).push(""); + } else positional.push(a); + } + return { flags, positional, one: (n) => flags[n]?.[flags[n].length - 1], has: (n) => n in flags, all: (n) => flags[n] ?? [] }; +} + +const num = (x) => typeof x === "number" && Number.isFinite(x); +const readJson = (file) => readFile(file, "utf8").then(JSON.parse, () => null); + +/** The `keep` keys of montage-rulings.json, in the file's order; [] without one. */ +export async function keepRulings(dir) { + const doc = await readJson(path.join(dir, RULINGS_FILE)); + const rulings = doc && typeof doc === "object" && doc.rulings && typeof doc.rulings === "object" ? doc.rulings : {}; + return Object.entries(rulings).filter(([, r]) => r && r.verdict === "keep").map(([k]) => k); +} + +/** A corpus video's whisper words and cues, read once each. */ +function transcriptReader(channelsDir) { + const cache = new Map(); + return (slug, video) => { + const key = `${slug}/${video}`; + if (!cache.has(key)) { + cache.set(key, (async () => { + const dir = await resolveVideoDir(channelsDir, slug, video).catch(() => path.join(channelsDir, slug, "data", video)); + const [words, cues] = await Promise.all([ + readJson(path.join(dir, "transcript.json")).then((d) => (d ? whisperWords(d) : null)), + readJson(path.join(dir, "transcript.cues.json")).then((d) => (Array.isArray(d?.cues) ? d.cues : [])), + ]); + return { words, cues }; + })()); + } + return cache.get(key); + }; +} + +/** + * The seconds one clip is scored on, in SOURCE time: the phrase ± the pad + * (`via` "words" | "cues"), else the cut ± the pad (`via` "cut"). + */ +export async function clipSpan(entry, slug, transcripts, { span = "phrase", pad = PHRASE_PAD_S } = {}) { + const hasCut = num(entry.cutStart) && num(entry.cutEnd); + const cut = hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end }; + const phrase = clipPhrase(entry); + if (span === "phrase" && phrase) { + const near = (cut.start + cut.end) / 2; + const range = { from: cut.start - 0.5, to: cut.end + 0.5, near }; + const t = await transcripts(slug, entry.video); + const byWords = t.words ? locatePhrase(phrase, t.words, range) : null; + const found = byWords ?? locatePhrase(phrase, t.cues, range); + if (found) { + return { + from: Math.max(0, found.start - pad), to: found.end + pad, via: byWords ? "words" : "cues", + cut: { from: Math.max(0, cut.start - pad), to: cut.end + pad }, + }; + } + } + return { from: Math.max(0, cut.start - pad), to: cut.end + pad, via: "cut", cut: null }; +} + +/** A clip-like entry for one phrase-scan instance (umtool's seed shape). */ +const instanceEntry = (i) => ({ + 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; + if (!slug || !entry.video) return; + const cutStart = num(entry.cutStart) ? entry.cutStart : entry.start; + const key = voiceMatchKey(slug, entry.video, cutStart); + if (seen.has(key)) return; + seen.add(key); + const s = await clipSpan(entry, slug, transcripts, { span, pad }); + const base = { key, ...(id ? { id } : {}), channel: slug, video: entry.video, from: s.from, to: s.to, via: s.via }; + let hit = await resolveLocalSource({ video: entry.video, slug, from: s.from, to: s.to }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + let from = s.from; + let to = s.to; + if (!hit && num(entry.cutStart) && num(entry.cutEnd)) { + // A window that holds the cut but not its pad: the cut alone. + hit = await resolveLocalSource({ video: entry.video, slug, from: entry.cutStart, to: entry.cutEnd }, { rawDir, channelsDir, audio: true, probe: ffprobeSource }); + if (hit) { + from = Math.max(entry.cutStart, hit.windowStart); + to = Math.min(entry.cutEnd, hit.windowEnd); + } + } + if (!hit) { + rows.push({ ...base, file: null, start: 0, dur: 0, missing: "no local window" }); + return; + } + const off = await clockOffset(hit.path); + const at = (t) => Math.max(0, t - hit.windowStart - off); + // The cut ± the pad, clamped to the window: what is decoded when the phrase + // span has too little speech in it. + const fb = s.cut && from === s.from ? { a: Math.max(s.cut.from, hit.windowStart), b: Math.min(s.cut.to, hit.windowEnd) } : null; + rows.push({ + ...base, file: hit.path, source: hit.kind, start: at(from), dur: to - from, + ...(fb && fb.b - fb.a > 0 ? { fallback: { start: at(fb.a), dur: fb.b - fb.a } } : {}), + }); + }; + for (const e of manifest?.timeline ?? []) { + if (e?.type === "clip" && !e.src) await add(e, e.id); + } + for (const i of instances) { + if (i && typeof i === "object" && i.slug && i.videoId && num(i.start) && num(i.end)) await add(instanceEntry(i), null); + } + return rows; +} + +const SOURCE_NAME = /^(?:saved-video\.json|source-media\.[a-z0-9]+|audio\.(?:mp3|m4a|opus))$/; + +/** + * Solo recordings of the host on disk, as reference pieces. Candidates: every + * video of `channels` with a whole source on disk (a saved video, a + * source-media file, its sound) whose transcript passes `soloRecordingWhy`; + * `pickReferenceRecordings` spreads `n` over the years. Each gives the first + * REFERENCE_SECONDS from its first cue, in REFERENCE_PIECE_S pieces. Or the + * named `videos` (`<channel>/<id>`), whatever their transcript says. + */ +export async function referenceRecordings({ channelsDir, channels, videos = [], n = REFERENCE_VIDEOS, exclude = new Set() }) { + /** @type {{ slug: string, videoId: string, date: string | null, title: string | null, first: number }[]} */ + let picked = []; + const skipped = []; + if (videos.length) { + for (const v of videos) { + const [slug, videoId] = String(v).split("/"); + if (!slug || !videoId) throw new CliError(`--reference-video ${v}: <channel>/<id>`); + const dir = await resolveVideoDir(channelsDir, slug, videoId).catch(() => path.join(channelsDir, slug, "data", videoId)); + const doc = await readJson(path.join(dir, "transcript.cues.json")); + picked.push({ slug, videoId, date: doc?.uploadDate ?? null, title: doc?.title ?? null, first: Number(doc?.cues?.[0]?.start ?? 0) || 0 }); + } + } else { + const candidates = []; + for (const slug of channels) { + const dataDir = path.join(channelsDir, slug, "data"); + const ids = await readdir(dataDir).catch(() => []); + for (const id of ids) { + if (exclude.has(`${slug}/${id}`)) continue; + const names = await readdir(path.join(dataDir, id)).catch(() => []); + if (!names.some((x) => SOURCE_NAME.test(x))) continue; + const doc = await readJson(path.join(dataDir, id, "transcript.cues.json")); + if (soloRecordingWhy(doc) !== null) continue; + candidates.push({ slug, videoId: String(doc.id ?? id), dirId: id, date: doc.uploadDate ?? null, title: doc.title ?? null, first: Number(doc.cues[0]?.start ?? 0) || 0 }); + } + } + picked = pickReferenceRecordings(candidates, n); + } + const items = []; + for (const r of picked) { + const from = Math.max(0, r.first); + const hit = await resolveLocalSource( + { video: r.videoId, slug: r.slug, from, to: from + REFERENCE_SECONDS }, + { channelsDir, audio: true, probe: ffprobeSource }, + ); + if (!hit) { + skipped.push({ channel: r.slug, video: r.videoId, why: "no local source covers it" }); + continue; + } + const off = await clockOffset(hit.path); + for (let k = 0; k * REFERENCE_PIECE_S < REFERENCE_SECONDS; k += 1) { + items.push({ + key: `${r.slug}/${r.videoId}#${k}`, slug: r.slug, video: r.videoId, date: r.date, title: r.title, + file: hit.path, start: Math.max(0, from + k * REFERENCE_PIECE_S - hit.windowStart - off), dur: REFERENCE_PIECE_S, + }); + } + } + return { items, skipped }; +} + +async function pickProject(arg, root) { + if (!arg) throw new CliError("which project? pass an id, a name, or a directory"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + return r.project; +} + +const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); + +/** + * `umtool voice-match …` + * @param {string[]} args everything after `voice-match` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, engine?: Record<string, unknown> }} [opts] + */ +export async function voiceMatchCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) { + try { + const p = parse(args); + if (p.has("--help") || !p.positional.length) { + log(VOICE_MATCH_USAGE); + return p.has("--help") ? 0 : 2; + } + const project = await pickProject(p.positional[0], reportsRoot); + const ndjson = p.one("--progress") === "ndjson"; + if (p.has("--progress") && !ndjson) throw new CliError("--progress takes ndjson"); + const say = (line) => (ndjson ? err(line) : log(line)); + const emit = (ev) => { + if (ndjson) log(JSON.stringify({ ev: "voice-match", ...ev })); + }; + const mode = p.one("--reference") ?? "auto"; + if (!REFERENCE_MODES.includes(mode)) throw new CliError(`--reference ${mode}: one of ${REFERENCE_MODES.join(", ")}`); + const span = p.one("--span") ?? "phrase"; + if (span !== "phrase" && span !== "cut") throw new CliError("--span phrase|cut"); + const pad = p.has("--pad") ? Number(p.one("--pad")) : PHRASE_PAD_S; + if (!Number.isFinite(pad) || pad < 0 || pad > 5) throw new CliError("--pad takes 0..5 seconds"); + const thresholds = { ...DEFAULT_THRESHOLDS }; + for (const k of /** @type {const} */ (["likely", "unlikely"])) { + if (p.has(`--${k}`)) { + const v = Number(p.one(`--${k}`)); + if (!Number.isFinite(v) || v < 0 || v > 1) throw new CliError(`--${k} takes 0..1`); + thresholds[k] = v; + } + } + if (thresholds.unlikely > thresholds.likely) throw new CliError("--unlikely is at most --likely"); + + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDir) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from"); + const instances = p.has("--instances") ? await readJson(path.resolve(/** @type {string} */ (p.one("--instances")))) : []; + if (!Array.isArray(instances)) throw new CliError("--instances: a JSON array of phrase-scan instances"); + + emit({ phase: "plan" }); + const clips = await planClips(project.dir, manifest, { channelsDir, instances, span, pad }); + const keeps = (await keepRulings(project.dir)).filter((k) => clips.some((c) => c.key === k && c.file)); + const useRulings = mode === "rulings" || (mode === "auto" && keeps.length >= REFERENCE_MIN_RULINGS); + if (mode === "rulings" && keeps.length < 2) throw new CliError(`--reference rulings: ${keeps.length} clip(s) ruled keep with a window; at least 2`); + /** @type {import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs").ReferenceSpec} */ + let reference; + let skipped = []; + if (useRulings) { + reference = { kind: "rulings", keys: keeps }; + say(`reference: ${keeps.length} clip(s) ruled keep`); + } else { + const channels = [...new Set([...clips.map((c) => c.channel), manifest.provenance?.channelSlug].filter(Boolean))]; + const extra = p.all("--reference-channel"); + const r = await referenceRecordings({ + channelsDir, + channels: extra.length ? extra : channels, + videos: p.all("--reference-video"), + n: p.has("--videos") ? Math.max(1, Number(p.one("--videos")) || REFERENCE_VIDEOS) : REFERENCE_VIDEOS, + }); + skipped = r.skipped; + if (!r.items.length) throw new CliError("no reference: no clip ruled keep and no solo recording on disk (--reference-video <channel>/<id>)"); + reference = { kind: "recordings", items: r.items }; + say(`reference: ${new Set(r.items.map((i) => `${i.slug}/${i.video}`)).size} recording(s), ${r.items.length} piece(s)`); + } + const missing = clips.filter((c) => !c.file).length; + say(`${clips.length} clip(s) to score${missing ? `, ${missing} with no local window` : ""}`); + if (p.has("--dry")) { + const plan = { clips, reference, skipped }; + log(p.has("--json") ? JSON.stringify(plan, null, 1) : clips.map((c) => `${c.id ?? "-"} ${c.key} ${c.via} ${c.file ? `${path.basename(c.file)} +${c.start.toFixed(2)} ${c.dur.toFixed(2)}s` : c.missing}`).join("\n")); + return 0; + } + + let settings = null; + try { + settings = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")); + } catch { + settings = null; + } + const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts }); + const scratch = path.join(process.env.VOICE_MATCH_SCRATCH ?? os.tmpdir(), `umtool-voice-match-${process.pid}`); + const t0 = Date.now(); + const doc = await runVoiceMatch({ + clips: clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })), + pad, + reference, + engine, + scratch, + thresholds, + onProgress: (e) => emit({ phase: e.event, ...(e.n ? { n: e.n, of: e.of } : {}), ...(e.items ? { items: e.items } : {}) }), + }); + if (skipped.length) doc.reference.skipped = skipped; + doc.span = span; + for (const c of clips) { + const row = doc.clips[c.key]; + if (!row) continue; + row.via = c.via; + if (!c.id) row.from = "instances"; + } + const out = p.has("--out") ? path.resolve(/** @type {string} */ (p.one("--out"))) : null; + const file = out + ? (await import("node:fs/promises")).writeFile(out, `${JSON.stringify(doc, null, 1)}\n`).then(() => out) + : writeVoiceMatch(project.dir, doc); + const written = await file; + emit({ phase: "done", file: written, counts: doc.counts, seconds: Math.round((Date.now() - t0) / 100) / 10 }); + if (p.has("--json")) log(JSON.stringify(doc, null, 1)); + else if (!ndjson) { + for (const c of clips) { + const r = doc.clips[c.key]; + log(`${(c.id ?? "-").padEnd(4)} ${c.key.padEnd(56)} ${r.score == null ? " - " : r.score.toFixed(3)} ${String(r.label ?? r.why ?? "").padEnd(9)} ${Number(r.speechSeconds).toFixed(1)}s`); + } + log(`${doc.counts.likely} likely · ${doc.counts.unsure} unsure · ${doc.counts.unlikely} unlikely of ${doc.counts.scored} scored → ${written}`); + } else say(`${doc.counts.likely} likely · ${doc.counts.unsure} unsure · ${doc.counts.unlikely} unlikely → ${written}`); + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool voice-match: ${e.message}` : `umtool voice-match: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} + +/** The CLI path the app's job runs. */ +const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + +/** + * The Cut tab's "Score the voices": ONE job step on lib/jobs.ts running this + * command, nice'd (it is light — TitaNet-small on a few seconds a clip — so it + * does not take the heavy slot). + * @param {{ id: string }} project + * @param {{ reference?: string }} [req] + */ +export function voiceMatchSteps(project, req = {}) { + const mode = typeof req.reference === "string" && REFERENCE_MODES.includes(req.reference) ? req.reference : "auto"; + return { + kind: `voice-match ${project.id}`, + steps: [{ + label: "score each clip's voice", + argv: ["nice", "-n", "10", "node", umtoolCli(), "voice-match", project.id, "--reference", mode, "--progress", "ndjson"], + cwd: UMTOOL_DIR, + env: {}, + ndjson: /** @type {const} */ (true), + timeoutMs: 15 * 60 * 1000, + }], + }; +} diff --git a/umtool/lib/report/voiceMatch.test.mjs b/umtool/lib/report/voiceMatch.test.mjs @@ -0,0 +1,163 @@ +// `umtool voice-match` (release 34 N2): the plan (which seconds of which file), +// the reference (keeps, else solo recordings on disk), the CLI end to end over a +// synthetic corpus with the test kit's fake embedder, and the app's job step. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; +import { keepRulings, planClips, referenceRecordings, voiceMatchCommand, voiceMatchSteps } from "./voiceMatch.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FAKE = path.resolve(HERE, "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx" }; +const KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +/** A wav of `x`, encoded by ffmpeg to an audio-only AAC file at `out`. */ +async function encode(x, out) { + const wav = `${out}.wav`; + await writeFile(wav, encodeWav16(x)); + execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "aac", "-b:a", "96k", out]); + await rm(wav); +} + +const cuesDoc = (id, cues, extra = {}) => ({ id, title: `Upload ${id}`, uploadDate: "20200101", duration: 200, source: "vtt", isLivestream: false, platform: "youtube", cues, ...extra }); + +/** + * A corpus and a project: three solo uploads of VOICE_A with their sound on + * disk (the reference), and clips whose windows say "slow news day" in + * VOICE_A (s01, s03, s04) or VOICE_B (s02, the guest). + */ +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), "voice-match-")); + const chans = path.join(root, "channels"); + const data = (id) => path.join(chans, "chan", "data", id); + for (const [i, date] of ["20190101", "20210101", "20230101"].entries()) { + const id = `solo${i}`; + await mkdir(data(id), { recursive: true }); + await writeFile(path.join(data(id), "transcript.cues.json"), JSON.stringify(cuesDoc(id, [{ start: 2, end: 5, text: "what is going on everyone" }], { uploadDate: date }))); + await encode(withSilence(syntheticVoice({ ...VOICE_A, seconds: 66, phase: i * 0.9 }), { before: 2 }), path.join(data(id), "audio.m4a")); + } + // An upload that is NOT a reference: a ">>" speaker change. + await mkdir(data("duo"), { recursive: true }); + await writeFile(path.join(data("duo"), "transcript.cues.json"), JSON.stringify(cuesDoc("duo", [{ start: 2, end: 5, text: ">> and you" }]))); + await encode(syntheticVoice({ ...VOICE_B, seconds: 70 }), path.join(data("duo"), "audio.m4a")); + + const clips = [ + ["s01", "host1", VOICE_A, 1.7], + ["s02", "guest1", VOICE_B, 0.4], + ["s03", "host2", VOICE_A, 3.1], + ["s04", "host3", VOICE_A, 4.6], + ]; + const timeline = []; + for (const [id, video, voice, phase] of clips) { + // The window is source seconds 100–108; the phrase is said at 102.5–104. + await mkdir(path.join(data(video), "clips"), { recursive: true }); + await writeFile(path.join(data(video), "transcript.cues.json"), JSON.stringify(cuesDoc(video, [{ start: 102.5, end: 104, text: "slow news day" }]))); + const sound = withSilence(syntheticVoice({ ...voice, seconds: 2.5, phase }), { before: 2, after: 3.5 }); + await encode(sound, path.join(data(video), "clips", "100.00-108.00.mp4")); + timeline.push({ type: "clip", id, channel: "chan", video, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, montage: { match: "slow news day" } }); + } + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "montage"); + await mkdir(dir, { recursive: true }); + const manifest = { schemaVersion: 1, slug: "montage", title: "Montage", kind: KIND, provenance: { channelsDir: "../../channels", channelSlug: "chan" }, render: {}, timeline }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 1)); + return { root, chans, dir, reportsRoot, manifest }; +} + +const quiet = () => { + const out = []; + return { out, log: (s) => out.push(s), err: (s) => out.push(s) }; +}; + +test("voice-match: the plan, the reference recordings, and the CLI over a synthetic corpus", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => { + const f = await fixture(); + try { + // The plan: the phrase found in the cues, ± 1 s, on the window's clock. + const plan = await planClips(f.dir, f.manifest, { channelsDir: f.chans }); + assert.equal(plan.length, 4); + const s01 = plan.find((c) => c.id === "s01"); + assert.equal(s01.key, "chan/host1@102.50"); + assert.equal(s01.via, "cues"); + assert.ok(Math.abs(s01.start - 1.5) < 0.05 && Math.abs(s01.dur - 3.5) < 0.05, `+${s01.start} ${s01.dur}s`); + assert.ok(s01.fallback, "the cut ± the pad is the fallback"); + + // The reference: the three solo uploads, not the one with a ">>". + const ref = await referenceRecordings({ channelsDir: f.chans, channels: ["chan"] }); + assert.deepEqual([...new Set(ref.items.map((i) => i.video))], ["solo0", "solo1", "solo2"]); + assert.equal(ref.items.length, 18, "six 10 s pieces each"); + assert.ok(Math.abs(ref.items[0].start - 2) < 0.05, "from the first cue"); + + // The CLI end to end. + const q = quiet(); + const code = await voiceMatchCommand(["montage", "--json"], { reportsRoot: f.reportsRoot, ...q, engine: ENGINE }); + assert.equal(code, 0, q.out.join("\n")); + const doc = JSON.parse(await readFile(path.join(f.dir, "voice-match.json"), "utf8")); + assert.equal(doc.version, 1); + assert.equal(doc.model, "titanet-small"); + assert.equal(doc.reference.kind, "recordings"); + assert.equal(doc.reference.recordings.length, 3); + assert.equal(doc.clips["chan/host1@102.50"].label, "likely"); + assert.equal(doc.clips["chan/guest1@102.50"].label, "unlikely"); + assert.equal(doc.clips["chan/host1@102.50"].id, "s01"); + assert.ok(doc.clips["chan/host1@102.50"].speechSeconds <= 2.6, "the pad's silence is not speech"); + + // Three keeps: the reference is the ruled clips, each scored against the others. + await writeFile( + path.join(f.dir, "montage-rulings.json"), + JSON.stringify({ version: 1, rulings: Object.fromEntries(["host1", "host2", "host3"].map((v) => [`chan/${v}@102.50`, { verdict: "keep", reason: "", at: "2026-10-18T00:00:00Z" }])) }), + ); + assert.deepEqual(await keepRulings(f.dir), ["chan/host1@102.50", "chan/host2@102.50", "chan/host3@102.50"]); + assert.equal(await voiceMatchCommand(["montage"], { reportsRoot: f.reportsRoot, ...quiet(), engine: ENGINE }), 0); + const ruled = JSON.parse(await readFile(path.join(f.dir, "voice-match.json"), "utf8")); + assert.equal(ruled.reference.kind, "rulings"); + assert.equal(ruled.clips["chan/host2@102.50"].inReference, true); + assert.equal(ruled.clips["chan/guest1@102.50"].label, "unlikely"); + + // --dry plans and writes nothing new. + const dry = quiet(); + assert.equal(await voiceMatchCommand(["montage", "--dry", "--reference", "recordings"], { reportsRoot: f.reportsRoot, ...dry, engine: ENGINE }), 0); + assert.match(dry.out.join("\n"), /s02 {2}chan\/guest1@102\.50 {2}cues {2}100\.00-108\.00\.mp4/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("voice-match: refusals in words", async () => { + const q = quiet(); + assert.equal(await voiceMatchCommand(["no-such-project"], { reportsRoot: path.join(tmpdir(), "nowhere-voice"), ...q }), 2); + assert.match(q.out.join("\n"), /no project matches/); + const help = quiet(); + assert.equal(await voiceMatchCommand(["--help"], { ...help }), 0); + assert.match(help.out.join("\n"), /usage: umtool voice-match/); +}); + +test("voiceMatchSteps: one nice'd job step running the CLI, NDJSON", () => { + const plan = voiceMatchSteps({ id: "montage" }, { reference: "recordings" }); + assert.equal(plan.kind, "voice-match montage"); + assert.equal(plan.steps.length, 1); + const [s] = plan.steps; + assert.deepEqual(s.argv.slice(0, 4), ["nice", "-n", "10", "node"]); + assert.match(s.argv[4], /umtool[\\/]bin[\\/]umtool\.mjs$/); + assert.deepEqual(s.argv.slice(5), ["voice-match", "montage", "--reference", "recordings", "--progress", "ndjson"]); + assert.equal(s.ndjson, true); + assert.equal(voiceMatchSteps({ id: "m" }, { reference: "bogus" }).steps[0].argv.includes("auto"), true); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -28,6 +28,7 @@ "./factcheck": "./factcheck.mjs", "./frames-cut": "./frames-cut.mjs", "./ledger-totals": "./ledger-totals.mjs", + "./montage": "./montage.mjs", "./montage-styles": "./montage-styles.mjs", "./lint": "./lint.mjs", "./local-media": "./local-media.mjs",