commit 135fd7b2a80be220b61df0ce4277b7f13b17de1a
parent 254bbac30bec0d5a595fd05abd8f7cc624bb544b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 22:26:19 -0400
common, umtool: the left panel's rules in common (panels.mjs); out/youtube.txt composed by the build (r28 M6)
panels.mjs is the one copy of the flips' and the threads' limits and
validators (validateFlips, validateFlipEntries, validateThreads,
validateThreadEntries, flipsOn, threadsOn, threadOf), moved from
report-to-video's flips.mjs and threads.mjs, which re-export them unchanged:
the flips and threads draft tasks check exactly what the build refuses.
youtube.mjs composes the upload's text from publish.youtube, the build's
chapter list (YouTube's rules: 0:00 first, at least three, ten seconds each;
a short chapter folded into the one before; else no block, and a note) and a
moment link per cited clip, in cut order, each once. muxChapters returns the
chapters it muxed; every build path that muxes them (or would, under
--no-chapters) writes out/youtube.txt (youtube-<variant>.txt for another
variant) when the manifest has publish.youtube.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 498 insertions(+), 168 deletions(-)
diff --git a/common/lib/report/panels.d.mts b/common/lib/report/panels.d.mts
@@ -0,0 +1,20 @@
+// Types for ./panels.mjs (release 28, M4/M5): the flips' and the threads'
+// limits and validators. See the module's header.
+
+export type FlipSide = { entry: string; when: string; words: string };
+export type FlipPair = { id: string; topic: string; then: FlipSide; now: FlipSide };
+export type Flips = { pairs: FlipPair[] };
+export type ThreadOutcome = { verdict: string; label?: string };
+export type Thread = { id: string; label: string; outcome?: ThreadOutcome };
+export type Threads = { list: Thread[] };
+
+export const FLIPS_LIMITS: Readonly<{ pairs: readonly [number, number]; topic: number; when: number; words: number }>;
+export const THREADS_LIMITS: Readonly<{ threads: readonly [number, number]; label: number; outcome: number }>;
+
+export function flipsOn(render: unknown): boolean;
+export function validateFlips(f: unknown, where?: string): string[];
+export function validateFlipEntries(manifest: unknown): string[];
+export function threadsOn(render: unknown): boolean;
+export function validateThreads(t: unknown, where?: string): string[];
+export function threadOf(entry: unknown): string | null;
+export function validateThreadEntries(manifest: unknown): string[];
diff --git a/common/lib/report/panels.mjs b/common/lib/report/panels.mjs
@@ -0,0 +1,180 @@
+// THE LEFT PANEL'S RULES — THE one copy of what a cut's flips
+// (`render.chrome.flips`) and threads (`render.chrome.threads`, each clip's
+// `thread`) may be: their limits and their validators (release 28, M4/M5:
+// moved here from umtool/report-to-video/flips.mjs and threads.mjs, which
+// re-export them unchanged, so the flips and threads draft tasks check
+// exactly what the build refuses).
+//
+// Plain JS (with ./panels.d.mts for TypeScript) for the reason
+// ./verdicts.mjs is: umtool's report-to-video scripts are `.mjs` run by bare
+// `node`, and the draft tasks are TypeScript. PURE: no fs.
+//
+// The two share the frame's left side: a cut has one or the other
+// (umtool's deck.mjs validateChrome refuses both).
+
+import { VERDICTS } from "./verdicts.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+// ─── flips ───
+
+/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */
+export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 });
+
+const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+const oneLineMax = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max;
+
+/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */
+export function flipsOn(render) {
+ const f = render?.chrome?.flips;
+ return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0;
+}
+
+/**
+ * Every reason `render.chrome.flips` cannot be built, as sentences. Shape
+ * only; `validateFlipEntries` checks the pairs against the timeline.
+ *
+ * @returns {string[]}
+ */
+export function validateFlips(f, where = "render.chrome.flips") {
+ if (f === undefined) return [];
+ if (!isObj(f)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`);
+ const [lo, hi] = FLIPS_LIMITS.pairs;
+ if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`];
+ const ids = new Set();
+ f.pairs.forEach((p, i) => {
+ const w = `${where}.pairs[${i}]`;
+ if (!isObj(p)) { errors.push(`${w} must be an object`); return; }
+ for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`);
+ if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
+ else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`);
+ else ids.add(p.id);
+ if (!oneLineMax(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`);
+ for (const side of ["then", "now"]) {
+ const s = p[side];
+ const ws = `${w}.${side}`;
+ if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; }
+ for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`);
+ if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`);
+ if (!oneLineMax(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`);
+ if (!oneLineMax(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`);
+ }
+ });
+ return errors;
+}
+
+/**
+ * The pairs against the timeline: each side names an entry of the cut, a clip
+ * (not a teaser), the THEN side before the NOW side, and no entry in two pairs.
+ *
+ * @returns {string[]}
+ */
+export function validateFlipEntries(manifest) {
+ const render = manifest?.render ?? {};
+ if (!flipsOn(render)) return [];
+ const errors = [];
+ const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }]));
+ const used = new Map();
+ render.chrome.flips.pairs.forEach((p, i) => {
+ const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`;
+ const idx = {};
+ for (const side of ["then", "now"]) {
+ const id = p?.[side]?.entry;
+ const hit = at.get(id);
+ if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; }
+ if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`);
+ if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`);
+ used.set(id, p.id);
+ idx[side] = hit.i;
+ }
+ if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`);
+ });
+ return errors;
+}
+
+// ─── threads ───
+
+/** The limits: how many threads, a label's and an outcome label's characters. */
+export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 });
+
+/** A thread id: letters, digits and `_ -`. */
+const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+
+const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v);
+
+/** Is the rail on: a `render.chrome.threads` with at least one thread. */
+export function threadsOn(render) {
+ const t = render?.chrome?.threads;
+ return isObj(t) && Array.isArray(t.list) && t.list.length > 0;
+}
+
+/**
+ * Every reason `render.chrome.threads` cannot be built, as sentences (empty:
+ * it can). validateChrome calls this, so umtool's writer and the build refuse
+ * the same things.
+ *
+ * @returns {string[]}
+ */
+export function validateThreads(t, where = "render.chrome.threads") {
+ if (t === undefined) return [];
+ if (!isObj(t)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`);
+ const [lo, hi] = THREADS_LIMITS.threads;
+ if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) {
+ return [...errors, `${where}.list must be ${lo} to ${hi} threads`];
+ }
+ const seen = new Set();
+ t.list.forEach((th, i) => {
+ const w = `${where}.list[${i}]`;
+ if (!isObj(th)) { errors.push(`${w} must be an object`); return; }
+ for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`);
+ if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
+ else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`);
+ else seen.add(th.id);
+ if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) {
+ errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`);
+ }
+ if (th.outcome !== undefined) {
+ const o = th.outcome;
+ if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; }
+ for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`);
+ if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`);
+ if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) {
+ errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`);
+ }
+ }
+ });
+ return errors;
+}
+
+/** The thread an entry belongs to, or null. */
+export function threadOf(entry) {
+ return typeof entry?.thread === "string" && entry.thread ? entry.thread : null;
+}
+
+/**
+ * Every `thread` in the timeline, checked against the list: it names a listed
+ * thread, it is not on a teaser, and every listed thread has a clip. The
+ * build refuses with these before it fetches.
+ *
+ * @returns {string[]}
+ */
+export function validateThreadEntries(manifest) {
+ const errors = [];
+ const render = manifest?.render ?? {};
+ const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set();
+ const used = new Set();
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.thread === undefined || e?.thread === null) return;
+ const where = `timeline[${i}] (${e.id ?? "?"}).thread`;
+ if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; }
+ if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; }
+ if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; }
+ used.add(e.thread);
+ });
+ for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`);
+ return errors;
+}
diff --git a/common/package.json b/common/package.json
@@ -36,6 +36,7 @@
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
+ "./lib/report/panels.mjs": "./lib/report/panels.mjs",
"./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs",
"./lib/toolProbe.mjs": "./lib/toolProbe.mjs",
"./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs",
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -143,6 +143,8 @@ import {
import { validateClaims } from "./factcheck.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
+// The upload's text (release 28 M6): composed by code, written beside the cut.
+import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs";
// A card's `narration` (release 25): validated, resolved and levelled in
// narration.mjs (pure); its synthesized sound is kept in out/narration/
// (narration-store.mjs) by asking the editor (narrate-via-editor.mjs).
@@ -408,7 +410,7 @@ export function variantPaths(outRoot, slug, variant) {
// printed -- this is a formatting switch, not new instrumentation.
//
// Events: start, card, clip, fetch, snap, segment, entry-failed, concat,
-// chapters, chrome, narrate, note, done.
+// chapters, youtube, chrome, narrate, note, done.
const HUMAN = {
start: (e) => `${e.title} — ${e.entries} entr(ies)`,
card: (e) => `card ${e.id}`,
@@ -432,6 +434,7 @@ const HUMAN = {
"entry-failed": (e) => ` ** ${e.id} failed: ${e.message}`,
concat: (e) => `${e.mode === "xfade" ? "crossfading" : "hard-cutting"} ${e.n} segments…`,
chapters: (e) => `chapters: ${e.n} marker(s) -> ${e.file}`,
+ youtube: (e) => `youtube: ${e.file}${e.chapters ? ` (${e.chapters} chapter(s))` : ""}${e.note ? ` — ${e.note}` : ""}`,
// The deck's steps. `phase` is schedule | compose | render | cached | overlay.
chrome: (e) =>
`chrome ${e.phase}` +
@@ -3947,23 +3950,29 @@ export async function measureChromeSchedule({ manifest, entries, segments, D })
return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] });
}
+// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`,
+// seconds) -- the list out/youtube.txt's Chapters are made from -- or null
+// when the cut is one segment and gets none.
async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null, { disclosure = null } = {}) {
- if (segments.length < 2) return;
+ if (segments.length < 2) return null;
// The cut's own offsets: under the deck a held clip is longer in the cut
// than its file, and every chapter after it starts that much later.
const { starts, total } = await cutOffsets(segments, D, fps, joins);
const lines = [";FFMETADATA1", ""];
+ const chapters = [];
for (let i = 0; i < entries.length; i += 1) {
// Land just PAST the crossfade, so the marker opens on the incoming clip
// rather than on the outgoing one mid-dissolve.
const start = i === 0 ? 0 : starts[i] + D;
const end = i === entries.length - 1 ? total : starts[i + 1] + D;
+ const title = await chapterTitle(entries[i], i, provenance, { deck });
+ chapters.push({ start, end, title });
lines.push(
"[CHAPTER]",
"TIMEBASE=1/1000",
`START=${Math.round(start * 1000)}`,
`END=${Math.round(end * 1000)}`,
- `title=${ffmetaEscape(await chapterTitle(entries[i], i, provenance, { deck }))}`,
+ `title=${ffmetaEscape(title)}`,
"",
);
}
@@ -3984,6 +3993,28 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance,
);
await rename(tmp, finalPath);
EMIT("chapters", { n: entries.length, file: path.basename(metaPath) });
+ return { chapters, total };
+}
+
+/**
+ * `out/youtube.txt` (youtube.mjs): the cut's `publish.youtube` title and
+ * description, the chapters the build just muxed (YouTube's rules, else left
+ * out with a note) and a moment link per cited clip. Written by every build
+ * that muxes chapters -- or would have, under --no-chapters -- when the
+ * manifest has `publish.youtube`; nothing otherwise.
+ *
+ * @param {{ chapters: Array<{ start: number, end: number, title: string }>, total: number } | null} muxed
+ * @param {string | null} [why] why there are no chapters (`--no-chapters`)
+ */
+async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why = null) {
+ const youtube = manifest.publish?.youtube;
+ if (!youtube?.title) return null;
+ const { chapters, note } = muxed ? youtubeChapters(muxed.chapters, muxed.total) : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` };
+ const text = composeYoutubeText({ youtube, chapters, sources: youtubeSources(entries, manifest.provenance) });
+ const file = path.join(outRoot, youtubeTextName(variant));
+ await writeFile(file, text, "utf8");
+ EMIT("youtube", { file: path.basename(file), chapters: chapters?.length ?? 0, note });
+ return file;
}
/**
@@ -4452,7 +4483,8 @@ 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: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed);
return { out: finalPath, failures: [] };
}
@@ -4486,9 +4518,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
await assertConcatLength(out, railPlan.total, render.fps, "rail build");
// 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: await readCutDisclosure(narrationStore, manifest, " ") });
- }
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
}
EMIT("done", { out, failures: [] });
return { out, failures: [] };
@@ -4594,7 +4627,10 @@ 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: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
await pruneFrames();
EMIT("done", { out: dirs.final, failures: [] });
return { out: dirs.final, failures: [] };
@@ -4717,7 +4753,10 @@ 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: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
// 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/flips.mjs b/umtool/report-to-video/flips.mjs
@@ -15,10 +15,12 @@
// threadsGeometry); the two are one region and a cut has one or the other.
//
// PURE, like threads.mjs. chrome-flips.mjs draws the panel.
+// The limits and the validators are common's (lib/report/panels.mjs, release
+// 28): the flips draft task checks exactly what the build refuses.
+import { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { planCues } from "./threads.mjs";
-/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */
-export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 });
+export { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips };
/**
* The panel's motion, in seconds: a pair rises in over `enter`, its NOW card
@@ -32,80 +34,6 @@ export const FLIP_MOTION = Object.freeze({
/** How bright the THEN card rests once NOW has landed. */
export const THEN_DIM = 0.5;
-const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
-const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
-const oneLine = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max;
-
-/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */
-export function flipsOn(render) {
- const f = render?.chrome?.flips;
- return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0;
-}
-
-/**
- * Every reason `render.chrome.flips` cannot be built, as sentences. Shape
- * only; `validateFlipEntries` checks the pairs against the timeline.
- *
- * @returns {string[]}
- */
-export function validateFlips(f, where = "render.chrome.flips") {
- if (f === undefined) return [];
- if (!isObj(f)) return [`${where} must be an object`];
- const errors = [];
- for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`);
- const [lo, hi] = FLIPS_LIMITS.pairs;
- if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`];
- const ids = new Set();
- f.pairs.forEach((p, i) => {
- const w = `${where}.pairs[${i}]`;
- if (!isObj(p)) { errors.push(`${w} must be an object`); return; }
- for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`);
- if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
- else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`);
- else ids.add(p.id);
- if (!oneLine(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`);
- for (const side of ["then", "now"]) {
- const s = p[side];
- const ws = `${w}.${side}`;
- if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; }
- for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`);
- if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`);
- if (!oneLine(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`);
- if (!oneLine(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`);
- }
- });
- return errors;
-}
-
-/**
- * The pairs against the timeline: each side names an entry of the cut, a clip
- * (not a teaser), the THEN side before the NOW side, and no entry in two pairs.
- *
- * @returns {string[]}
- */
-export function validateFlipEntries(manifest) {
- const render = manifest?.render ?? {};
- if (!flipsOn(render)) return [];
- const errors = [];
- const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }]));
- const used = new Map();
- render.chrome.flips.pairs.forEach((p, i) => {
- const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`;
- const idx = {};
- for (const side of ["then", "now"]) {
- const id = p?.[side]?.entry;
- const hit = at.get(id);
- if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; }
- if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`);
- if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`);
- used.set(id, p.id);
- idx[side] = hit.i;
- }
- if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`);
- });
- return errors;
-}
-
/** The years between two `when`s, when both carry one (`2019`, `May 2019`): else null. */
export function yearsBetween(a, b) {
const y = (s) => {
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -40,6 +40,7 @@
"./resolve-windows": "./resolve-windows.mjs",
"./shoot-page": "./shoot-page.mjs",
"./sources": "./sources.mjs",
- "./verify-build": "./verify-build.mjs"
+ "./verify-build": "./verify-build.mjs",
+ "./youtube": "./youtube.mjs"
}
}
diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs
@@ -19,10 +19,12 @@
// PURE, like factcheck.mjs: the settings, their validation, the schedule and
// the cues. No fs. deck.mjs imports this file -- never the other way round.
// chrome-threads.mjs draws the rail.
-import { resolveFactcheck, VERDICTS } from "./factcheck.mjs";
+import { resolveFactcheck } from "./factcheck.mjs";
+// The limits and the validators are common's (lib/report/panels.mjs, release
+// 28): the threads draft task checks exactly what the build refuses.
+import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs";
-/** The limits: how many threads, a label's and an outcome label's characters. */
-export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 });
+export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads };
/**
* The rail's motion, in seconds: a card lights over `light` and its string
@@ -37,17 +39,7 @@ export const THREAD_MOTION = Object.freeze({
/** How long before its thread's last clip ends the outcome lands, at most. */
export const OUTCOME_LEAD = 1.8;
-/** A thread id: letters, digits and `_ -`. */
-const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
-
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
-const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v);
-
-/** Is the rail on: a `render.chrome.threads` with at least one thread. */
-export function threadsOn(render) {
- const t = render?.chrome?.threads;
- return isObj(t) && Array.isArray(t.list) && t.list.length > 0;
-}
/**
* The threads with their outcomes resolved: `[{ id, label, outcome: { verdict,
@@ -68,75 +60,6 @@ export function resolveThreads(render) {
}
/**
- * Every reason `render.chrome.threads` cannot be built, as sentences (empty:
- * it can). validateChrome calls this, so umtool's writer and the build refuse
- * the same things.
- *
- * @returns {string[]}
- */
-export function validateThreads(t, where = "render.chrome.threads") {
- if (t === undefined) return [];
- if (!isObj(t)) return [`${where} must be an object`];
- const errors = [];
- for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`);
- const [lo, hi] = THREADS_LIMITS.threads;
- if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) {
- return [...errors, `${where}.list must be ${lo} to ${hi} threads`];
- }
- const seen = new Set();
- t.list.forEach((th, i) => {
- const w = `${where}.list[${i}]`;
- if (!isObj(th)) { errors.push(`${w} must be an object`); return; }
- for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`);
- if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
- else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`);
- else seen.add(th.id);
- if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) {
- errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`);
- }
- if (th.outcome !== undefined) {
- const o = th.outcome;
- if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; }
- for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`);
- if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`);
- if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) {
- errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`);
- }
- }
- });
- return errors;
-}
-
-/** The thread an entry belongs to, or null. */
-export function threadOf(entry) {
- return typeof entry?.thread === "string" && entry.thread ? entry.thread : null;
-}
-
-/**
- * Every `thread` in the timeline, checked against the list: it names a listed
- * thread, it is not on a teaser, and every listed thread has a clip. The
- * build refuses with these before it fetches.
- *
- * @returns {string[]}
- */
-export function validateThreadEntries(manifest) {
- const errors = [];
- const render = manifest?.render ?? {};
- const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set();
- const used = new Set();
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.thread === undefined || e?.thread === null) return;
- const where = `timeline[${i}] (${e.id ?? "?"}).thread`;
- if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; }
- if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; }
- if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; }
- used.add(e.thread);
- });
- for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`);
- return errors;
-}
-
-/**
* The rail's schedule, in the cut's clock. `segments` are the schedule's, in
* order, each `{ id, start, duration, thread }`; `moves` are the footage's
* moves for popup posts (deck.mjs footageMoves).
diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs
@@ -0,0 +1,147 @@
+// THE YOUTUBE TEXT (release 28, M6): what a cut's upload says, composed by
+// CODE from `publish.youtube { title, description }` (drafted by the youtube
+// task or written by hand), the build's own chapter list and the cut's
+// citations. The build writes it to `out/youtube.txt` (`out/youtube-<variant>.txt`
+// for a variant other than `sourced`, as the cut's mp4 is named); umtool shows
+// and copies it, and previews it the same way, without chapters, before a build.
+//
+// <title>
+//
+// <description>
+//
+// Chapters
+// 0:00 <chapter>
+// …
+//
+// Sources
+// <a moment link per cited clip, in cut order, each once>
+//
+// The chapters are YouTube's: the first at 0:00, at least three, each at
+// least ten seconds. A chapter shorter than that is folded into the one
+// before it (a first one shorter than that takes the next one's span). A list
+// that is still too short, or does not start at 0:00, is left out -- and the
+// result's `notes` say why.
+//
+// PURE: no fs. build-video.mjs writes the file.
+
+/** YouTube's rules for a description's chapters. */
+export const YOUTUBE_CHAPTERS = Object.freeze({ min: 3, minSeconds: 10 });
+
+/** `m:ss`, or `h:mm:ss` from an hour. */
+export function chapterStamp(seconds) {
+ const s = Math.max(0, Math.floor(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+}
+
+const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
+
+/**
+ * The chapters as YouTube takes them, from the build's list (`{ start, end?,
+ * title }`, seconds, in order; `total` the cut's length for the last one's
+ * span): `{ chapters, note }` -- `chapters` null when the block is left out,
+ * `note` saying what was folded or why the block is left out.
+ *
+ * @param {Array<{ start: number, end?: number, title: string }> | null | undefined} list
+ * @param {number | null} [total]
+ */
+export function youtubeChapters(list, total = null) {
+ if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" };
+ const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" }));
+ if (all[0].start !== 0) return { chapters: null, note: `no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00` };
+ const end = Number.isFinite(Number(total)) && total !== null
+ ? Math.floor(Number(total))
+ : Math.floor(Number(list.at(-1).end ?? all.at(-1).start + YOUTUBE_CHAPTERS.minSeconds));
+ const kept = [all[0]];
+ let folded = 0;
+ for (const c of all.slice(1)) {
+ if (c.start - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) {
+ folded++;
+ // A first chapter too short to stand takes the next one's span under its own 0:00.
+ continue;
+ }
+ kept.push(c);
+ }
+ // The last must run ten seconds too.
+ while (kept.length > 1 && end - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) {
+ kept.pop();
+ folded++;
+ }
+ const foldNote = folded ? `${folded} chapter(s) under ${YOUTUBE_CHAPTERS.minSeconds} s folded into the one before` : "";
+ if (kept.length < YOUTUBE_CHAPTERS.min) {
+ return {
+ chapters: null,
+ note: `no chapters: ${kept.length} of at least ${YOUTUBE_CHAPTERS.min}` + (foldNote ? ` (${foldNote})` : ""),
+ };
+ }
+ return { chapters: kept, note: foldNote };
+}
+
+/**
+ * A clip's moment link: its `citeUrl` when it has one, else the archive's page
+ * at the cited second (`cite`, else `start`) -- the link the citation makes
+ * (`<origin>/?v=<channel>%2F<video>&t=<s>`). A clip from a file beside the
+ * manifest (`src`) with no `citeUrl` has none; nor has any other entry.
+ */
+export function momentLinkOf(entry, provenance = {}) {
+ if (entry?.type !== "clip") return null;
+ if (entry.citeUrl) return entry.citeUrl;
+ if (entry.src != null) return null;
+ const origin = String(provenance?.siteOrigin ?? "").replace(/\/+$/, "");
+ const channel = entry.channel ?? provenance?.channelSlug;
+ if (!origin || !channel || !entry.video) return null;
+ const at = Number.isFinite(Number(entry.cite)) ? Number(entry.cite) : Number(entry.start);
+ return `${origin}/?v=${encodeURIComponent(`${channel}/${entry.video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`;
+}
+
+/** The cut's moment links, in cut order, each once. */
+export function youtubeSources(entries, provenance = {}) {
+ const out = [];
+ const seen = new Set();
+ for (const e of entries ?? []) {
+ const href = momentLinkOf(e, provenance);
+ if (!href || seen.has(href)) continue;
+ seen.add(href);
+ out.push(href);
+ }
+ return out;
+}
+
+/**
+ * The text. `chapters` is youtubeChapters' (null: no block); `sources` the
+ * links. Null when the manifest has no `publish.youtube` title.
+ *
+ * @param {{ youtube?: { title?: string, description?: string } | null, chapters?: Array<{ start: number, title: string }> | null, sources?: string[] }} o
+ * @returns {string | null}
+ */
+export function composeYoutubeText({ youtube, chapters = null, sources = [] }) {
+ const title = oneLine(youtube?.title);
+ if (!title) return null;
+ const parts = [title];
+ const description = String(youtube?.description ?? "").trim();
+ if (description) parts.push(description);
+ if (chapters?.length) parts.push(["Chapters", ...chapters.map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`)].join("\n"));
+ if (sources.length) parts.push(["Sources", ...sources].join("\n"));
+ return `${parts.join("\n\n")}\n`;
+}
+
+/** The file a variant's text is written to, in the project's `out/`. */
+export function youtubeTextName(variant = "sourced") {
+ return variant === "sourced" ? "youtube.txt" : `youtube-${variant}.txt`;
+}
+
+/**
+ * The preview umtool shows before a build: composed the same way, without
+ * chapters (the build makes them), over the default cut's entries -- an entry
+ * tagged with another `variant` is left out, as build-video's selectVariant
+ * leaves it out of `sourced`.
+ *
+ * @returns {{ text: string | null, note: string }}
+ */
+export function youtubePreview(manifest) {
+ const entries = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => !e?.variant || e.variant === "sourced");
+ const text = composeYoutubeText({ youtube: manifest?.publish?.youtube, chapters: null, sources: youtubeSources(entries, manifest?.provenance) });
+ return { text, note: "chapters are added by the build" };
+}
diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs
@@ -0,0 +1,91 @@
+// out/youtube.txt's composition (release 28 M6): the title, the summary, the
+// chapters on YouTube's rules (0:00 first, at least three, ten seconds each),
+// the sources in cut order, each once.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import {
+ chapterStamp, composeYoutubeText, momentLinkOf, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS,
+} from "./youtube.mjs";
+
+const FULL = new URL("../../common/testing/draft/manifests/full.video.manifest.json", import.meta.url);
+const YT = { title: "What the baker says about the bakery", description: "Synth Kitchen on the bakery and the contest." };
+
+test("stamps: m:ss, h:mm:ss from an hour", () => {
+ assert.equal(chapterStamp(0), "0:00");
+ assert.equal(chapterStamp(65.9), "1:05");
+ assert.equal(chapterStamp(3725), "1:02:05");
+});
+
+test("chapters: 0:00 first, at least three, each ten seconds — short ones folded into the one before", () => {
+ const list = [
+ { start: 0, title: "Title" },
+ { start: 4, title: "The bakery" }, // 4 s after the first: folded
+ { start: 12.4, title: "Not for sale" },
+ { start: 30, title: "The contest" },
+ { start: 55, title: "Last" }, // 5 s before the end: folded
+ ];
+ const r = youtubeChapters(list, 60);
+ assert.deepEqual(r.chapters.map((c) => [c.start, c.title]), [[0, "Title"], [12, "Not for sale"], [30, "The contest"]]);
+ assert.match(r.note, /2 chapter\(s\) under 10 s folded/);
+ assert.equal(YOUTUBE_CHAPTERS.min, 3);
+});
+
+test("chapters: fewer than three, or not starting at 0:00, are left out — and the note says why", () => {
+ const two = youtubeChapters([{ start: 0, title: "A" }, { start: 20, title: "B" }], 40);
+ assert.equal(two.chapters, null);
+ assert.match(two.note, /^no chapters: 2 of at least 3/);
+ const late = youtubeChapters([{ start: 2, title: "A" }, { start: 20, title: "B" }, { start: 40, title: "C" }], 60);
+ assert.equal(late.chapters, null);
+ assert.match(late.note, /first starts at 0:02, not 0:00/);
+ assert.match(youtubeChapters(null).note, /made none/);
+});
+
+test("sources: a moment link per cited clip in cut order, each once; citeUrl wins; a src clip and a card have none", () => {
+ const prov = { siteOrigin: "https://synth.example/", channelSlug: "synth-kitchen" };
+ const entries = [
+ { type: "card", id: "t" },
+ { type: "clip", id: "c02", video: "bread-day-01", start: 24.2, cite: 25 },
+ { type: "clip", id: "c01", channel: "synth-kitchen", video: "bread-day-01", start: 15 },
+ { type: "clip", id: "c02b", video: "bread-day-01", start: 25, cite: 25.9 }, // the same moment again
+ { type: "clip", id: "x", citeUrl: "https://x.example/post/1" },
+ { type: "clip", id: "local", src: "a.mp4", start: 0 },
+ ];
+ assert.deepEqual(youtubeSources(entries, prov), [
+ "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25",
+ "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15",
+ "https://x.example/post/1",
+ ]);
+ assert.equal(momentLinkOf({ type: "clip", video: "v" }, {}), null, "no origin: no link");
+});
+
+test("the text: title, a blank, the summary, Chapters, Sources; nothing without a title", () => {
+ const text = composeYoutubeText({
+ youtube: YT,
+ chapters: [{ start: 0, title: "Title" }, { start: 12, title: "Not for sale" }, { start: 75, title: "The contest" }],
+ sources: ["https://a.example/1", "https://a.example/2"],
+ });
+ assert.equal(
+ text,
+ "What the baker says about the bakery\n\nSynth Kitchen on the bakery and the contest.\n\nChapters\n0:00 Title\n0:12 Not for sale\n1:15 The contest\n\nSources\nhttps://a.example/1\nhttps://a.example/2\n",
+ );
+ assert.equal(composeYoutubeText({ youtube: { title: " ", description: "x" } }), null);
+ assert.equal(composeYoutubeText({ youtube: { title: "T" } }), "T\n");
+ assert.equal(youtubeTextName(), "youtube.txt");
+ assert.equal(youtubeTextName("full"), "youtube-full.txt");
+});
+
+test("the preview: the default cut's sources, no chapters", async () => {
+ const m = JSON.parse(await readFile(FULL, "utf8"));
+ m.publish = { youtube: YT };
+ m.timeline.push({ type: "clip", id: "only-full", variant: "full", channel: "synth-kitchen", video: "qa-long-03", start: 5, cite: 5 });
+ const p = youtubePreview(m);
+ const lines = p.text.split("\n");
+ assert.equal(lines[0], YT.title);
+ assert.ok(!p.text.includes("Chapters"));
+ const sources = lines.slice(lines.indexOf("Sources") + 1).filter(Boolean);
+ assert.equal(sources.length, 7, "seven clips, seven moments");
+ assert.ok(!p.text.includes("qa-long-03&t=5"), "an entry of another variant is not in the default cut");
+ assert.equal(youtubePreview({ timeline: [] }).text, null);
+});