Archilyzer · Source

archilyzer

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

commit 15dd29e11907f698198e20205590c16bbd8b4a96
parent 67e550327e55193694d3c71863dbd375fe9630e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 00:25:02 -0500

cleanup: clean after capture, and nothing deletes audio before its voice fingerprint -- diarization.cleanAfterCapture (default off) runs the per-video half of Clean audio the moment a diarization unit is done with voiceprints; diarization.requireVoiceprints (default on) holds a diarized video's audio until its sidecar carries them ("awaiting voice fingerprint")

- cleanAudioFromTranscribed is factored around ONE per-video gate,
  audioCleanGate (transcript.json, keep-latest, do-not-clean, diarization,
  now voiceprints), applied in the same order by the channel sweep and by the
  new cleanAudioForVideo, which also asks verifyBeforeClean for its one id (a
  gone-upstream video is pinned, not deleted) and removes through
  removeMediaFile. Both count bytes freed (stat through tier links). The
  sweep's log strings are unchanged unless a voiceprint hold occurs:
  "Skipped <id> (awaiting voice fingerprint)" and a ", N awaiting voice
  fingerprint" clause, appended only when non-zero.
- The hook: runOperationUnit, AFTER its finally (never racing the re-acquire
  cleanup), for a diarization unit that is done -- local or remote, the lane
  runner and the per-channel run alike. Live settings per unit; a failure
  there never fails the unit. Freed bytes go on the unit report, the batch
  summary ("freed X of audio from N video(s) after capture") and a small
  ledger at the corpus root, speakers-run.json (lib/speakersLedger-server.ts),
  which is the readout's "freed this run".
- The channel snapshot's hold partition follows the sweep: a sidecar without
  voiceprints holds its audio at the awaiting-diarization gate (read only for
  videos with both a sidecar and audio), and the reclaimable bucket agrees.
- SETTINGS.md and settings.json.example regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
MSETTINGS.md | 6+++++-
Mcommon/controller/channelSnapshot.ts | 20++++++++++++++++++--
Acommon/controller/cleanAfterCapture.test.ts | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/cleanAudioFromTranscribed.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcommon/controller/operationBatch.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/operationJobs.ts | 4++++
Mcommon/lib/settingsSchema.ts | 26++++++++++++++++++++++++++
Acommon/lib/speakersLedger-server.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/diarize-sherpa.test.mjs | 2+-
Msettings.json.example | 4+++-
10 files changed, 603 insertions(+), 44 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -774,6 +774,8 @@ Speaker diarization captured right after transcription, while the audio is still | `sortformerModel` | `""` | Model for the sortformer engine, produced by scripts/build-sortformer.sh. Empty = that engine cannot run, reported as the same `not-configured` skip as an unset `sortformerBin`. | | `concurrency` | `1` | How many diarize runs may execute at once in the backfill pass. Kept low by default: diarization is CPU-bound and competes with GPU feeding and the digest sweep for the same 8 threads. | | `maxAudioHours` | `0` | Videos longer than this are DEFERRED rather than diarized: reported as a third number that is never summed into reachable work, so a capped corpus can never read as finished.<br><br>THIS IS A STOPGAP AND IT IS NOT THE FIX. sherpa-onnx's clustering holds a pairwise distance matrix over speech-segment embeddings — O(n^2) in SEGMENT count — and speaker-turn density varies 40x across this corpus (33-1364 turns/hour), so duration does not actually predict the blowup: a sparse 7h42m video completed while a dense 6h12m one was OOM-killed. Duration is merely the only predictor available for free, from metadata already on disk, BEFORE spending 45 minutes to find out. n^2 at 30k segments is 6.7 GiB and at 40k is 11.9 GiB, which brackets the 10.6 GB and 9.6 GB peaks measured on this 16 GB box.<br><br>0 disables the cap. That is where this goes once windowed diarization lands: windowing divides per-window n by the window count, so the matrix falls by its square, and the cap stops being needed rather than being tuned. | +| `cleanAfterCapture` | `false` | Delete a video's audio as soon as the Speakers lane has captured it.<br><br>When ON, a diarization unit that finishes with a complete set of voice fingerprints (diarization.json `voiceprints`) is followed at once by the per-video half of Clean audio, with every one of its gates: a transcript.json, outside the keep-latest window, not marked do-not-clean, and the availability check (a video gone upstream is pinned, not deleted). The bytes freed are logged and counted in the speakers readout. OFF by default: nothing deletes audio until the operator says so. | +| `requireVoiceprints` | `true` | Hold a video's audio until its diarization.json carries voice fingerprints.<br><br>A fingerprint is the one part of a diarization that cannot be made again once the audio is gone, so with this ON (the default) Clean audio skips a diarized video whose sidecar has none, saying "awaiting voice fingerprint", and the Speakers lane adds them from the existing turns. Applies only while diarization is enabled, like the diarization guard itself. | Default: @@ -791,7 +793,9 @@ Default: "sortformerBin": "", "sortformerModel": "", "concurrency": 1, - "maxAudioHours": 0 + "maxAudioHours": 0, + "cleanAfterCapture": false, + "requireVoiceprints": true } ``` diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -27,6 +27,8 @@ import { isTierable } from "../lib/mediaTier"; import { isDriveNotAnswering, onDrive } from "../lib/storageHealth"; import { CLIPS_DIR_NAME } from "../lib/clipWindow"; import { getSettings } from "../lib/settings"; +import { hasVoiceprints } from "../lib/diarization"; +import { loadDiarization } from "../lib/diarization-server"; import { loadAvailability, resolveEffectiveAvailability, @@ -1224,6 +1226,11 @@ export async function generateChannelSnapshot( // once per snapshot rather than per video — this and the sweep's own guard key // off the same setting, and they have to agree or the reclaim estimate lies. const diarizationEnabled = getSettings().diarization.enabled; + // …and, with diarization.requireVoiceprints, until the sidecar carries voice + // fingerprints (cleanAudioFromTranscribed's audioCleanGate). Read only for a + // video that has BOTH a sidecar and audio — the one population it can hold. + const voiceprintGuardOn = + diarizationEnabled && getSettings().diarization.requireVoiceprints; // Videos the user has opted out of the truncated/incomplete-transcript check // (e.g. legitimately have no speech for the back half). Suppressed from the @@ -1361,6 +1368,15 @@ export async function generateChannelSnapshot( 0, ); totalAudioBytes += audioBytes; + // Diarized AS FAR AS THE SWEEP IS CONCERNED: a sidecar without voice + // fingerprints is held at the same gate as an absent one — what it waits + // for is the Speakers lane either way. Only a video that holds audio pays + // the read. + const diarizedForCleanup = + files.hasDiarization && + (!voiceprintGuardOn || + files.audioFiles.length === 0 || + hasVoiceprints(await loadDiarization(path.join(dataDir, id)))); if (files.audioFiles.length > 0) { const gate = attributeAudioHold({ // The sweep's own gate — entries.includes("transcript.json"). NOT @@ -1376,7 +1392,7 @@ export async function generateChannelSnapshot( inKeepLatestWindow: keptIds.has(id), doNotClean: doNotCleanIds.has(id), diarizationGuardOn: diarizationEnabled, - hasDiarization: files.hasDiarization, + hasDiarization: diarizedForCleanup, }); if (gate === "reclaimable") { // What verifyBeforeClean is likely to refuse at sweep time, from the @@ -1549,7 +1565,7 @@ export async function generateChannelSnapshot( // Held back by the diarization guard in cleanAudioFromTranscribed. Kept // out of the bucket AND its byte total so "Est. reclaim" never promises // space the sweep is going to refuse to take. - !(diarizationEnabled && !files.hasDiarization) + !(diarizationEnabled && !diarizedForCleanup) ) { transcribedWithAudio.push(id); for (const name of files.audioFiles) { diff --git a/common/controller/cleanAfterCapture.test.ts b/common/controller/cleanAfterCapture.test.ts @@ -0,0 +1,203 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { Operation } from "../lib/operations"; +import { cleanAudioForVideo, cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; +import { runOperationUnit, type OperationRun } from "./operationBatch"; +import { readSpeakersLedger } from "../lib/speakersLedger-server"; +import { defaultSiteSettings, getSettings } from "../lib/settings"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/cleanAfterCapture.test.ts +// +// Temp corpus, temp settings.json. Nothing here probes the network: availability +// is checked from availability.json (tier A) or switched off per test. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-after-capture-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; + +async function settings(diarization: Record<string, unknown>, over: Record<string, unknown> = {}) { + await writeFile( + process.env.SETTINGS_FILE!, + JSON.stringify({ + verifyAvailabilityBeforeClean: false, + diarization: { enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", ...diarization }, + ...over, + }), + ); +} + +const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: [0.6, 0.8], embeddingModel: "emb.onnx" }]; + +function sidecar(voiceprints: boolean): string { + return JSON.stringify({ + videoId: "v", + generatedAt: "2026-08-07T00:00:00.000Z", + speakers: 1, + turns: [{ start: 0, end: 4, speaker: 0 }], + engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, + ...(voiceprints ? { voiceprints: VOICEPRINTS } : {}), + }); +} + +let n = 0; +async function corpus() { + const dir = path.join(ROOT, `c${n++}`); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + ytdlpBin: path.join(dir, "no-such-ytdlp"), + } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile(path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ name: "ch" })); + const video = async ( + id: string, + o: { transcript?: boolean; diarization?: "none" | "plain" | "voiceprints"; doNotClean?: boolean; gone?: boolean; bytes?: number } = {}, + ) => { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}"); + await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.bytes ?? 1000)); + if (o.diarization === "plain") await writeFile(path.join(v, "diarization.json"), sidecar(false)); + if (o.diarization === "voiceprints") await writeFile(path.join(v, "diarization.json"), sidecar(true)); + if (o.doNotClean) await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify({ setAt: "now" })); + if (o.gone) { + await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "deleted" })); + } + return v; + }; + return { paths, video }; +} + +const exists = (f: string) => access(f).then(() => true, () => false); + +test("Clean audio holds a diarized video whose sidecar has no voice fingerprints, and says so", async () => { + await settings({}); + const { paths, video } = await corpus(); + const plain = await video("plain", { diarization: "plain" }); + const done = await video("done", { diarization: "voiceprints", bytes: 4096 }); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m) }); + assert.equal(await exists(path.join(plain, "audio.mp3")), true, "awaiting its fingerprint"); + assert.equal(await exists(path.join(done, "audio.mp3")), false); + assert.equal(r.awaitingVoiceprint, 1); + assert.equal(r.bytesFreed, 4096); + assert.ok(logs.includes("Skipped plain (awaiting voice fingerprint)")); + assert.ok( + logs.some((l) => l.endsWith("Skipped 1 (0 protected, 0 gone-from-source pinned, 0 unverified, 1 awaiting voice fingerprint).")), + logs.join("\n"), + ); +}); + +test("requireVoiceprints off: the old rule — a diarization.json is enough", async () => { + await settings({ requireVoiceprints: false }); + const { paths, video } = await corpus(); + const plain = await video("plain", { diarization: "plain" }); + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} }); + assert.equal(await exists(path.join(plain, "audio.mp3")), false); + assert.equal(r.awaitingVoiceprint, 0); +}); + +test("defaults: requireVoiceprints ON, cleanAfterCapture OFF", () => { + assert.equal(defaultSiteSettings().diarization.requireVoiceprints, true); + assert.equal(defaultSiteSettings().diarization.cleanAfterCapture, false); +}); + +test("cleanAudioForVideo keeps every gate of the channel sweep", async () => { + await settings({}, { verifyAvailabilityBeforeClean: true }); + const { paths, video } = await corpus(); + await video("untranscribed", { transcript: false, diarization: "voiceprints" }); + await video("pinned", { diarization: "voiceprints", doNotClean: true }); + await video("nodiar"); + await video("plain", { diarization: "plain" }); + const gone = await video("gone", { diarization: "voiceprints", gone: true }); + const ok = await video("ok", { diarization: "voiceprints", bytes: 2048 }); + await writeFile(path.join(ok, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "public" })); + const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {} }); + assert.deepEqual(await one("untranscribed"), { outcome: "held", gate: "no-transcript", removedFiles: 0, bytesFreed: 0 }); + assert.equal((await one("pinned")).gate, "do-not-clean"); + assert.equal((await one("nodiar")).gate, "awaiting-diarization"); + assert.equal((await one("plain")).gate, "awaiting-voiceprint"); + // Gone upstream: pinned do-not-clean, audio kept. + assert.equal((await one("gone")).outcome, "pinned"); + assert.equal(await exists(path.join(gone, "audio.mp3")), true); + assert.equal(await exists(path.join(gone, "do-not-clean.json")), true); + assert.deepEqual(await one("ok"), { outcome: "cleaned", removedFiles: 1, bytesFreed: 2048 }); + assert.equal(await exists(path.join(ok, "audio.mp3")), false); +}); + +// ---- the hook: a diarization unit that returns done -------------------------- + +function fakeDiarization(write: "voiceprints" | "plain"): Operation { + return { + id: "diarization", + lane: { queueKey: "backfill", contendsFor: "cpu" }, + resolveTarget: () => ({}), + state: async () => "missing", + run: async ({ videoDir }: { videoDir: string }) => { + await writeFile(path.join(videoDir, "diarization.json"), sidecar(write === "voiceprints")); + return "done"; + }, + inputs: () => [], + outputs: ["diarization.json"], + } as unknown as Operation; +} + +function fakeRun(paths: Paths): OperationRun { + return { + lane: "backfill", + paths, + settings: getSettings(), + force: false, + allowRedownload: false, + live: { llmActive: 0, unitActive: 0, costUsd: 0, diskFloorHit: false }, + backfill: { targets: new Map(), llmFanout: null }, + log: () => {}, + } as unknown as OperationRun; +} + +test("clean after capture: on, a captured video's audio goes at once, counted and ledgered", async () => { + await settings({ cleanAfterCapture: true }); + const { paths, video } = await corpus(); + const v = await video("v1", { bytes: 5000 }); + const logs: string[] = []; + const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: (m) => logs.push(m) }); + assert.equal(report.outcome, "done"); + assert.equal(await exists(path.join(v, "audio.mp3")), false); + assert.equal(report.audioCleaned, 1); + assert.equal(report.audioFreedBytes, 5000); + const ledger = await readSpeakersLedger(paths); + assert.equal(ledger.freedBytes, 5000); + assert.equal(ledger.freedVideos, 1); + assert.ok(logs.some((l) => l.startsWith("Freed 4.9 KB of audio from v1")), logs.join("\n")); +}); + +test("clean after capture: never before the fingerprint exists", async () => { + await settings({ cleanAfterCapture: true, requireVoiceprints: false }); + const { paths, video } = await corpus(); + const v = await video("v1"); + const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("plain") }, { onLog: () => {} }); + assert.equal(report.outcome, "done"); + assert.equal(await exists(path.join(v, "audio.mp3")), true); + assert.equal(report.audioCleaned, 0); +}); + +test("clean after capture: off by default, and a protected video stays protected", async () => { + await settings({}); + const { paths, video } = await corpus(); + const a = await video("v1"); + await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: () => {} }); + assert.equal(await exists(path.join(a, "audio.mp3")), true, "off by default"); + + await settings({ cleanAfterCapture: true }); + const b = await video("v2", { doNotClean: true }); + const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v2", op: fakeDiarization("voiceprints") }, { onLog: () => {} }); + assert.equal(await exists(path.join(b, "audio.mp3")), true, "do-not-clean holds"); + assert.equal(report.audioCleaned, 0); +}); + +test.after(() => rm(ROOT, { recursive: true, force: true })); diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -3,15 +3,16 @@ import path from "node:path"; import fs from "fs-extra"; import type { Paths } from "../lib/paths"; import { isDoNotClean } from "../lib/doNotClean-server"; -import { hasDiarization } from "../lib/diarization-server"; -import { getSettings } from "../lib/settings"; +import { loadDiarization } from "../lib/diarization-server"; +import { hasVoiceprints } from "../lib/diarization"; +import { getSettings, type DiarizationSettings } from "../lib/settings"; import { audioFilesToRemove } from "../lib/videoStatus"; import { readChannelConfig } from "./channels"; import { computeKeptVideoIds } from "./keptVideos"; import { pruneSavedVideos } from "./pruneSavedVideos"; import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean"; -const { pathExists, readdir } = fs; +const { pathExists, readdir, stat } = fs; export type CleanAudioOptions = { channelSlug: string; @@ -42,6 +43,12 @@ export type CleanAudioResult = { // catches up, and a number that only ever grows is the signal that the CPU // lane has fallen behind the GPU. awaitingDiarization: number; + // Left alone because the video IS diarized but its diarization.json has no + // voice fingerprints yet (diarization.requireVoiceprints). Transient like + // awaitingDiarization: the Speakers lane adds them while the audio is here. + awaitingVoiceprint: number; + // Bytes of audio removed (through tier links: the bytes on the media tier). + bytesFreed: number; // Saved-store containers evicted because they rolled out of the keep-latest // window (the retention prune runs alongside the audio sweep). prunedSavedVideos: number; @@ -54,6 +61,80 @@ type CleanCandidate = { audioFiles: string[]; }; +// Where ONE video's audio leaves the sweep, or "candidate" when it passes every +// gate that needs no network. The ONE rule both the channel sweep and the +// per-video clean (cleanAudioForVideo) apply, in the same order, so the two can +// never disagree about what is safe to delete. Availability (verifyBeforeClean) +// is the last gate and is asked by the caller, for every candidate at once. +export type AudioCleanGate = + | "candidate" + | "no-transcript" + | "no-audio" + | "keep-latest" + | "do-not-clean" + | "awaiting-diarization" + | "awaiting-voiceprint"; + +export async function audioCleanGate( + videoDir: string, + id: string, + ctx: { keptIds: Set<string>; diarization: DiarizationSettings }, +): Promise<{ gate: AudioCleanGate; audioFiles: string[] }> { + const entries = await readdir(videoDir).catch(() => [] as string[]); + if (!entries.includes("transcript.json")) return { gate: "no-transcript", audioFiles: [] }; + const audioFiles = audioFilesToRemove(entries); + if (audioFiles.length === 0) return { gate: "no-audio", audioFiles }; + if (ctx.keptIds.has(id)) return { gate: "keep-latest", audioFiles }; + if (await isDoNotClean(videoDir)) return { gate: "do-not-clean", audioFiles }; + // While diarization is enabled, a transcribed video that still has audio but + // no diarization.json is NOT cleanable yet — its diarize job hasn't run. + // + // This guard is the whole reason deferring diarization to an async job is + // safe. Without it the sweep would delete the audio out from under a queued + // diarize job, silently and permanently: audio is the one input in this + // pipeline that cannot be regenerated, and the failure would leave no trace. + // + // A malformed sidecar reads as absent (loadDiarization), as it always has. + if (ctx.diarization.enabled) { + const record = entries.includes("diarization.json") + ? await loadDiarization(videoDir) + : null; + if (!record) return { gate: "awaiting-diarization", audioFiles }; + // The voice fingerprint is the part of a diarization that cannot be made + // again without the audio, so it is waited for too. + if (ctx.diarization.requireVoiceprints && !hasVoiceprints(record)) { + return { gate: "awaiting-voiceprint", audioFiles }; + } + } + return { gate: "candidate", audioFiles }; +} + +const SKIP_LOG: Partial<Record<AudioCleanGate, string>> = { + "keep-latest": "in keep-latest window", + "do-not-clean": "marked do not clean", + "awaiting-diarization": "awaiting diarization", + "awaiting-voiceprint": "awaiting voice fingerprint", +}; + +// Remove a candidate's audio files, through removeMediaFile (a tier link takes +// its bytes on the media tier with it). Returns the bytes freed. +async function removeCandidateAudio( + c: CleanCandidate, + log: (m: string) => void, +): Promise<{ removed: number; bytes: number }> { + let removed = 0; + let bytes = 0; + for (const f of c.audioFiles) { + // stat follows a tier link to the bytes it frees. + const size = await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + await removeMediaFile(c.videoDir, f); + log(`Removed ${c.id}/${f}`); + removed++; + bytes += size; + } + return { removed, bytes }; +} + export async function cleanAudioFromTranscribed({ channelSlug, paths, @@ -73,6 +154,8 @@ export async function cleanAudioFromTranscribed({ pinned: 0, unverified: 0, awaitingDiarization: 0, + awaitingVoiceprint: 0, + bytesFreed: 0, prunedSavedVideos: 0, prunedBytes: 0, }; @@ -90,16 +173,11 @@ export async function cleanAudioFromTranscribed({ let cleanedDirs = 0; let removedFiles = 0; + let bytesFreed = 0; let protectedCount = 0; let awaitingDiarization = 0; + let awaitingVoiceprint = 0; - // While diarization is enabled, a transcribed video that still has audio but - // no diarization.json is NOT cleanable yet — its diarize job hasn't run. - // - // This guard is the whole reason deferring diarization to an async job is - // safe. Without it the sweep would delete the audio out from under a queued - // diarize job, silently and permanently: audio is the one input in this - // pipeline that cannot be regenerated, and the failure would leave no trace. const diarization = getSettings().diarization; // --- Discover ------------------------------------------------------------- @@ -109,26 +187,13 @@ export async function cleanAudioFromTranscribed({ for (const id of dirs) { if (signal?.aborted) break; const videoDir = path.join(dataDir, id); - const entries = await readdir(videoDir).catch(() => [] as string[]); - if (!entries.includes("transcript.json")) continue; - const audioFiles = audioFilesToRemove(entries); - if (audioFiles.length === 0) continue; - if (keptIds.has(id)) { - log(`Skipped ${id} (in keep-latest window)`); - protectedCount++; - continue; - } - if (await isDoNotClean(videoDir)) { - log(`Skipped ${id} (marked do not clean)`); - protectedCount++; - continue; - } - if (diarization.enabled && !(await hasDiarization(videoDir))) { - log(`Skipped ${id} (awaiting diarization)`); - awaitingDiarization++; - continue; - } - candidates.push({ id, videoDir, audioFiles }); + const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); + if (gate === "no-transcript" || gate === "no-audio") continue; + if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); + if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; + else if (gate === "awaiting-diarization") awaitingDiarization++; + else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; + else candidates.push({ id, videoDir, audioFiles }); } // --- Verify --------------------------------------------------------------- @@ -155,28 +220,28 @@ export async function cleanAudioFromTranscribed({ for (const candidate of candidates) { if (signal?.aborted) break; if (excluded.has(candidate.id)) continue; - for (const f of candidate.audioFiles) { - // Through its link when tiered (release 17): the bytes on the media tier go too. - await removeMediaFile(candidate.videoDir, f); - log(`Removed ${candidate.id}/${f}`); - removedFiles++; - } + const out = await removeCandidateAudio(candidate, log); + removedFiles += out.removed; + bytesFreed += out.bytes; cleanedDirs++; } - const skipped = protectedCount + pinned + unverified + awaitingDiarization; + const skipped = + protectedCount + pinned + unverified + awaitingDiarization + awaitingVoiceprint; // Keep the historical wording when the gate had nothing to report, and break // the total down only when it would otherwise be misleading. // The diarization clause is appended only when it is non-zero, so the message // stays byte-identical for every install that doesn't use the capture lane — // a "0 awaiting diarization" on a box with diarization off is noise, and this // exact string is asserted in pre-clean-availability.spec. + // The voice-fingerprint clause follows the same rule. const diarNote = - awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : ""; + (awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : "") + + (awaitingVoiceprint > 0 ? `, ${awaitingVoiceprint} awaiting voice fingerprint` : ""); const skippedNote = skipped === 0 ? "" - : pinned === 0 && unverified === 0 && awaitingDiarization === 0 + : pinned === 0 && unverified === 0 && awaitingDiarization === 0 && awaitingVoiceprint === 0 ? ` Skipped ${skipped} (do not clean).` : ` Skipped ${skipped} (${protectedCount} protected, ${pinned} gone-from-source pinned, ${unverified} unverified${diarNote}).`; log( @@ -195,7 +260,83 @@ export async function cleanAudioFromTranscribed({ pinned, unverified, awaitingDiarization, + awaitingVoiceprint, + bytesFreed, prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, }; } + +export type CleanOneOptions = { + channelSlug: string; + paths: Paths; + videoId: string; + verifyAvailability?: boolean; + onLog?: (msg: string) => void; + signal?: AbortSignal; +}; + +export type CleanOneResult = { + // cleaned: the audio is gone. held: a gate kept it (`gate` says which). + // pinned / unverified: the availability check kept it (gone upstream — now + // do-not-clean — or could not be resolved). + outcome: "cleaned" | "held" | "pinned" | "unverified"; + gate?: AudioCleanGate; + removedFiles: number; + bytesFreed: number; +}; + +// THE PER-VIDEO HALF of cleanAudioFromTranscribed, for clean-after-capture: the +// same gates in the same order (audioCleanGate), the same availability check +// (a gone-upstream video is pinned, not deleted), the same removeMediaFile. +// Nothing about it is looser than the channel sweep; it only asks about one id. +// No saved-video prune: that is the channel sweep's retention pass. +export async function cleanAudioForVideo({ + channelSlug, + paths, + videoId, + verifyAvailability, + onLog, + signal, +}: CleanOneOptions): Promise<CleanOneResult> { + const log = onLog ?? ((m: string) => console.log(m)); + const held = (gate: AudioCleanGate): CleanOneResult => ({ + outcome: "held", + gate, + removedFiles: 0, + bytesFreed: 0, + }); + const videoDir = path.join(paths.channelsDir, channelSlug, "data", videoId); + const config = await readChannelConfig(paths, channelSlug); + const keptIds = await computeKeptVideoIds({ + paths, + channelSlug, + keepLatest: config?.keepLatest ?? 0, + }); + const diarization = getSettings().diarization; + const { gate, audioFiles } = await audioCleanGate(videoDir, videoId, { keptIds, diarization }); + if (gate !== "candidate") { + if (SKIP_LOG[gate]) log(`Kept ${videoId}'s audio (${SKIP_LOG[gate]})`); + return held(gate); + } + if (signal?.aborted) return held(gate); + const verify = verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean; + if (verify) { + const verdicts = await verifyBeforeClean({ + channelSlug, + paths, + candidateIds: [videoId], + onLog: log, + signal, + }); + if (verdicts.pinned.has(videoId) || verdicts.alreadyGone.has(videoId)) { + return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 }; + } + if (excludedIds(verdicts).has(videoId)) { + return { outcome: "unverified", removedFiles: 0, bytesFreed: 0 }; + } + } + if (signal?.aborted) return held(gate); + const out = await removeCandidateAudio({ id: videoId, videoDir, audioFiles }, log); + return { outcome: "cleaned", removedFiles: out.removed, bytesFreed: out.bytes }; +} diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts @@ -50,6 +50,7 @@ import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus"; import { + DIARIZATION_OPERATION_ID, DIGEST_OPERATION_ID, addOperationState, digestLaneFor, @@ -73,6 +74,11 @@ import { TranscribeError } from "./transcribeError"; import { readDigestContext } from "../lib/digestContext-server"; import type { StartWorkerUnitInput } from "./workerServer"; import { reacquireMediaFor, type ReacquireOutcome } from "./backfillReacquire"; +import { cleanAudioForVideo } from "./cleanAudioFromTranscribed"; +import { hasVoiceprints } from "../lib/diarization"; +import { loadDiarization } from "../lib/diarization-server"; +import { recordSpeakersFreed } from "../lib/speakersLedger-server"; +import { formatBytes } from "../lib/format"; import { batchRecencyComparator } from "./batchRecency"; import { digestGate, @@ -915,6 +921,10 @@ export type OperationUnitReport = { reacquireHandedOff: number; reacquireFailed: number; diskFloorHit: boolean; + // Clean-after-capture (diarization.cleanAfterCapture): audio removed right + // after this unit captured the video's speakers and voice fingerprints. + audioCleaned: number; + audioFreedBytes: number; }; function emptyReport( @@ -932,6 +942,8 @@ function emptyReport( reacquireHandedOff: 0, reacquireFailed: 0, diskFloorHit: false, + audioCleaned: 0, + audioFreedBytes: 0, }; } @@ -1062,9 +1074,53 @@ export async function runOperationUnit( } } } + // AFTER the finally: a re-acquired file has already been removed above, and + // this must never race that cleanup. + if (report.outcome === "done" && unit.op.id === DIARIZATION_OPERATION_ID && !aborted()) { + await cleanAfterCapture(run, unit, videoDir, report, log, signal); + } return report; } +// CLEAN AFTER CAPTURE. The per-video half of Clean audio, run the moment a +// diarization unit has captured a video's speakers — and only when its sidecar +// carries the voice fingerprints, because those are the part a deleted audio +// can never give back. Every gate of the channel sweep applies +// (cleanAudioForVideo → audioCleanGate + verifyBeforeClean); a gone-upstream +// video is pinned, not deleted. Live settings, read per unit, so switching it +// off mid-run takes effect on the next video. Never fails the unit: the +// capture succeeded whatever happens here. +async function cleanAfterCapture( + run: OperationRun, + unit: OperationUnit, + videoDir: string, + report: OperationUnitReport, + log: (m: string) => void, + signal: AbortSignal, +): Promise<void> { + if (!getSettings().diarization.cleanAfterCapture) return; + try { + if (!hasVoiceprints(await loadDiarization(videoDir))) { + log(`Kept ${unit.videoId}'s audio: its diarization has no voice fingerprints yet.`); + return; + } + const out = await cleanAudioForVideo({ + channelSlug: unit.channelSlug, + paths: run.paths, + videoId: unit.videoId, + onLog: log, + signal, + }); + if (out.outcome !== "cleaned") return; + report.audioCleaned = 1; + report.audioFreedBytes = out.bytesFreed; + await recordSpeakersFreed(run.paths, out.bytesFreed); + log(`Freed ${formatBytes(out.bytesFreed)} of audio from ${unit.videoId} (speakers captured).`); + } catch (err) { + log(`Clean after capture for ${unit.videoId} failed: ${(err as Error)?.message ?? String(err)}`); + } +} + // The work itself: a tagged remote executor when one is free, else the llm // fan-out for the call-bound operations, else the local run. // @@ -1511,6 +1567,9 @@ export type OperationBatchResult = { reacquireHandedOff: number; reacquireFailed: number; diskFloorHit: boolean; + // Clean-after-capture: videos whose audio was removed, and the bytes. + audioCleaned: number; + audioFreedBytes: number; // Digest: mirrors that received the canonical member's digest, and mirrors // the alignment gate refused. A refusal is a normal outcome, not an error. shared: number; @@ -1541,6 +1600,8 @@ export function emptyOperationBatchResult(): OperationBatchResult { reacquireHandedOff: 0, reacquireFailed: 0, diskFloorHit: false, + audioCleaned: 0, + audioFreedBytes: 0, shared: 0, misaligned: 0, engineCalls: 0, @@ -2028,6 +2089,8 @@ function foldUnitReport( result.reacquireCleaned += report.reacquireCleaned; result.reacquireHandedOff += report.reacquireHandedOff; result.reacquireFailed += report.reacquireFailed; + result.audioCleaned += report.audioCleaned; + result.audioFreedBytes += report.audioFreedBytes; if (report.diskFloorHit) result.diskFloorHit = true; switch (report.outcome) { case "done": diff --git a/common/controller/operationJobs.ts b/common/controller/operationJobs.ts @@ -25,6 +25,7 @@ // without this module knowing Next exists. The digest runner already had one. import type { Paths } from "../lib/paths"; +import { formatBytes } from "../lib/format"; import { getSettings } from "../lib/settings"; import { runManagedFunction, @@ -143,6 +144,9 @@ export async function runBackfillChannelJob( ? `, ${batch.reacquireHandedOff} handed to auto-transcribe` : "") : "") + + (batch.audioCleaned > 0 + ? `; freed ${formatBytes(batch.audioFreedBytes)} of audio from ${batch.audioCleaned} video(s) after capture` + : "") + (batch.diskFloorHit ? " (stopped re-acquiring at the disk floor)" : "") + (batch.stoppedForRelocation ? " (stopped: a relocation is in flight)" diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -333,6 +333,8 @@ export type DiarizationSettings = { sortformerModel: string; concurrency: number; maxAudioHours: number; + cleanAfterCapture: boolean; + requireVoiceprints: boolean; }; export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = { @@ -435,6 +437,25 @@ export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = { "lands: windowing divides per-window n by the window count, so the " + "matrix falls by its square, and the cap stops being needed rather than" + " being tuned.", + cleanAfterCapture: + "Delete a video's audio as soon as the Speakers lane has captured it.\n\n" + + "When ON, a diarization unit that finishes with a complete set of voice " + + "fingerprints (diarization.json `voiceprints`) is followed at once by the " + + "per-video half of Clean audio, with every one of its gates: a " + + "transcript.json, outside the keep-latest window, not marked do-not-clean, " + + "and the availability check (a video gone upstream is pinned, not " + + "deleted). The bytes freed are logged and counted in the speakers " + + "readout. OFF by default: nothing deletes audio until the operator says " + + "so.", + requireVoiceprints: + "Hold a video's audio until its diarization.json carries voice " + + "fingerprints.\n\n" + + "A fingerprint is the one part of a diarization that cannot be made " + + "again once the audio is gone, so with this ON (the default) Clean audio " + + "skips a diarized video whose sidecar has none, saying \"awaiting voice " + + "fingerprint\", and the Speakers lane adds them from the existing turns. " + + "Applies only while diarization is enabled, like the diarization guard " + + "itself.", }; // Configuration for the derived-corpus digest layer. Local-first by decision: @@ -1558,6 +1579,8 @@ export function defaultDiarization(): DiarizationSettings { // stays honest about what it does, for a machine smaller than this one or a // recording longer than anything measured here. maxAudioHours: 0, + cleanAfterCapture: false, + requireVoiceprints: true, }; } @@ -1600,6 +1623,9 @@ export function sanitizeDiarization(value: unknown): DiarizationSettings { r.maxAudioHours >= 0 ? r.maxAudioHours : d.maxAudioHours, + cleanAfterCapture: r.cleanAfterCapture === true, + // ON unless explicitly switched off: the safe direction is to keep audio. + requireVoiceprints: r.requireVoiceprints !== false, }; } diff --git a/common/lib/speakersLedger-server.ts b/common/lib/speakersLedger-server.ts @@ -0,0 +1,100 @@ +// What the Speakers lane has freed since it was last started: the "freed this +// run" half of the speakers readout (controller/speakersReadout.ts). +// +// A file, not a counter in the runner: the lane runs for weeks across editor +// restarts, and a number that resets on every restart would say "freed 0 GB" +// the morning after a night that freed forty. One small JSON at the corpus +// root, read-modify-written under the in-process file lock; the lane runs at +// concurrency 1 and the per-channel batch shares its queue, so there is one +// writer at a time anyway. +// +// "This run" begins when the operator presses Work through speakers on a lane +// that was paused or disarmed (startSpeakersRun); Pause does not reset it, so a +// paused-then-resumed night is still one run. + +import path from "node:path"; +import type { Paths } from "./paths"; +import { + readJsonFile, + withJsonFileLock, + writeJsonAtomic, +} from "./jsonFile-server"; + +export const SPEAKERS_LEDGER_FILENAME = "speakers-run.json"; + +export type SpeakersLedger = { + version: 1; + // ISO 8601: when this run began (null before the first one). + startedAt: string | null; + // Audio removed by clean-after-capture this run. + freedBytes: number; + freedVideos: number; + // ISO 8601 of the last change. + updatedAt: string | null; +}; + +export function emptySpeakersLedger(): SpeakersLedger { + return { version: 1, startedAt: null, freedBytes: 0, freedVideos: 0, updatedAt: null }; +} + +export function speakersLedgerPath(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, SPEAKERS_LEDGER_FILENAME); +} + +function coerce(value: unknown): SpeakersLedger { + const v = value as Partial<SpeakersLedger> | null; + const n = (x: unknown) => (typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : 0); + const s = (x: unknown) => (typeof x === "string" ? x : null); + if (!v || typeof v !== "object") return emptySpeakersLedger(); + return { + version: 1, + startedAt: s(v.startedAt), + freedBytes: n(v.freedBytes), + freedVideos: n(v.freedVideos), + updatedAt: s(v.updatedAt), + }; +} + +export async function readSpeakersLedger( + paths: Pick<Paths, "transcriptsDir">, +): Promise<SpeakersLedger> { + const read = await readJsonFile(speakersLedgerPath(paths)); + return read.ok ? coerce(read.value) : emptySpeakersLedger(); +} + +async function update( + paths: Pick<Paths, "transcriptsDir">, + fn: (l: SpeakersLedger) => SpeakersLedger, +): Promise<SpeakersLedger> { + const file = speakersLedgerPath(paths); + return withJsonFileLock(file, async () => { + const next = fn(await readSpeakersLedger(paths)); + await writeJsonAtomic(file, next, { indent: 2 }); + return next; + }); +} + +// A new run: the freed tally starts again from zero. +export function startSpeakersRun( + paths: Pick<Paths, "transcriptsDir">, + now: Date = new Date(), +): Promise<SpeakersLedger> { + const at = now.toISOString(); + return update(paths, () => ({ ...emptySpeakersLedger(), startedAt: at, updatedAt: at })); +} + +// One video's audio freed by clean-after-capture. +export function recordSpeakersFreed( + paths: Pick<Paths, "transcriptsDir">, + bytes: number, + now: Date = new Date(), +): Promise<SpeakersLedger> { + const at = now.toISOString(); + return update(paths, (l) => ({ + ...l, + startedAt: l.startedAt ?? at, + freedBytes: l.freedBytes + Math.max(0, bytes), + freedVideos: l.freedVideos + 1, + updatedAt: at, + })); +} diff --git a/scripts/diarize-sherpa.test.mjs b/scripts/diarize-sherpa.test.mjs @@ -59,7 +59,7 @@ function writeWav(file, plan, total = 14) { writeFileSync(file, Buffer.concat([h, pcm])); } -const env = { ...process.env, PYTHONPATH: STUB }; +const env = { ...process.env, PYTHONPATH: STUB, PYTHONDONTWRITEBYTECODE: "1" }; function engine(args) { return JSON.parse(execFileSync("python3", [SCRIPT, ...args], { env, stdio: ["ignore", "pipe", "pipe"] }).toString()); diff --git a/settings.json.example b/settings.json.example @@ -183,7 +183,9 @@ "sortformerBin": "", "sortformerModel": "", "concurrency": 1, - "maxAudioHours": 0 + "maxAudioHours": 0, + "cleanAfterCapture": false, + "requireVoiceprints": true }, "backfill": { "concurrency": 1,