From fc5a5de67851e030b4673309b9983761efce91fc Mon Sep 17 00:00:00 2001 From: M Dhanush <145998378+DhanushMurugesanG@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:35:06 +0530 Subject: [PATCH 1/4] feat(parsers): narration.json model and caption-array reader Adds two subpaths that later narration work builds on. No behaviour changes: nothing imports them yet. - @hyperframes/parsers/narration: reads, checks and writes narration.json, the script of a narrated project (each line's text, voice, audio file and what it was last voiced from), keeping unknown keys. Lengths and word timings are not copied into it: narrationTimingsOf() reads them from media-use's audio_meta.json by line id. - @hyperframes/parsers/caption-array: finds const/let/var `script` and `TRANSCRIPT` caption arrays in HTML, reads their words, and splices or shifts words while every other element stays byte-identical. Refs #6708 --- packages/parsers/package-subpaths.json | 12 + packages/parsers/package.json | 20 ++ packages/parsers/src/captionArray.test.ts | 128 +++++++++++ packages/parsers/src/captionArray.ts | 261 ++++++++++++++++++++++ packages/parsers/src/narration.test.ts | 129 +++++++++++ packages/parsers/src/narration.ts | 237 ++++++++++++++++++++ packages/parsers/tsup.config.ts | 2 + 7 files changed, 789 insertions(+) create mode 100644 packages/parsers/src/captionArray.test.ts create mode 100644 packages/parsers/src/captionArray.ts create mode 100644 packages/parsers/src/narration.test.ts create mode 100644 packages/parsers/src/narration.ts diff --git a/packages/parsers/package-subpaths.json b/packages/parsers/package-subpaths.json index 7b9c637a520..9698338fae5 100644 --- a/packages/parsers/package-subpaths.json +++ b/packages/parsers/package-subpaths.json @@ -187,6 +187,18 @@ "runtime": "./dist/compositionDuration.js", "types": "./dist/compositionDuration.d.ts", "environments": ["browser", "bun", "node"] + }, + "./narration": { + "source": "./src/narration.ts", + "runtime": "./dist/narration.js", + "types": "./dist/narration.d.ts", + "environments": ["browser", "bun", "node"] + }, + "./caption-array": { + "source": "./src/captionArray.ts", + "runtime": "./dist/captionArray.js", + "types": "./dist/captionArray.d.ts", + "environments": ["browser", "bun", "node"] } } } diff --git a/packages/parsers/package.json b/packages/parsers/package.json index 843727caf34..f4044f99994 100644 --- a/packages/parsers/package.json +++ b/packages/parsers/package.json @@ -195,6 +195,18 @@ "node": "./dist/compositionDuration.js", "import": "./src/compositionDuration.ts", "types": "./src/compositionDuration.ts" + }, + "./narration": { + "bun": "./src/narration.ts", + "node": "./dist/narration.js", + "import": "./src/narration.ts", + "types": "./src/narration.ts" + }, + "./caption-array": { + "bun": "./src/captionArray.ts", + "node": "./dist/captionArray.js", + "import": "./src/captionArray.ts", + "types": "./src/captionArray.ts" } }, "publishConfig": { @@ -320,6 +332,14 @@ "./composition-duration": { "import": "./dist/compositionDuration.js", "types": "./dist/compositionDuration.d.ts" + }, + "./narration": { + "import": "./dist/narration.js", + "types": "./dist/narration.d.ts" + }, + "./caption-array": { + "import": "./dist/captionArray.js", + "types": "./dist/captionArray.d.ts" } }, "main": "./dist/index.js", diff --git a/packages/parsers/src/captionArray.test.ts b/packages/parsers/src/captionArray.test.ts new file mode 100644 index 00000000000..6c509756782 --- /dev/null +++ b/packages/parsers/src/captionArray.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import { + locateCaptionArrays, + pickCaptionArray, + shiftCaptionWords, + spliceCaptionWords, +} from "./captionArray.js"; + +// The layout transcribe writes: JSON, one key per line, indented inside a `; + +const compact = `let script = [{ text: "One", start: 1, end: 1.2 }, { text: "two", start: 1.3, end: 1.6 }];`; + +describe("locateCaptionArrays", () => { + it("reads every word of a transcribed array with its line tag", () => { + const [array] = locateCaptionArrays(transcribed); + expect(array?.name).toBe("TRANSCRIPT"); + expect(array?.keyword).toBe("const"); + expect(array?.editable).toBe(true); + expect(array?.words.map((w) => [w.id, w.text, w.startTime, w.endTime, w.line])).toEqual([ + ["w0", "Hello", 0.1, 0.4, "l1"], + ["w1", "there.", 0.5, 0.9, "l1"], + ["w2", "Bye.", 2, 2.3, "l2"], + ]); + }); + + it("finds let and var arrays with bare keys", () => { + expect(locateCaptionArrays(compact)[0]?.words.map((w) => w.text)).toEqual(["One", "two"]); + const withVar = compact.replace("let script", "var script"); + expect(locateCaptionArrays(withVar)[0]?.keyword).toBe("var"); + }); + + it("marks an array with a computed element read-only and skips arrays that are not literals", () => { + const computed = `const script = [{ text: "a", start: 0, end: 1 }, makeWord()];`; + expect(locateCaptionArrays(computed)[0]?.editable).toBe(false); + expect(locateCaptionArrays(`const script = [oops;`)).toEqual([]); + }); + + it("picks the named array, else script before TRANSCRIPT", () => { + const both = `${transcribed}\n`; + const arrays = locateCaptionArrays(both); + expect(pickCaptionArray(arrays)?.name).toBe("script"); + expect(pickCaptionArray(arrays, "TRANSCRIPT")?.name).toBe("TRANSCRIPT"); + }); +}); + +describe("spliceCaptionWords", () => { + it("replaces one line's words and leaves every other element byte-identical", () => { + const [array] = locateCaptionArrays(transcribed); + const out = spliceCaptionWords(transcribed, array!, 0, 2, [ + { id: "l1w0", text: "Hi", start: 0.1, end: 0.3, line: "l1" }, + ]); + const [after] = locateCaptionArrays(out); + expect(after?.words.map((w) => [w.text, w.startTime, w.line])).toEqual([ + ["Hi", 0.1, "l1"], + ["Bye.", 2, "l2"], + ]); + const untouched = transcribed.slice(array!.words[2]!.start, array!.words[2]!.end); + expect(out).toContain(untouched); + // Written in the array's own layout: quoted keys, one per line, same indent. + expect(out).toContain(`{\n "id": "l1w0",\n "text": "Hi",`); + }); + + it("inserts into a compact array in its style and removes words with their separator", () => { + const [array] = locateCaptionArrays(compact); + const inserted = spliceCaptionWords(compact, array!, 1, 0, [ + { text: "and", start: 1.2, end: 1.3 }, + ]); + expect(inserted).toBe( + `let script = [{ text: "One", start: 1, end: 1.2 }, { text: "and", start: 1.2, end: 1.3 }, { text: "two", start: 1.3, end: 1.6 }];`, + ); + const removed = spliceCaptionWords(compact, array!, 0, 1, []); + expect(removed).toBe(`let script = [{ text: "two", start: 1.3, end: 1.6 }];`); + }); + + it("refuses a range outside the array", () => { + const [array] = locateCaptionArrays(compact); + expect(() => spliceCaptionWords(compact, array!, 1, 5, [])).toThrow(RangeError); + }); +}); + +describe("shiftCaptionWords", () => { + it("moves later words by the delta and touches nothing else", () => { + const [array] = locateCaptionArrays(transcribed); + const out = shiftCaptionWords(transcribed, array!, 2, 0.75); + const [after] = locateCaptionArrays(out); + expect(after?.words.map((w) => [w.startTime, w.endTime])).toEqual([ + [0.1, 0.4], + [0.5, 0.9], + [2.75, 3.05], + ]); + expect(out.slice(0, array!.words[2]!.start)).toBe(transcribed.slice(0, array!.words[2]!.start)); + }); + + it("works whatever order start and end are written in", () => { + const reversed = `const script = [{ text: "a", end: 2, start: 1 }];`; + const [array] = locateCaptionArrays(reversed); + expect(shiftCaptionWords(reversed, array!, 0, 1)).toBe( + `const script = [{ text: "a", end: 3, start: 2 }];`, + ); + }); +}); diff --git a/packages/parsers/src/captionArray.ts b/packages/parsers/src/captionArray.ts new file mode 100644 index 00000000000..0152122feb7 --- /dev/null +++ b/packages/parsers/src/captionArray.ts @@ -0,0 +1,261 @@ +import { parseExpressionAt, type Expression, type Node, type ObjectExpression } from "acorn"; + +/** + * Caption word arrays written into composition scripts, such as + * `const TRANSCRIPT = [{ "text": "Hello", "start": 0.1, "end": 0.4 }, ...];`. + * + * Caption spans are built by script at runtime, so the array is the only place a word can carry a + * link back to its narration line (`line: "l2"`). These helpers find the arrays, read their words, + * and edit them in place: every element outside the edited range stays byte-identical. + */ + +export const CAPTION_ARRAY_NAMES = ["script", "TRANSCRIPT"] as const; +export type CaptionArrayName = (typeof CAPTION_ARRAY_NAMES)[number]; + +export interface CaptionArrayWord { + /** Source offsets of the element's object literal. */ + start: number; + end: number; + text: string; + startTime: number; + endTime: number; + id?: string; + line?: string; + /** Source offsets of the start and end numbers, for shifting a word in place. */ + startTimeSpan: [number, number]; + endTimeSpan: [number, number]; +} + +export interface CaptionArrayLocation { + name: CaptionArrayName; + keyword: "const" | "let" | "var"; + /** Offsets of the `[` ... `]` array literal. */ + arrayStart: number; + arrayEnd: number; + words: CaptionArrayWord[]; + /** False when an element is not a plain object of literals; such arrays are read-only. */ + editable: boolean; +} + +/** What a new caption word carries; extra keys (`id`, `line`, ...) are written as given. */ +export interface CaptionWordInput { + text: string; + start: number; + end: number; + [key: string]: unknown; +} + +const DECLARATION = /\b(const|let|var)\s+(script|TRANSCRIPT)\s*=\s*\[/g; + +type Literal = { value: string | number; span: [number, number] }; + +function literalOf(node: Node): Literal | null { + if (node.type === "Literal") { + const { value } = node as Node & { value: unknown }; + if (typeof value === "string" || typeof value === "number") { + return { value, span: [node.start, node.end] }; + } + return null; + } + if (node.type === "UnaryExpression") { + const unary = node as Node & { operator: string; argument: Node }; + const inner = unary.operator === "-" ? literalOf(unary.argument) : null; + if (inner && typeof inner.value === "number") { + return { value: -inner.value, span: [node.start, node.end] }; + } + } + return null; +} + +function keyOf(property: Node & { key: Node; computed: boolean }): string | null { + if (property.computed) return null; + if (property.key.type === "Identifier") return (property.key as Node & { name: string }).name; + const literal = literalOf(property.key); + return literal && typeof literal.value === "string" ? literal.value : null; +} + +/** The object's keys and literal values, or null when any property is not a plain literal. */ +function literalFields(node: ObjectExpression): Map | null { + const fields = new Map(); + for (const property of node.properties) { + const key = property.type === "Property" ? keyOf(property) : null; + const value = key === null ? null : literalOf((property as { value: Node }).value); + if (key === null || value === null) return null; + fields.set(key, value); + } + return fields; +} + +const stringField = (fields: Map, key: string) => { + const value = fields.get(key)?.value; + return typeof value === "string" ? value : undefined; +}; + +const numberField = (fields: Map, key: string) => { + const field = fields.get(key); + return typeof field?.value === "number" ? { value: field.value, span: field.span } : undefined; +}; + +/** The optional string tags a word carries: its `id` and its narration `line`. */ +const wordTags = (fields: Map) => + Object.fromEntries( + (["id", "line"] as const).flatMap((key) => { + const value = stringField(fields, key); + return value === undefined ? [] : [[key, value]]; + }), + ) as Pick; + +function wordFrom(node: ObjectExpression, fields: Map): CaptionArrayWord | null { + const text = stringField(fields, "text"); + const start = numberField(fields, "start"); + const end = numberField(fields, "end"); + if (text === undefined || !start || !end) return null; + return { + start: node.start, + end: node.end, + text, + startTime: start.value, + endTime: end.value, + ...wordTags(fields), + startTimeSpan: start.span, + endTimeSpan: end.span, + }; +} + +function readWord(node: ObjectExpression): CaptionArrayWord | null { + const fields = literalFields(node); + return fields ? wordFrom(node, fields) : null; +} + +function readArray(source: string, at: number): Omit { + const array = parseExpressionAt(source, at, { ecmaVersion: "latest" }) as Expression; + if (array.type !== "ArrayExpression") throw new Error("not an array"); + const words: CaptionArrayWord[] = []; + let editable = true; + for (const element of array.elements) { + const word = element?.type === "ObjectExpression" ? readWord(element) : null; + if (word) words.push(word); + else editable = false; + } + return { arrayStart: array.start, arrayEnd: array.end, words, editable }; +} + +/** Every `script` / `TRANSCRIPT` caption array in `source` (a script or a whole HTML file). */ +export function locateCaptionArrays(source: string): CaptionArrayLocation[] { + const found: CaptionArrayLocation[] = []; + for (const match of source.matchAll(DECLARATION)) { + const at = match.index + match[0].length - 1; + try { + found.push({ + name: match[2] as CaptionArrayName, + keyword: match[1] as CaptionArrayLocation["keyword"], + ...readArray(source, at), + }); + } catch { + // Not a parseable literal array: leave it to the composition. + } + } + return found; +} + +/** The array a caller means: `name` when given, else `script` before `TRANSCRIPT`, as transcribe patches them. */ +export function pickCaptionArray( + arrays: CaptionArrayLocation[], + name?: string, +): CaptionArrayLocation | undefined { + if (name) return arrays.find((array) => array.name === name); + return arrays.find((array) => array.name === "script") ?? arrays[0]; +} + +function formatNumber(value: number): string { + return String(Math.round(value * 1000) / 1000); +} + +/** The text between two neighbouring elements, and the indent of the first one, as the array writes them. */ +function arrayStyle(source: string, location: CaptionArrayLocation) { + const [first, second] = location.words; + const separator = first && second ? source.slice(first.end, second.start) : ", "; + const lineStart = first ? source.lastIndexOf("\n", first.start) + 1 : 0; + const indent = first ? source.slice(lineStart, first.start).replace(/\S.*$/, "") : ""; + const multiline = first ? source.slice(first.start, first.end).includes("\n") : false; + const quotedKeys = first ? /^\{\s*"/.test(source.slice(first.start, first.end)) : true; + return { separator, indent, multiline, quotedKeys }; +} + +function serializeWord(word: CaptionWordInput, style: ReturnType): string { + const entries = Object.entries(word) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => { + const name = style.quotedKeys ? JSON.stringify(key) : key; + const text = + typeof value === "number" + ? formatNumber(value) + : JSON.stringify(value).replace(/ `${style.indent} ${entry}`).join(",\n"); + return `{\n${inner}\n${style.indent}}`; +} + +/** + * Replaces `deleteCount` words starting at `index` with `words`, written in the array's own style. + * Elements outside that range, and the text between them, are left exactly as they were. + */ +export function spliceCaptionWords( + source: string, + location: CaptionArrayLocation, + index: number, + deleteCount: number, + words: CaptionWordInput[], +): string { + if (!location.editable) throw new Error(`The ${location.name} array is not plain data`); + const total = location.words.length; + if (index < 0 || index > total || deleteCount < 0 || index + deleteCount > total) { + throw new RangeError(`Cannot replace words ${index}..${index + deleteCount} of ${total}`); + } + const style = arrayStyle(source, location); + const text = words.map((word) => serializeWord(word, style)).join(style.separator); + const removed = location.words.slice(index, index + deleteCount); + if (removed.length > 0) { + const from = removed[0]!.start; + const to = removed.at(-1)!.end; + if (text) return source.slice(0, from) + text + source.slice(to); + // Removing words outright: take one separator with them. + const before = location.words[index - 1]; + const after = location.words[index + deleteCount]; + if (after) return source.slice(0, from) + source.slice(after.start); + if (before) return source.slice(0, before.end) + source.slice(to); + return source.slice(0, location.arrayStart + 1) + source.slice(location.arrayEnd - 1); + } + if (!text) return source; + const next = location.words[index]; + if (next) return source.slice(0, next.start) + text + style.separator + source.slice(next.start); + const previous = location.words[index - 1]; + if (previous) + return source.slice(0, previous.end) + style.separator + text + source.slice(previous.end); + return `${source.slice(0, location.arrayStart + 1)}${text}${source.slice(location.arrayEnd - 1)}`; +} + +/** Moves every word from `fromIndex` on by `delta` seconds, rewriting only their start and end numbers. */ +export function shiftCaptionWords( + source: string, + location: CaptionArrayLocation, + fromIndex: number, + delta: number, +): string { + if (delta === 0) return source; + if (!location.editable) throw new Error(`The ${location.name} array is not plain data`); + const edits = location.words.slice(fromIndex).flatMap((word) => [ + { span: word.startTimeSpan, value: word.startTime + delta }, + { span: word.endTimeSpan, value: word.endTime + delta }, + ]); + // Last offset first, so each edit leaves the offsets before it valid. + edits.sort((a, b) => b.span[0] - a.span[0]); + let out = source; + for (const { span, value } of edits) { + out = out.slice(0, span[0]) + formatNumber(value) + out.slice(span[1]); + } + return out; +} diff --git a/packages/parsers/src/narration.test.ts b/packages/parsers/src/narration.test.ts new file mode 100644 index 00000000000..9cf509f4813 --- /dev/null +++ b/packages/parsers/src/narration.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from "vitest"; +import { + narrationComparableWords, + narrationTimingsOf, + narrationVoiceKey, + normalizeNarrationText, + parseNarrationManifest, + serializeNarrationManifest, +} from "./narration.js"; + +const manifest = { + version: 1, + defaults: { provider: "kokoro", voice: "af_heart", speed: 1, lang: "en-us" }, + captions: { file: "index.html", array: "TRANSCRIPT" }, + lines: [ + { + id: "l1", + text: "Hello there.", + audio: "assets/voice/l1.wav", + voiced: { textHash: "a", voiceKey: "kokoro:af_heart:1:en-us", audioHash: "b" }, + note: "kept", + }, + ], + owner: "someone else's key", +}; + +describe("parseNarrationManifest", () => { + it("accepts a manifest and round-trips unknown keys in their order", () => { + const text = JSON.stringify(manifest, null, 2) + "\n"; + const parsed = parseNarrationManifest(text); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(serializeNarrationManifest(parsed.manifest)).toBe(text); + parsed.manifest.lines[0]!.text = "Hi there."; + const rewritten = JSON.parse(serializeNarrationManifest(parsed.manifest)); + expect(rewritten.owner).toBe("someone else's key"); + expect(rewritten.lines[0].note).toBe("kept"); + }); + + it("names every problem", () => { + const broken = { + version: 2, + lines: [ + { id: "l 1", text: 3, audio: "" }, + { id: "l2", text: "x", audio: "a.wav", voiced: { textHash: 1 } }, + { id: "l2", text: "y", audio: "b.wav", speed: "fast" }, + ], + }; + const parsed = parseNarrationManifest(JSON.stringify(broken)); + expect(parsed.ok).toBe(false); + if (parsed.ok) return; + expect(parsed.problems).toEqual([ + "version must be 1", + 'lines[0].id must be a plain name such as "l2"', + "lines[0].text must be a string", + "lines[0].audio must name the line's audio file", + "lines[1].voiced.textHash must be a string", + "lines[1].voiced.voiceKey must be a string", + "lines[1].voiced.audioHash must be a string", + 'lines[2].id "l2" is used twice', + "lines[2].speed must be a number", + ]); + }); + + it("reports invalid JSON", () => { + const parsed = parseNarrationManifest("{"); + expect(parsed.ok).toBe(false); + }); +}); + +describe("narrationTimingsOf", () => { + it("reads each voice's length and words from audio_meta.json by line id", () => { + const meta = { + tts_provider: "kokoro", + voices: [ + { + id: "l1", + path: "assets/voice/l1.wav", + duration_s: 1.2, + words: [ + { text: "Hello", start: 0.1, end: 0.4, score: 0.9 }, + { text: "there.", start: 0.5, end: 0.9 }, + { text: "bad", start: 2, end: 1 }, + ], + }, + { id: 2, duration_s: 0.8 }, + { id: "no-length", words: [] }, + "not a voice", + ], + bgm: null, + }; + const timings = narrationTimingsOf(JSON.stringify(meta)); + expect([...timings!.keys()]).toEqual(["l1", "2"]); + expect(timings!.get("l1")).toEqual({ + path: "assets/voice/l1.wav", + durationSeconds: 1.2, + words: [ + { text: "Hello", start: 0.1, end: 0.4 }, + { text: "there.", start: 0.5, end: 0.9 }, + ], + }); + expect(timings!.get("2")).toEqual({ durationSeconds: 0.8, words: [] }); + }); + + it("returns null without a voices list or valid JSON", () => { + expect(narrationTimingsOf("{")).toBeNull(); + expect(narrationTimingsOf('{"bgm": null}')).toBeNull(); + expect(narrationTimingsOf('{"voices": []}')!.size).toBe(0); + }); +}); + +describe("voice and text helpers", () => { + it("builds the voice key from the line over the defaults", () => { + expect(narrationVoiceKey({ voice: "bf_emma" }, manifest.defaults)).toBe( + "kokoro:bf_emma:1:en-us", + ); + expect(narrationVoiceKey({})).toBe("kokoro::1:"); + }); + + it("normalises whitespace for hashing and compares words without punctuation", () => { + expect(normalizeNarrationText(" Hello\n there. ")).toBe("Hello there."); + expect(narrationComparableWords("Hello, there! It's 47.")).toEqual([ + "hello", + "there", + "it's", + "47", + ]); + }); +}); diff --git a/packages/parsers/src/narration.ts b/packages/parsers/src/narration.ts new file mode 100644 index 00000000000..bffa940cd48 --- /dev/null +++ b/packages/parsers/src/narration.ts @@ -0,0 +1,237 @@ +/** + * The narration manifest, `narration.json` at the project root: the script. One entry per voiced + * line, holding what the line says, in which voice, and the audio clip and caption words that show + * it. `voiced` records what the line was last voiced from, so a later edit to the text, the voice + * or the WAV shows up as drift. + * + * What a voice turned out to be (its length and word timings) is not copied here. media-use already + * records that in `audio_meta.json`, keyed by the same line id; `narrationTimingsOf` reads it. So + * narration.json says what each line should be, and audio_meta.json what was generated. + * + * Keys this module does not know are kept: parse, edit the returned object, serialize. + */ + +export const NARRATION_FILE = "narration.json"; +/** media-use's record of generated voices: `voices[].{id, path, duration_s, words}`. */ +export const AUDIO_META_FILE = "audio_meta.json"; +export const NARRATION_VERSION = 1; +export const NARRATION_LINE_ATTR = "data-narration-line"; + +export interface NarrationWord { + text: string; + start: number; + end: number; + [key: string]: unknown; +} + +export interface NarrationVoiced { + textHash: string; + voiceKey: string; + audioHash: string; + at?: string; + [key: string]: unknown; +} + +export interface NarrationVoiceSettings { + provider?: string; + voice?: string; + speed?: number; + lang?: string; +} + +export interface NarrationLine extends NarrationVoiceSettings { + id: string; + text: string; + /** Project-relative audio file that speaks the line. */ + audio: string; + voiced?: NarrationVoiced; + [key: string]: unknown; +} + +/** One line's generated voice, from audio_meta.json: its file, length, and words from its start. */ +export interface NarrationTiming { + path?: string; + durationSeconds: number; + words: NarrationWord[]; +} + +export interface NarrationCaptions { + /** Project-relative HTML file holding the caption array. */ + file?: string; + /** The array's name: `script` or `TRANSCRIPT`. */ + array?: string; + [key: string]: unknown; +} + +export interface NarrationManifest { + version: number; + defaults?: NarrationVoiceSettings & Record; + captions?: NarrationCaptions; + lines: NarrationLine[]; + [key: string]: unknown; +} + +export type NarrationParseResult = + | { ok: true; manifest: NarrationManifest } + | { ok: false; problems: string[] }; + +const LINE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const isFiniteNumber = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + +function voicedProblems(voiced: unknown, where: string): string[] { + if (voiced === undefined) return []; + if (!isRecord(voiced)) return [`${where}.voiced must be an object`]; + return ["textHash", "voiceKey", "audioHash"] + .filter((key) => typeof voiced[key] !== "string") + .map((key) => `${where}.voiced.${key} must be a string`); +} + +function idProblems(id: unknown, where: string, seen: Set): string[] { + if (typeof id !== "string" || !LINE_ID.test(id)) { + return [`${where}.id must be a plain name such as "l2"`]; + } + if (seen.has(id)) return [`${where}.id "${id}" is used twice`]; + seen.add(id); + return []; +} + +/** Each field check: the problem when the line's value fails it. */ +const LINE_FIELDS: Array<[string, (value: unknown) => boolean, string]> = [ + ["text", (value) => typeof value === "string", "must be a string"], + [ + "audio", + (value) => typeof value === "string" && value !== "", + "must name the line's audio file", + ], + ["speed", (value) => value === undefined || isFiniteNumber(value), "must be a number"], +]; + +function lineProblems(line: unknown, index: number, seen: Set): string[] { + const where = `lines[${index}]`; + if (!isRecord(line)) return [`${where} must be an object`]; + return [ + ...idProblems(line.id, where, seen), + ...LINE_FIELDS.filter(([key, ok]) => !ok(line[key])).map( + ([key, , problem]) => `${where}.${key} ${problem}`, + ), + ...voicedProblems(line.voiced, where), + ]; +} + +/** Every problem that keeps `value` from being a narration manifest; empty when it is one. */ +export function narrationManifestProblems(value: unknown): string[] { + if (!isRecord(value)) return ["the manifest must be a JSON object"]; + const problems: string[] = []; + if (value.version !== NARRATION_VERSION) { + problems.push(`version must be ${NARRATION_VERSION}`); + } + if (value.defaults !== undefined && !isRecord(value.defaults)) { + problems.push("defaults must be an object"); + } + if (value.captions !== undefined && !isRecord(value.captions)) { + problems.push("captions must be an object"); + } + if (!Array.isArray(value.lines)) return [...problems, "lines must be an array"]; + const seen = new Set(); + return [...problems, ...value.lines.flatMap((line, index) => lineProblems(line, index, seen))]; +} + +export function parseNarrationManifest(text: string): NarrationParseResult { + let value: unknown; + try { + value = JSON.parse(text); + } catch (error) { + return { ok: false, problems: [`not valid JSON: ${(error as Error).message}`] }; + } + const problems = narrationManifestProblems(value); + return problems.length > 0 + ? { ok: false, problems } + : { ok: true, manifest: value as NarrationManifest }; +} + +const isWord = (value: unknown): value is NarrationWord => + isRecord(value) && + typeof value.text === "string" && + isFiniteNumber(value.start) && + isFiniteNumber(value.end) && + value.end >= value.start; + +/** + * Each line's generated voice from audio_meta.json's text, by line id. A voice entry without an id + * or a length is left out, and so is a malformed word. Returns null when the text isn't JSON or has + * no `voices` list, so a caller can tell "no timings" from "no voice for this line". + */ +export function narrationTimingsOf(text: string): Map | null { + let value: unknown; + try { + value = JSON.parse(text); + } catch { + return null; + } + if (!isRecord(value) || !Array.isArray(value.voices)) return null; + const timings = new Map(); + for (const voice of value.voices) { + if (!isRecord(voice) || voice.id === undefined || voice.id === null) continue; + if (!isFiniteNumber(voice.duration_s) || voice.duration_s < 0) continue; + const words = Array.isArray(voice.words) ? voice.words.filter(isWord) : []; + timings.set(String(voice.id), { + ...(typeof voice.path === "string" ? { path: voice.path } : {}), + durationSeconds: voice.duration_s, + words: words.map(({ text: said, start, end }) => ({ text: said, start, end })), + }); + } + return timings; +} + +/** Two-space JSON with a final newline; keys keep the order they were parsed or set in. */ +export function serializeNarrationManifest(manifest: NarrationManifest): string { + return `${JSON.stringify(manifest, null, 2)}\n`; +} + +export function findNarrationLine( + manifest: NarrationManifest, + id: string, +): NarrationLine | undefined { + return manifest.lines.find((line) => line.id === id); +} + +/** A line's own voice settings over the manifest defaults. */ +export function narrationVoiceOf( + line: NarrationVoiceSettings, + defaults: NarrationVoiceSettings = {}, +): Required { + return { + provider: line.provider ?? defaults.provider ?? "kokoro", + voice: line.voice ?? defaults.voice ?? "", + speed: line.speed ?? defaults.speed ?? 1, + lang: line.lang ?? defaults.lang ?? "", + }; +} + +/** The voice a line is spoken in, as one comparable string: `provider:voice:speed:lang`. */ +export function narrationVoiceKey( + line: NarrationVoiceSettings, + defaults: NarrationVoiceSettings = {}, +): string { + const voice = narrationVoiceOf(line, defaults); + return [voice.provider, voice.voice, voice.speed, voice.lang].join(":"); +} + +/** The text as it is hashed: whitespace collapsed, so a reflowed line is not a changed line. */ +export function normalizeNarrationText(text: string): string { + return text.replace(/\s+/g, " ").trim(); +} + +/** Words for comparing what a caption shows with what a line says: lower case, no punctuation. */ +export function narrationComparableWords(text: string): string[] { + return text + .toLowerCase() + .replace(/[^\p{L}\p{N}\s'-]/gu, " ") + .split(/\s+/) + .map((word) => word.replace(/^['-]+|['-]+$/g, "")) + .filter(Boolean); +} diff --git a/packages/parsers/tsup.config.ts b/packages/parsers/tsup.config.ts index 3c17b318563..da2eef003c5 100644 --- a/packages/parsers/tsup.config.ts +++ b/packages/parsers/tsup.config.ts @@ -32,6 +32,8 @@ export default defineConfig({ timeSpans: "src/timeSpans.ts", mediaTiming: "src/mediaTiming.ts", referenceResolver: "src/referenceResolver.ts", + narration: "src/narration.ts", + captionArray: "src/captionArray.ts", }, format: ["esm"], outDir: "dist", From a11b8967400d85eb439c1aec7cdd0fc731aedb6e Mon Sep 17 00:00:00 2001 From: M Dhanush <145998378+DhanushMurugesanG@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:37:03 +0530 Subject: [PATCH 2/4] feat(lint): detect narration drift against narration.json A project with narration.json now gets a warning when a line's text, voice or WAV changed since it was voiced, when a line has no linked clip or its clip is the wrong length, and when the caption words that show it no longer match its voice. Captions that read differently from the script get an info. No manifest, no findings, and nothing blocks a render. Lengths and word timings come from media-use's audio_meta.json by line id. Without it, the length isn't checked and a line's captions only need to fall inside its clip. Refs #6708 --- docs/reference/lint-rules.mdx | 40 +++ packages/lint/src/project.ts | 41 ++- packages/lint/src/projectNarration.test.ts | 325 +++++++++++++++++++++ packages/lint/src/projectNarration.ts | 281 ++++++++++++++++++ 4 files changed, 684 insertions(+), 3 deletions(-) create mode 100644 packages/lint/src/projectNarration.test.ts create mode 100644 packages/lint/src/projectNarration.ts diff --git a/docs/reference/lint-rules.mdx b/docs/reference/lint-rules.mdx index 86d1fe373ee..16fd4ff5ffb 100644 --- a/docs/reference/lint-rules.mdx +++ b/docs/reference/lint-rules.mdx @@ -886,6 +886,46 @@ Source: `packages/lint/src/rules/linkedClips.ts`. **Fix:** Give every member the same `data-start`, `data-duration`, `data-media-start` and `data-playback-rate`, or remove `data-link` from all of them to unlink. +## Narration + +Source: `packages/lint/src/projectNarration.ts`. These run only when the project has a `narration.json`: the script of a narrated video, listing each voiced line's text and voice, linked to the `