// A CLIP'S WORDS, for where its edges may go (pauses.mjs; 2026-11-02). // // What the trailer (and the clip editor's pause snap) reads to know where a // recording's words start and what they say, in SOURCE seconds, from the // corpus beside the recording -- the first of: // // data//words.json the word-timings sidecar (common // wordTimings-server.ts): timed words // data//transcript.json a whisper transcript's tokens (montage.mjs // whisperWords): timed words // the English caption track YouTube's en-orig `` word timings (the // cue record's `vttFile`, else transcript.en-orig.vtt, // else transcript.en.vtt): each word's START only // // Never a cue spread by its characters (fx.mjs fxWordsOf): those places are // made up, and a pause read off them is not a pause. A clip from a file beside // the manifest, a recording the corpus does not hold, or one with none of the // three: null -- the caller goes by the silences alone. // // Reads only. Plain ESM. import { readFile } from "node:fs/promises"; import path from "node:path"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { whisperWords } from "./montage.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); /** `hh:mm:ss.mmm` (or `mm:ss.mmm`) as seconds. */ function clockSeconds(s) { const parts = String(s).split(":").map(Number); return parts.reduce((acc, n) => acc * 60 + n, 0); } const ENTITIES = { " ": " ", "&": "&", "<": "<", ">": ">", """: '"', "'": "'", "'": "'" }; const decode = (s) => String(s).replace(/&(?:nbsp|amp|lt|gt|quot|apos|#39);/g, (m) => ENTITIES[m] ?? m); /** * A word-timed caption track's words: `{ start, text }` for each word YouTube * timed with ` word` (the first on a line at its cue's * start). The rolling track repeats each line without its tags: those are * skipped, as is a word timed twice. Empty for a track without word timing. * * @param {string} vtt * @returns {Array<{ start: number, text: string }>} */ export function vttWordStarts(vtt) { const seen = new Set(); const out = []; let cueStart = null; const push = (start, text) => { const t = decode(text).replace(/\s+/g, " ").trim(); if (!t || !fin(start)) return; const key = `${start.toFixed(3)}|${t}`; if (seen.has(key)) return; seen.add(key); out.push({ start, text: t }); }; for (const line of String(vtt ?? "").split(/\r?\n/)) { const head = line.match(/^((?:\d+:)?\d{2}:\d{2}\.\d{3})\s+-->\s+/); if (head) { cueStart = clockSeconds(head[1]); continue; } if (!line.includes("") || cueStart === null) continue; push(cueStart, line.split("<")[0]); for (const m of line.matchAll(/<((?:\d+:)?\d{2}:\d{2}\.\d{3})>([^<]*)<\/c>/g)) push(clockSeconds(m[1]), m[2]); } return out.sort((a, b) => a.start - b.start); } /** * The clip's recording's words in [from, to] (source seconds), and where they * came from: `{ words, timed, from }`, or null (see the header). * * @param {{ channel?: string, video?: string, src?: string }} entry * @param {{ channelSlug?: string } | null | undefined} provenance * @param {number} from * @param {number} to * @param {{ channelsDir: string | null }} o * @returns {Promise<{ words: Array<{ start: number, end?: number, text: string }>, timed: boolean, from: "words.json" | "transcript.json" | "captions" } | null>} */ export async function clipWords(entry, provenance, from, to, { channelsDir }) { if (!channelsDir || !entry?.video || hasLocalMedia(entry)) return null; const slug = entry.channel ?? provenance?.channelSlug; if (!slug) return null; const dir = await resolveVideoDir(channelsDir, slug, entry.video).catch(() => null); if (!dir) return null; const json = (name) => readFile(path.join(dir, name), "utf8").then((t) => JSON.parse(t), () => null); const inSpan = (w) => w.start >= from && w.start <= to; const sidecar = await json("words.json"); if (Array.isArray(sidecar?.words) && sidecar.words.length) { const words = sidecar.words .map((w) => ({ start: Number(w?.start), end: Number(w?.end), text: String(w?.w ?? w?.word ?? w?.text ?? "") })) .filter((w) => fin(w.start) && fin(w.end) && inSpan(w)); if (words.length) return { words, timed: true, from: "words.json" }; } const whisper = await json("transcript.json"); const ww = whisper ? whisperWords(whisper, from, to) : null; if (ww?.length) { const words = ww.map((w) => ({ start: w.start, end: w.end, text: w.text })).filter(inSpan); if (words.length) return { words, timed: true, from: "transcript.json" }; } const cues = await json("transcript.cues.json"); const names = [...new Set([typeof cues?.vttFile === "string" ? path.basename(cues.vttFile) : null, "transcript.en-orig.vtt", "transcript.en.vtt"].filter(Boolean))]; for (const name of names) { // Either form (common/lib/storedText-read.mjs): a stored caption is read. const text = await readStoredText(dir, name, "utf8").catch(() => null); if (!text) continue; const words = vttWordStarts(text).filter(inSpan); if (words.length) return { words, timed: false, from: "captions" }; } return null; }