Archilyzer · Source

archilyzer

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

commit c8c9fe13e8c060803c830b824fb8c1229bbc280b
parent 5663717e438bd0ea7b8fd2e8b2daa629d5d22436
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 14:33:21 -0500

umtool: quick clip -- umtool clip <ch>/<vid>@<s>-<e>, POST /api/report/quick-clip, umtool share

One moment to a shareable mp4: a basic-mode project (the umtool new path, the one clip
its timeline, render.mode written by the look's writer) under quick-clips/, its window
asked of the editor (the fetch-windows batch followed to its end; Rumble fetched
whole, the editor decides), --snap words its edges snapped to the words heard there
(the editor's transcribe op, quote-check's call: the first word mostly after the
start, the last mostly before the end, a breath either side, never into a neighbour),
rendered as the take `clip` (the heavy slot, its record, the take panel), then the
output and the share line. --json {project, output, share}; --progress ndjson for the
app's job (POST /api/report/quick-clip, one job on the runner, GET ?job for the result).
umtool share <p> [<clip>] [--take] [--site] is the share line's CLI twin.

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

Diffstat:
Aumtool/app/api/report/quick-clip/route.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/share-line/route.ts | 31+++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 9+++++++++
Mumtool/lib/report/modulesCli.test.mjs | 2+-
Aumtool/lib/report/quickClip.mjs | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/quickClip.test.mjs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/shareLineCli.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 585 insertions(+), 1 deletion(-)

diff --git a/umtool/app/api/report/quick-clip/route.ts b/umtool/app/api/report/quick-clip/route.ts @@ -0,0 +1,60 @@ +import path from "node:path"; +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { refuseCaller } from "@/lib/report/caller"; +import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; +import { parseClipSpec } from "@/lib/report/clipEditorModel.mjs"; + +export const dynamic = "force-dynamic"; + +// QUICK CLIP (lane output-modes; umtool/docs/knobs.md, "Quick clip"): one +// moment of one recording to a basic-mode mp4 and its share line -- +// `umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>]` +// (lib/report/quickClip.mjs) as ONE job on the app's runner (lib/jobs.ts: one +// at a time, a log, Stop). The command asks the editor for the window, snaps +// the edges to the words when asked, and renders through the take maker (the +// heavy slot); its last NDJSON event is `quick-clip` {project, output, share}. +// +// POST { spec: "<channel>/<video>@<start>-<end>", snap?: "words", title?, site? } -> 202 { job } +// | 400 a spec that is not one | 409 another job is running +// GET ?job=<id> -> { job, done?: { project, output, share: { platform, archive, text }, snapped? }, error? } +const headers = { "cache-control": "no-store" }; +const SITE_RE = /^[a-z0-9][a-z0-9._-]*$/i; + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/quick-clip"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers }); + const spec = String(body.spec ?? "").trim(); + const parsed = parseClipSpec(spec); + if (!parsed || !(parsed.end > parsed.start)) { + return Response.json({ error: "spec is <channel>/<video>@<start>-<end> in seconds, the end after the start" }, { status: 400, headers }); + } + const snap = body.snap === undefined || body.snap === null || body.snap === "" ? null : String(body.snap); + if (snap !== null && snap !== "words") return Response.json({ error: "snap is words, or nothing" }, { status: 400, headers }); + const title = typeof body.title === "string" && body.title.trim() ? body.title.trim().slice(0, 120) : null; + const site = typeof body.site === "string" && body.site.trim() ? body.site.trim() : null; + if (site && !SITE_RE.test(site)) return Response.json({ error: "site is a site's id (transcripts/sites/<id>)" }, { status: 400, headers }); + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind}) — make the clip when it is done`, running: jobView(running) }, { status: 409, headers }); + const argv = [ + process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", spec, + ...(snap ? ["--snap", snap] : []), ...(title ? ["--title", title] : []), ...(site ? ["--site", site] : []), "--progress", "ndjson", + ]; + const job = startJob(`quick clip ${spec}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quick clip ${spec}${snap ? " (snapped to the words)" : ""}`, argv, ndjson: true, timeoutMs: 90 * 60_000 }]); + return Response.json({ ok: true, job: jobView(job) }, { status: 202, headers }); +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const id = url.searchParams.get("job"); + const job = id ? getJob(id) : null; + if (!job) return Response.json({ error: "no such job" }, { status: 404, headers }); + const view = jobView(job, Math.max(0, job.log.length - 12)); + const ev = [...job.events].reverse().find((e) => e.ev === "quick-clip" || e.ev === "quick-clip-failed") as Record<string, unknown> | undefined; + if (ev?.ev === "quick-clip") { + return Response.json({ job: view, done: { project: ev.project, output: ev.output, share: ev.share, ...(ev.snapped ? { snapped: ev.snapped } : {}) } }, { headers }); + } + const error = ev?.ev === "quick-clip-failed" ? String(ev.error ?? "the quick clip failed") : job.state === "failed" ? (job.error ?? "the quick clip failed") : null; + return Response.json({ job: view, ...(error ? { error } : {}) }, { headers }); +} diff --git a/umtool/app/api/report/share-line/route.ts b/umtool/app/api/report/share-line/route.ts @@ -0,0 +1,31 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { projectShareLine } from "@/lib/report/shareLine.mjs"; + +export const dynamic = "force-dynamic"; + +// A CLIP'S SHARE LINE (lane output-modes): what the take panel's and Play's +// **Copy share line** copy -- the platform's page at the first second the clip +// plays and its moment on the archive (lib/report/shareLine.mjs; a Rumble +// folder id as the embed id the archive serves). `umtool share <p> [<clip>] +// [--take <t>]` is its twin. +// +// GET ?project=<id>[&clip=<id>][&take=<id>] -> { clip, seconds, platform, archive, text } +const headers = { "cache-control": "no-store" }; +const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "a share line is a report video's clip's" }, { status: 400, headers }); + const clip = url.searchParams.get("clip") || null; + const take = url.searchParams.get("take") || null; + if ((clip && !ID_RE.test(clip)) || (take && !ID_RE.test(take))) return Response.json({ error: "clip and take are ids" }, { status: 400, headers }); + try { + const line = await projectShareLine(project, { clip, take }); + return Response.json(line, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404, headers }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -1080,6 +1080,11 @@ function usage() { " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", " umtool refresh --check [<article>] [--force] [--json] the daily suggestion check, now", + " umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--json]", + " QUICK CLIP: a basic-mode project (the footage alone), its window asked of the editor, its", + " edges snapped to the words (--snap words), rendered as a take; prints the mp4 and its share line", + " umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform", + " page at the moment and its archive moment (a Rumble folder id mapped to the embed id)", " umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title", " umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--section N]", " [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S]", @@ -1193,6 +1198,10 @@ const COMMANDS = { trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // A vertical short (1080x1920) of a take's items, natively or reframed: lib/report/verticalCli.mjs. vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))), + // Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs. + clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))), + // A clip's share line (lane output-modes): lib/report/shareLineCli.mjs. + share: async () => process.exit(await (await import("../lib/report/shareLineCli.mjs")).shareCommand(argv.slice(argv.indexOf("share") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), // The cast: characters' voices across projects, auditions, a project's voices (operator, 6 Nov): lib/report/castCli.mjs. diff --git a/umtool/lib/report/modulesCli.test.mjs b/umtool/lib/report/modulesCli.test.mjs @@ -85,7 +85,7 @@ test("modules list and preset list", async () => { for (const id of ["pair", "chapter", "status", "finale", "intro"]) assert.ok(ids.includes(id), id); const t = sink(); assert.equal(await presetCommand(["list", "--json"], t), 0); - assert.deepEqual(JSON.parse(t.lines[0]).map((p) => p.name).sort(), ["archive-catalog", "ember-deck", "huck-deck", "plain-deck"]); + assert.deepEqual(JSON.parse(t.lines[0]).map((p) => p.name).sort(), ["archive-catalog", "basic", "ember-deck", "huck-deck", "plain-deck"]); }); test("umtool look takes the story modules' keys, through updateChrome", async () => { diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs @@ -0,0 +1,296 @@ +// QUICK CLIP (lane output-modes): one moment of one recording to a shareable +// mp4 and a share line, in one command -- +// +// umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson] +// +// what was done by hand on 8 Nov (occo-remarks' raw-render.mjs), as a fixed +// verb over the app's own pieces: +// +// 1. a BASIC-mode project (the `umtool new` path, scaffoldReportVideo with the +// one clip as its timeline; render.mode "basic" written by the look's +// writer), its slug from --title, else `<channel>-<video>-<start>`, under +// `<reports>/<folder>/` (default quick-clips); +// 2. its window ASKED OF THE EDITOR (fetchWindows.mjs: the fetch-windows +// batch, followed to its end; a Rumble recording is fetched whole -- the +// editor decides), never fetched here; +// 3. with `--snap words`, its edges snapped to the words heard there: the +// editor's transcribe op (`{path, start, end, words: true}`, quote-check's +// call) over the window, the first word that mostly plays after the start +// and the last that mostly plays before the end, 0.15 s of breath before +// and 0.3 s after (quoteCheck.mjs ALIGN_LEAD_S / ALIGN_TAIL_S), never into +// a neighbouring word -- written as the clip's cut; +// 4. rendered as a TAKE (`umtool take <p> --id clip --full`: the heavy slot, +// its render record, the take panel), the basic renderer's spans; +// 5. the output's path and its SHARE LINE (shareLine.mjs) printed; `--json` +// prints `{project, output, share: {platform, archive, text}}`. +// +// `--site <id>`: the archive the share line links (transcripts/sites/<id>/ +// site.json `siteUrl`); without it, the first public site that carries the +// channel, else none (the platform's page alone). +// +// The app's `POST /api/report/quick-clip` runs exactly this command as one job. +// Plain ESM: the CLI runs it under bare node. +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { resolveLocalSource } from "umtool-report-to-video/sources"; +import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; +import { parseClipSpec } from "./clipEditorModel.mjs"; +import { ALIGN_LEAD_S, ALIGN_TAIL_S } from "./quoteCheck.mjs"; +import { siteVideoFor, shareLineText, projectShareLine } from "./shareLine.mjs"; + +export const QUICK_CLIP_USAGE = [ + "usage: umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]", + " one moment to a shareable mp4: a basic-mode project (the footage alone, no deck), its window asked of the", + " editor (a Rumble recording fetched whole), --snap words: its edges snapped to the words heard there (the", + " editor's transcribe op), rendered as a take (umtool take <p> --id clip --full, the heavy slot), then the", + " output's path and the SHARE LINE: the platform's page at the moment, and its moment on the archive.", + " --title names the project (else <channel>-<video>-<start>); --folder (default quick-clips); --site <id> the", + " archive linked (else the first public site that carries the channel). --json: {project, output, share}.", + " The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).", +].join("\n"); + +export const QUICK_CLIP_FOLDER = "quick-clips"; +export const QUICK_CLIP_TAKE = "clip"; +/** Seconds either side of the asked edges that are transcribed for --snap words. */ +export const SNAP_PAD_S = 2; +/** How often the editor's fetch jobs are asked how they are (UMTOOL_FETCH_POLL_MS, as `umtool fetch --wait`). */ +const POLL_MS = Number(process.env.UMTOOL_FETCH_POLL_MS) > 0 ? Number(process.env.UMTOOL_FETCH_POLL_MS) : 5000; + +class CliError extends Error {} +const r2 = (x) => Math.round(Number(x) * 100) / 100; +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** A project slug from words: lower-case letters, digits and dashes, at most 48, never `share-…` (a deliverables link's name). */ +export function quickClipSlug({ title = null, channel, video, start }) { + const clean = (words) => String(words).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, ""); + let slug = clean(title ?? "") || clean(`${channel}-${video}-${Math.floor(Number(start) || 0)}`) || "clip"; + if (slug.startsWith("share-")) slug = `clip-${slug}`; + return slug; +} + +/** + * The cut snapped to the words heard: the first word whose middle is at or after + * `start`, the last whose middle is at or before `end`; a breath before and a + * ring after, never into the word either side. `null` when no word is inside. + * Words are `{w|text, start, end}` on the CUE clock. Pure. + * + * @param {{ start: number, end: number, w?: string, text?: string }[]} words + * @param {number} start + * @param {number} end + * @param {{ lead?: number, tail?: number }} [o] + * @returns {null | { cutStart: number, cutEnd: number, first: string, last: string }} + */ +export function snapToWords(words, start, end, { lead = ALIGN_LEAD_S, tail = ALIGN_TAIL_S } = {}) { + const ws = (words ?? []).filter((w) => fin(w?.start) && fin(w?.end) && w.end >= w.start).sort((a, b) => a.start - b.start); + const mid = (w) => (w.start + w.end) / 2; + const i = ws.findIndex((w) => mid(w) >= start); + let j = -1; + for (let k = ws.length - 1; k >= 0; k -= 1) if (mid(ws[k]) <= end) { j = k; break; } + if (i < 0 || j < 0 || j < i) return null; + const prev = ws[i - 1]; + const next = ws[j + 1]; + const cutStart = r2(Math.max(prev ? prev.end : -Infinity, ws[i].start - lead, 0)); + const cutEnd = r2(Math.min(next ? next.start : Infinity, ws[j].end + tail)); + if (!(cutEnd > cutStart)) return null; + const say = (w) => String(w.w ?? w.text ?? "").trim(); + return { cutStart, cutEnd, first: say(ws[i]), last: say(ws[j]) }; +} + +/** The first public site (a `siteUrl`) whose channels carry `slug`, as its origin; null for none. */ +export async function siteOriginFor(slug, { sitesDir = SITES_DIR } = {}) { + let ids; + try { + ids = (await readdir(sitesDir)).sort(); + } catch { + return null; + } + for (const id of ids) { + const site = await readFile(path.join(/* turbopackIgnore: true */ sitesDir, id, "site.json"), "utf8").then(JSON.parse, () => null); + if (!site || typeof site.siteUrl !== "string" || !/^https?:\/\//.test(site.siteUrl.trim())) continue; + const pool = [...(Array.isArray(site.channels) ? site.channels.map((c) => (typeof c === "string" ? c : c?.slug)) : []), ...(Array.isArray(site.citedChannels) ? site.citedChannels : [])]; + if (pool.includes(slug)) return site.siteUrl.trim().replace(/\/+$/, ""); + } + return null; +} + +/** A site's public origin by its id (`--site`): its site.json `siteUrl`, or a sentence why not. */ +export async function siteOriginOf(id, { sitesDir = SITES_DIR } = {}) { + if (!/^[a-z0-9][a-z0-9._-]*$/i.test(String(id))) throw new CliError(`--site ${id}: a site's id (transcripts/sites/<id>)`); + const site = await readFile(path.join(/* turbopackIgnore: true */ sitesDir, String(id), "site.json"), "utf8").then(JSON.parse, () => null); + if (!site) throw new CliError(`--site ${id}: no ${path.join(sitesDir, String(id), "site.json")}`); + if (typeof site.siteUrl !== "string" || !/^https?:\/\//.test(site.siteUrl.trim())) throw new CliError(`--site ${id}: its site.json has no public siteUrl`); + return site.siteUrl.trim().replace(/\/+$/, ""); +} + +/** Ask the editor for the project's windows and follow its jobs to the end. Throws on a window it did not fetch. */ +async function fetchThroughEditor(project, { cfg, pollMs, say }) { + const fw = await import("./fetchWindows.mjs"); + const { body, skipped } = await fw.projectFetchBody(project, { reason: "quick clip", localIds: true }); + if (!body.items.length) throw new Error(`nothing to fetch: ${skipped.map((s) => `${s.clipId} (${s.why})`).join(", ") || "the clip has no window"}`); + const answer = await fw.postFetchWindows(cfg, body); + const run = await fw.recordFetchRun(project.dir, { body, answer }); + const s = fw.summarizeAnswer(answer); + if (s.unresolved.length) throw new Error(`the editor could not resolve ${s.unresolved.map((u) => `${u.clipId}: ${u.error}`).join("; ")}`); + if (s.refused.length) throw new Error(`the editor refused ${s.refused.map((r) => `${r.platform}: ${r.error}`).join("; ")}`); + say(s.jobs.length ? `asked the editor: ${s.jobs.map((j) => `job ${j.jobId} (${j.platform}, ${j.items} window(s))`).join(", ")}` : `the window is on disk already (${s.cached.join(", ") || "cached"})`); + for (let polls = 0; s.jobs.length || s.inFlight.length; polls += 1) { + const doc = await fw.readFetchRuns(project.dir); + const mine = doc.runs.find((x) => x.at === run.at && x.bodyHash === run.bodyHash) ?? run; + const states = await fw.followRun(cfg, project.dir, { ...mine, jobIds: [...(mine.jobIds ?? []), ...s.inFlight.map((f) => f.jobId)] }); + if (states.every((st) => fw.TERMINAL.has(st.status))) { + const bad = states.filter((st) => st.status !== "done" || st.failed?.length); + if (bad.length) throw new Error(`the editor's fetch did not land the window: ${bad.map((b) => `job ${b.jobId} ${b.status}${b.failed?.length ? ` (${b.failed.map((f) => `${f.class}: ${f.message}`).join("; ")})` : ""}`).join(", ")}`); + say("the window is on disk"); + return; + } + if (polls % 6 === 0) say(states.map((st) => `job ${st.jobId}: ${st.status}${st.queue?.position ? ` (queued, position ${st.queue.position})` : ""}`).join(", ")); + await new Promise((r) => setTimeout(r, pollMs)); + } +} + +/** The editor's words over a file's span, on the file's clock (quote-check's call). */ +async function editorWords({ path: file, start, end, out }, { emit = () => {} } = {}) { + const { askEditorOp } = await import("umtool-report-to-video/narrate-via-editor"); + await askEditorOp("/api/ops/transcribe", { path: file, start, end, words: true, out }, { emit }); + const doc = JSON.parse(await readFile(out, "utf8")); + return Array.isArray(doc.words) ? doc.words : []; +} + +/** + * Quick clip, start to end. Everything that talks to the editor or renders is + * a dependency, so a test runs the flow over its own stubs. + * + * @param {{ spec: string, snap?: "words" | null, title?: string | null, site?: string | null, folder?: string | null }} ask + * @param {{ root?: string, channelsDir?: string, sitesDir?: string, say?: (s: string) => void, cfg?: any, pollMs?: number, progress?: string | null, + * log?: (s: string) => void, err?: (s: string) => void, + * deps?: { fetch?: (project: { id: string, dir: string }) => Promise<void>, transcribe?: typeof editorWords, take?: (args: string[], o: any) => Promise<number> } }} [o] + * @returns {Promise<{ project: string, dir: string, output: string, snapped: null | { cutStart: number, cutEnd: number, first: string, last: string }, share: { platform: string | null, archive: string | null, text: string } }>} + */ +export async function quickClip(ask, { root = REPORTS_ROOT, channelsDir = CHANNELS_DIR, sitesDir = SITES_DIR, say = () => {}, cfg = null, pollMs = POLL_MS, progress = null, log = console.log, err = console.error, deps = {} } = {}) { + const spec = parseClipSpec(ask.spec); + if (!spec) throw new CliError(`"${ask.spec}" is not <channel>/<video>@<start>-<end> (seconds)`); + if (!(spec.end > spec.start)) throw new CliError(`${ask.spec}: the end must be after the start`); + if (ask.snap && ask.snap !== "words") throw new CliError(`--snap ${ask.snap}: words is the one snap`); + // The recording as the corpus keeps it (a Rumble embed id: its URL-slug folder), and the id the archive serves. + const video = await resolveVideoDirId(channelsDir, spec.channel, spec.video).catch(() => spec.video); + const siteVideo = await siteVideoFor({ channelsDir, slug: spec.channel, video }); + const origin = ask.site ? await siteOriginOf(ask.site, { sitesDir }) : await siteOriginFor(spec.channel, { sitesDir }); + + // 1. The project: the `umtool new` path, one clip, the footage alone. + const { scaffoldReportVideo } = await import("../projects/scaffold.mjs"); + const folder = ask.folder ?? QUICK_CLIP_FOLDER; + const base = quickClipSlug({ title: ask.title, channel: spec.channel, video: spec.video, start: spec.start }); + let slug = base; + for (let n = 2; await stat(path.join(root, folder, slug)).then(() => true, () => false); n += 1) slug = `${base}-${n}`; + const clip = { + type: "clip", id: "c01", channel: spec.channel, video, start: r2(spec.start), end: r2(spec.end), cite: Math.floor(spec.start), + ...(siteVideo ? { siteVideo } : {}), + }; + const made = await scaffoldReportVideo({ + root, slug, folder, title: String(ask.title ?? "").trim() || `${spec.channel}/${spec.video} at ${Math.floor(spec.start)} s`, + siteOrigin: origin, channelsDir, timeline: [clip], + }); + const project = { id: made.id, dir: made.dir }; + const { updateRender } = await import("./manifest.mjs"); + await updateRender(project.dir, { mode: "basic" }); + say(`project ${project.id} (basic: the footage alone)${origin ? `, archive ${origin}` : ""}`); + + // 2. The window, asked of the editor. + if (deps.fetch) await deps.fetch(project); + else { + const fw = await import("./fetchWindows.mjs"); + await fetchThroughEditor(project, { cfg: cfg ?? fw.editorConfig(), pollMs, say }); + } + + // 3. --snap words: the edges to the words heard. + let snapped = null; + if (ask.snap === "words") { + const from = Math.max(0, spec.start - SNAP_PAD_S); + const to = spec.end + SNAP_PAD_S; + const src = await resolveLocalSource({ video, slug: spec.channel, from, to }, { rawDir: path.join(project.dir, "out", "clips-raw"), channelsDir }); + if (!src) throw new Error(`--snap words: no window on disk holds ${from.toFixed(2)}–${to.toFixed(2)} (the fetch landed a narrower one?)`); + const { mkdir } = await import("node:fs/promises"); + const work = path.join(project.dir, "out", "quick-clip"); + await mkdir(work, { recursive: true }); + const a = Math.max(from, src.windowStart); + const b = Math.min(to, src.windowEnd); + const words = await (deps.transcribe ?? editorWords)({ path: src.path, start: r2(a - src.windowStart), end: r2(b - src.windowStart), out: path.join(work, "words.json") }); + const heard = words.map((w) => ({ w: w.w ?? w.text, start: w.start + src.windowStart, end: w.end + src.windowStart })); + snapped = snapToWords(heard, spec.start, spec.end); + if (!snapped) say("--snap words: no word heard inside the edges -- they stay as asked"); + else { + const { updateClip } = await import("./manifest.mjs"); + await updateClip(project.dir, "c01", { + start: r2(Math.min(spec.start, snapped.cutStart)), end: r2(Math.max(spec.end, snapped.cutEnd)), cutStart: snapped.cutStart, cutEnd: snapped.cutEnd, + }); + say(`snapped to the words: ${snapped.cutStart}–${snapped.cutEnd} ("${snapped.first}" … "${snapped.last}")`); + } + } + + // 4. The render, as a take: the heavy slot, the record, the take panel. + const take = deps.take ?? (await import("./takeCli.mjs")).takeCommand; + const code = await take([project.id, "--id", QUICK_CLIP_TAKE, "--label", "Quick clip", "--full", ...(progress ? ["--progress", progress] : [])], { reportsRoot: root, log, err }); + if (code !== 0) throw new Error(`the render failed (umtool take ${project.id} --id ${QUICK_CLIP_TAKE} exited ${code}; its record: umtool take status ${project.id} --id ${QUICK_CLIP_TAKE})`); + const { takesDirOf } = await import("./takes.mjs"); + const output = path.join(takesDirOf(project.dir), QUICK_CLIP_TAKE, "preview.mp4"); + + // 5. The share line. + const share = await projectShareLine(project, { clip: "c01" }); + return { project: project.id, dir: project.dir, output, snapped, share: { platform: share.platform, archive: share.archive, text: share.text || shareLineText(share) } }; +} + +/** + * `umtool clip …` + * @param {string[]} args the words after `clip` + * @param {{ root?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: any, cfg?: any, pollMs?: number, channelsDir?: string, sitesDir?: string }} [o] + * @returns {Promise<number>} + */ +export async function quickClipCommand(args, { root = REPORTS_ROOT, log = console.log, err = console.error, ...rest } = {}) { + const valued = new Set(["--snap", "--title", "--site", "--folder", "--progress"]); + const flags = new Map(); + const words = []; + try { + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (!a.startsWith("--")) words.push(a); + else if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags.set(a, args[++i]); + } else if (a === "--json" || a === "--help") flags.set(a, true); + else throw new CliError(`unknown flag ${a}`); + } + if (flags.has("--help")) { + log(QUICK_CLIP_USAGE); + return 0; + } + if (words.length !== 1) throw new CliError(QUICK_CLIP_USAGE); + const progress = flags.get("--progress") ?? null; + if (progress && progress !== "ndjson") throw new CliError("--progress takes ndjson"); + const json = flags.has("--json"); + const ndjson = progress === "ndjson"; + // Under NDJSON, stdout is events only; the prose goes to stderr. + const say = ndjson ? (s) => log(JSON.stringify({ ev: "quick-clip-step", message: s })) : json ? (s) => err(s) : (s) => log(s); + const r = await quickClip( + { spec: words[0], snap: flags.get("--snap") ?? null, title: flags.get("--title") ?? null, site: flags.get("--site") ?? null, folder: flags.get("--folder") ?? null }, + { root, say, progress, log: ndjson || !json ? log : err, err, ...rest }, + ); + const doc = { project: r.project, output: r.output, share: r.share, ...(r.snapped ? { snapped: r.snapped } : {}) }; + if (ndjson) log(JSON.stringify({ ev: "quick-clip", ...doc })); + else if (json) log(JSON.stringify(doc, null, 2)); + else { + log(r.output); + log(r.share.text ? `share: ${r.share.text}` : "share: (no platform page or archive to link)"); + } + return 0; + } catch (e) { + if (e instanceof CliError) { + err(e.message); + return 2; + } + const message = e instanceof Error ? e.message : String(e); + if (flags.get("--progress") === "ndjson") log(JSON.stringify({ ev: "quick-clip-failed", error: message })); + err(message); + return 1; + } +} diff --git a/umtool/lib/report/quickClip.test.mjs b/umtool/lib/report/quickClip.test.mjs @@ -0,0 +1,134 @@ +// Quick clip (lane output-modes): `umtool clip <ch>/<vid>@<s>-<e>` -- a +// basic-mode project, its window asked of the editor, the edges snapped to the +// words heard, rendered as a take, the output and its share line. The editor +// and the render are the flow's dependencies, stubbed here; e2e +// (basic-mode.spec.ts) runs it whole against the stub editor. Synthetic. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "umtool-quick-")); +const CORPUS = path.join(ROOT, "channels"); +const SITES = path.join(ROOT, "sites"); +const REPORTS = path.join(ROOT, "reports"); +process.env.CHANNELS_DIR = CORPUS; +process.env.SITES_DIR = SITES; +process.env.CHANNELS_FALLBACK = "0"; + +const { quickClip, quickClipCommand, quickClipSlug, siteOriginFor, snapToWords } = await import("./quickClip.mjs"); +const { shareCommand } = await import("./shareLineCli.mjs"); + +test.after(() => rm(ROOT, { recursive: true, force: true })); +const have = spawnSync("ffmpeg", ["-version"]).status === 0; + +const json = (file, doc) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(doc)); +}; +json(path.join(CORPUS, "yt", "config.json"), { platform: "youtube", url: "https://www.youtube.com/@yt" }); +json(path.join(CORPUS, "yt", "data", "vid1", "transcript.cues.json"), { webpageUrl: "https://www.youtube.com/watch?v=vid1", cues: [{ start: 40, end: 60, text: "words" }] }); +json(path.join(SITES, "a-site", "site.json"), { siteUrl: "https://a-site.example/", channels: [{ slug: "yt" }] }); +json(path.join(SITES, "private", "site.json"), { channels: [{ slug: "yt" }] }); + +test("quickClipSlug: the title's words, else <channel>-<video>-<start>; never a share- name", () => { + assert.equal(quickClipSlug({ title: "Momma Occo's remarks!", channel: "c", video: "v", start: 1 }), "momma-occo-s-remarks"); + assert.equal(quickClipSlug({ channel: "MommaOcco", video: "n8G_ysDV2bA", start: 4132.5 }), "mommaocco-n8g-ysdv2ba-4132"); + assert.equal(quickClipSlug({ title: "Share this", channel: "c", video: "v", start: 1 }), "clip-share-this"); + assert.equal(quickClipSlug({ title: "!!!", channel: "c", video: "v", start: 1 }), "c-v-1"); +}); + +test("snapToWords: the first word mostly after the start, the last mostly before the end; a breath, never into a neighbour", () => { + const words = [ + { w: "before", start: 9.0, end: 9.6 }, + { w: "half", start: 9.8, end: 10.4 }, // mid 10.1: after 10.0, so the first + { w: "middle", start: 11, end: 12 }, + { w: "last", start: 19.5, end: 19.9 }, // mid 19.7 ≤ 20 + { w: "over", start: 19.95, end: 20.6 }, // mid 20.27 > 20: out + ]; + const s = snapToWords(words, 10, 20); + assert.deepEqual(s, { cutStart: 9.65, cutEnd: 19.95, first: "half", last: "last" }, "0.15 s lead, the tail stopped at the next word"); + assert.deepEqual(snapToWords([{ text: "solo", start: 5, end: 6 }], 4, 7), { cutStart: 4.85, cutEnd: 6.3, first: "solo", last: "solo" }); + assert.equal(snapToWords([], 1, 2), null); + assert.equal(snapToWords([{ w: "x", start: 30, end: 31 }], 1, 2), null, "no word inside"); +}); + +test("siteOriginFor: the first public site that carries the channel", async () => { + assert.equal(await siteOriginFor("yt"), "https://a-site.example"); + assert.equal(await siteOriginFor("nobody"), null); +}); + +test("quickClip: a basic project, the window asked, the edges snapped, the take rendered, the share line", { skip: !have && "no ffmpeg" }, async () => { + const asked = []; + const deps = { + // The editor's fetch, stubbed: the window it would land, in the corpus. + fetch: async (project) => { + const m = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8")); + asked.push({ fetch: project.id, mode: m.render.mode, clip: m.timeline[0] }); + const dir = path.join(CORPUS, "yt", "data", "vid1", "clips"); + await mkdir(dir, { recursive: true }); + const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=10:d=26", "-f", "lavfi", "-i", "sine=duration=26", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(dir, "37.00-63.00.mp4")]); + assert.equal(r.status, 0, String(r.stderr)); + }, + // The editor's words, on the FILE's clock (the window starts at 37). + transcribe: async (req) => { + asked.push({ transcribe: req }); + return [{ w: "so", start: 2.5, end: 2.9 }, { w: "anyway", start: 3.2, end: 3.8 }, { w: "done", start: 22.5, end: 22.9 }, { w: "next", start: 23.4, end: 23.9 }]; + }, + take: async (args, o) => { + asked.push({ take: args }); + const dir = path.join(REPORTS, "quick-clips", args[0].split("/").pop(), "takes", "clip"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "preview.mp4"), "mp4"); + assert.equal(o.reportsRoot, REPORTS); + return 0; + }, + }; + const r = await quickClip({ spec: "yt/vid1@40-60", snap: "words", title: "A quick one" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps }); + assert.equal(r.project, "quick-clips/a-quick-one"); + assert.equal(r.output, path.join(REPORTS, "quick-clips", "a-quick-one", "takes", "clip", "preview.mp4")); + assert.equal(asked[0].mode, "basic", "the project is basic before its window is asked for"); + assert.deepEqual(asked[1].transcribe.start, 1, "the window's seconds: 38 - 37"); + assert.deepEqual(asked[2].take, ["quick-clips/a-quick-one", "--id", "clip", "--label", "Quick clip", "--full"]); + // The words heard: "anyway" (40.2–40.8) first, "done" (59.5–59.9) last; "so" (39.5–39.9) mostly before 40. + assert.deepEqual(r.snapped, { cutStart: 40.05, cutEnd: 60.2, first: "anyway", last: "done" }); + const m = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8")); + assert.equal(m.render.mode, "basic"); + assert.equal(m.provenance.siteOrigin, "https://a-site.example"); + assert.deepEqual([m.timeline[0].start, m.timeline[0].end, m.timeline[0].cutStart, m.timeline[0].cutEnd], [40, 60.2, 40.05, 60.2], "the extent widened to hold the cut"); + assert.deepEqual(r.share, { + platform: "https://www.youtube.com/watch?v=vid1&t=40s", + archive: "https://a-site.example/?v=yt%2Fvid1&t=40", + text: "https://www.youtube.com/watch?v=vid1&t=40s · archive: https://a-site.example/?v=yt%2Fvid1&t=40", + }); + + // Again: a fresh project beside it, never over it. + const again = await quickClip({ spec: "yt/vid1@40-60", title: "A quick one", site: "a-site" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps }); + assert.equal(again.project, "quick-clips/a-quick-one-2"); + assert.equal(again.snapped, null); + + // The CLI: --json, and `umtool share` (the Copy share line's twin). + const out = []; + const code = await quickClipCommand(["yt/vid1@41-59", "--json"], { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps, log: (s) => out.push(s), err: () => {} }); + assert.equal(code, 0); + const doc = JSON.parse(out.join("\n")); + assert.equal(doc.project, "quick-clips/yt-vid1-41"); + assert.equal(doc.share.platform, "https://www.youtube.com/watch?v=vid1&t=41s"); + const lines = []; + assert.equal(await shareCommand([doc.project, "c01", "--site", "a-site"], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s), sitesDir: SITES }), 0); + assert.equal(lines[0], "https://www.youtube.com/watch?v=vid1&t=41s · archive: https://a-site.example/?v=yt%2Fvid1&t=41"); + assert.equal(await shareCommand([doc.project, "nope"], { root: REPORTS, out: () => {}, err: () => {} }), 1); + // ndjson: events only on stdout, the last one the result. + const ev = []; + assert.equal(await quickClipCommand(["yt/vid1@42-58", "--progress", "ndjson"], { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps, log: (s) => ev.push(JSON.parse(s)), err: () => {} }), 0); + assert.equal(ev.at(-1).ev, "quick-clip"); + assert.ok(ev.slice(0, -1).every((e) => e.ev === "quick-clip-step")); + // Refusals: a bad spec, a site with no siteUrl. + assert.equal(await quickClipCommand(["yt/vid1"], { root: REPORTS, log: () => {}, err: () => {} }), 2); + await assert.rejects(quickClip({ spec: "yt/vid1@1-2", site: "private" }, { root: REPORTS, channelsDir: CORPUS, sitesDir: SITES, deps }), /no public siteUrl/); +}); diff --git a/umtool/lib/report/shareLineCli.mjs b/umtool/lib/report/shareLineCli.mjs @@ -0,0 +1,54 @@ +// `umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json]` (lane +// output-modes): a clip's SHARE LINE -- the CLI twin of the take panel's and +// Play's **Copy share line** (GET /api/report/share-line). The clip named, else +// the cut's (or the take's) first. shareLine.mjs builds it. +// +// Plain ESM: the CLI runs it under bare node. +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { projectShareLine } from "./shareLine.mjs"; +import { siteOriginOf } from "./quickClip.mjs"; + +export const SHARE_USAGE = [ + "usage: umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json]", + " a clip's share line: its platform page at the first second it plays (YouTube t=, Rumble start=) and its", + " moment on the archive (the manifest's siteOrigin, or --site's), a Rumble folder id as the embed id the", + " archive serves. The clip named, else the first; --take: the take's cut. --json: {clip, seconds, platform, archive, text}.", +].join("\n"); + +class CliError extends Error {} + +/** + * @param {string[]} args the words after `share` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [o] + * @returns {Promise<number>} + */ +export async function shareCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) { + try { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--take" || a === "--site") { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags.set(a, args[++i]); + } else if (a === "--json" || a === "--help") flags.set(a, true); + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (flags.has("--help") || !words.length || words.length > 2) { + (flags.has("--help") ? out : err)(SHARE_USAGE); + return flags.has("--help") ? 0 : 2; + } + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const origin = flags.has("--site") ? await siteOriginOf(String(flags.get("--site")), sitesDir ? { sitesDir } : {}) : undefined; + const line = await projectShareLine(r.project, { clip: words[1] ?? null, take: flags.get("--take") ?? null, ...(origin !== undefined ? { origin } : {}) }); + if (flags.has("--json")) out(JSON.stringify(line, null, 2)); + else out(line.text || `${line.clip}: no platform page or archive to link`); + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError || (e instanceof Error && e.constructor?.name === "CliError") ? 2 : 1; + } +}