// quote-in-audio — IS THE QUOTE IN THE SECONDS THE CLIP PLAYS? (lane one-clock) // // The per-clip guarantee the operator's ear was giving: transcribe what the // render will actually play (the clip's source window, words timed), find the // clip's `quote` in those words, and say how far from the cue clock's seconds // it is. On 6 Nov seven Rumble clips played other words than their quotes // (c43 +13.1 s: the 9:18 "310" misclip, c45 +13.6 s, c20 +5.2 s, k41 +2.6 s, // c18 +1.6 s, k46 −0.7 s, c19 ≈ −1 s) and only listening caught it. // // THE MATCH is loose on purpose: the quote is prose a person wrote about speech // a machine transcribed. Case, punctuation, `[bracketed]` editorial words and // apostrophes go; NUMBERS are one token however they are written ("thirty eight // point five" = "38.5", "a hundred" = "100", "three hundred ten point five" = // "310.5"); a word one letter off still counts ("weighed"/"waited" does not — // two letters). An ellipsis splits the quote into fragments found in order. The // alignment is a local one (Smith–Waterman over tokens), so a quote that starts // a word early or runs past the window is still found by its middle. // // Pure. The transcription is the caller's (lib/report/quoteCheck.mjs asks the // editor's transcribe op); words arrive on the CUE clock. const ONES = { zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, }; const TENS = { twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }; const DIGIT_WORDS = { zero: "0", oh: "0", one: "1", two: "2", three: "3", four: "4", five: "5", six: "6", seven: "7", eight: "8", nine: "9" }; /** The minimum share of the quote's tokens a match must align to be FOUND. */ export const MIN_MATCH = 0.6; /** Within this many seconds of the cue clock, a found quote is where the clip says. */ export const ON_TIME_S = 0.5; /** * Raw word tokens of a text: lower case, no `[bracketed]` editorial, no * apostrophes, digits with their decimal point and thousands commas folded. * @param {string} text * @returns {string[]} */ export function rawTokens(text) { return String(text ?? "") .toLowerCase() .replace(/\[[^\]]*\]/g, " ") .replace(/(\d),(\d{3})\b/g, "$1$2") .replace(/%/g, " percent ") .replace(/[’'`]/g, "") .replace(/(\d)\.(\d)/g, "$1\u0000$2") .replace(/[^a-z0-9\u0000]+/g, " ") .replace(/\u0000/g, ".") .split(" ") .filter(Boolean); } /** * Fold every run of number words into one numeric token, keeping which raw * tokens each output token came from. * @param {string[]} toks * @returns {{ t: string, from: number, to: number }[]} `from`/`to`: raw token indexes (inclusive) */ export function foldNumbers(toks) { const out = []; let i = 0; while (i < toks.length) { const w = toks[i]; const startsNumber = w in ONES || w in TENS || (w === "a" && toks[i + 1] === "hundred"); if (!startsNumber) { out.push({ t: w, from: i, to: i }); i += 1; continue; } let total = 0; let cur = 0; let j = i; let lastKind = ""; for (; j < toks.length; j += 1) { const x = toks[j]; if (x in ONES) { // "twenty twenty one", "five five": a second small number starts anew. if (lastKind === "one" || (lastKind === "ten" && ONES[x] >= 10)) break; cur += ONES[x]; lastKind = "one"; } else if (x in TENS) { if (lastKind === "one" || lastKind === "ten") break; cur += TENS[x]; lastKind = "ten"; } else if (x === "a" && toks[j + 1] === "hundred" && lastKind === "") { cur = 1; lastKind = "a"; } else if (x === "hundred" && (lastKind === "one" || lastKind === "a" || lastKind === "ten")) { cur = (cur || 1) * 100; lastKind = "hundred"; } else if (x === "thousand" && lastKind !== "") { total += (cur || 1) * 1000; cur = 0; lastKind = "thousand"; } else if (x === "and" && (lastKind === "hundred" || lastKind === "thousand") && (toks[j + 1] in ONES || toks[j + 1] in TENS)) { lastKind = "and"; } else break; } let value = String(total + cur); let end = j - 1; // "point five", "point one five": decimals digit by digit. if (toks[j] === "point" && toks[j + 1] in DIGIT_WORDS) { let k = j + 1; let dec = ""; while (k < toks.length && toks[k] in DIGIT_WORDS) { dec += DIGIT_WORDS[toks[k]]; k += 1; } value = `${value}.${dec}`; end = k - 1; j = k; } if (end < i) { out.push({ t: w, from: i, to: i }); i += 1; continue; } out.push({ t: value, from: i, to: end }); i = end + 1; } return out; } /** A text as match tokens. @param {string} text @returns {string[]} */ export const quoteTokens = (text) => foldNumbers(rawTokens(text)).map((x) => x.t); /** * Timed words as match tokens: each token keeps the start of its first word and * the end of its last. * @param {{ w?: string, text?: string, start: number, end: number }[]} words * @returns {{ t: string, start: number, end: number }[]} */ export function timedTokens(words) { const raw = []; for (const w of words ?? []) { rawTokens(w.w ?? w.text ?? "").forEach((t, k) => raw.push({ t, start: Number(w.start), end: Number(w.end), anchor: k === 0 && w.anchor === true }), ); } return foldNumbers(raw.map((r) => r.t)).map((x) => ({ t: x.t, start: raw[x.from].start, end: raw[x.to].end, ...(raw[x.from].anchor ? { anchor: true } : {}), })); } function lev1(a, b) { if (a === b) return true; if (a.length < 4 || b.length < 4 || Math.abs(a.length - b.length) > 1) return false; let i = 0; let j = 0; let edits = 0; while (i < a.length && j < b.length) { if (a[i] === b[j]) { i += 1; j += 1; continue; } edits += 1; if (edits > 1) return false; if (a.length > b.length) i += 1; else if (b.length > a.length) j += 1; else { i += 1; j += 1; } } return edits + (a.length - i) + (b.length - j) <= 1; } /** Same token: equal, a near spelling, or one number written two ways ("40" / "40.0"). */ export function sameToken(a, b) { if (a === b) return true; const na = Number(a); const nb = Number(b); if (/^\d/.test(a) && /^\d/.test(b) && Number.isFinite(na) && na === nb) return true; return lev1(a, b); } /** * The best LOCAL alignment of `q` inside `w` (Smith–Waterman: match +2, * mismatch −1, gap −1), searching from `w[from]` on. * @param {string[]} q * @param {{ t: string }[]} w * @param {number} [from] * @returns {{ pairs: [number, number][], score: number }} pairs: [q index, w index], in order */ export function alignLocal(q, w, from = 0) { const n = q.length; const m = w.length - from; if (!n || m <= 0) return { pairs: [], score: 0 }; const H = Array.from({ length: n + 1 }, () => new Float64Array(m + 1)); const B = Array.from({ length: n + 1 }, () => new Uint8Array(m + 1)); // 1 diag, 2 up, 3 left let best = 0; let bi = 0; let bj = 0; for (let i = 1; i <= n; i += 1) { for (let j = 1; j <= m; j += 1) { const match = sameToken(q[i - 1], w[from + j - 1].t); const d = H[i - 1][j - 1] + (match ? 2 : -1); const u = H[i - 1][j] - 1; const l = H[i][j - 1] - 1; let v = 0; let b = 0; if (d > v) [v, b] = [d, 1]; if (u > v) [v, b] = [u, 2]; if (l > v) [v, b] = [l, 3]; H[i][j] = v; B[i][j] = b; if (v > best) [best, bi, bj] = [v, i, j]; } } const pairs = []; let i = bi; let j = bj; while (i > 0 && j > 0 && H[i][j] > 0) { const b = B[i][j]; if (b === 1) { if (sameToken(q[i - 1], w[from + j - 1].t)) pairs.push([i - 1, from + j - 1]); i -= 1; j -= 1; } else if (b === 2) i -= 1; else if (b === 3) j -= 1; else break; } pairs.reverse(); return { pairs, score: best }; } /** * Find a clip's quote in timed words (CUE clock). * * @param {string} quote * @param {{ w?: string, text?: string, start: number, end: number }[]} words * @param {{ expectedStart?: number | null, expectedEnd?: number | null, minMatch?: number }} [opts] * `expectedStart`/`expectedEnd`: where the clip says the quote is (its * quoteStart/quoteEnd, else its cut, else its extent) — the offset is * measured from there. * @returns {{ * found: boolean, match: number, tokens: number, matched: number, * from: number | null, to: number | null, offset: number | null, * fragments: { text: string, match: number, from: number | null, to: number | null }[], * pairs: { q: number, start: number, end: number, anchor?: boolean }[], * heard: string, * }} * `pairs`: each matched quote token (its index in the whole quote) and the * seconds it was heard at — what quoteOffset compares two findings by. */ export function findQuote(quote, words, { expectedStart = null, expectedEnd = null, minMatch = MIN_MATCH } = {}) { const w = timedTokens(words); const frags = String(quote ?? "") .split(/\.{3}|…/) .map((f) => f.trim()) .filter((f) => quoteTokens(f).length); const total = frags.reduce((n, f) => n + quoteTokens(f).length, 0); const fragments = []; const timed = []; let after = 0; let matched = 0; let first = null; let firstQ = 0; let last = null; let base = 0; for (const f of frags) { const q = quoteTokens(f); const { pairs } = alignLocal(q, w, after); const share = q.length ? pairs.length / q.length : 0; for (const [qi, wi] of pairs) { timed.push({ q: base + qi, start: w[wi].start, end: w[wi].end, ...(w[wi].anchor ? { anchor: true } : {}) }); } base += q.length; if (!pairs.length) { fragments.push({ text: f, match: 0, from: null, to: null }); continue; } matched += pairs.length; const a = w[pairs[0][1]]; const b = w[pairs[pairs.length - 1][1]]; fragments.push({ text: f, match: round2(share), from: a.start, to: b.end }); if (first === null) { first = a; // How far into the whole quote the first matched token is. firstQ = fragments.length === 1 ? pairs[0][0] : 0; } last = b; after = pairs[pairs.length - 1][1] + 1; } const share = total ? matched / total : 0; // Short quotes (under four tokens) must match whole. const need = total < 4 ? 1 : minMatch; const found = share >= need && first !== null; let offset = null; if (found && Number.isFinite(expectedStart)) { // The expected second of the first MATCHED token: the quote's own span, // shared out by token, when the clip says where it ends too. const span = Number.isFinite(expectedEnd) && expectedEnd > expectedStart ? expectedEnd - expectedStart : 0; const at = expectedStart + (total ? (span * firstQ) / total : 0); offset = round2(first.start - at); } const heard = w .filter((x) => found && x.start >= (first?.start ?? 0) - 0.01 && x.end <= (last?.end ?? 0) + 0.01) .map((x) => x.t) .join(" "); return { found, match: round2(share), tokens: total, matched, from: found ? first.start : null, to: found ? last.end : null, offset, fragments, pairs: found ? timed : [], heard, }; } /** * How far the quote was HEARD from where the CUES have it: the median, over the * quote's tokens both found, of heard − cued. Null when they share none. * @param {{ pairs: { q: number, start: number }[] }} heard * @param {{ pairs: { q: number, start: number }[] }} cued */ export function quoteOffset(heard, cued) { // A cue's FIRST word is timed exactly (the cue starts on it); the words after // it are spread over the cue and can be seconds off where the speaker paused // inside one. The exact ones decide when the quote shares any. const exact = cued.pairs.filter((p) => p.anchor); const use = heard.pairs.some((h) => exact.some((c) => c.q === h.q)) ? exact : cued.pairs; const at = new Map(use.map((p) => [p.q, p.start])); const d = heard.pairs.filter((p) => at.has(p.q)).map((p) => p.start - /** @type {number} */ (at.get(p.q))); if (!d.length) return null; d.sort((a, b) => a - b); const mid = d.length >> 1; return round2(d.length % 2 ? d[mid] : (d[mid - 1] + d[mid]) / 2); } /** * Cues as timed words: each cue's words spread over its span by their length * (a cue carries no word timings; this is good to a fraction of a second, and * the offsets that matter are seconds). * @param {{ start: number, end: number, text: string }[]} cues * @param {{ from?: number, to?: number }} [span] only the cues overlapping it * @returns {{ w: string, start: number, end: number, anchor?: boolean }[]} `anchor`: a * cue's first word, timed exactly */ export function cueWords(cues, { from = -Infinity, to = Infinity } = {}) { const out = []; for (const c of cues ?? []) { const s = Number(c.start); const e = Number(c.end); if (!(e >= from && s <= to)) continue; const ws = String(c.text ?? "").split(/\s+/).filter(Boolean); const total = ws.reduce((n, x) => n + x.length + 1, 0); let at = s; ws.forEach((x, k) => { const d = total ? ((e - s) * (x.length + 1)) / total : 0; out.push({ w: x, start: round2(at), end: round2(at + d), ...(k === 0 ? { anchor: true } : {}) }); at += d; }); } return out; } const round2 = (x) => Math.round(x * 100) / 100; /** * The verdict for a found (or not) quote: `ok` within ON_TIME_S of the cue * clock, `moved` further, `not-found`. * @param {ReturnType} r */ export function quoteStatus(r, onTime = ON_TIME_S) { if (!r.found) return "not-found"; if (r.offset !== null && Math.abs(r.offset) > onTime) return "moved"; return "ok"; }