Archilyzer · Source

archilyzer

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

commit 977e795b92bfa9ba3a72b58bea41b3d5bd1586d4
parent e74358bd3f0d054cddf14fc25ce283aac41c381f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 12:26:32 -0400

umtool: updateRender + /api/report/render, a clip's vertical, setSpeakerLabel, the shorts job and route

lib/report/manifest.mjs updateRender(dir, patch, {token}) — headerHeight, footerHeight, qr, transition,
transitionStyle, loudness, captions; null removes; never render.chrome; the build's own checks; atomic,
token-guarded (RenderRefused, lookOf, LOOK_KEYS). updateClip takes `vertical`. common/lib/clips/reactions.mjs
gains setSpeakerLabel (after setSpeakerRole), re-exported by the clip editor's bridge; the clip editor's ops
gain `label` and `vertical`, its view the crop and the shorts on disk. lib/report/shorts.mjs: shortSteps
(build-video --short as a job step), readShorts (stale / gone), setShortAside (the replace guard).
/api/report/shorts: list, file (ranges, download), job, POST start, cancel. look.test.mjs: 5 tests.

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

Diffstat:
Mcommon/lib/clips/reactions.d.mts | 1+
Mcommon/lib/clips/reactions.mjs | 23+++++++++++++++++++++++
Aumtool/app/api/report/render/route.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/shorts/route.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/clipEditor.mjs | 31++++++++++++++++++++++++++++---
Mumtool/lib/report/clipEditorBridge.mjs | 7+++++++
Mumtool/lib/report/clipEditorTypes.ts | 4++++
Aumtool/lib/report/look.test.mjs | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/shorts.mjs | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 644 insertions(+), 3 deletions(-)

diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts @@ -42,3 +42,4 @@ export function readReactions(dir: string): Promise<ReactionsDoc | null>; export function writeReactions(dir: string, doc: ReactionsDoc): Promise<string>; export function operatorRoles(doc: ReactionsDoc | null): Record<string, Role>; export function setSpeakerRole(dir: string, index: number, role: Role | null, opts?: { now?: () => Date }): Promise<ReactionsDoc>; +export function setSpeakerLabel(dir: string, index: number, label: string | null): Promise<ReactionsDoc>; diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs @@ -92,3 +92,26 @@ export async function setSpeakerRole(dir, index, role, { now = () => new Date() await writeReactions(dir, doc); return doc; } + +/** + * A person's name for one speaker (release 36 lane C): what the speaker + * captions head that voice's lines with. Trimmed, up to 40 characters; null + * or empty gives back the default ("Host", "Subject", "Speaker N"), which the + * captions never print. A role change (setSpeakerRole) resets it. + * + * @param {string} dir the project + * @param {number} index the speaker (diarization cluster) + * @param {string|null} label + * @returns {Promise<any>} the document as written + */ +export async function setSpeakerLabel(dir, index, label) { + const doc = await readReactions(dir); + if (!doc) throw new Error(`no ${REACTIONS_FILE} in ${dir}`); + const s = doc.speakers.find((x) => isObj(x) && x.index === index); + if (!s) throw new Error(`no speaker ${index} in ${REACTIONS_FILE}`); + const text = label === null || label === undefined ? "" : String(label).replace(/\s+/g, " ").trim(); + if (text.length > 40) throw new Error("a speaker's label is up to 40 characters"); + s.label = text || labelOf(s.role, index); + await writeReactions(dir, doc); + return doc; +} diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts @@ -0,0 +1,65 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender } from "@/lib/report/manifest.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { deckOn } from "umtool-report-to-video/deck"; +import { validateLook } from "umtool-report-to-video/look"; +import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition"; + +export const dynamic = "force-dynamic"; + +// THE LOOK (release 36 lane C): the render keys the Look panel sets -- +// headerHeight, footerHeight, qr, transition, transitionStyle, loudness, +// captions -- never render.chrome (the deck's own route). The client sends a +// project id, a PATCH of those keys (null removes one) and the token it read; +// the writer (lib/report/manifest.mjs updateRender) validates with the +// build's own checks, so a look this route accepts is one the build accepts. +// +// GET ?project=<id> { look, deck, montage, styles, keys, errors, token } +// PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors } + +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const render = (r.manifest.render ?? {}) as Record<string, unknown>; + return Response.json( + { + look: lookOf(render), + deck: deckOn(render), + montage: render.montage !== undefined && render.montage !== null, + styles: TRANSITION_STYLES, + keys: LOOK_KEYS, + // A look somebody hand-edited into a state the build would refuse. + errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest)], + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const { result: res, editNotes } = await withEditNotes(r.project, () => + updateRender(r.project.dir, (body.patch ?? null) as Record<string, unknown>, { + token: body.token === undefined || body.token === null ? null : String(body.token), + }), + ); + return Response.json({ ok: true, look: res.look, token: res.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) { + return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); + } + if (e instanceof RenderRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/shorts/route.ts b/umtool/app/api/report/shorts/route.ts @@ -0,0 +1,97 @@ +import { stat } from "node:fs/promises"; +import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; +import { readShorts, setShortAside, shortFile, shortSteps } from "@/lib/report/shorts.mjs"; + +export const dynamic = "force-dynamic"; + +// VERTICAL SHORTS (release 36 lane C): `<project>/shorts/<clipId>.mp4`, one +// clip at 1080x1920 (build-video.mjs --short, in the heavy slot), as ONE job +// on the app's runner (lib/jobs.ts: one at a time, a log, Cancel) -- the +// clip editor's Make a short and the Deliver tab's Shorts list. +// +// GET ?project=<id> { shorts, running } +// GET ?project=<id>&clip=<id>&file=1 the mp4 (ranges; `download=1` as an attachment) +// GET ?job=<id>[&since=&sinceEvent=] that job +// POST { project, clip, replace? } make it; 409 { needsReplace } when one is there +// ?cancel=<job> stop it +const headers = { "cache-control": "no-store" }; +const isShortJob = (kind: string) => /^short /.test(kind); + +async function reportProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a short is made of a report video's clip" }, { status: 400, headers }) }; + return { project }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const jobId = url.searchParams.get("job"); + if (jobId) { + const job = getJob(jobId); + if (!job) return Response.json({ error: "no such job" }, { status: 404, headers }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const r = await reportProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + if (url.searchParams.get("file")) { + const clip = url.searchParams.get("clip") ?? ""; + const abs = shortFile(r.project.dir, clip); + const st = abs ? await stat(abs).catch(() => null) : null; + if (!abs || !st?.isFile()) return new Response(`no short of ${clip}`, { status: 404 }); + return rangeResponse(request, { + abs, + size: st.size, + headers: { + "content-type": "video/mp4", + "accept-ranges": "bytes", + "cache-control": url.searchParams.get("v") === String(Math.round(st.mtimeMs)) ? "private, max-age=3600, immutable" : "private, no-store", + ...(url.searchParams.get("download") ? { "content-disposition": `attachment; filename="${clip}-short.mp4"` } : {}), + }, + }); + } + const manifest = await readManifest(r.project.dir); + const running = runningJob(); + return Response.json( + { + shorts: await readShorts(r.project.dir, manifest), + running: running && running.project === r.project.id && isShortJob(running.kind) ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers }); + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await reportProject(body.project); + if ("error" in r) return r.error; + const manifest = await readManifest(r.project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers }); + const clip = String(body.clip ?? ""); + if (!clipsOf(manifest).some((e: { id: string }) => e.id === clip) || !shortFile(r.project.dir, clip)) { + return Response.json({ error: `no clip with id ${clip}` }, { status: 400, headers }); + } + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers }); + let aside: string | null = null; + try { + aside = await setShortAside(r.project.dir, clip, { replace: body.replace === true }); + } catch (e) { + const needsReplace = !!(e as { needsReplace?: boolean })?.needsReplace; + return Response.json({ error: e instanceof Error ? e.message : String(e), needsReplace }, { status: 409, headers }); + } + try { + const job = startJob(`short ${r.project.id} ${clip}`, shortSteps(r.project, clip), { project: r.project.id }); + return Response.json({ ok: true, clip, aside, job: jobView(job) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers }); + } +} diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -38,7 +38,8 @@ import { updateClip, } from "./manifest.mjs"; import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; -import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; +import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; +import { readShorts } from "./shorts.mjs"; import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; @@ -83,7 +84,8 @@ export async function readWords(dir, reactions = null) { /** * @typedef {{ id: string, channel: string | null, video: string, start: number, end: number, * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, - * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean }} EditorClip + * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean, + * vertical: { crop: number[], aspect?: number } | null }} EditorClip */ /** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ @@ -110,8 +112,11 @@ export async function clipEditorView(project) { key, ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null, montage: isObj(e.montage), + // A short's framing (release 36): fractions of the source picture. + vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null, }; }); + const shorts = await readShorts(project.dir, manifest); const doc = reactions.doc; return { clips, @@ -130,6 +135,7 @@ export async function clipEditorView(project) { } : null, repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, + shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), }; } @@ -229,6 +235,8 @@ const num = (v, what) => { * bring-in { proposal } one of the clip finder's unused proposals * ruling { clip, verdict: "keep" | "cut" | null } * role { speaker, role | null } reactions.json, through the clip finder's writer + * label { speaker, label | null } a speaker's name for the captions (reactions.json) + * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short * with `token` (the manifest's, from the view) on every manifest edit. * Returns `{ op, result, carried, view }`. */ @@ -338,8 +346,25 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { structural = false; break; } + case "label": { + const index = Number(body.speaker); + if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index"); + if (body.label !== null && typeof body.label !== "string") throw new OpError("label is a text, or null for the default"); + const doc = await setSpeakerLabel(dir, index, body.label); + result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null }; + structural = false; + break; + } + case "vertical": { + const e = needClip(); + const v = body.crop === null ? null : { crop: body.crop, ...(body.aspect !== undefined ? { aspect: Number(body.aspect) } : {}) }; + // A "trim" that leaves the cut where it is: the clip's assist is not touched. + result = await updateClip(dir, e.id, { vertical: v }, { token, edit: "trim", now }); + structural = false; + break; + } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling or role"); + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label or vertical"); } let carried = null; if (structural) { diff --git a/umtool/lib/report/clipEditorBridge.mjs b/umtool/lib/report/clipEditorBridge.mjs @@ -48,6 +48,13 @@ export async function readReactions(dir) { */ export { setSpeakerRole } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +/** + * A person's name for one speaker (release 36): THE CLIP FINDER'S FILE, the + * one other write the editor makes into it -- what the speaker captions head + * that voice's lines with. Empty gives the default back. + */ +export { setSpeakerLabel } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; + /** Re-propose is the clip finder's proposal pass: POST /api/report/clips {project, mode: "propose"} (`umtool clips propose`, a job). */ export const reproposeAvailable = true; export const REPROPOSE_UNAVAILABLE = null; diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -25,6 +25,8 @@ export type EditorClip = { key: string | null; ruling: string | null; montage: boolean; + /** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */ + vertical: { crop: number[]; aspect?: number } | null; }; export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; @@ -45,6 +47,8 @@ export type EditorView = { rolesChangedAt: string | null; } | null; repropose: { available: boolean; why: string | null }; + /** The shorts on disk, by clip id (release 36). */ + shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>; }; export type Turn = { start: number; end: number; speaker: number }; diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs @@ -0,0 +1,187 @@ +// The look in umtool (release 36 lane C): updateRender (the Look panel's +// writer), a clip's `vertical` through updateClip and the clip editor's +// `vertical` / `label` operations, and the shorts on disk (readShorts, the +// replace guard, the job's step). Synthetic. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { LOOK_KEYS, MANIFEST_NAME, RenderRefused, StaleToken, lookOf, manifestToken, updateClip, updateRender } from "./manifest.mjs"; +import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs"; +import { readShorts, safeClipId, setShortAside, shortFile, shortSteps } from "./shorts.mjs"; + +const manifest = (render = {}) => ({ + schemaVersion: 1, + slug: "look", + provenance: { channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000" }, ...render }, + timeline: [ + { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q", assist: { by: "assistant", proposal: "p001", original: { start: 10, end: 20, cutStart: 11, cutEnd: 19 }, edits: [] } }, + { type: "clip", id: "r002", video: "v1", start: 30, end: 40 }, + ], +}); +const REACTIONS = { + version: 1, + source: { channel: "chan", video: "v1", duration: 80, words: null }, + params: {}, + speakers: [ + { index: 0, role: "host", label: "Host", how: "auto" }, + { index: 1, role: "subject", label: "Subject", how: "auto" }, + ], + turns: [], laughs: [], moments: [], proposals: [], +}; + +async function project(render = {}) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-look-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(render), null, 2) + "\n"); + await writeFile(path.join(dir, "reactions.json"), JSON.stringify(REACTIONS, null, 1) + "\n"); + return { id: "reports/look", dir, kind: "report" }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + +test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => { + const p = await project({ transition: 0.4, crf: 21 }); + try { + assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]); + const token = await manifestToken(p.dir); + const r = await updateRender(p.dir, { + headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", + loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } }, + }, { token }); + assert.deepEqual(r.look, { + headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", + loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } }, + }); + const m = await read(p.dir); + assert.equal(m.render.crf, 21, "the rest of the render is as it was"); + assert.equal(m.render.width, 1920); + assert.deepEqual(lookOf(m.render), r.look); + // A stale token is refused; nothing written. + await assert.rejects(updateRender(p.dir, { qr: true }, { token }), StaleToken); + // null removes; qr: true turns the code back on (removes the false). + const r2 = await updateRender(p.dir, { headerHeight: null, qr: true, loudness: null, transitionStyle: null }); + assert.equal("headerHeight" in r2.look, false); + assert.equal("qr" in r2.look, false); + assert.equal("loudness" in r2.look, false); + assert.equal("transitionStyle" in r2.look, false); + // Refusals: the build's own sentences, and nothing written. + const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"); + await assert.rejects(updateRender(p.dir, { chrome: { engine: "hyperframes" } }), (e) => e instanceof RenderRefused && /render\.chrome is the deck's/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { crf: 18 }), (e) => e instanceof RenderRefused && /render\.crf is not a look setting/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { loudness: { target: -40 } }), (e) => e instanceof RenderRefused && /target must be a number from -30 to -8/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { captions: { style: "karaoke" } }), (e) => e instanceof RenderRefused && /captions\.style/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { transitionStyle: "spin" }), (e) => e instanceof RenderRefused); + await assert.rejects(updateRender(p.dir, { headerHeight: 12.5 }), (e) => e instanceof RenderRefused && /whole number of pixels/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { transition: 9 }), (e) => e instanceof RenderRefused && /from 0 \(a hard cut\) to 3/.test(e.errors[0])); + await assert.rejects(updateRender(p.dir, { qr: "yes" }), (e) => e instanceof RenderRefused); + assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("updateRender: captions beside the deck are refused (the deck draws its own words)", async () => { + const p = await project({ chrome: { engine: "hyperframes", layout: "deck" } }); + try { + await assert.rejects(updateRender(p.dir, { captions: { style: "speakers" } }), (e) => e instanceof RenderRefused && /does not combine with render\.chrome/.test(e.errors.join(" "))); + // Loudness is fine under a deck. + const r = await updateRender(p.dir, { loudness: { target: -14 } }); + assert.deepEqual(r.look.loudness, { target: -14 }); + assert.deepEqual((await read(p.dir)).render.chrome, { engine: "hyperframes", layout: "deck" }, "never touches render.chrome"); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("updateClip: a clip's vertical crop, checked, rounded, removable; the assistant's clip stays the assistant's", async () => { + const p = await project(); + try { + await updateClip(p.dir, "r001", { vertical: { crop: [0.123456, 0, 0.316406, 1], aspect: 16 / 9 } }); + let e = (await read(p.dir)).timeline[0]; + assert.deepEqual(e.vertical, { crop: [0.1235, 0, 0.3164, 1], aspect: 1.7778 }); + assert.equal(e.assist.by, "assistant"); + assert.deepEqual(e.assist.edits, []); + await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0, 0, 0.6, 1] } }), /must be 9:16 on the source/); + await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0.9, 0, 0.3164, 1] } }), /inside the picture/); + await updateClip(p.dir, "r001", { vertical: null }); + e = (await read(p.dir)).timeline[0]; + assert.equal(e.vertical, undefined); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("the clip editor: vertical and label operations; the view carries the crop and the shorts", async () => { + const p = await project(); + try { + let view = await clipEditorView(p); + assert.equal(view.clips[0].vertical, null); + assert.deepEqual(view.shorts, {}); + const r = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: [0.5, 0, 0.3164, 1], aspect: 1.7778, token: view.token }); + assert.deepEqual(r.view.clips[0].vertical, { crop: [0.5, 0, 0.3164, 1], aspect: 1.7778 }); + const r2 = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: null, token: r.view.token }); + assert.equal(r2.view.clips[0].vertical, null); + // A speaker's name: the captions' label. + const l = await runClipEditorOp(p, { op: "label", speaker: 0, label: " Nik " }); + assert.equal(l.result.speaker.label, "Nik"); + assert.equal(l.result.speaker.role, "host"); + const doc = JSON.parse(await readFile(path.join(p.dir, "reactions.json"), "utf8")); + assert.equal(doc.speakers[0].label, "Nik"); + assert.equal(doc.speakers[1].label, "Subject", "only that speaker"); + // Empty: the default again. + const back = await runClipEditorOp(p, { op: "label", speaker: 0, label: null }); + assert.equal(back.result.speaker.label, "Host"); + await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: "x".repeat(41) }), /up to 40 characters/); + await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 9, label: "x" }), /no speaker 9/); + await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: 3 }), /label is a text/); + // A short on disk shows in the view; stale once the clip moves. + await mkdir(path.join(p.dir, "shorts"), { recursive: true }); + await writeFile(path.join(p.dir, "shorts", "r001.mp4"), "mp4"); + await writeFile(path.join(p.dir, "shorts", "r001.json"), JSON.stringify({ version: 1, clip: "r001", requested: { cutStart: 11, cutEnd: 19 }, crop: null })); + view = await clipEditorView(p); + assert.equal(view.shorts.r001.stale, false); + await updateClip(p.dir, "r001", { cutStart: 12 }); + view = await clipEditorView(p); + assert.equal(view.shorts.r001.stale, true); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("shorts: listed newest first, a set-aside one kept and not listed, the replace guard, the job's one step", async () => { + const p = await project(); + try { + assert.deepEqual(await readShorts(p.dir), []); + await mkdir(path.join(p.dir, "shorts"), { recursive: true }); + await writeFile(path.join(p.dir, "shorts", "r002.mp4"), "two"); + await writeFile(path.join(p.dir, "shorts", "gone1.mp4"), "old"); + await writeFile(path.join(p.dir, "shorts", "r002.20260101-1200.mp4"), "aside"); + const m = await read(p.dir); + const list = await readShorts(p.dir, m); + assert.deepEqual(list.map((x) => x.clip).sort(), ["gone1", "r002"]); + assert.equal(list.find((x) => x.clip === "gone1").gone, true); + assert.equal(list.find((x) => x.clip === "r002").gone, false); + // The guard: there is one, so it is refused unless replace. + await assert.rejects(setShortAside(p.dir, "r002"), (e) => e.needsReplace === true); + const aside = await setShortAside(p.dir, "r002", { replace: true, now: new Date(2026, 9, 19, 9, 5) }); + assert.equal(path.basename(aside), "r002.20261019-0905.mp4"); + assert.equal(await stat(path.join(p.dir, "shorts", "r002.mp4")).catch(() => null), null); + assert.equal(await setShortAside(p.dir, "r001"), null, "nothing there: nothing to set aside"); + // Names only. + assert.equal(shortFile(p.dir, "../x"), null); + assert.equal(safeClipId("r001-2"), true); + assert.equal(safeClipId("a/b"), false); + const [step] = shortSteps(p, "r001"); + assert.deepEqual(step.argv.slice(-4), ["--short", "r001", "--progress", "ndjson"]); + assert.ok(step.argv[1].endsWith(path.join("report-to-video", "build-video.mjs"))); + assert.equal(step.argv[2], path.join(p.dir, "video.manifest.json")); + assert.equal(step.ndjson, true); + assert.throws(() => shortSteps(p, "../etc"), /not a clip id/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -33,6 +33,8 @@ import { isCalendarDate } from "umtool-report-to-video/attribution"; import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck"; import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs"; import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; +import { validateLook, verticalErrors } from "umtool-report-to-video/look"; +import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; import { validateNarration } from "umtool-report-to-video/narration"; @@ -380,6 +382,23 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri // and a row saved from the On-screen table cannot store different shapes. if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen); + // ---- the vertical short's framing (release 36 lane C) -------------------- + // + // `vertical: {crop: [x, y, w, h], aspect?}` -- fractions of the source + // picture, 9:16 on it (look.mjs verticalErrors, the build's own check). + // null or "" removes it: the short is cut from the centre again. + if (patch.vertical !== undefined) { + const v = patch.vertical; + if (v === null || v === "") delete entry.vertical; + else { + const errors = verticalErrors(v, "vertical"); + if (errors.length) throw new Error(errors.join("; ")); + const r4 = (n) => Number(Number(n).toFixed(4)); + const vv = /** @type {{ crop: number[], aspect?: number }} */ (v); + entry.vertical = { crop: vv.crop.map(r4), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}) }; + } + } + // ---- an assistant's clip, edited by a person (release 35 C2) ------------- // // A clip the clip finder proposed carries `assist`. The first human edit @@ -893,6 +912,100 @@ export class ChromeRefused extends Error { // --------------------------------------------------------------------------- +// THE LOOK (release 36 lane C): the render keys a person sets for a cut that +// has no deck -- the header and footer heights, the QR, the crossfade's length +// and style, the loudness target, the speaker captions. Never `render.chrome` +// (updateChrome is its writer). Token-guarded, validated with the build's own +// checks against the render as it will be, then written atomically. +// --------------------------------------------------------------------------- + +/** The render keys the Look panel writes, in its order. */ +export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]); + +/** The look keys of a render block as written (absent keys left out). */ +export function lookOf(render) { + const r = isObj(render) ? render : {}; + /** @type {Record<string, unknown>} */ + const out = {}; + for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k]; + return out; +} + +/** The build's sentences for a refused look, thrown whole so a route can return each one. */ +export class RenderRefused extends Error { + /** @param {string[]} errors */ + constructor(errors) { + super(`render: ${errors.join("; ")}`); + this.name = "RenderRefused"; + this.errors = errors; + } +} + +const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi; + +/** + * Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the + * key (the build's default again). `qr: true` turns the code back on (removes + * a `false`; an object of settings is kept), `qr: false` turns it off. + * + * @param {string} dir + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ look: Record<string, unknown>, token: string | null }>} + */ +export async function updateRender(dir, patch, { token = null } = {}) { + if (!isObj(patch)) throw new RenderRefused(["the patch must be an object of render keys"]); + const errors = []; + for (const k of Object.keys(patch)) { + if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here"); + else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`); + } + if (errors.length) throw new RenderRefused(errors); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const render = { ...(isObj(manifest.render) ? manifest.render : {}) }; + for (const [k, v] of Object.entries(patch)) { + if (v === null) { + delete render[k]; + continue; + } + switch (k) { + case "headerHeight": + case "footerHeight": + if (!intIn(v, 0, 240)) errors.push(`render.${k} must be a whole number of pixels from 0 to 240`); + else render[k] = v; + break; + case "qr": + if (v === false) render.qr = false; + else if (v === true) { + if (render.qr === false) delete render.qr; + } else errors.push("render.qr must be true (on) or false (off)"); + break; + case "transition": + if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 3) errors.push("render.transition must be a number of seconds from 0 (a hard cut) to 3"); + else render.transition = round2(v); + break; + case "transitionStyle": + if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`); + else render.transitionStyle = v; + break; + default: + // loudness, captions: stored as given; the build's validators below say what is wrong. + render[k] = v; + } + } + const next = { ...manifest, render }; + errors.push(...validateTransitionStyle(next), ...validateLook(next)); + if (errors.length) throw new RenderRefused(errors); + manifest.render = render; + const nextToken = await writeManifestAtomic(dir, manifest); + return { look: lookOf(render), token: nextToken }; + }); +} + +// --------------------------------------------------------------------------- // POSTS: the two things a person decides about a post once an agent has put it // in the manifest -- which clip it rides on, and whether it is shown at all. // diff --git a/umtool/lib/report/shorts.mjs b/umtool/lib/report/shorts.mjs @@ -0,0 +1,119 @@ +// VERTICAL SHORTS (release 36 lane C): one clip of a report video as a +// 1080x1920 file, `<project>/shorts/<clipId>.mp4`, made by build-video.mjs +// `--short <clipId>` (report-to-video/look.mjs shortRender: the clip's +// `vertical.crop`, large speaker captions, no header or QR, the loudness +// target) as a job through lib/jobs.ts, which build-video's CLI runs inside +// the machine's heavy slot. A record beside each (`<clipId>.json`) says what +// it was made from, so the list can say when the clip has moved since. +import { readFile, readdir, rename, stat } from "node:fs/promises"; +import path from "node:path"; +import { PIPELINE_DIR } from "./driver.mjs"; + +export const SHORTS_DIR = "shorts"; +/** A short of a clip is minutes at most; a stuck encode is not left forever. */ +export const SHORT_TIMEOUT_MS = 20 * 60_000; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +/** A clip id as a file name: letters, digits, `.`, `_`, `-` only. */ +export const safeClipId = (id) => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(id) && !id.includes(".."); + +export const shortsDirOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SHORTS_DIR); + +/** `<project>/shorts/<clipId>.mp4`, or null for an id that is not a file name. */ +export function shortFile(dir, clipId) { + return safeClipId(clipId) ? path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clipId}.mp4`) : null; +} + +/** + * The job's one step: build-video `--short`, NDJSON progress, beside the + * build's own steps (lib/report/driver.mjs). No path or argv from a client. + * + * @param {{ dir: string }} project + * @param {string} clipId + */ +export function shortSteps(project, clipId) { + if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`); + return [ + { + cwd: PIPELINE_DIR, + env: {}, + label: `make the short of ${clipId} (1080×1920)`, + argv: [ + "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), + path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), + "--out", path.join(/* turbopackIgnore: true */ project.dir, "out"), + "--short", clipId, "--progress", "ndjson", + ], + ndjson: true, + timeoutMs: SHORT_TIMEOUT_MS, + }, + ]; +} + +const sameNums = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < 0.011); + +/** + * Every short on disk, newest first: `{ clip, size, mtimeMs, record, stale, + * gone }`. `stale`: the clip's cut or crop moved since the short was made; + * `gone`: no clip has that id now. + * + * @param {string} dir the project + * @param {any} [manifest] the manifest as read (for stale / gone) + */ +export async function readShorts(dir, manifest = null) { + const names = await readdir(shortsDirOf(dir)).catch(() => []); + const clips = new Map((manifest?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e])); + const out = []; + for (const name of names) { + // A short set aside (`<id>.<stamp>.mp4`) is kept, not listed. + if (!name.endsWith(".mp4") || /\.\d{8}-\d{4}\.mp4$/.test(name)) continue; + const clip = name.slice(0, -4); + if (!safeClipId(clip)) continue; + const st = await stat(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), name)).catch(() => null); + if (!st?.isFile()) continue; + const record = await readFile(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clip}.json`), "utf8").then(JSON.parse, () => null); + const e = clips.get(clip) ?? null; + let stale = false; + if (e && isObj(record)) { + const want = [e.cutStart ?? e.start, e.cutEnd ?? e.end]; + const had = isObj(record.requested) ? [record.requested.cutStart, record.requested.cutEnd] : null; + const crop = Array.isArray(e.vertical?.crop) ? e.vertical.crop : null; + stale = (had !== null && had.every(fin) && !sameNums(want, had)) || JSON.stringify(crop) !== JSON.stringify(record.crop ?? null); + } + out.push({ clip, size: st.size, mtimeMs: Math.round(st.mtimeMs), record: isObj(record) ? record : null, stale, gone: manifest ? !e : false }); + } + return out.sort((a, b) => b.mtimeMs - a.mtimeMs); +} + +/** `20260817-1408`: a short set aside before it is made again. */ +function stamp(d = new Date()) { + const p = (n) => String(n).padStart(2, "0"); + return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`; +} + +/** + * The replace guard: a short that is there is never overwritten unasked. + * With `replace`, it is moved aside to `shorts/<clipId>.<stamp>.mp4` (its + * record too) and the path it went to is returned; without, an error naming + * `replace`. No short there: null. + * + * @param {string} dir + * @param {string} clipId + * @param {{ replace?: boolean, now?: Date }} [o] + */ +export async function setShortAside(dir, clipId, { replace = false, now = new Date() } = {}) { + const file = shortFile(dir, clipId); + if (!file) throw new Error(`not a clip id: ${clipId}`); + const st = await stat(file).catch(() => null); + if (!st) return null; + if (!replace) { + const err = new Error(`${clipId} has a short already — make it again to set that one aside (replace)`); + /** @type {any} */ (err).needsReplace = true; + throw err; + } + const aside = file.replace(/\.mp4$/, `.${stamp(now)}.mp4`); + await rename(file, aside); + await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {}); + return aside; +}