// LIVE PRE-CLIP's project (plans/live-preclip.md): `POST /api/report/clips // {mode: "live", slug, from: "/", final?, check?}` — the editor's // live-preclip job asks it after each tick. SYNCHRONOUS: a proposal pass is // arithmetic, and it must not wait behind a render on the app's one-job runner. // // THE RECORDING IS THE PROJECT'S OWN COPY while the stream is live: a project // with a `.shadow-channels/` reads its recording from there // (report-to-video/sources.mjs channelsDirFor), and this keeps it current from // the editor's data//live-transcript.json: // // .shadow-channels//data//transcript.cues.json the live cues // .shadow-channels//data//diarization.json one speaker, turns from // the cues (the clip finder // needs turns; the real // speakers come with the // landing) // .shadow-channels//data//metadata.info.json the record's // .shadow-channels//data//clips -> /data//clips // the editor's clip cache, // where a live share's // window lands // words.json the live words // scans/--.audio.json the live laugh scan // live-preclip.json this module's record: // the source, the passes, // the flags // // Each pass proposes over [0, transcribedTo − 20 s] (the live edge waits for the // next tick: a proposal there would be cut mid-thought). Ids are stable across // passes (clips.mjs stableIds), ruled and edited clips are protected // (rulingsGuard), so the windows grow without re-proposing what was proposed. // // FINAL (`final: true`, the live transcript superseded by the corpus's): the // shadow goes — the project reads the corpus from now on, the final cues and, // once diarized, the speakers — and words.json becomes the corpus's words.json // (or goes, so the captions come from transcript.json). The windows stay where // they are, by source second: the recording is append-only from its start, so // the partial's clock is the landed video's. A landing check that was not // "same" flags them (live-preclip.json `flags`, the clip editor's banner). // // Plain ESM: the route calls it; its tests run with bare node. import { copyFile, lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { LAUGH_CLASSES } from "yt-dlp-transcript-common/lib/clips/clips.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { REPORTS_ROOT } from "../projects/core.mjs"; import { GLOBAL_CHANNELS_DIR, readManifest, clipsOf } from "../projects/report.mjs"; import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs"; import { sharedWalk } from "../projects/walk.mjs"; import { SHADOW_CHANNELS } from "umtool-report-to-video/sources"; import { ClipsNewError } from "./clipsNew.mjs"; import { WORDS_FILE, proposeProject } from "./reactions.mjs"; import { LIVE_PROJECT_FILE, readLiveProject } from "./liveProject.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json"; export { LIVE_PROJECT_FILE, readLiveProject }; /** The live edge a pass leaves for the next tick (lib/livePreclip.ts PRECLIP_MINE_EDGE_SECONDS). */ export const LIVE_MINE_EDGE_S = 20; /** Two cues closer than this are one turn. */ export const LIVE_TURN_GAP_S = 1.5; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); const readJson = (f) => readFile(f, "utf8").then(JSON.parse, () => null); async function writeWhole(file, doc) { await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc)}\n`); await rename(tmp, file); } /** * The turns of a one-speaker recording from its cues: consecutive cues with * gaps under `gap` are one turn, speaker 0. * @param {{ start: number, end: number }[]} cues */ export function liveTurns(cues, gap = LIVE_TURN_GAP_S) { const out = []; for (const c of [...cues].filter((x) => num(x?.start) && num(x?.end) && x.end > x.start).sort((a, b) => a.start - b.start)) { const last = out.at(-1); if (last && c.start - last.end < gap) last.end = Math.max(last.end, c.end); else out.push({ start: c.start, end: c.end, speaker: 0 }); } return out.map((t) => ({ start: Math.round(t.start * 1000) / 1000, end: Math.round(t.end * 1000) / 1000, speaker: 0 })); } /** The request's fields, checked. */ export function parseLiveBody(body) { const b = isObj(body) ? body : {}; const slug = String(b.slug ?? "").trim().toLowerCase(); if (!SLUG_RE.test(slug)) throw new ClipsNewError(`slug "${b.slug ?? ""}": lower-case letters, digits and dashes`); const m = /^([^/]+)\/([^/]+)$/.exec(String(b.from ?? "")); if (!m || !CHANNEL_SLUG_RE.test(m[1]) || !CHANNEL_SLUG_RE.test(m[2])) throw new ClipsNewError(`from "${b.from ?? ""}": /`); const check = isObj(b.check) && typeof b.check.verdict === "string" ? { verdict: String(b.check.verdict), why: String(b.check.why ?? ""), ...(num(b.check.lagSeconds) ? { lagSeconds: b.check.lagSeconds } : {}) } : null; return { slug, channel: m[1], video: m[2], final: b.final === true, check }; } /** The editor's live transcript of a recording, or null. */ export async function readLiveTranscript(channelsDir, channel, video) { const doc = await readJson(path.join(channelsDir, channel, "data", video, LIVE_TRANSCRIPT_FILENAME)); return isObj(doc) && doc.version === 1 && Array.isArray(doc.cues) ? doc : null; } /** * The project's copy of the recording, written from the live transcript. * `shadowRoot` is the `.shadow-channels` dir (the project's, or a staging one). */ export async function writeShadow({ shadowRoot, channelsDir, channel, video, doc }) { const dir = path.join(shadowRoot, channel, "data", video); await mkdir(dir, { recursive: true }); const duration = num(doc.transcribedTo) ? doc.transcribedTo : 0; const turns = liveTurns(doc.cues); // The clip finder refuses a recording with no turns; a live one with no words yet has one silent turn. if (!turns.length) turns.push({ start: 0, end: Math.max(1, duration), speaker: 0 }); await writeWhole(path.join(dir, "transcript.cues.json"), { version: 1, source: "live-preclip", provisional: true, duration, cues: doc.cues }); await writeWhole(path.join(dir, "diarization.json"), { turns, audioSeconds: duration, generatedAt: String(doc.updatedAt ?? new Date().toISOString()), engine: { engine: "live-preclip (one speaker until the landing)" }, }); const meta = await readJson(path.join(channelsDir, channel, "data", video, "metadata.info.json")); if (meta) await writeWhole(path.join(dir, "metadata.info.json"), meta); const clips = path.join(dir, "clips"); const there = await lstat(clips).catch(() => null); if (!there) await symlink(path.join(channelsDir, channel, "data", video, "clips"), clips).catch(() => {}); return { dir, turns: turns.length, duration }; } /** The live laugh scan as the clip finder's scan cache (reactions.mjs readScans). */ export function liveScanDoc(doc, now = new Date()) { const s = doc.scan; if (!isObj(s) || !Array.isArray(s.energy)) return null; return { version: 1, window: s.window, hop: s.hop, t0: 0, windows: s.energy.length, energy: s.energy, laugh: Array.isArray(s.laugh) ? s.laugh : null, model: typeof s.model === "string" ? { file: s.model, sherpaOnnx: null, classes: [...LAUGH_CLASSES] } : null, classes: [...LAUGH_CLASSES], source: { path: LIVE_TRANSCRIPT_FILENAME, size: s.energy.length, mtimeMs: 0 }, clock: 0, kind: "live", madeAt: now.toISOString(), }; } async function findProject(reportsRoot, slug) { for (const p of await sharedWalk(reportsRoot, { since: Date.now() })) if (p.id === slug) return p; return null; } const countOf = async (dir) => { const [reactions, manifest] = await Promise.all([readReactions(dir), readManifest(dir)]); return { proposals: reactions?.proposals?.length ?? 0, clips: manifest ? clipsOf(manifest).length : 0 }; }; /** * One `mode: "live"` request: the project made or grown, or finalized. * @param {unknown} body * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string, now?: Date }} [o] */ export async function liveClips(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined, now = new Date() } = {}) { const req = parseLiveBody(body); if (!channelsDir) throw new ClipsNewError("no channels directory (CHANNELS_DIR)", 500); const doc = await readLiveTranscript(channelsDir, req.channel, req.video); if (!doc) throw new ClipsNewError(`${req.channel}/${req.video} has no live transcript (${LIVE_TRANSCRIPT_FILENAME})`, 404); const notes = []; let found = await findProject(reportsRoot, req.slug); let live = found ? await readLiveProject(found.dir) : null; if (found && (!live || live.source?.channel !== req.channel || live.source?.video !== req.video)) { throw new ClipsNewError(`project ${req.slug} exists and is not the live project of ${req.channel}/${req.video}: name another ("project")`, 409); } const flags = [...(Array.isArray(live?.flags) ? live.flags : [])]; const flag = (why) => { if (!flags.some((f) => f.why === why)) flags.push({ at: now.toISOString(), why }); }; if (live && num(live.restarts) && num(doc.restarts) && doc.restarts > live.restarts) { flag(`the recording restarted on another clock (${doc.restarts}×): windows proposed before ${now.toISOString().slice(11, 16)} may not sit on the landed video's seconds`); } if (req.check && req.check.verdict !== "same" && req.check.verdict !== "same-recording") { flag(`landing check: ${req.check.verdict} — ${req.check.why}`); } // FINAL: the corpus from now on. if (req.final) { if (!found) throw new ClipsNewError(`no live project ${req.slug} to finalize`, 404); await rm(path.join(found.dir, SHADOW_CHANNELS), { recursive: true, force: true }); const corpusWords = path.join(channelsDir, req.channel, "data", req.video, WORDS_FILE); if (await stat(corpusWords).then((s) => s.isFile(), () => false)) { await copyFile(corpusWords, path.join(found.dir, WORDS_FILE)); notes.push("words.json: the final word timings"); } else { await rm(path.join(found.dir, WORDS_FILE), { force: true }); notes.push("words.json removed: the captions come from the final transcript"); } await rm(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), { force: true }); await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), { ...live, status: "final", finalAt: now.toISOString(), check: req.check ?? live?.check ?? null, flags }); notes.push(`the shadow recording is gone: ${req.slug} reads ${req.channel}/${req.video} from the corpus (Find clips on the landed video re-analyzes it with the speakers and the sound)`); const c = await countOf(found.dir); return { project: req.slug, created: false, final: true, ...c, flags, notes, href: `/projects/${encodeURIComponent(req.slug)}/clips` }; } // A pass over the live transcript. let created = false; if (!found) { const staging = path.join(reportsRoot, `.live-staging-${req.slug}-${process.pid}`); await rm(staging, { recursive: true, force: true }); try { await writeShadow({ shadowRoot: staging, channelsDir, channel: req.channel, video: req.video, doc }); let r; try { r = await scaffoldReportVideo({ root: reportsRoot, slug: req.slug, from: `${req.channel}/${req.video}`, seed: "reactions", channelsDir: staging, ...(sitesDir ? { sitesDir } : {}) }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400); } await rename(staging, path.join(r.dir, SHADOW_CHANNELS)); found = { id: r.id, dir: r.dir, kind: r.kind }; created = true; notes.push(...(r.notes ?? []).filter((n) => !/umtool clips analyze|pnpm ops transcribe/.test(n))); } finally { await rm(staging, { recursive: true, force: true }); } } else { await writeShadow({ shadowRoot: path.join(found.dir, SHADOW_CHANNELS), channelsDir, channel: req.channel, video: req.video, doc }); } if (Array.isArray(doc.words) && doc.words.length) await writeWhole(path.join(found.dir, WORDS_FILE), { words: doc.words, provisional: true }); const scan = liveScanDoc(doc, now); if (scan) await writeWhole(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), scan); const upTo = Math.max(0, (num(doc.transcribedTo) ? doc.transcribedTo : 0) - LIVE_MINE_EDGE_S); const pass = await proposeProject({ project: { id: found.id, dir: found.dir }, from: { channel: req.channel, video: req.video }, params: { scopeFrom: 0, scopeTo: Math.round(upTo * 1000) / 1000 }, now, }); const passes = (num(live?.passes) ? live.passes : 0) + 1; await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), { version: 1, status: "live", source: { channel: req.channel, video: req.video }, madeAt: live?.madeAt ?? now.toISOString(), passes, lastPass: now.toISOString(), transcribedTo: doc.transcribedTo ?? 0, minedTo: upTo, restarts: num(doc.restarts) ? doc.restarts : 0, ...(req.check ? { check: req.check } : live?.check ? { check: live.check } : {}), flags, }); live = { passes }; return { project: found.id, created, final: false, proposals: pass.doc.proposals.length, clips: clipsOf({ timeline: pass.timeline }).length, minedTo: upTo, flags, notes, href: `/projects/${encodeURIComponent(found.id)}/clips`, }; }