import { type Aliases, expandAliases, matchingBlocks, round, tokenize } from './promo-text.ts' import { type Span } from './media-logs.ts' export type ScriptLine = { id: string; text: string } export type AsrWord = { start: number; end: number; text: string } export type NarrationAlignInput = { lines: ScriptLine[] /** whisper.cpp `-ml 1 -sow` segments, seconds in the take file. */ asrWords: AsrWord[] /** silencedetect noise=-45dB:d=0.15 spans on the take (see SILENCE_REFINE). */ silences: Span[] durationSeconds: number /** Extra spoken-form aliases, e.g. `{ "cody|kodi|kogi": "kody" }`. */ aliases?: Aliases /** Minimum fraction of script words matched to ASR words. Default 0.9. */ minMatchRatio?: number /** Max distance a refined line edge may sit from its ASR estimate. Default 1 s. */ maxLineShiftSeconds?: number } export type AlignedWord = { line: string; token: string; start: number; end: number; matched: boolean } export type AlignedLine = { id: string; start: number; end: number; words: number; matched: number } export type Cluster = { from: string; to: string; line: string; t: number; n: number } export type NarrationAlignResult = { pass: boolean matchRatio: number firstWordSeconds: number durationSeconds: number lines: AlignedLine[] words: AlignedWord[] clusters: Cluster[] issues: string[] next: string params: { minMatchRatio: number; maxLineShiftSeconds: number; aliases: Array<[string, string]>; silenceRefine: typeof SILENCE_REFINE } } // Chunking silences: cut the take at natural pauses so whisper times don't drift. export const SILENCE_CHUNK = { noiseDb: -40, minSeconds: 0.25 } as const // Refinement silences: measured pauses used for line and phrase edges. export const SILENCE_REFINE = { noiseDb: -45, minSeconds: 0.15 } as const export type ChunkPlanInput = { durationSeconds: number; silences: Span[]; maxChunkSeconds?: number } // Chunk cut points (take seconds, including 0 and the end) from SILENCE_CHUNK silences. export function chunkPlan(input: ChunkPlanInput): number[] { const max = input.maxChunkSeconds ?? 8 const dur = input.durationSeconds const mids = input.silences .filter((s) => s.start > 0.05 && s.end < dur - 0.05) .map((s) => (s.start + s.end) / 2) const cuts = [0] let last = 0 for (const m of mids) { if (m - last > max * 0.6) { cuts.push(m) last = m } } cuts.push(dur) return cuts } // whisper-cli arguments used per chunk. A short vocabulary prompt only: a full-script prompt inflates word times. export function whisperArgs(opts: { model: string; file: string; outBase: string; prompt?: string; threads?: number }) { const args = ['-m', opts.model, '-f', opts.file, '-ml', '1', '-sow', '-oj', '-of', opts.outBase, '-np', '-t', String(opts.threads ?? 4)] if (opts.prompt) args.push('--prompt', opts.prompt) return args } type Tok = { token: string; start: number; end: number } function splitPhrases(text: string) { return text.split(/(?<=[,.:;?!])\s+/).filter((p) => p.trim()) } /** * Align ONE continuous narration take to the exact script, word by word. * Pure and deterministic: pass whisper.cpp word segments and ffmpeg silences * (the local runner `skills/product-promo-video/scripts/narration-align.mjs` * produces both); get per-word and per-line take times plus a pass/fail verdict. * * Method: script tokens are matched to ASR tokens (difflib-style blocks); line * boundaries are then moved to the measured pause nearest each ASR estimate, * and inside each line punctuation phrases are paired with measured speech * segments by dynamic programming, because whisper.cpp offsets collapse on * fast continuous speech. Three or more words on one timestamp fail the run. * * @param input - script lines, ASR words, silences (-45 dB / 0.15 s), take duration * @returns words, lines, matchRatio, clusters, pass, issues, next * * @example * import narrationAlign from 'kody:@kody/skills/narration-align' * * const align = await narrationAlign({ * lines: [{ id: 'n01', text: 'One package. Two accounts.' }], * asrWords: [{ start: 0, end: 0.4, text: 'One' }, { start: 0.4, end: 0.9, text: 'package.' }], * silences: [{ start: 0.9, end: 1.1 }], * durationSeconds: 2, * }) */ export default function narrationAlign(input: NarrationAlignInput): NarrationAlignResult { if (!input || typeof input !== 'object') throw new Error('input object is required') const allowed = new Set(['lines', 'asrWords', 'silences', 'durationSeconds', 'aliases', 'minMatchRatio', 'maxLineShiftSeconds']) const unknown = Object.keys(input).filter((k) => !allowed.has(k)) if (unknown.length) throw new Error(`unknown input key(s): ${unknown.join(', ')}`) if (!Array.isArray(input.lines) || !input.lines.length) throw new Error('lines must be a non-empty array') if (!Array.isArray(input.asrWords) || !input.asrWords.length) throw new Error('asrWords must be a non-empty array') if (!Array.isArray(input.silences)) throw new Error('silences must be an array') if (!(input.durationSeconds > 0)) throw new Error('durationSeconds must be > 0') const dur = input.durationSeconds const aliases = input.aliases ?? {} const minMatchRatio = input.minMatchRatio ?? 0.9 const maxLineShift = input.maxLineShiftSeconds ?? 1 const issues: string[] = [] // 1. ASR words -> tokens (spread evenly over the word), merging multi-token aliases split across words. const asr = input.asrWords.filter((w) => w.text.trim()) let hyp: Tok[] = [] for (const w of asr) { const ts = tokenize(w.text, aliases) ts.forEach((token, j) => { hyp.push({ token, start: w.start + ((w.end - w.start) * j) / ts.length, end: w.start + ((w.end - w.start) * (j + 1)) / ts.length }) }) } for (const [from, to] of expandAliases(aliases)) { const parts = from.split(' ') if (parts.length < 2) continue const merged: Tok[] = [] for (let i = 0; i < hyp.length; i++) { if (parts.every((p, k) => hyp[i + k]?.token === p)) { merged.push({ token: to, start: hyp[i].start, end: hyp[i + parts.length - 1].end }) i += parts.length - 1 } else merged.push(hyp[i]) } hyp = merged } // 2. Script tokens; matched script words take ASR times, unmatched are interpolated. const ref = input.lines.flatMap((l) => tokenize(l.text, aliases).map((token) => ({ line: l.id, token }))) const times: Array<[number, number] | null> = ref.map(() => null) for (const blk of matchingBlocks(ref.map((r) => r.token), hyp.map((h) => h.token))) { for (let k = 0; k < blk.size; k++) times[blk.a + k] = [hyp[blk.b + k].start, hyp[blk.b + k].end] } const known = times.map((t, i) => (t ? i : -1)).filter((i) => i >= 0) const knownSet = new Set(known) for (let i = 0; i < ref.length; i++) { if (times[i]) continue const before = known.filter((k) => k < i) const after = known.filter((k) => k > i) const p = before.length ? before[before.length - 1] : null const n = after.length ? after[0] : null const t0 = p !== null ? times[p]![1] : 0 const t1 = n !== null ? times[n]![0] : dur const gp = i - (p ?? -1) const gn = (n ?? ref.length) - (p ?? -1) const s = t0 + ((t1 - t0) * (gp - 1)) / Math.max(gn - 1, 1) times[i] = [s, Math.min(t1, s + (t1 - t0) / Math.max(gn - 1, 1))] } // 3. Refine with measured speech segments. const sil = input.silences const segs: Array<[number, number]> = [] let cur = 0 for (const g of sil) { if (g.start - cur > 0.02) segs.push([Math.max(cur, 0), g.start]) cur = g.end } if (dur - cur > 0.02) segs.push([cur, dur]) const raw = times.map((t) => [...t!] as [number, number]) const reliable = (i: number) => knownSet.has(i) && raw[i][1] - raw[i][0] >= 0.06 && raw[i][1] - raw[i][0] <= 1.2 const interior = sil.filter((g) => g.start > 0.02 && g.end < dur - 0.02) const lineIds = input.lines.map((l) => l.id) const idx = new Map(lineIds.map((id) => [id, ref.map((r, i) => (r.line === id ? i : -1)).filter((i) => i >= 0)])) if (!segs.length) issues.push('no speech segments found between silences') else { type Bound = number | Span const bounds: Bound[] = [segs[0][0]] for (let n = 0; n + 1 < lineIds.length; n++) { const a = idx.get(lineIds[n])! const b = idx.get(lineIds[n + 1])! const lastOk = a.filter(reliable).map((i) => raw[i][1]).slice(-1) const firstOk = b.filter(reliable).map((i) => raw[i][0]).slice(0, 1) const est = ((lastOk[0] ?? raw[a[a.length - 1]][1]) + (firstOk[0] ?? raw[b[0]][0])) / 2 const prev = bounds[bounds.length - 1] const prevPos = typeof prev === 'number' ? prev : prev.end let cand = interior.filter((g) => (g.start + g.end) / 2 > prevPos + 0.3) if (!cand.length) cand = interior if (!cand.length) { issues.push(`no measured pause between ${lineIds[n]} and ${lineIds[n + 1]}`) bounds.push({ start: est, end: est }) continue } let best = cand[0] for (const g of cand) if (Math.abs((g.start + g.end) / 2 - est) < Math.abs((best.start + best.end) / 2 - est)) best = g bounds.push(best) } bounds.push(segs[segs.length - 1][1]) lineIds.forEach((id, n) => { const lo = n === 0 ? (bounds[0] as number) : (bounds[n] as Span).end const hi = n + 1 === lineIds.length ? (bounds[n + 1] as number) : (bounds[n + 1] as Span).start const lsegs = segs.filter((g) => g[1] > lo + 0.01 && g[0] < hi - 0.01).map((g) => [Math.max(g[0], lo), Math.min(g[1], hi)] as [number, number]) const text = input.lines[n].text const phr = splitPhrases(text).map((p) => tokenize(p, aliases)).filter((p) => p.length) const ws = idx.get(id)! if (phr.reduce((s, p) => s + p.length, 0) !== ws.length || !lsegs.length) { issues.push(`${id}: phrase refinement skipped (${lsegs.length ? 'phrase tokens differ from line tokens' : 'no speech segment inside the line'}); ASR times kept`) return } const pc = phr.map((p) => p.reduce((s, t) => s + t.length + 1, 0)) const rate = lsegs.reduce((s, g) => s + g[1] - g[0], 0) / Math.max(pc.reduce((s, c) => s + c, 0), 1) const P = phr.length const S = lsegs.length const f = Array.from({ length: P + 1 }, () => new Array(S + 1).fill(Infinity)) const back: Array> = Array.from({ length: P + 1 }, () => new Array(S + 1).fill(null)) f[0][0] = 0 for (let pi = 1; pi <= P; pi++) for (let sj = 1; sj <= S; sj++) for (let a = 1; a <= Math.min(pi, 4); a++) for (let b = 1; b <= Math.min(sj, 4); b++) { if (f[pi - a][sj - b] === Infinity) continue let segt = 0 for (let m = sj - b; m < sj; m++) segt += lsegs[m][1] - lsegs[m][0] const want = rate * pc.slice(pi - a, pi).reduce((s, c) => s + c, 0) const c = f[pi - a][sj - b] + (segt - want) ** 2 + 0.05 * (a - 1 + b - 1) if (c < f[pi][sj]) { f[pi][sj] = c back[pi][sj] = [a, b] } } if (f[P][S] === Infinity) { issues.push(`${id}: ${P} phrases cannot pair with ${S} speech segments; ASR times kept`) return } const groups: Array<[number[], number[]]> = [] let pi = P let sj = S while (pi > 0) { const [a, b] = back[pi][sj]! groups.push([Array.from({ length: a }, (_, k) => pi - a + k), Array.from({ length: b }, (_, k) => sj - b + k)]) pi -= a sj -= b } groups.reverse() let wi = 0 for (const [prs, sgs] of groups) { const gw: number[] = [] for (const pr of prs) { gw.push(...ws.slice(wi, wi + phr[pr].length)) wi += phr[pr].length } const tot = sgs.reduce((s, m) => s + lsegs[m][1] - lsegs[m][0], 0) const chars = gw.map((w) => ref[w].token.length + 1) const ctot = chars.reduce((s, c) => s + c, 0) const at = (x: number) => { for (const m of sgs) { const d = lsegs[m][1] - lsegs[m][0] if (x <= d) return lsegs[m][0] + x x -= d } return lsegs[sgs[sgs.length - 1]][1] } let acc = 0 gw.forEach((w, k) => { times[w] = [at((tot * acc) / ctot), at((tot * (acc + chars[k])) / ctot)] acc += chars[k] }) } }) } const words: AlignedWord[] = ref.map((r, i) => ({ line: r.line, token: r.token, start: round(times[i]![0]), end: round(times[i]![1]), matched: knownSet.has(i) })) const clusters: Cluster[] = [] let run = 1 for (let i = 1; i <= words.length; i++) { if (i < words.length && Math.abs(words[i].start - words[i - 1].start) < 0.02) run++ else { if (run >= 3) clusters.push({ from: words[i - run].token, to: words[i - 1].token, line: words[i - 1].line, t: words[i - 1].start, n: run }) run = 1 } } const lines: AlignedLine[] = input.lines.map((l) => { const w = words.filter((x) => x.line === l.id) return { id: l.id, start: w[0]?.start ?? 0, end: w[w.length - 1]?.end ?? 0, words: w.length, matched: w.filter((x) => x.matched).length } }) for (const l of lines) if (!l.words) issues.push(`${l.id}: no script words`) // Guard: refinement may only nudge a line to real pause edges, never relocate it onto other speech. const drifted: string[] = [] for (const l of lines) { const li = idx.get(l.id) ?? [] // With no reliable word (collapsed times) only the start edge is a usable estimate. const hasReliable = li.some(reliable) const ri = hasReliable ? li.filter(reliable) : li.filter((i) => knownSet.has(i)) if (!ri.length) continue const ds = Math.abs(l.start - raw[ri[0]][0]) const de = hasReliable ? Math.abs(l.end - raw[ri[ri.length - 1]][1]) : 0 if (ds > maxLineShift || de > maxLineShift) { drifted.push(l.id) issues.push(`${l.id}: refined edges moved ${round(ds)}s / ${round(de)}s from the ASR estimate (max ${maxLineShift}s); a line boundary has no measured pause`) } } const matchRatio = round(known.length / Math.max(ref.length, 1)) if (clusters.length) issues.push(`collapsed word times: ${clusters.map((c) => `${c.line} "${c.from}..${c.to}" x${c.n} at ${c.t}s`).join('; ')}`) if (matchRatio < minMatchRatio) issues.push(`matchRatio ${matchRatio} < ${minMatchRatio}`) const pass = !clusters.length && !drifted.length && matchRatio >= minMatchRatio && !lines.some((l) => !l.words) return { pass, matchRatio, firstWordSeconds: round(asr[0].start), durationSeconds: round(dur), lines, words, clusters, issues, next: pass ? 'Run voice-pauses on the same take, then voice-timing with this result.' : 'Fix the take or alignment before timing anything. See references/troubleshooting.md (alignment).', params: { minMatchRatio, maxLineShiftSeconds: maxLineShift, aliases: expandAliases(aliases), silenceRefine: SILENCE_REFINE }, } }