// An article's iterations, on the video side (release 27 S7): what a new // iteration's video project keeps from its parent's, and the bytes the // projects of one article share. // // A project is `//i/` (common/lib/report/ // iterations.ts projectOf, D1): video.manifest.json and out/. Two things here, // ported from the stopgap (~/reports/local-reports seed_version.py and // dedupe_media.py): // // seedFromParent a card of the new manifest with no narration takes its // parent card's (matched by id, else by heading), and the // parent's synthesized voices are hard-linked in, so // narrate-via-editor finds them kept and no voice is made // again; a card whose words changed gets new audio // dedupeMedia byte-identical files across the projects are made one // file (hard links) — ONLY the files the tools never write // in place, so a later build of one iteration can never // write through a link into another's: a segment // (`out//segments/*.mp4`; build-video unlinks a // linked segment before it rebuilds it, detachSegmentFiles) // and a voice (`out/narration/*.{wav,json}`, named by the // content key of the words and the voice, never rewritten) // // Plain node: no TypeScript, no Next. Server-only (node:fs). import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST_NAME = "video.manifest.json"; // Below this a segment is not worth a hash (a voice always is: it is small // and there are many). export const DEDUPE_MIN_BYTES = 64 * 1024; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const headKey = (c) => String(c?.heading ?? "").trim().toLowerCase(); async function readJson(file) { return JSON.parse(await readFile(file, "utf8")); } // Replace `file` whole: a temp beside it, then a rename. async function writeJsonAtomic(file, value) { const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } /** * Carry what a new iteration's video project can keep from its parent's. * * @param {string} parentDir the parent iteration's project (its manifest and out/) * @param {string} newDir the new project, its manifest freshly made * @returns {Promise<{ carried: number, linked: number }>} */ export async function seedFromParent(parentDir, newDir) { const parent = await readJson(path.join(parentDir, MANIFEST_NAME)); const manifestFile = path.join(newDir, MANIFEST_NAME); const next = await readJson(manifestFile); const narrated = (parent.timeline ?? []).filter((c) => c?.type === "card" && isObj(c.narration) && c.narration.text); const byId = new Map(narrated.map((c) => [c.id, c])); const byHead = new Map(); for (const c of narrated) if (headKey(c) && !byHead.has(headKey(c))) byHead.set(headKey(c), c); let carried = 0; for (const c of next.timeline ?? []) { if (c?.type !== "card" || (isObj(c.narration) && c.narration.text)) continue; const src = byId.get(c.id) ?? (headKey(c) ? byHead.get(headKey(c)) : undefined); if (!src) continue; c.narration = { ...src.narration }; // A narrated card is timed by its voice. if (src.seconds === "auto") c.seconds = "auto"; carried += 1; } if (carried > 0) await writeJsonAtomic(manifestFile, next); let linked = 0; const from = path.join(parentDir, "out", "narration"); const to = path.join(newDir, "out", "narration"); let names = []; try { names = await readdir(from); } catch { names = []; } const voices = names.filter((f) => f.endsWith(".wav") || f.endsWith(".json")); if (voices.length > 0) await mkdir(to, { recursive: true }); for (const f of voices) { const src = path.join(from, f); const dst = path.join(to, f); if (!(await lstat(src).catch(() => null))?.isFile()) continue; if (await lstat(dst).catch(() => null)) continue; await link(src, dst); linked += 1; } return { carried, linked }; } // Every file dedupe may link under one project: its segments and its voices. async function candidates(projectDir) { const out = []; const outDir = path.join(projectDir, "out"); const files = async (dir, test) => { let names = []; try { names = await readdir(dir); } catch { return; } for (const f of names) { if (!test(f)) continue; const p = path.join(dir, f); const st = await lstat(p).catch(() => null); if (st?.isFile()) out.push(p); } }; let variants = []; try { variants = (await readdir(outDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); } catch { variants = []; } for (const v of variants) { if (v === "narration") continue; await files(path.join(outDir, v, "segments"), (f) => f.endsWith(".mp4")); } await files(path.join(outDir, "narration"), (f) => f.endsWith(".wav") || f.endsWith(".json")); return out; } function sha256(file) { return new Promise((resolve, reject) => { const h = createHash("sha256"); createReadStream(file) .on("error", reject) .on("data", (b) => h.update(b)) .on("end", () => resolve(h.digest("hex"))); }); } /** * Hard-link byte-identical segments and voices across the projects under * `root` (each subdirectory a project: an article's `i1/`, `i2/`, …). Same * filesystem only. A file already one with its twin is left as it is. * * @param {string} root * @param {{ dry?: boolean }} [opts] * @returns {Promise<{ links: number, freedBytes: number }>} */ export async function dedupeMedia(root, { dry = false } = {}) { let projects = []; try { projects = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort(); } catch { return { links: 0, freedBytes: 0 }; } const bySize = new Map(); for (const p of projects) { for (const file of await candidates(path.join(root, p))) { const st = await stat(file); if (st.size < DEDUPE_MIN_BYTES && !file.endsWith(".wav")) continue; const key = `${st.dev}:${st.size}`; if (!bySize.has(key)) bySize.set(key, []); bySize.get(key).push(file); } } let links = 0; let freedBytes = 0; for (const [key, files] of bySize) { if (files.length < 2) continue; const size = Number(key.split(":")[1]); const keep = new Map(); for (const file of files) { const digest = await sha256(file); const first = keep.get(digest); if (!first) { keep.set(digest, file); continue; } if ((await stat(first)).ino === (await stat(file)).ino) continue; if (!dry) { const tmp = `${file}.dedupe-tmp`; await rm(tmp, { force: true }); await link(first, tmp); await rename(tmp, file); } links += 1; freedBytes += size; } } return { links, freedBytes }; }