// `umtool shorts` (lane clip-kit, slice A): every listed clip of a take, in every listed format, into the project's // `shorts-/`, through the ONE builder behind `umtool vertical` (verticalCli.mjs buildShort). The rules -- the // names, the formats, the snapshot -- are lib/report/shortsBatch.mjs's. // // umtool shorts --take (--items a,b | --all | --again) [--formats vertical,landscape] // [--clip full|framed|quote] [--hook title|section|""] [--captions l|xl] [--lines 1|2] // [--loudness -14] [--max-vertical 180] [--max-landscape 140] [--deck stacked|bare] // [--replace] [--dry-run] [--json] // // One command, one record: each build takes the heavy slot as `umtool vertical` does (another job may run between // two clips); a clip that fails is recorded with its error, the rest go on, and the command exits 1 at the end. import { existsSync } from "node:fs"; import { readFile, rename } from "node:fs/promises"; import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { deliverableDir } from "./storage.mjs"; import { BATCH_FILE, BATCH_FORMATS, FORMAT_NAMES, againOf, asideName, assignNames, batchDirName, batchItems, knobsForFormat, parseFormats, rowAfter, safeName, snapshotOf } from "./shortsBatch.mjs"; import { CliError, buildShort, isRefusal, knobsOfFlags, promoOptionsOf, takeManifestOf } from "./verticalCli.mjs"; export const SHORTS_USAGE = [ "usage: umtool shorts --take (--items ,… | --all | --again) [--formats vertical,desktop,landscape]", " [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]", " [--hook title|section|\"\"] [--captions l|xl] [--lines 1|2]", " [--loudness -14] [--max-vertical 180] [--max-desktop 140] [--max-landscape 140]", " [--deck stacked|bare] [--qr on|off] [--qr-corner tr|tl|br|bl] [--no-promo]", " [--promo-lead 4.5] [--promo-fade 0.7] [--promo-hold 1.5] [--no-cold-open] [--replace] [--dry-run] [--json]", "", "A batch of shorts: each clip (--items, or --all of the take's) in each format -- vertical (1080x1920, the", "`umtool vertical` layouts and flags), desktop (1920x1080, minimal chrome: `umtool vertical --desktop`) and", "landscape (the take's own 16:9 look) -- into the project's", "shorts-/ as ..mp4, each with its record, and batch.json. A clip's name is its own `name`, else", "its title's slug, else its id; one another clip holds already gets -; once given, it is kept. A file", "there is not replaced unless --replace (the old one set aside as ...mp4). --again builds the", "folder's batch.json again: its clips, formats and knobs, each clip framed as the record saw it. Over its length", "(--max-vertical 180 s, --max-desktop and --max-landscape 140 s) a short is said so: a note, never a refusal. Each build runs in the", "heavy slot, as `umtool vertical`'s does; a clip that fails is recorded and the rest go on (exit 1 at the end).", "When the take sets a channel promo (render.promo), each vertical and desktop clip ends on its card (--no-promo: not).", ].join("\n"); const VALUED = new Set(["--take", "--items", "--formats", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max-vertical", "--max-landscape", "--max-desktop", "--deck", "--qr", "--qr-corner", "--promo-lead", "--promo-fade", "--promo-hold"]); const BOOL = new Set(["--all", "--again", "--replace", "--dry-run", "--json", "--help", "--no-promo", "--no-cold-open"]); function parse(args) { /** @type {Record} */ const flags = {}; const positional = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a.startsWith("--")) { if (VALUED.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); flags[a] = args[++i]; } else if (BOOL.has(a)) flags[a] = ""; else throw new CliError(`unknown flag ${a}`); } else positional.push(a); } return { flags, positional, has: (n) => n in flags }; } const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); /** Write a file through a rename (a reader never sees half of it). */ const writeJson = (file, doc) => writeFileAtomic(file, JSON.stringify(doc, null, 2) + "\n", "utf8"); /** * `umtool shorts …` * @param {string[]} args everything after `shorts` * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, build?: typeof buildShort }} [opts] * `build` the builder (tests stand one in). * @returns {Promise} */ export async function shortsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, build = buildShort } = {}) { try { const p = parse(args); if (p.has("--help") || !p.positional.length) { log(SHORTS_USAGE); return p.has("--help") ? 0 : 2; } const json = p.has("--json"); const say = json ? err : log; const take = p.flags["--take"] ?? null; if (!take) throw new CliError("--take : the take whose clips the shorts are cut from"); if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); const r = await resolveProject(p.positional[0], reportsRoot); if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`); if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); const dir = r.project.dir; const folder = path.join(dir, batchDirName(take)); const prior = await readJson(path.join(folder, BATCH_FILE)); // What is asked: the flags, or (--again) the folder's record -- each clip with its own formats, knobs and snapshot. /** @type {Array<{ id: string, formats: string[], knobs: Record, snapshot: Record | null }> | null} */ let again = null; const replace = p.has("--replace") || p.has("--again"); if (p.has("--again")) { if (!prior) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} is not there — make the batch first`); try { again = againOf(prior); } catch (e) { throw new CliError(`--again: ${e instanceof Error ? e.message : e}`); } if (!again.length) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} names no clip with a file`); } let formats; try { formats = parseFormats(p.flags["--formats"] ?? "vertical"); } catch (e) { throw new CliError(e instanceof Error ? e.message : String(e)); } // The channel promo's flags ride in the knobs a row records (`promo`: false, or its timing). const po = promoOptionsOf(p.flags); const knobs = { ...knobsOfFlags(p.flags), ...(po.promo === false ? { promo: false } : po.promoKnobs ? { promo: po.promoKnobs } : {}), ...(p.has("--no-cold-open") ? { coldOpen: false } : {}) }; const takeManifest = await takeManifestOf(dir, take); let entries; try { entries = batchItems(takeManifest.timeline ?? [], { items: again ? again.map((c) => c.id) : p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null, all: p.has("--all") }); } catch (e) { throw new CliError(e instanceof Error ? e.message : String(e)); } const projectManifest = await readJson(path.join(dir, "video.manifest.json")); const projectById = new Map((projectManifest?.timeline ?? []).filter((e) => typeof e?.id === "string").map((e) => [e.id, e])); const priorRows = new Map((Array.isArray(prior?.clips) ? prior.clips : []).filter((c) => isObj(c) && typeof c.id === "string").map((c) => [c.id, c])); // A name read back is kept only when it is a plain file name of this folder (a record edited by hand is not trusted). const priorNames = Object.fromEntries([...priorRows.values()].filter((c) => safeName(c.name)).map((c) => [c.id, c.name])); // A clip's name reads its PROJECT entry (a pinned `name`, a title set after the take), over the take's. const names = assignNames(entries.map((e) => ({ ...e, ...(projectById.get(e.id) ?? {}) })), priorNames); const caps = { vertical: p.flags["--max-vertical"] !== undefined ? Number(p.flags["--max-vertical"]) : BATCH_FORMATS.vertical.maxSeconds, landscape: p.flags["--max-landscape"] !== undefined ? Number(p.flags["--max-landscape"]) : BATCH_FORMATS.landscape.maxSeconds, desktop: p.flags["--max-desktop"] !== undefined ? Number(p.flags["--max-desktop"]) : BATCH_FORMATS.desktop.maxSeconds, }; for (const [f, n] of Object.entries(caps)) if (!(Number.isFinite(n) && n >= 5 && n <= 600)) throw new CliError(`--max-${f} is 5 to 600 seconds`); const { PROJECT_KEYS } = await import("umtool-report-to-video/vertical-plan"); const againById = new Map((again ?? []).map((c) => [c.id, c])); const plan = entries.map((e) => { const ag = againById.get(e.id) ?? null; const fs = ag ? ag.formats : formats; return { id: e.id, name: names[e.id], title: projectById.get(e.id)?.title ?? e.title ?? null, knobs: ag ? ag.knobs : knobs, snapshot: ag?.snapshot ?? snapshotOf(projectById.get(e.id) ?? e, PROJECT_KEYS), look: ag?.look ?? null, files: Object.fromEntries(fs.map((f) => [f, `${names[e.id]}.${f}.mp4`])), }; }); if (p.has("--dry-run")) { const out = { project: r.project.id, take, folder, clips: plan.map((c) => ({ id: c.id, name: c.name, title: c.title, knobs: c.knobs, files: c.files, exists: Object.values(c.files).filter((f) => existsSync(path.join(folder, f))) })) }; log(json ? JSON.stringify(out, null, 2) : [`would write into ${folder}`, ...out.clips.map((c) => ` ${c.id} ${Object.values(c.files).join(" ")}${c.exists.length ? ` (there: ${c.exists.join(", ")}${replace ? ", set aside" : " — --replace to make again"})` : ""}`)].join("\n")); return 0; } const outDir = await deliverableDir(dir, batchDirName(take)); const started = Date.now(); const record = { version: 1, kind: "shorts-batch", project: r.project.id, take, // The last run: what it was asked. Each clip's row says what IT was last built with. last: { argv: ["shorts", r.project.id, "--take", take, ...(again ? ["--again"] : ["--items", entries.map((e) => e.id).join(","), "--formats", formats.join(",")])], caps, madeAt: new Date().toISOString(), buildSeconds: 0 }, clips: /** @type {any[]} */ ([...priorRows.values()]), }; const put = (row) => { const i = record.clips.findIndex((x) => x.id === row.id); if (i >= 0) record.clips[i] = row; else record.clips.push(row); }; let failed = 0; for (const c of plan) { for (const f of Object.keys(c.files)) { const file = path.join(outDir, c.files[f]); const base = { id: c.id, name: c.name, title: c.title, format: f, knobs: c.knobs, snapshot: c.snapshot }; let row; let aside = null; try { if (existsSync(file)) { if (!replace) throw new CliError(`${c.files[f]} is there — --replace to make it again (the old one set aside)`); aside = asideName(file); await rename(file, aside); await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {}); } say(`shorts: ${c.id} (${c.name}) ${f} …`); const { promo: promoKnob, coldOpen: coldKnob, ...rest } = c.knobs ?? {}; const fk = knobsForFormat(rest, f); const done = await build( { project: r.project.id, take, items: [c.id], knobs: { ...fk.knobs, maxSeconds: caps[f] }, name: "shorts", out: file, landscape: BATCH_FORMATS[f].landscape, desktop: BATCH_FORMATS[f].desktop, overrides: { [c.id]: c.snapshot }, ...(promoKnob === false ? { promo: false } : promoKnob && typeof promoKnob === "object" ? { promoKnobs: promoKnob } : {}), ...(coldKnob === false ? { coldOpen: false } : {}), ...(c.look ? { look: c.look } : {}), }, { reportsRoot, say }, ); const rec = "record" in done ? done.record : null; row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, file: c.files[f], seconds: rec?.seconds ?? null, notes: [...(fk.note ? [fk.note] : []), ...(rec?.notes ?? [])], look: rec?.look ?? null }); } catch (e) { if (!(e instanceof Error)) throw e; // A rebuild that failed puts the old file back where it was (and its record). if (aside && !existsSync(file) && existsSync(aside)) { await rename(aside, file).catch(() => {}); await rename(aside.replace(/\.mp4$/, ".json"), file.replace(/\.mp4$/, ".json")).catch(() => {}); } failed += 1; err(`shorts: ${c.id} ${f}: ${e.message}`); row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, error: e.message, exists: existsSync(file) }); } put(row); record.last.buildSeconds = Math.round((Date.now() - started) / 1000); await writeJson(path.join(outDir, BATCH_FILE), record); } } if (json) log(JSON.stringify(record, null, 2)); else { for (const c of record.clips.filter((x) => entries.some((e) => e.id === x.id))) { for (const [f, ns] of Object.entries(c.notes ?? {})) for (const n of ns) log(`note: ${c.id} ${f}: ${n}`); log(`${c.id} ${Object.values(c.files).join(" ") || "(nothing made)"}`); } log(`wrote ${path.join(outDir, BATCH_FILE)}${failed ? ` — ${failed} failed` : ""}`); } return failed ? 1 : 0; } catch (e) { if (isRefusal(e)) { err(`umtool shorts: ${e.message}`); return 2; } throw e; } } export { FORMAT_NAMES };