Archilyzer · Source

archilyzer

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

commit 8727a1ee5dd5a290b6e63ca14fb3d8dfdb1490cf
parent b62666fabe6dbad93b44cf395dff93b064a0a49f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 01:18:22 -0400

umtool: narration follows T1 as shipped — the editor's disclosure line verbatim, exact tags, a late result line

The disclosure a narrated cut carries (its metadata, the description and
chapters exports, the podcast's tags and show notes) is now the editor's own
`disclosure` from each job's result, kept in the narration's record ("Narration:
synthetic voice (Kokoro-82M · af_heart)"), each line once; a narration not
kept yet says the line in the editor's form. Expressive tags are matched
lowercase and exact, as the editor reads them (`<SIGH>` is refused with a
hint), and a test holds the list equal to TTS_EXPRESSIVE_TAGS. A done job
whose result line is not in its tail yet is re-read briefly before it counts
as missing. The e2e stub's result carries the editor's keys.

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

Diffstat:
Mumtool/docs/report-video.md | 2+-
Mumtool/e2e/fixtures/editor-stub.mjs | 7++++++-
Mumtool/e2e/report-narration.spec.ts | 2+-
Mumtool/lib/report/export-narration.test.mjs | 2+-
Mumtool/lib/report/export.mjs | 9+++++----
Mumtool/report-to-video/README.md | 12++++++++----
Mumtool/report-to-video/build-podcast.mjs | 8+++++---
Mumtool/report-to-video/build-podcast.test.mjs | 12++++++------
Mumtool/report-to-video/build-video.mjs | 14+++++++-------
Mumtool/report-to-video/narrate-via-editor.mjs | 16+++++++++++++++-
Mumtool/report-to-video/narrate.test.mjs | 16++++++++++++----
Mumtool/report-to-video/narration-store.mjs | 18++++++++++++++++--
Mumtool/report-to-video/narration.mjs | 55+++++++++++++++++++++++++++++++++++++++----------------
Mumtool/report-to-video/narration.test.mjs | 22+++++++++++++++++-----
Mumtool/report-to-video/package.json | 1+
15 files changed, 140 insertions(+), 56 deletions(-)

diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -781,7 +781,7 @@ over the segments, else a refusal with the reason. `toc-bbcode` reproduces the hand-made `toc.bbcode.txt` shape; `description` adds the source list; `chapters` is YouTube's form and includes cards. Cite URLs follow the QR's rule. A cut with a narrated card (`narration`, below) ends its `description` and `chapters` -with the disclosure line, `Narration: synthetic voice (kokoro · af_heart)`. +with the editor's disclosure line, `Narration: synthetic voice (Kokoro-82M · af_heart)`. **podcast** (one button per cut in the same row) is a build-route run with `options.podcast`: `build-podcast.mjs` renders the built cut as sound only — diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -164,7 +164,12 @@ const server = http.createServer((req, res) => { if (r.status !== 0) return json(res, 500, { ok: false, error: "ffmpeg failed writing the stub's voice" }); ttsJobs.set(id, { polls: 0, - result: { wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0 }, + result: { + wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0, + sha: id, sampleRate: 48000, speed: body.speed ?? 1, + // The editor's own line, which umtool uses verbatim. + disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice ?? "af_heart"})`, + }, }); json(res, 202, { ok: true, jobId: id }); }); diff --git a/umtool/e2e/report-narration.spec.ts b/umtool/e2e/report-narration.spec.ts @@ -23,7 +23,7 @@ const PROJECT = "reports/narration-fixture"; const OUT = path.join(FIXTURE, "reports", "narration-fixture", "out"); const SEGS = path.join(OUT, "sourced", "segments"); const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); -const DISCLOSURE = "Narration: synthetic voice (kokoro · af_heart)"; +const DISCLOSURE = "Narration: synthetic voice (Kokoro-82M · af_heart)"; type Job = { id: string; state: string; error: string | null; events?: { ev: string; id?: string; cached?: boolean }[] }; diff --git a/umtool/lib/report/export-narration.test.mjs b/umtool/lib/report/export-narration.test.mjs @@ -34,7 +34,7 @@ test("description and chapters disclose a narrated cut's synthetic voice; a plai clip, ]); const plain = project(root, [{ id: "k1", type: "card", heading: "Then", seconds: 4 }, clip]); - const line = "Narration: synthetic voice (kokoro · af_heart)"; + const line = "Narration: synthetic voice (Kokoro-82M · af_heart)"; const desc = (await exportProject(narrated, "description")).text; assert.ok(desc.trimEnd().endsWith(line), desc); diff --git a/umtool/lib/report/export.mjs b/umtool/lib/report/export.mjs @@ -19,7 +19,7 @@ import path from "node:path"; import { DEFAULT_VARIANT, selectVariant, segmentOffsets } from "umtool-report-to-video/build-video"; import { citeUrlFor, channelFor, readAvailability, readManifest } from "../projects/report.mjs"; import { teaserTitle } from "umtool-report-to-video/deck"; -import { narrationDisclosure } from "umtool-report-to-video/narration"; +import { narrationDir, readCutDisclosure } from "umtool-report-to-video/narration-store"; import { outDirState } from "./storage.mjs"; export const EXPORT_FORMATS = ["toc-bbcode", "toc-markdown", "description", "chapters"]; @@ -157,8 +157,9 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = cite: e.type === "clip" ? citeUrlFor(m, e) : null, })); const clipRows = rows.filter((r) => r.e.type === "clip"); - // "Narration: synthetic voice (kokoro · af_heart)", or null for a cut with none. - const disclosure = narrationDisclosure(m); + // The editor's own line for each voice the cut's narration kept + // ("Narration: synthetic voice (Kokoro-82M · af_heart)"), or null for a cut with none. + const disclosure = await readCutDisclosure(narrationDir(path.join(dir, "out")), m, "\n"); let text; if (format === "toc-bbcode") { @@ -182,7 +183,7 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = ].join("\n"); } else if (format === "chapters") { // YouTube needs the first at 00:00 and every entry present, cards included. - // A narrated cut says so below them (narrationDisclosure); one without + // A narrated cut says so below them (the disclosure lines); one without // narration exports exactly as it did. text = rows.map((r) => `${ytTime(r.i === 0 ? 0 : r.at)} ${r.title}`).join("\n") + "\n" + (disclosure ? `\n${disclosure}\n` : ""); diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1112,14 +1112,18 @@ exactly as it did — every card's sound is still `anullsrc`. narration's sha256, the sound's filter, the encode); a build whose key matches leaves the segment alone, and one that differs writes a new file through a rename. -- **The disclosure** — `Narration: synthetic voice (kokoro · af_heart)`, each - engine · voice once — is in the cut's `comment` metadata, at the end of the - `description` and `chapters` exports, and in each narration's record. +- **The disclosure** is the editor's own line from the job's result, used + verbatim — `Narration: synthetic voice (Kokoro-82M · af_heart)`, plus an + attribution sentence for an engine whose licence asks for one — each line + once. It is in each narration's record, the cut's `comment` metadata, and at + the end of the `description` and `chapters` exports. - **Validated** by `validateNarration` (narration.mjs), which the build runs before a single fetch and the lint reports: narration on cards only; text non-empty, at most 300 words (tags not counted); the only `<…>` allowed are Orpheus's expressive tags `<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> - <yawn> <gasp>` (Kokoro's side strips them); an engine of the three, a voice + <yawn> <gasp>`, lowercase and exact — the editor's `TTS_EXPRESSIVE_TAGS` + (Kokoro's side strips them); an engine of the three (the editor refuses + `orpheus` until it has it), a voice that is a stock voice's id, each setting in its range, `lead`/`tail` at least the crossfade, and `seconds: "auto"` only beside a narration. Voices are stock voices only — no reference audio, no cloning, ever. diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -40,7 +40,8 @@ import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { deckOn, deckQrUrl, muteSegmentSeconds, teaserTitle } from "./deck.mjs"; -import { hasNarration, narrationDisclosure, narrationsOf } from "./narration.mjs"; +import { hasNarration, narrationsOf } from "./narration.mjs"; +import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -363,8 +364,9 @@ export async function buildPodcast({ manifestPath, variant = "sourced", out = nu // 3. The chapters (the video's titles, the podcast's offsets) and the files. const titles = (await videoTitles(dirs.dir, entries)) ?? entries.map((e, i) => fallbackTitle(e, i, { deck: deckOn(render) })); const chapters = podcastChapters(items, durations, titles); - const disclosure = narrationDisclosure(manifest); - await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure }), "utf8"); + // The editor's own disclosure lines, from the narrations the build kept. + const disclosure = await readCutDisclosure(narrationDir(outRoot), manifest, "\n"); + await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure: disclosure?.replace(/\n/g, " ") ?? null }), "utf8"); emit("podcast", { phase: "encode", m4a: path.basename(m4a), mp3: mp3 ? path.basename(mp3) : null }); const encode = async (file, codec) => { const tmp = file.replace(/(\.[a-z0-9]+)$/, `.${process.pid}.tmp$1`); diff --git a/umtool/report-to-video/build-podcast.test.mjs b/umtool/report-to-video/build-podcast.test.mjs @@ -55,8 +55,8 @@ test("chapters at the podcast's own offsets, with the video's titles; ffmeta and const titles = ["Title", "Then", "Chan · 2024-01-01 — One", "Image", "Other · Two", "Soon"]; const ch = podcastChapters(items, [4.1, 3.6, 2], titles); assert.deepEqual(ch.map((c) => [c.title, c.start, c.end]), [["Then", 0, 4.1], ["Chan · 2024-01-01 — One", 4.1, 7.7], ["Other · Two", 7.7, 9.7]]); - const meta = podcastFfmeta(ch, { title: "The Pod", disclosure: "Narration: synthetic voice (kokoro · af_heart)" }); - assert.match(meta, /^;FFMETADATA1\ntitle=The Pod\ncomment=Narration: synthetic voice \(kokoro · af_heart\)\n/); + const meta = podcastFfmeta(ch, { title: "The Pod", disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart)" }); + assert.match(meta, /^;FFMETADATA1\ntitle=The Pod\ncomment=Narration: synthetic voice \(Kokoro-82M · af_heart\)\n/); assert.equal((meta.match(/\[CHAPTER\]/g) ?? []).length, 3); assert.match(meta, /START=4100\nEND=7700\ntitle=Chan · 2024-01-01 — One/); assert.deepEqual(ffmetaTitles(meta), ["Then", "Chan · 2024-01-01 — One", "Other · Two"]); @@ -69,7 +69,7 @@ test("chapters at the podcast's own offsets, with the video's titles; ffmeta and { label: "Other · Two", url: "https://mirror.example/v2?t=3" }, { label: "Someone (bluesky, 2026-08-13)", url: "https://bsky.example/p/1" }, ]); - const notes = showNotes({ manifest: M(), chapters: ch, sources, disclosure: "Narration: synthetic voice (kokoro · af_heart)", duration: 9.7 }); + const notes = showNotes({ manifest: M(), chapters: ch, sources, disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart)", duration: 9.7 }); assert.equal(notes, [ "# The Pod", "", "a test", "", "Length: 0:09", "", "## Chapters", "", "- 0:00 — Then", "- 0:04 — Chan · 2024-01-01 — One", "- 0:07 — Other · Two", "", @@ -78,7 +78,7 @@ test("chapters at the podcast's own offsets, with the video's titles; ffmeta and "- Image — <https://example.test/post/1>", "- Other · Two — <https://mirror.example/v2?t=3>", "- Someone (bluesky, 2026-08-13) — <https://bsky.example/p/1>", - "", "Narration: synthetic voice (kokoro · af_heart)", "", + "", "Narration: synthetic voice (Kokoro-82M · af_heart)", "", ].join("\n")); assert.equal(clock(3725), "1:02:05"); }); @@ -147,14 +147,14 @@ test("a render: m4a and mp3 with chapters at −16 LUFS, the show notes, the dis assert.ok(Math.abs(Number(info.chapters[1].start_time) - 3.6) < 0.05, `${file}: ${info.chapters[1].start_time}`); const tags = Object.fromEntries(Object.entries(info.format.tags ?? {}).map(([k, v]) => [k.toLowerCase(), v])); assert.equal(tags.title, "The Pod"); - assert.equal(tags.comment, "Narration: synthetic voice (kokoro · af_heart)"); + assert.equal(tags.comment, "Narration: synthetic voice (Kokoro-82M · af_heart)"); const l = lufsOf(file); assert.ok(Math.abs(l + 16) < 1.5, `${file} at ${l} LUFS`); } const notes = readFileSync(r.notes, "utf8"); assert.match(notes, /- 0:03 — Chan · One/); assert.match(notes, /<https:\/\/archive\.example\/\?v=chan%2Fv1&t=10>/); - assert.match(notes, /Narration: synthetic voice \(kokoro · af_heart\)\n$/); + assert.match(notes, /Narration: synthetic voice \(Kokoro-82M · af_heart\)\n$/); const rec = JSON.parse(readFileSync(path.join(dir, "podcast.json"), "utf8")); assert.deepEqual(rec.left, ["t0", "i1", "z1"]); assert.equal(rec.lufs, -16); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -138,10 +138,10 @@ import { validateFlipEntries } from "./flips.mjs"; // narration.mjs (pure); its synthesized sound is kept in out/narration/ // (narration-store.mjs) by asking the editor (narrate-via-editor.mjs). import { - hasNarration, narratedCardSeconds, narrationAudioFilter, narrationDisclosure, narrationGainDb, narrationsOf, + hasNarration, narratedCardSeconds, narrationAudioFilter, narrationGainDb, narrationsOf, cardNarrationSeconds, resolveNarrationRender, validateNarration, } from "./narration.mjs"; -import { narrationDir, narrationWavPath, readNarrationRecords } from "./narration-store.mjs"; +import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs"; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; @@ -3965,7 +3965,7 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, FFMPEG, ["-nostdin", "-v", "error", "-y", "-i", finalPath, "-i", metaPath, "-map", "0", "-map_metadata", "0", "-map_chapters", "1", - // A narrated cut says so in its own metadata (narrationDisclosure); a cut + // A narrated cut says so in its own metadata (the editor's disclosure lines); a cut // without narration is muxed exactly as it always was. ...(disclosure ? ["-metadata", `comment=${disclosure}`] : []), "-c", "copy", tmp], @@ -4432,7 +4432,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // Under the deck the cut's offsets include the holds: measured, not written. const joins = deck ? segmentJoins(await measureChromeSchedule({ manifest, entries, segments: segs, D })) : null; - await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); + await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); return { out: finalPath, failures: [] }; } @@ -4467,7 +4467,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // applyRail re-encodes, so the chapters muxed onto the previous final are // gone. Put them back, or --rail-only quietly ships a chapterless cut. if (!opts.noChapters) { - await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: narrationDisclosure(manifest) }); + await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); } } EMIT("done", { out, failures: [] }); @@ -4574,7 +4574,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build"); // The overlay re-encodes, so the chapters on the previous final are gone. - if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); + if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -4697,7 +4697,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // shortest=1), and a hang means an unbounded -loop 1. if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build"); - if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); + if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -15,6 +15,12 @@ // reads it from there. A narration already kept is not asked again; the editor // answers a repeat ask from its own cache too. // +// The ask's body keys are the editor's (`{text, engine, voice, speed}` of its +// `{text, file, voice, engine, speed, out}`); `out` is never sent -- the +// editor writes into its own cache and its result names the file. Its result +// line carries the disclosure ("Narration: synthetic voice (Kokoro-82M · +// af_heart)"), which is kept with the narration and used verbatim. +// // The editor is `ARCHILYZER_EDITOR_URL` (default http://localhost:3001), asked // with the shared `WORKER_TOKEN` -- both from the environment, never argv, as // fetch-via-editor.mjs. It waits as long as the jobs do (the editor's tts @@ -39,6 +45,8 @@ const POLL_MS = Number(process.env.NARRATE_VIA_EDITOR_POLL_MS) > 0 ? Number(proc const MAX_POLL_FAILURES = 10; const MAX_BACKOFF_MS = 30_000; const TAIL_LINES = 80; +// Re-reads of a done job's tail before its result line counts as missing. +const RESULT_RETRIES = 10; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -166,7 +174,13 @@ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), em } if (status === "queued" || status === "running") continue; pending.delete(jobId); - const done = await poll(jobId, true); + let done = await poll(jobId, true); + // A cache hit can say `done` a few ms before its log line is on disk: + // read the tail again, briefly, before calling the result missing. + for (let i = 0; status === "done" && !ttsResultIn(done.tail) && i < RESULT_RETRIES; i += 1) { + await sleep(Math.max(pollMs, 100)); + done = await poll(jobId, true); + } if (status !== "done") { const why = (done.tail ?? []).slice(-3).join(" / "); failed.push(`${label}: editor job ${jobId} ${status === "archived" ? "was lost by the editor (restarted?)" : status}${why ? ` — ${why}` : ""}`); diff --git a/umtool/report-to-video/narrate.test.mjs b/umtool/report-to-video/narrate.test.mjs @@ -65,7 +65,10 @@ async function fakeEditor(dir) { "-ac", "1", "-c:a", "pcm_s16le", wav, ]); assert.equal(r.status, 0, String(r.stderr)); - jobs.set(id, { polls: 0, fail: /FAIL/.test(body.text), result: { wav, seconds, engine: body.engine, voice: body.voice, cached: false, durationMs: 12, waitedMs: 3 } }); + jobs.set(id, { + polls: 0, tails: 0, fail: /FAIL/.test(body.text), + result: { wav, seconds, engine: body.engine, voice: body.voice, cached: false, durationMs: 12, waitedMs: 3, sha: "s", sampleRate: 48000, speed: body.speed, disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice})` }, + }); send(202, { ok: true, jobId: id }); }); return; @@ -76,11 +79,15 @@ async function fakeEditor(dir) { const j = jobs.get(m[1]); const tail = url.searchParams.get("tail"); if (!tail) j.polls += 1; + else j.tails += 1; const status = j.polls <= 1 ? "queued" : j.polls === 2 ? "running" : j.fail ? "failed" : "done"; + // The editor's caveat, played: the first tail of a done job does not + // have the result line on disk yet. + const lineOnDisk = j.tails > 1; return send(200, { ok: true, job: { id: m[1], kind: "tts-file", status, ...(status === "queued" ? { queue: { key: "tts", position: 1, queued: 2 } } : {}) }, - ...(tail ? { tail: j.fail ? ["synthesizing", "kokoro: the model is missing"] : ["synthesizing", `${TTS_RESULT_MARKER}${JSON.stringify(j.result)}`] } : {}), + ...(tail ? { tail: j.fail ? ["synthesizing", "kokoro: the model is missing"] : ["synthesizing", ...(lineOnDisk ? [`${TTS_RESULT_MARKER}${JSON.stringify(j.result)}`] : [])] } : {}), }); } req.resume(); @@ -157,7 +164,8 @@ test("narrateCut: one batch, engine and voice always named, followed to the resu assert.ok(Math.abs(rec.seconds - 2.45) < 0.05, `seconds ${rec.seconds}`); assert.ok(rec.lufs < -10 && rec.lufs > -40, `lufs ${rec.lufs}`); assert.match(rec.sha256, /^[0-9a-f]{64}$/); - assert.equal(rec.disclosure, "Narration: synthetic voice (kokoro · af_heart)"); + assert.equal(rec.disclosure, "Narration: synthetic voice (Kokoro-82M · af_heart)", "the editor's line, verbatim"); + assert.equal(rec.editor.sha, "s"); assert.equal(rec.editor.jobId, "tts-1"); // A copy beside the build, not the editor's file. assert.ok(statSync(path.join(dir, `${rec.key}.wav`)).size > 0); @@ -267,7 +275,7 @@ test("a build: the narrated card's sound is the voice, \"auto\" its length, rebu assert.ok(maxVolume(path.join(segs, "k1.mp4")) > -30, "the narrated card speaks"); assert.equal(maxVolume(path.join(segs, "k0.mp4")), -91, "a card without narration is digital silence (anullsrc)"); const tags = probe(path.join(proj, "out", "narrated.mp4"), "format_tags=comment").format.tags ?? {}; - assert.equal(tags.comment, "Narration: synthetic voice (kokoro · af_heart)"); + assert.equal(tags.comment, "Narration: synthetic voice (Kokoro-82M · af_heart)"); // Again, unchanged: no ask, no encode. const before = statSync(path.join(segs, "k1.mp4")).mtimeMs; diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -18,7 +18,7 @@ import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/ import path from "node:path"; import { promisify } from "node:util"; -import { narrationDisclosure } from "./narration.mjs"; +import { disclosureLine, narrationDisclosure, narrationsOf } from "./narration.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -120,8 +120,12 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { ...(Number.isFinite(Number(result.seconds)) ? { seconds: Number(result.seconds) } : {}), ...(Number.isFinite(Number(result.durationMs)) ? { durationMs: Number(result.durationMs) } : {}), ...(Number.isFinite(Number(result.waitedMs)) ? { waitedMs: Number(result.waitedMs) } : {}), + ...(typeof result.sha === "string" ? { sha: result.sha } : {}), }, - disclosure: narrationDisclosure({ timeline: [{ type: "card", id: n.id, narration: { text: n.text, engine, voice } }] }), + // The editor's own line, verbatim (it may carry an engine's attribution). + disclosure: typeof result.disclosure === "string" && result.disclosure.trim() + ? result.disclosure.trim() + : disclosureLine(engine, voice), createdAt: new Date().toISOString(), }; const recTmp = path.join(dir, `.${n.key}.${process.pid}.tmp.json`); @@ -129,3 +133,13 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { await rename(recTmp, narrationRecordPath(dir, n.key)); return record; } + +/** + * A cut's disclosure, from the narrations it keeps (`out/narration/`): the + * editor's lines, each once, joined by `sep`; null when nothing is narrated. + * A narration not kept yet says the line its engine and voice would. + */ +export async function readCutDisclosure(dir, manifest, sep = "\n") { + const records = await readNarrationRecords(dir, narrationsOf(manifest)); + return narrationDisclosure(manifest, records, sep); +} diff --git a/umtool/report-to-video/narration.mjs b/umtool/report-to-video/narration.mjs @@ -50,12 +50,22 @@ export const NARRATION_LIMITS = Object.freeze({ }); /** - * The expressive tags a narration may carry: Orpheus speaks them; Kokoro has - * none, and the editor strips them before it synthesizes. Any other `<…>` is - * refused, by name. + * The expressive tags a narration may carry, lowercase and exact: Orpheus + * speaks them; Kokoro has none, and the editor strips them before it + * synthesizes. Any other `<…>` is refused, by name -- the editor's own list + * and rule (`TTS_EXPRESSIVE_TAGS`, common/lib/ttsText.ts; a test holds the + * two equal), mirrored here because this file runs in bare node and in + * umtool's client bundle. */ export const NARRATION_TAGS = Object.freeze(["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]); +/** + * Each engine's name as the editor's disclosure line says it (ttsApps.ts + * `label`). Only for a narration whose record carries no line of the editor's + * own -- the editor's `disclosure` is used verbatim whenever there is one. + */ +export const NARRATION_ENGINE_LABELS = Object.freeze({ kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG", orpheus: "Orpheus" }); + const RENDER_KEYS = new Set(Object.keys(NARRATION_DEFAULTS)); const CARD_KEYS = new Set(["text", "voice", "engine"]); // A stock voice's id: `af_heart`, `bm_george`, `en-us` (espeak-ng). Never a path. @@ -126,10 +136,11 @@ function textProblems(text) { const out = []; if (typeof text !== "string" || !text.trim()) return ["text must be non-empty words"]; for (const m of text.matchAll(TAG_RE)) { - const tag = m[1].trim().toLowerCase(); - if (!NARRATION_TAGS.includes(tag)) { - out.push(`the tag <${m[1]}> is not one of ${NARRATION_TAGS.map((t) => `<${t}>`).join(" ")}`); - } + if (NARRATION_TAGS.includes(m[1])) continue; + // Exact, as the editor reads them: `<Sigh>` and `< sigh >` are not tags. + const near = m[1].trim().toLowerCase(); + const hint = NARRATION_TAGS.includes(near) ? ` (did you mean <${near}>?)` : ""; + out.push(`the tag <${m[1]}>${hint} is not one of ${NARRATION_TAGS.map((t) => `<${t}>`).join(" ")}`); } const words = narrationWords(text); if (words === 0) out.push("text has no words outside its tags"); @@ -304,17 +315,29 @@ export function narrationAudioFilter({ seconds, lead, gainDb, render }) { ].join(","); } +/** The disclosure line for one engine and voice, as the editor writes it (ttsApps.ts `ttsDisclosure`). */ +export const disclosureLine = (engine, voice) => + `Narration: synthetic voice (${NARRATION_ENGINE_LABELS[engine] ?? engine} · ${voice})`; + /** - * The disclosure a narrated output carries -- in its description and chapters - * export, its show notes, its file's metadata: - * "Narration: synthetic voice (kokoro · af_heart)". Each engine · voice pair - * used, in order, once. Null when nothing in the cut is narrated. + * The disclosure lines a narrated output carries -- in its description and + * chapters export, its show notes, its file's metadata -- each once, in cut + * order: every narration's record's own line (the editor's, verbatim: + * "Narration: synthetic voice (Kokoro-82M · af_heart)"), else one made the + * same way from the engine and voice asked for. `records` maps a card id to + * its record (narration-store). Empty when nothing in the cut is narrated. */ -export function narrationDisclosure(manifest) { - const pairs = []; +export function disclosureLines(manifest, records = new Map()) { + const lines = []; for (const n of narrationsOf(manifest)) { - const p = `${n.engine} · ${n.voice}`; - if (!pairs.includes(p)) pairs.push(p); + const line = records.get(n.id)?.disclosure || disclosureLine(n.engine, n.voice); + if (!lines.includes(line)) lines.push(line); } - return pairs.length ? `Narration: synthetic voice (${pairs.join("; ")})` : null; + return lines; +} + +/** disclosureLines as one text (`sep` between lines), or null when nothing is narrated. */ +export function narrationDisclosure(manifest, records = new Map(), sep = "\n") { + const lines = disclosureLines(manifest, records); + return lines.length ? lines.join(sep) : null; } diff --git a/umtool/report-to-video/narration.test.mjs b/umtool/report-to-video/narration.test.mjs @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { - NARRATION_DEFAULTS, NARRATION_TAGS, cardNarrationSeconds, estimatedNarratedCardSeconds, narratedCardSeconds, + NARRATION_DEFAULTS, NARRATION_TAGS, cardNarrationSeconds, disclosureLines, estimatedNarratedCardSeconds, narratedCardSeconds, narrationAudioFilter, narrationDisclosure, narrationGainDb, narrationKey, narrationWords, narrationsOf, resolveNarration, stripNarrationTags, validateNarration, } from "./narration.mjs"; @@ -25,7 +25,10 @@ test("a valid narration, and a manifest without any, say nothing", () => { test("the text: non-empty, the expressive tags only, words capped without the tags", () => { const errs = (text) => validateNarration(M([card({ narration: { text } })])); assert.match(errs(" ")[0], /k1\.narration: text must be non-empty words/); - assert.deepEqual(errs("Well <laugh> that went well <SIGH>."), []); + assert.deepEqual(errs("Well <laugh> that went well <sigh>."), []); + // Exact, as the editor reads them. + assert.match(errs("Well <SIGH>.")[0], /the tag <SIGH> \(did you mean <sigh>\?\) is not one of/); + assert.match(errs("Well < laugh >.")[0], /the tag < laugh > \(did you mean <laugh>\?\)/); for (const t of NARRATION_TAGS) assert.deepEqual(errs(`Then <${t}> on.`), [], t); const bad = errs("Then <whisper> on, and <b>this</b>."); assert.equal(bad.length, 3, bad.join("\n")); @@ -122,13 +125,17 @@ test("the sound's filter: rate, layout, level, limit, lead, exact length", () => assert.equal(narrationGainDb(null, -17.7), 0); }); -test("the disclosure line: each engine · voice once, none without narration", () => { - assert.equal(narrationDisclosure(M([card()])), "Narration: synthetic voice (kokoro · af_heart)"); +test("the disclosure: the record's own line, else the editor's form; each once; none without narration", () => { + assert.equal(narrationDisclosure(M([card()])), "Narration: synthetic voice (Kokoro-82M · af_heart)"); assert.equal( narrationDisclosure(M([card(), card({ id: "k2", narration: { text: "Two.", voice: "am_adam" } }), card({ id: "k3" })])), - "Narration: synthetic voice (kokoro · af_heart; kokoro · am_adam)", + "Narration: synthetic voice (Kokoro-82M · af_heart)\nNarration: synthetic voice (Kokoro-82M · am_adam)", ); assert.equal(narrationDisclosure(M([{ type: "card", id: "a", seconds: 3 }])), null); + // The editor's line wins, verbatim, attribution and all. + const recs = new Map([["k1", { disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart). Some attribution." }]]); + assert.equal(narrationDisclosure(M([card(), card({ id: "k2" })]), recs, " "), "Narration: synthetic voice (Kokoro-82M · af_heart). Some attribution. Narration: synthetic voice (Kokoro-82M · af_heart)"); + assert.deepEqual(disclosureLines(M([card({ narration: { text: "a", engine: "espeak-ng", voice: "en-us" } })])), ["Narration: synthetic voice (eSpeak NG · en-us)"]); }); test("the lint: an authored seconds shorter than the narration is an ERROR; an unsynthesized one is a note", () => { @@ -143,3 +150,8 @@ test("the lint: an authored seconds shorter than the narration is an ERROR; an u const bad = lintManifest(M([card({ narration: { text: "a <whisper> b" } })])); assert.ok(bad.errors.some((e) => /<whisper>/.test(e)), bad.errors.join("\n")); }); + +test("the tags are the editor's: TTS_EXPRESSIVE_TAGS (common/lib/ttsText.ts)", async () => { + const { TTS_EXPRESSIVE_TAGS } = await import("yt-dlp-transcript-common/lib/ttsText"); + assert.deepEqual([...NARRATION_TAGS], [...TTS_EXPRESSIVE_TAGS]); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -30,6 +30,7 @@ "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", "./narration": "./narration.mjs", + "./narration-store": "./narration-store.mjs", "./package.json": "./package.json", "./post-links": "./post-links.mjs", "./prune-frames": "./prune-frames.mjs",