// "Find clips" from the editor (release 36 B5): `POST /api/report/clips // {mode: "new", slug, from: "/", target?, scope?, segment?, // wordsPath?}` — a recording to a clip-finder project and its analysis, as // ONE call. The editor's find-clips job (release 36 lane A) makes the words, // the chat and the speakers first, then asks this. // // the scope "auto" (the default) is the narrated video auto-scope finds // (lib/clips/segments.mjs): `segment` names one, else the // longest; `[from, to]` is a scope by hand; "all" the whole // a project already made for the same recording whose scope covers the // chosen one (scopeOverlapsSegment) is analyzed AGAIN, as it // is — its scope, its params, and its cut: `--keep-cut`, so // no clip is moved, removed or added and the new proposals // (the chat's among them) are listed unused for the clip // editor → `created: false`; else a new project `slug` is // scaffolded with the reactions seed → `created: true` // the words `wordsPath` (an absolute path to a words file, `{words: // [{w, start, end}]}` as `pnpm ops transcribe {words: true, // out}` writes) is copied in as /words.json — into // an existing project only when it has none // the job `clips analyze` (the laugh scan, the voices, then a // proposal pass), one step on the app's runner // // Plain ESM: the route calls it, and its tests run with bare node. import { copyFile, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { PARAM_BOUNDS, cleanWords, normalizeScope } from "yt-dlp-transcript-common/lib/clips/clips.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { pickSegment, scopeOverlapsSegment } from "yt-dlp-transcript-common/lib/clips/segments.mjs"; import { REPORTS_ROOT } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { GLOBAL_CHANNELS_DIR } from "../projects/report.mjs"; import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs"; import { sharedWalk } from "../projects/walk.mjs"; import { ClipsError, WORDS_FILE, clipsSteps, loadRecording, recordingSegments } from "./reactions.mjs"; /** A refusal with the HTTP status the route answers. */ export class ClipsNewError extends ClipsError { /** @param {string} message @param {number} [status] */ constructor(message, status = 400) { super(message); this.status = status; } } const WORDS_MAX_BYTES = 256 * 1024 * 1024; /** The request's fields, checked. */ export function parseNewBody(body) { const b = body && typeof body === "object" ? 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 ?? ""}": /`); let target; if (b.target !== undefined && b.target !== null && b.target !== "") { target = Number(b.target); const [lo, hi] = PARAM_BOUNDS.target; if (!Number.isFinite(target) || target < lo || target > hi) throw new ClipsNewError(`target must be ${lo}..${hi} seconds`); } /** @type {"auto" | "all" | [number, number | null]} */ let scope = "auto"; if (b.scope === "all") scope = "all"; else if (Array.isArray(b.scope)) { try { scope = normalizeScope(b.scope) ?? "all"; } catch (e) { throw new ClipsNewError(e instanceof Error ? e.message : String(e)); } } else if (b.scope !== undefined && b.scope !== null && b.scope !== "auto") throw new ClipsNewError(`scope: "auto", "all" or [from, to]`); const segment = typeof b.segment === "string" && b.segment ? b.segment : null; if (segment && !/^s\d+$/.test(segment)) throw new ClipsNewError(`segment "${segment}": s1, s2, …`); if (segment && scope !== "auto") throw new ClipsNewError("segment goes with scope \"auto\""); const wordsPath = typeof b.wordsPath === "string" && b.wordsPath ? b.wordsPath : null; if (wordsPath && !path.isAbsolute(wordsPath)) throw new ClipsNewError("wordsPath must be an absolute path"); return { slug, channel: m[1], video: m[2], target, scope, segment, wordsPath }; } /** The words file, checked: a regular file holding words. */ async function checkWords(file) { const s = await stat(file).catch(() => null); if (!s || !s.isFile()) throw new ClipsNewError(`wordsPath ${file}: no such file`, 404); if (s.size > WORDS_MAX_BYTES) throw new ClipsNewError(`wordsPath ${file}: too large`); let doc; try { doc = JSON.parse(await readFile(file, "utf8")); } catch { throw new ClipsNewError(`wordsPath ${file}: not JSON`); } const list = Array.isArray(doc) ? doc : Array.isArray(doc?.words) ? doc.words : null; if (!list || !cleanWords(list).length) throw new ClipsNewError(`wordsPath ${file} holds no words ({ words: [{ w, start, end }] })`); } /** * The reactions projects already made for this recording whose scope covers * `span` — the best cover first (the most overlap, then the latest pass). */ export async function projectsCovering({ reportsRoot, channel, video, span, duration }) { const out = []; for (const p of await sharedWalk(reportsRoot, { since: Date.now() })) { if (!kindMakesTakes(p.kind)) continue; const doc = await readReactions(p.dir); if (!doc || doc.source?.channel !== channel || doc.source?.video !== video) continue; const scope = doc.params?.scope ?? null; if (!scopeOverlapsSegment(scope, span, duration)) continue; const a = Array.isArray(scope) ? scope[0] : 0; const b = Array.isArray(scope) && scope[1] !== null ? scope[1] : duration; out.push({ project: p, overlap: Math.max(0, Math.min(b, span.to) - Math.max(a, span.from)), at: String(doc.proposedAt ?? "") }); } return out.sort((x, y) => y.overlap - x.overlap || (y.at > x.at ? 1 : y.at < x.at ? -1 : 0)).map((x) => x.project); } /** * Plan a `mode: "new"` request: the project (found or scaffolded), the job's * steps, and what the editor is told. Scaffolds and copies the words; does * not start the job (the route does, on lib/jobs.ts). * @param {unknown} body * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string }} [o] */ export async function planClipsNew(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined } = {}) { const req = parseNewBody(body); let rec; try { rec = await loadRecording({ channelsDir, channel: req.channel, video: req.video }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); throw new ClipsNewError(msg, /no video directory/.test(msg) ? 404 : 400); } const segments = recordingSegments(rec); let span; let segment = null; if (req.scope === "auto") { try { segment = pickSegment(segments, req.segment); } catch (e) { throw new ClipsNewError(e instanceof Error ? e.message : String(e)); } span = segment ? { from: segment.from, to: segment.to } : { from: 0, to: rec.duration }; } else if (req.scope === "all") span = { from: 0, to: rec.duration }; else span = { from: req.scope[0], to: req.scope[1] ?? rec.duration }; const [existing] = await projectsCovering({ reportsRoot, channel: req.channel, video: req.video, span, duration: rec.duration }); const notes = []; let project; let created; if (existing) { project = { id: existing.id, dir: existing.dir, kind: existing.kind }; created = false; notes.push(`${existing.id} already reads this part of ${req.channel}/${req.video}: analyzed again with its scope and its cut kept as they are (the new proposals are listed, unused)`); if (req.wordsPath) { if (await stat(path.join(project.dir, WORDS_FILE)).then(() => true, () => false)) notes.push(`${WORDS_FILE} kept (the project has one)`); else { await checkWords(req.wordsPath); await copyFile(req.wordsPath, path.join(project.dir, WORDS_FILE)); notes.push(`${WORDS_FILE} copied in`); } } } else { if (req.wordsPath) await checkWords(req.wordsPath); let r; try { r = await scaffoldReportVideo({ root: reportsRoot, slug: req.slug, from: `${req.channel}/${req.video}`, seed: "reactions", channelsDir, ...(sitesDir ? { sitesDir } : {}), ...(req.target !== undefined ? { target: req.target } : {}), ...(req.scope === "auto" ? { scope: "auto", ...(req.segment ? { segment: req.segment } : {}) } : req.scope === "all" ? {} : { scope: req.scope }), }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400); } project = { id: r.id, dir: r.dir, kind: r.kind }; created = true; notes.push(...r.notes); if (req.wordsPath) { await copyFile(req.wordsPath, path.join(r.dir, WORDS_FILE)); notes.push(`${WORDS_FILE} copied in`); } } const doc = await readReactions(project.dir); const plan = clipsSteps(project, { mode: "analyze", ...(created ? {} : { keepCut: true }) }); return { project, created, segments, // The segment chosen (auto-scope's); an existing project keeps its own scope. segment: segment?.id ?? doc?.segment ?? null, scope: doc?.params?.scope ?? null, plan, notes, }; }