Archilyzer · Source

archilyzer

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

commit 19fc36d4e0ebcc426e480e3ffcbf0565ce1dbd89
parent 18e9ea74c08511dfd590c05c786a1291187d4475
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 12:30:32 -0400

live pre-clip: ops live-preclip and live-clip, /api/media/live-window, settings.livePreclip

pnpm ops live-preclip {slug, id, action: start | stop | status | finalize};
record-live's "preclip" starts it from the recording job. pnpm ops live-clip
{slug, id, start, end | clip} asks umtool's live share and follows it.
/api/media/live-window (WORKER_TOKEN) is the window umtool asks for: cut now
from the recording in progress, no network. settings.livePreclip holds the
defaults; SETTINGS.md and COMMANDS.md regenerated.

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

Diffstat:
MCOMMANDS.md | 4+++-
MSETTINGS.md | 27+++++++++++++++++++++++++++
Mcommon/controller/livePreclip.ts | 3+--
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.ts | 42++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/media/live-window/route.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/live-clip/route.ts | 20++++++++++++++++++++
Aeditor/app/api/ops/live-preclip/route.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/liveMediaActions.ts | 87++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.mjs | 43++++++++++++++++++++++++++++++++++++++++++-
Msettings.json.example | 7+++++++
11 files changed, 321 insertions(+), 5 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -120,7 +120,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | | | `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(&lt;id&gt;)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` | | `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.&lt;fmt&gt;, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` | -| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'` | +| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` | +| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, &lt;id&gt;-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/&lt;id&gt;/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` | +| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | diff --git a/SETTINGS.md b/SETTINGS.md @@ -21,6 +21,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`cookieMode`](#cookiemode) | `"when-required"` | | [`social`](#social) | object — see below | | [`sleepBetweenDownloadsSeconds`](#sleepbetweendownloadsseconds) | `10` | +| [`livePreclip`](#livepreclip) | object — see below | | [`pacing`](#pacing) | object — see below | | [`downloadFormat`](#downloadformat) | `"auto"` | | [`sourceVideoQuality`](#sourcevideoquality) | `"original"` | @@ -210,6 +211,32 @@ Pause (seconds) inserted between per-video yt-dlp invocations in managed batch d Default: `10` +## `livePreclip` + +The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `"preclip": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts. + +#### `livePreclip` + +| Key | Default | Description | +|---|---|---| +| `everyMinutes` | `10` | Minutes between two pre-clip ticks of a live recording. A tick transcribes only what was recorded since the last one; a tick with under 30 s new is skipped. Clamped 1–120; default 10. | +| `maxChunkMinutes` | `20` | The most one tick transcribes, minutes of audio. A recording further behind (pre-clip started late, the worker was busy) is caught up in ticks of this size, back to back. Clamped 2–60; default 20. | +| `overlapSeconds` | `15` | Seconds each tick re-reads before the end of what is transcribed, so a word the boundary cut is heard whole once; the splice keeps each side's half. Clamped 0–60; default 15. | +| `scan` | `true` | Run the clip finder's laugh scan (CED when its model is installed, the energy always) on each tick's span. Default true. | +| `mine` | `true` | Hand the live transcript to umtool's clip finder after each tick (`POST /api/report/clips {mode: "live"}`), growing the stream's project. Default true. | + +Default: + +```json +{ + "everyMinutes": 10, + "maxChunkMinutes": 20, + "overlapSeconds": 15, + "scan": true, + "mine": true +} +``` + ## `pacing` How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts. diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts @@ -126,8 +126,7 @@ export function livePreclipQueueKey(slug: string, id: string): string { /** settings.livePreclip over the built-in defaults. */ export function preclipDefaults(): Omit<PreclipOptions, "project"> { - const s = (getSettings() as { livePreclip?: Partial<PreclipOptions> }).livePreclip; - return { ...PRECLIP_DEFAULTS, ...(s ?? {}) }; + return { ...PRECLIP_DEFAULTS, ...(getSettings().livePreclip ?? {}) }; } /** HEAVY_MIN_FREE_MB when set (0 = no floor), else the slot's 6000. */ diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -21,6 +21,7 @@ import { BUILD_PIPELINE_SETTINGS_FIELD_DOCS, DIARIZATION_SETTINGS_FIELD_DOCS, PACING_SETTINGS_FIELD_DOCS, + LIVE_PRECLIP_SETTINGS_FIELD_DOCS, PUBLISH_SETTINGS_FIELD_DOCS, REPORT_SCHEDULE_SETTINGS_FIELD_DOCS, DIGEST_SETTINGS_FIELD_DOCS, @@ -149,6 +150,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, { path: "workers[].remote", docs: REMOTE_WORKER_CONFIG_FIELD_DOCS }, { path: "workers[].llm", docs: LLM_WORKER_CONFIG_FIELD_DOCS }, ], + livePreclip: [ + { + path: "livePreclip", + docs: LIVE_PRECLIP_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.livePreclip), + }, + ], pacing: [ { path: "pacing", diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -874,6 +874,45 @@ export function sanitizePacing(v: unknown): PacingSettingsBlock { }; } +// LIVE PRE-CLIP (plans/live-preclip.md): the defaults a `preclip: true` on +// record-live (and `pnpm ops live-preclip`) takes. Each field is documented in +// LIVE_PRECLIP_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md). +export type LivePreclipSettingsBlock = { + everyMinutes: number; + maxChunkMinutes: number; + overlapSeconds: number; + scan: boolean; + mine: boolean; +}; + +export const LIVE_PRECLIP_SETTINGS_FIELD_DOCS: FieldDocs<LivePreclipSettingsBlock> = { + everyMinutes: + "Minutes between two pre-clip ticks of a live recording. A tick transcribes only what was recorded since the last " + + "one; a tick with under 30 s new is skipped. Clamped 1–120; default 10.", + maxChunkMinutes: + "The most one tick transcribes, minutes of audio. A recording further behind (pre-clip started late, the worker was " + + "busy) is caught up in ticks of this size, back to back. Clamped 2–60; default 20.", + overlapSeconds: + "Seconds each tick re-reads before the end of what is transcribed, so a word the boundary cut is heard whole once; " + + "the splice keeps each side's half. Clamped 0–60; default 15.", + scan: + "Run the clip finder's laugh scan (CED when its model is installed, the energy always) on each tick's span. Default true.", + mine: + "Hand the live transcript to umtool's clip finder after each tick (`POST /api/report/clips {mode: \"live\"}`), growing the " + + "stream's project. Default true.", +}; + +export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock { + const r = (v && typeof v === "object" ? v : {}) as Record<string, unknown>; + return { + everyMinutes: clampInt(r.everyMinutes, 1, 120, 10), + maxChunkMinutes: clampInt(r.maxChunkMinutes, 2, 60, 20), + overlapSeconds: clampInt(r.overlapSeconds, 0, 60, 15), + scan: r.scan !== false, + mine: r.mine !== false, + }; +} + export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600; export const SLEEP_BETWEEN_DOWNLOADS_DEFAULT_SECONDS = 10; @@ -1846,6 +1885,9 @@ export const siteSettingsSchema = z.object({ sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", ), + livePreclip: settingsField((v): LivePreclipSettingsBlock => sanitizeLivePreclip(v)).describe( + "The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `\"preclip\": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.", + ), pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe( "How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.", ), diff --git a/editor/app/api/media/live-window/route.ts b/editor/app/api/media/live-window/route.ts @@ -0,0 +1,54 @@ +import { NextResponse } from "next/server"; +import { authorizeWorkerRequest } from "yt-dlp-transcript-common/lib/workerToken"; +import { liveWindowAction } from "../../../channels/[slug]/liveMediaActions"; + +export const dynamic = "force-dynamic"; + +// A WINDOW OF A RECORDING IN PROGRESS, cut now (controller/liveClip.ts +// liveWindow) — what umtool's live share (`/api/report/live-share`) asks +// before it makes the short. The same door as /api/media/fetch-window (the +// WORKER_TOKEN), but it never reaches the network: the window is read from the +// part being recorded (or the saved video, once landed) into +// data/<id>/clips/<from>-<to>.mp4, or found there already. +// +// POST { slug, id, from, to, requestedBy?, manifest?, clipId?, reason? } +// -> 200 { path, file, from, to, bytes, source, recordedSeconds } +// -> 409 { error } past what is recorded ("ask again in N s"), or the +// recording not readable yet +// -> 400/404/503 { error } +const ID_RE = /^[\w.-]+$/; +const num = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); +const str = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined); + +export async function POST(request: Request) { + const auth = authorizeWorkerRequest(request.headers.get("authorization")); + if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status }); + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return NextResponse.json({ error: "body must be a JSON object" }, { status: 400 }); + const slug = str(body.slug); + const id = str(body.id); + if (!slug || !id || !ID_RE.test(id) || id === "." || id === "..") { + return NextResponse.json({ error: '"slug" and "id" are required' }, { status: 400 }); + } + if (!num(body.from) || !num(body.to)) return NextResponse.json({ error: '"from" and "to" are seconds' }, { status: 400 }); + const r = await liveWindowAction({ + slug, + id, + from: body.from, + to: body.to, + ...(str(body.requestedBy) ? { requestedBy: str(body.requestedBy)! } : {}), + ...(str(body.manifest) ? { manifest: str(body.manifest)! } : {}), + ...(str(body.clipId) ? { clipId: str(body.clipId)! } : {}), + ...(str(body.reason) ? { reason: str(body.reason)! } : {}), + }); + if (!r.ok) return NextResponse.json({ error: r.error }, { status: r.status }); + return NextResponse.json({ + path: r.window.path, + file: r.window.file, + from: r.window.from, + to: r.window.to, + bytes: r.window.bytes, + source: r.source, + recordedSeconds: r.recordedSeconds, + }); +} diff --git a/editor/app/api/ops/live-clip/route.ts b/editor/app/api/ops/live-clip/route.ts @@ -0,0 +1,20 @@ +import { LIVE_CLIP_BODY_KEYS } from "yt-dlp-transcript-common/controller/liveClip"; +import { liveClipAction } from "../../../channels/[slug]/liveMediaActions"; +import { jobResponse, ops, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, id, start, end | clip, project?, replace? } -> { ok: true, jobId } +// +// A SHAREABLE CLIP OF A STREAM STILL LIVE (controller/liveClip.ts): umtool's +// live share — the window cut now from the recording in progress (no network), +// the clip added to the stream's project when given by seconds, its short made +// with the live transcript's captions — followed to the end as a `live-clip` +// job. A clip is at most 2:20 (X's limit). `project` defaults to `<id>-live`, +// the project live pre-clip grows. +export async function POST(request: Request) { + return ops(request, LIVE_CLIP_BODY_KEYS, async (body) => { + reqSlug(body, "slug"); + return jobResponse(await liveClipAction(body)); + }); +} diff --git a/editor/app/api/ops/live-preclip/route.ts b/editor/app/api/ops/live-preclip/route.ts @@ -0,0 +1,31 @@ +import { NextResponse } from "next/server"; +import { LIVE_PRECLIP_BODY_KEYS } from "yt-dlp-transcript-common/controller/livePreclip"; +import { livePreclipAction } from "../../../channels/[slug]/liveMediaActions"; +import { opsFail, ops, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, id, action?: "start" (default) | "stop" | "status" | "finalize", +// everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?, +// project? } +// start -> { ok: true, jobId } the live-preclip job for a recording in +// progress (record-live's `preclip` starts +// it by itself) +// stop -> { ok: true, jobId } that job cancelled; the recording goes on +// status -> { ok: true, status } live-preclip.json, the live transcript's +// summary and last cues, the job +// finalize -> { ok: true, project } the supersede by hand, once the final +// transcript is here +// +// LIVE PRE-CLIP (controller/livePreclip.ts; plans/live-preclip.md): every few +// minutes the new span of the growing recording is transcribed on a worker +// lease and spliced into data/<id>/live-transcript.json, and umtool's clip +// finder grows the stream's project — no network request. +export async function POST(request: Request) { + return ops(request, LIVE_PRECLIP_BODY_KEYS, async (body) => { + reqSlug(body, "slug"); + const r = await livePreclipAction(body); + if (!r.ok) return opsFail(r.error, 400, r.info ? { info: true } : undefined); + return NextResponse.json(r); + }); +} diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts @@ -8,6 +8,13 @@ // instead (attachMediaAction). // recordLiveAction `pnpm ops record-live`, "Record live" — controller/ // recordLive.ts. +// livePreclipAction `pnpm ops live-preclip`, the video page's Live pre-clip +// panel — controller/livePreclip.ts (start, stop, +// status, finalize). +// liveClipAction `pnpm ops live-clip` — controller/liveClip.ts: a share +// of a stream still live, made by umtool. +// liveWindowAction `POST /api/media/live-window` (umtool's share asks it): +// a window cut now from the recording in progress. // // Both land through controller/landMedia.ts, and with `transcribe: true` ask // for a transcribe-one job (whisperVideoAction) once the audio is in place — @@ -23,6 +30,17 @@ import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/ import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport"; import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia"; import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive"; +import { + finalizeLivePreclip, + livePreclipStatus, + parseLivePreclipBody, + preclipDefaults, + startLivePreclipJob, + stopLivePreclip, + type LivePreclipStatusView, +} from "yt-dlp-transcript-common/controller/livePreclip"; +import { liveWindow, parseLiveClipBody, runLiveClipJob, type LiveWindowOutcome } from "yt-dlp-transcript-common/controller/liveClip"; +import type { PreclipOptions } from "yt-dlp-transcript-common/lib/livePreclip"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { attachMediaAction } from "./attachMediaActions"; @@ -74,7 +92,7 @@ export async function importMediaAction(body: Record<string, unknown>): Promise< } export async function recordLiveAction(body: Record<string, unknown>): Promise<StreamActionResult> { - const req = parseRecordLiveRequest(body); + const req = parseRecordLiveRequest(body, preclipDefaults()); if ("error" in req) return { ok: false, error: req.error }; if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` }; const paths = getPaths(); @@ -86,6 +104,73 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S channelConfig: config, cookiePolicy: resolveCookiePolicy(getSettings(), config), requestTranscription, + startPreclip: async (slug: string, id: string, options: PreclipOptions) => { + const r = await startLivePreclipJob({ paths, slug, id, channelConfig: config, options, requireRecording: false }); + if (!r.ok) return { ok: false, error: r.error }; + void r.stream.cancel(); + return { ok: true, jobId: r.jobId }; + }, afterRun: () => safeRevalidate([`/channels/${req.slug}`]), }); } + +export type LivePreclipActionResult = + | { ok: true; action: "start"; jobId: string } + | { ok: true; action: "stop"; jobId: string } + | { ok: true; action: "status"; status: LivePreclipStatusView } + | { ok: true; action: "finalize"; project: string | null } + | { ok: false; error: string; info?: boolean }; + +export async function livePreclipAction(body: Record<string, unknown>): Promise<LivePreclipActionResult> { + const parsed = parseLivePreclipBody(body, preclipDefaults()); + if (!parsed.ok) return parsed; + const { slug, id, action, options } = parsed.value; + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + if (action === "status") return { ok: true, action, status: await livePreclipStatus(paths, slug, id) }; + if (action === "stop") { + const r = stopLivePreclip(slug, id); + return r.ok ? { ok: true, action, jobId: r.jobId } : r; + } + if (action === "finalize") { + const r = await finalizeLivePreclip({ paths, slug, id, ...(options.project ? { options: { project: options.project } } : {}) }); + return r.ok ? { ok: true, action, project: r.project } : r; + } + const r = await startLivePreclipJob({ paths, slug, id, channelConfig: config, options }); + if (!r.ok) return { ok: false, error: r.error, ...(r.info ? { info: true } : {}) }; + void r.stream.cancel(); + safeRevalidate([`/channels/${slug}/videos/${id}`]); + return { ok: true, action, jobId: r.jobId }; +} + +export async function liveClipAction(body: Record<string, unknown>): Promise<StreamActionResult> { + const parsed = parseLiveClipBody(body); + if (!parsed.ok) return parsed; + if (!isValidChannelSlug(parsed.value.slug)) return { ok: false, error: `"${parsed.value.slug}" is not a channel slug` }; + const paths = getPaths(); + if (!(await readChannelConfig(paths, parsed.value.slug))) return { ok: false, error: `Channel "${parsed.value.slug}" not found` }; + return runLiveClipJob({ paths, request: parsed.value }); +} + +export async function liveWindowAction(body: { + slug: string; + id: string; + from: number; + to: number; + requestedBy?: string; + manifest?: string; + clipId?: string; + reason?: string; +}): Promise<LiveWindowOutcome> { + if (!isValidChannelSlug(body.slug)) return { ok: false, status: 400, error: `"${body.slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, body.slug); + if (!config) return { ok: false, status: 404, error: `Channel "${body.slug}" not found` }; + try { + return await liveWindow({ paths, channelConfig: config, ...body }); + } catch (e) { + return { ok: false, status: 500, error: (e as Error).message }; + } +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -50,6 +50,9 @@ // pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait // pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}' // pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}' +// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}' +// pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}' +// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait // pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait @@ -394,6 +397,14 @@ const ACTIONS = [ // job; both land through the same code. "import-media", "record-live", + // LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed + // and mined while it records ({slug, id, action?: start | stop | status | + // finalize, everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?, + // project?}) — record-live's "preclip" starts it by itself — and a + // shareable clip of it cut now and made by umtool ({slug, id, start, end | + // clip, project?, replace?}). + "live-preclip", + "live-clip", // A channel's saved containers remuxed losslessly into browser-playable // copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}). "prepare-playable", @@ -634,6 +645,9 @@ export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing "; // The same for Find clips (FIND_CLIPS_RESULT_MARKER in // common/controller/findClips.ts). export const FIND_CLIPS_RESULT_MARKER = "@@find-clips "; +// The same for a live share (LIVE_CLIP_RESULT_MARKER in +// common/controller/liveClip.ts). +export const LIVE_CLIP_RESULT_MARKER = "@@live-clip "; // The provenance a tag write from this CLI carries. Everything else ignores it. function agentSource() { @@ -883,6 +897,7 @@ export function parseArgs(argv) { ...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}), ...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}), ...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}), + ...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}), ...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}), wait, quiet, @@ -1524,7 +1539,33 @@ export function usage() { " polled from its first segment beside the channel's live stream. One job", " per stream; job cancel stops it with SIGINT and lands what it has (video", " and audio left unmerged are merged, -c copy); the longest part wins.", - " Refused for a stream that is not live.", + " Refused for a stream that is not live. \"preclip\": true (or", + ' {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine",', + ' "project"}, over settings.livePreclip) starts live-preclip once the first', + ' part begins, and implies "transcribe".', + "", + 'live-preclip transcribes and mines a recording WHILE it records: {"slug",', + ' "id", "action"?: "start" (default) | "stop" | "status" | "finalize"}, and', + ' for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"?', + ' (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the', + " umtool project, <id>-live). One job per stream beside the recorder's: each", + " tick reads only the new span of the growing file (never writing it),", + " transcribes it on a worker lease (one at a time — a busy worker coalesces", + " ticks), splices it into data/<id>/live-transcript.json (provisional) and", + " grows the umtool project. Skipped and said: under 30 s new, MemAvailable", + " under HEAVY_MIN_FREE_MB (6000), the store's disk under 2 GB. When the", + " stream lands: the clock check (flagged when the landed video's start", + " differs), then the final transcript supersedes the live one. stop cancels", + " the job, never the recording; status prints the state; finalize does the", + " supersede by hand. No network request.", + "", + 'live-clip makes a shareable clip of a stream still live: {"slug", "id",', + ' "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id', + ' of the project), "project"? (<id>-live), "replace"?. umtool cuts the', + " window from the recording now (the editor's /api/media/live-window: the", + " part being written, or the saved video once landed; no network), adds", + " the clip, and makes its short with the live transcript's captions. With", + " --wait the result (the short's URL) is stdout.", "", 'prepare-playable remuxes each of a channel\'s saved containers, losslessly', ' (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes', diff --git a/settings.json.example b/settings.json.example @@ -9,6 +9,13 @@ "x": {} }, "sleepBetweenDownloadsSeconds": 10, + "livePreclip": { + "everyMinutes": 10, + "maxChunkMinutes": 20, + "overlapSeconds": 15, + "scan": true, + "mine": true + }, "pacing": { "sleepRequestsCapSeconds": 16, "decayAfterCleanUnits": 5,