Archilyzer · Source

archilyzer

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

commit 908b3568ca357fb7f7cc9e369c8875648706d59a
parent 2106d96cc14adba19f7d5a5a1605c305339c4a6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 22:54:14 -0400

umtool: the phrase seed takes a cap -- N instances spread across the years (release 35 O1, slice 2)

`umtool new … --seed phrase --max N`, the New project form's Max and the
phrase finder's Max clips keep N instances: each year's share in proportion
to its count, at least one for every year that has any (largest-remainder
rounding; fewer than the years: one each for N years spread across them),
chronological, within a year the ones without a speakerCheck first, picked
evenly through the year. capInstances in common/lib/montage/phraseScan.mjs.
phrase-scan.json gains `max` and `skippedByCap` (the instance shape); the
README checklist and the scaffold's notes name the cap. No max: the manifest,
README and phrase-scan.json keys are what they were.

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

Diffstat:
Mcommon/lib/montage/phraseScan.d.mts | 4++++
Mcommon/lib/montage/phraseScan.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/montage/phraseScan.test.ts | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/bin/umtool.mjs | 6++++--
Mumtool/components/NewProjectMenu.tsx | 7+++++++
Mumtool/components/tools/PhraseFinder.tsx | 17++++++++++++++++-
Mumtool/lib/projects/scaffold.mjs | 40+++++++++++++++++++++++++++++++---------
Mumtool/lib/projects/scaffold.ts | 3+++
Mumtool/lib/scaffold-phrase.test.mjs | 45+++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 249 insertions(+), 13 deletions(-)

diff --git a/common/lib/montage/phraseScan.d.mts b/common/lib/montage/phraseScan.d.mts @@ -71,6 +71,10 @@ export function phraseScanMany(opts: { }): Promise<PhraseScanManyResult[]>; export { phraseSourceOf, phraseWords, wordsPhraseSource } from "./phraseSource.mjs"; export function niceDate(s: unknown): string; +export function capInstances<T extends { date?: string | null; speakerCheck?: boolean }>( + instances: T[], + max: number | null | undefined, +): { kept: T[]; skipped: T[] }; export function instancesAsClips( instances: PhraseInstance[], opts?: { pad?: number; idPrefix?: string }, diff --git a/common/lib/montage/phraseScan.mjs b/common/lib/montage/phraseScan.mjs @@ -372,6 +372,84 @@ function alternateOf(h) { } /** + * The cap (release 35, `max`): N of the instances, spread across the years in + * proportion to each year's count — at least one for every year that has any + * (largest-remainder rounding), or, when N is fewer than the years, one each + * for N years spread across them. Within a year the instances without a + * `speakerCheck` come first, picked evenly through the year (not its first + * few). `kept` and `skipped` are both chronological (the order given); an + * instance with no date is its own year, last. `max` absent, not a positive + * whole number, or ≥ the count → everything kept. + * + * @template T + * @param {T[]} instances chronological + * @param {number | null | undefined} max + * @returns {{ kept: T[], skipped: T[] }} + */ +export function capInstances(instances, max) { + const list = Array.isArray(instances) ? instances : []; + if (!(Number.isInteger(max) && max > 0) || max >= list.length) return { kept: [...list], skipped: [] }; + const yearOf = (i) => /^(\d{4})/.exec(String(i?.date ?? ""))?.[1] ?? "~"; + const byYear = new Map(); + list.forEach((inst, k) => { + const y = yearOf(inst); + if (!byYear.has(y)) byYear.set(y, []); + byYear.get(y).push(k); + }); + const years = [...byYear.keys()].sort(); + const alloc = new Map(years.map((y) => [y, 0])); + if (max < years.length) { + for (const k of spreadIndices(years.length, max)) alloc.set(years[k], 1); + } else { + const quota = new Map(years.map((y) => [y, (max * byYear.get(y).length) / list.length])); + for (const y of years) alloc.set(y, Math.min(byYear.get(y).length, Math.max(1, Math.floor(quota.get(y))))); + let sum = years.reduce((n, y) => n + alloc.get(y), 0); + // How far a year is under its quota: at its floor, the remainder. + const under = (y) => quota.get(y) - alloc.get(y); + while (sum < max) { + // The largest remainder first (ties: the bigger year, then the earlier). + const y = years + .filter((y) => alloc.get(y) < byYear.get(y).length) + .sort((a, b) => under(b) - under(a) || byYear.get(b).length - byYear.get(a).length || a.localeCompare(b))[0]; + alloc.set(y, alloc.get(y) + 1); + sum++; + } + while (sum > max) { + // The ≥ 1 floor overshot: take back from the most over-allotted year that keeps one. + const y = years + .filter((y) => alloc.get(y) > 1) + .sort((a, b) => under(a) - under(b) || byYear.get(b).length - byYear.get(a).length || b.localeCompare(a))[0]; + alloc.set(y, alloc.get(y) - 1); + sum--; + } + } + const keep = new Set(); + for (const y of years) { + const n = alloc.get(y); + if (!n) continue; + const ks = byYear.get(y); + const clean = ks.filter((k) => !list[k]?.speakerCheck); + const checked = ks.filter((k) => list[k]?.speakerCheck); + if (n <= clean.length) for (const j of spreadIndices(clean.length, n)) keep.add(clean[j]); + else { + for (const k of clean) keep.add(k); + for (const j of spreadIndices(checked.length, n - clean.length)) keep.add(checked[j]); + } + } + const kept = []; + const skipped = []; + list.forEach((inst, k) => (keep.has(k) ? kept : skipped).push(inst)); + return { kept, skipped }; +} + +/** `n` of `0..len-1`, evenly spread (the middle of each of n equal stretches). */ +function spreadIndices(len, n) { + const out = []; + for (let j = 0; j < n; j++) out.push(Math.min(len - 1, Math.floor(((j + 0.5) * len) / n))); + return out; +} + +/** * Many phrases in ONE pass over the transcripts (release 34): each cue file is * read and parsed once, its text joined once, and every phrase matched in it. * Each phrase's result is what `phraseScan` returns for it alone — the same diff --git a/common/lib/montage/phraseScan.test.ts b/common/lib/montage/phraseScan.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; -import { dayNumber, hitsInCues, instancesAsClips, niceDate, phraseRegExp, phraseScan } from "./phraseScan.mjs"; +import { capInstances, dayNumber, hitsInCues, instancesAsClips, niceDate, phraseRegExp, phraseScan } from "./phraseScan.mjs"; const PHRASE = String.raw`\bslow[\s,.\-]+news\b(?:[\s,.\-]+(?:day|week|cycle))?`; @@ -110,3 +110,63 @@ test("dates and the phrase", () => { assert.equal(dayNumber("nope"), null); assert.throws(() => phraseRegExp(" "), /phrase is required/); }); + +// Release 35: the cap. N instances spread across years in proportion to each +// year's count (≥ 1 per year that has any; largest remainder), chronological, +// the ones without a speakerCheck first within a year, spread through it. +type I = { id: string; date: string | null; speakerCheck?: boolean }; +const inst = (spec: Record<string, number>, checked: string[] = []): I[] => { + const out: I[] = []; + for (const [year, n] of Object.entries(spec)) { + for (let k = 0; k < n; k++) { + const id = `${year}-${String(k).padStart(2, "0")}`; + out.push({ id, date: year === "none" ? null : `${year}${String(1 + (k % 12)).padStart(2, "0")}15`, speakerCheck: checked.includes(id) }); + } + } + return out.sort((a, b) => String(a.date ?? "~").localeCompare(String(b.date ?? "~")) || a.id.localeCompare(b.id)); +}; +const years = (l: I[]) => l.reduce<Record<string, number>>((m, i) => ((m[i.id.slice(0, 4)] = (m[i.id.slice(0, 4)] ?? 0) + 1), m), {}); + +test("capInstances: proportional to each year, at least one each, largest remainder, chronological", () => { + const all = inst({ 2019: 2, 2020: 30, 2021: 10, 2022: 1, 2023: 7 }); + const { kept, skipped } = capInstances(all, 10); + assert.equal(kept.length, 10); + assert.equal(skipped.length, all.length - 10); + // 50 instances, 10 kept: quotas 0.4, 6, 2, 0.2, 1.4 -> floors with a floor of one 1, 6, 2, 1, 1 = 11 -> one back + // from a year above one at its quota (2020 and 2021 tie at 0; the bigger year gives it up). + assert.deepEqual(years(kept), { 2019: 1, 2020: 5, 2021: 2, 2022: 1, 2023: 1 }); + const order = all.map((i) => i.id); + const pos = (l: I[]) => l.map((i) => order.indexOf(i.id)); + assert.deepEqual(pos(kept), [...pos(kept)].sort((a, b) => a - b), "kept is chronological"); + assert.deepEqual(pos(skipped), [...pos(skipped)].sort((a, b) => a - b), "skipped is chronological"); + assert.deepEqual(new Set([...kept, ...skipped].map((i) => i.id)), new Set(order)); + // Largest remainder: 20 of the same 50 -> 0.8, 12, 4, 0.4, 2.8 -> 1, 12, 4, 1, 2 = 20. + assert.deepEqual(years(capInstances(all, 20).kept), { 2019: 1, 2020: 12, 2021: 4, 2022: 1, 2023: 2 }); + // 24 -> 0.96, 14.4, 4.8, 0.48, 3.36 -> 1, 14, 4, 1, 3 = 23, +1 to 2021 (.8 under). + assert.deepEqual(years(capInstances(all, 24).kept), { 2019: 1, 2020: 14, 2021: 5, 2022: 1, 2023: 3 }); +}); + +test("capInstances: spread through the year, not its first few; the speaker-checked last", () => { + const all = inst({ 2020: 12 }, ["2020-00", "2020-06"]); + const { kept } = capInstances(all, 3); + // Ten clean ones, three spread through them (the middle of each third): clean #1, #5, #8. + assert.deepEqual(kept.map((i) => i.id), ["2020-02", "2020-07", "2020-10"]); + assert.ok(kept.every((i) => !i.speakerCheck)); + // More asked than clean: every clean one, then the checked. + const few = inst({ 2021: 4 }, ["2021-00", "2021-01", "2021-02"]); + // The one clean (03) and the middle of the three checked (01), chronological. + assert.deepEqual(capInstances(few, 2).kept.map((i) => i.id), ["2021-01", "2021-03"]); +}); + +test("capInstances: fewer than the years -> one each for years spread across them; no cap -> all", () => { + const all = inst({ 2016: 3, 2017: 3, 2018: 3, 2019: 3, 2020: 3, 2021: 3 }); + assert.deepEqual(Object.keys(years(capInstances(all, 3).kept)), ["2017", "2019", "2021"]); + for (const max of [undefined, null, 0, -1, 2.5, 18, 100]) { + const r = capInstances(all, max as number); + assert.equal(r.kept.length, 18); + assert.deepEqual(r.skipped, []); + } + // A dateless instance is its own year, last. + const mixed = [...inst({ 2020: 4 }), { id: "none-00", date: null }]; + assert.ok(capInstances(mixed, 2).kept.some((i) => i.id === "none-00")); +}); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -707,7 +707,8 @@ function usage() { " --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]: every time", " the phrase was said in those channels' transcripts, chronological, cut from the --prefer", " channel's copy where it has one (a twin by date and duration); a context matching --exclude", - " is left out; the scan beside the manifest as phrase-scan.json", + " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances", + " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", " umtool doctor [--json] exit 1 if the report pipeline is missing a tool", " or the media root is set and not there; the roots, and a leftover old cache", @@ -1122,7 +1123,7 @@ async function cmdNew() { "usage: umtool new <slug> [--kind report-video] [--title T]\n" + " [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" + " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" + - " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]]", + " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]", ); } const kind = val("--kind") ?? "report-video"; @@ -1147,6 +1148,7 @@ async function cmdNew() { exclude: val("--exclude") ?? null, } : {}), + ...(val("--max") != null ? { max: Number(val("--max")) } : {}), }); } catch (e) { die(e?.message ?? String(e)); diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx @@ -32,6 +32,7 @@ import { useHydrated } from "@/components/ui/use-hydrated"; // the frames seed's length budget is [data-new-target], seconds. // Release 33: with no source, [data-new-seed] offers "a phrase across channels" // ([data-new-phrase], [data-new-channels], [data-new-prefer], [data-new-exclude]). +// Release 35: [data-new-max] caps the reel at N instances spread across the years. type Brand = { id: string; label: string }; type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null }; @@ -46,6 +47,7 @@ const FIELD_HINT: Record<string, string> = { channels: "the channel slugs to scan, separated by commas", prefer: "the channel to cut from where it holds a copy of the same stream (optional)", exclude: "leave out a hit whose surrounding words match this regular expression (optional)", + max: "keep at most this many instances, spread across the years in proportion (optional)", brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card", }; @@ -92,6 +94,7 @@ export default function NewProjectMenu({ const [channels, setChannels] = useState(""); const [prefer, setPrefer] = useState(""); const [exclude, setExclude] = useState(""); + const [max, setMax] = useState(""); const [target, setTarget] = useState("240"); // What the video can be seeded from (null: not asked yet, or not a video). const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean } | null>(null); @@ -136,6 +139,7 @@ export default function NewProjectMenu({ if (fields.includes("siteOrigin") && origin.trim()) body.siteOrigin = origin.trim(); if (asksPhrase && seed === "phrase") { Object.assign(body, { seed, phrase, channels, prefer, exclude }); + if (max.trim()) body.max = Number(max.trim()); } else if (fields.includes("seed") && seed && seed !== "phrase" && looksLikeVideo) { body.seed = seed; if (seed === "frames") body.target = Number(target); @@ -312,6 +316,9 @@ export default function NewProjectMenu({ <Field label="Exclude"> <Input value={exclude} onChange={(e) => setExclude(e.target.value)} placeholder="optional" aria-label={`exclude — ${FIELD_HINT.exclude}`} title={FIELD_HINT.exclude} data-new-exclude className="w-44" /> </Field> + <Field label="Max"> + <Input value={max} onChange={(e) => setMax(e.target.value)} inputMode="numeric" placeholder="all" aria-label={`max — ${FIELD_HINT.max}`} title={FIELD_HINT.max} data-new-max className="w-20" /> + </Field> </> )} {asksSeed && seed === "frames" && ( diff --git a/umtool/components/tools/PhraseFinder.tsx b/umtool/components/tools/PhraseFinder.tsx @@ -526,6 +526,8 @@ function Sample({ s, names }: { s: PhraseSample; names: Map<string, string> }) { function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRowView }) { const router = useRouter(); const [slug, setSlug] = useState(() => montageSlug(row.label ?? row.text)); + // The cap (release 35): N instances spread across the years; empty = all. + const [max, setMax] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const empty = row.summary.instances === 0; @@ -547,6 +549,7 @@ function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRow prefer: scan.spec.prefer, exclude: scan.spec.exclude, scan: { id: scan.id, row: row.id }, + ...(max.trim() ? { max: Number(max.trim()) } : {}), }), }); const j = await r.json(); @@ -569,7 +572,19 @@ function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRow <Field label="Montage project"> <Input value={slug} onChange={(e) => setSlug(e.target.value)} aria-label="montage project slug" className="w-72" data-phrase-slug="" /> </Field> - <Button type="submit" disabled={busy || empty || !slug.trim()} title={empty ? "nothing to cut" : `${row.summary.instances} clips, chronological`} data-phrase-create=""> + <Field label="Max clips"> + <Input + value={max} + onChange={(e) => setMax(e.target.value)} + inputMode="numeric" + placeholder="all" + aria-label="max clips — at most this many, spread across the years in proportion" + title="at most this many, spread across the years in proportion (empty: all)" + className="w-20" + data-phrase-max="" + /> + </Field> + <Button type="submit" disabled={busy || empty || !slug.trim()} title={empty ? "nothing to cut" : `${max.trim() && Number(max) < row.summary.instances ? `${Number(max)} of ${row.summary.instances}` : row.summary.instances} clips, chronological`} data-phrase-create=""> {busy ? "Creating…" : "Create montage"} </Button> {error && ( diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -7,7 +7,7 @@ import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { BRAND_IDS } from "umtool-report-to-video/brand-ids"; import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut"; -import { instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; +import { capInstances, instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs"; export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; @@ -211,6 +211,15 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po return framesCut(scan, { channel, video, cues, stats, ...(target !== undefined ? { target } : {}) }); } +// The most clips a phrase seed's cap (`--max`) can ask for. +export const MAX_PHRASE_CAP = 10000; + +/** The cap, said once for the README and the scaffold's notes. */ +const capNote = (max, kept, found) => + kept < found + ? `Capped at ${max} (--max): ${kept} of ${found} instance(s) kept, spread across the years in proportion; the other ${found - kept} are in phrase-scan.json ("skippedByCap")` + : `Capped at ${max} (--max): all ${found} instance(s) kept`; + /** * Write the project. Refuses an existing directory and a slug that will not * route; everything else it cannot know is written EMPTY so `check` blocks. @@ -228,10 +237,13 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po * 34) is that answer already made — the phrase finder's search with these * same settings (phraseScanMany answers each phrase as phraseScan does) — so a * project is seeded from what the page showed without reading the corpus again. + * `max` (release 35) caps the reel at N instances spread across the years + * (common/lib/montage/phraseScan.mjs `capInstances`); the rest are listed in + * phrase-scan.json as `skippedByCap`. No `max`: the output is what it was. * - * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null }} args + * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null }} args */ -export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null }) { +export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -262,9 +274,13 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site if (!list.length) throw new Error("--seed phrase needs --channels (and optionally --prefer)"); for (const c of list) if (!CHANNEL_SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`); if (given && !(Array.isArray(given.instances) && Array.isArray(given.hits) && Array.isArray(given.dropped))) throw new Error("a phrase scan is { instances, hits, dropped, scanned }"); - } else if (phrase || channels?.length || prefer || exclude || given) { - throw new Error("--phrase, --channels, --prefer and --exclude go with --seed phrase"); + } else if (phrase || channels?.length || prefer || exclude || given || (max !== null && max !== undefined)) { + throw new Error("--phrase, --channels, --prefer, --exclude and --max go with --seed phrase"); + } + if (max !== null && max !== undefined && !(Number.isInteger(max) && max >= 1 && max <= MAX_PHRASE_CAP)) { + throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`); } + const capped = max !== null && max !== undefined; if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); if (target !== undefined && seed !== "frames") throw new Error("--target is the frames seed's length budget: give it with --seed frames"); if (target !== undefined && !(Number.isFinite(target) && target >= 10 && target <= 3600)) { @@ -329,7 +345,9 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site let phraseSeeded = null; if (seed === "phrase") { const chans = (channels ?? []).map((c) => String(c).trim()).filter(Boolean); - const scan = given ?? (await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null })); + const found = given ?? (await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null })); + const { kept, skipped } = capInstances(found.instances, capped ? max : null); + const scan = capped ? { ...found, instances: kept, skippedByCap: skipped, found: found.instances.length } : found; doc.timeline = instancesAsClips(scan.instances); doc.render.transition = 0; // The window already carries its margin (2.5 s each side), and the editor @@ -340,7 +358,8 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site else if (chans.length === 1) doc.provenance.channelSlug = chans[0]; seeded = doc.timeline.length; phraseSeeded = scan; - notes.push(`${scan.scanned} transcript(s) read, ${scan.hits.length} hit(s), ${scan.instances.length} instance(s)`); + notes.push(`${scan.scanned} transcript(s) read, ${scan.hits.length} hit(s), ${capped ? found.instances.length : scan.instances.length} instance(s)`); + if (capped) notes.push(capNote(max, scan.instances.length, found.instances.length)); const placed = scan.instances.filter((i) => i.via).length; if (placed) notes.push(`${placed} hit(s) from another channel placed in the ${prefer} copy by their words — check the cut lands on the phrase`); if (scan.dropped.length) notes.push(`${scan.dropped.length} left out by --exclude (phrase-scan.json, "dropped")`); @@ -360,8 +379,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8"); if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8"); if (phraseSeeded) { - const { instances, dropped, hits, scanned } = phraseSeeded; - const scanDoc = { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, scanned, hits: hits.length, instances, dropped }; + const { instances, dropped, hits, scanned, skippedByCap } = phraseSeeded; + const scanDoc = capped + ? { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, max, scanned, hits: hits.length, instances, skippedByCap, dropped } + : { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, scanned, hits: hits.length, instances, dropped }; await writeFile(path.join(dir, "phrase-scan.json"), JSON.stringify(scanDoc, null, 1) + "\n", "utf8"); } @@ -390,6 +411,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site "Every window below is a place the transcripts say the phrase: the cues it was", "said in, chronological. A transcript can mishear and a line can be someone", "else's (a co-host, chat read out): listen to each in the bench before you keep it.", + ...(capped ? ["", `${capNote(max, phraseSeeded.instances.length, phraseSeeded.found)}.`] : []), "", ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.onscreen?.subtitle ?? ""} ${c.channel}/${c.video} ${c.cutStart}–${c.cutEnd} "${c.onscreen?.title ?? ""}"${c.note ? ` (${c.note})` : ""}`), ); diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts @@ -28,6 +28,8 @@ export type NewProjectBody = { // The phrase finder's search these settings came from (release 34): the // project is seeded from its answer, not from a second read of the corpus. scan?: { id?: string; row?: string } | null; + // The phrase seed's cap (release 35): N instances spread across the years. + max?: number | string | null; }; /** @@ -77,6 +79,7 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str prefer: body.prefer || null, exclude: body.exclude || null, ...(scan ? { scan } : {}), + ...(body.max !== undefined && body.max !== null && body.max !== "" ? { max: Number(body.max) } : {}), } : {}), ...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}), diff --git a/umtool/lib/scaffold-phrase.test.mjs b/umtool/lib/scaffold-phrase.test.mjs @@ -87,3 +87,48 @@ test("--seed phrase with a finished scan (release 34, the phrase finder): the sa await rm(tmp, { recursive: true, force: true }); } }); + +test("--seed phrase --max N (release 35): N instances spread across the years, the rest as skippedByCap, the cap in the README", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-phrase-seed-")); + try { + const channelsDir = path.join(tmp, "channels"); + // 2019: 1, 2020: 6, 2021: 3 — ten instances, each its own video. + const plan = [["2019", 1], ["2020", 6], ["2021", 3]]; + for (const [year, n] of plan) { + for (let k = 0; k < n; k++) { + await video(channelsDir, "synth-yt", `y${year}${k}`, { uploadDate: `${year}${String(k + 1).padStart(2, "0")}10`, duration: 600, platform: "youtube", cues: [{ start: 10, end: 13, text: k === 0 && year === "2020" ? ">> a slow news day" : "a slow news day" }] }); + } + } + const base = { root: path.join(tmp, "reports"), seed: "phrase", phrase: String.raw`slow[\s,]+news`, channels: ["synth-yt"], channelsDir }; + const capped = await scaffoldReportVideo({ ...base, slug: "capped", max: 5 }); + assert.equal(capped.seeded, 5); + const doc = JSON.parse(await readFile(path.join(capped.dir, "video.manifest.json"), "utf8")); + // 5 of 10: quotas 0.5, 3, 1.5 -> 1, 3, 1 = 5. The 2020 speaker-checked instance is passed over. + assert.deepEqual(doc.timeline.map((c) => c.video), ["y20190", "y20201", "y20203", "y20205", "y20211"]); + assert.deepEqual(doc.timeline.map((c) => [c.id, c.montage.n, c.montage.of]), [["s01", 1, 5], ["s02", 2, 5], ["s03", 3, 5], ["s04", 4, 5], ["s05", 5, 5]]); + const scan = JSON.parse(await readFile(path.join(capped.dir, "phrase-scan.json"), "utf8")); + assert.equal(scan.max, 5); + assert.equal(scan.instances.length, 5); + assert.deepEqual(scan.skippedByCap.map((i) => i.videoId), ["y20200", "y20202", "y20204", "y20210", "y20212"]); + assert.ok(scan.instances.every((i) => Array.isArray(i.alternates)), "the instance shape, alternates and all"); + const readme = await readFile(path.join(capped.dir, "README.md"), "utf8"); + assert.match(readme, /Capped at 5 \(--max\): 5 of 10 instance\(s\) kept, spread across the years in proportion; the other 5 are in phrase-scan.json \("skippedByCap"\)\./); + assert.ok(capped.notes.some((n) => /Capped at 5/.test(n))); + + // No cap and a cap above the count: the same manifest; only a cap writes max / skippedByCap. + const plain = await scaffoldReportVideo({ ...base, slug: "plain" }); + const roomy = await scaffoldReportVideo({ ...base, slug: "roomy", max: 50 }); + const text = async (r, f) => (await readFile(path.join(r.dir, f), "utf8")).replaceAll(path.basename(r.dir), "X"); + assert.equal(await text(roomy, "video.manifest.json"), await text(plain, "video.manifest.json")); + const plainScan = JSON.parse(await readFile(path.join(plain.dir, "phrase-scan.json"), "utf8")); + assert.equal("max" in plainScan || "skippedByCap" in plainScan, false); + assert.doesNotMatch(await text(plain, "README.md"), /Capped/); + assert.match(await text(roomy, "README.md"), /Capped at 50 \(--max\): all 10 instance\(s\) kept/); + + await assert.rejects(scaffoldReportVideo({ ...base, slug: "bad", max: 0 }), /--max must be a whole number/); + await assert.rejects(scaffoldReportVideo({ ...base, slug: "bad", max: 2.5 }), /--max must be a whole number/); + await assert.rejects(scaffoldReportVideo({ root: base.root, slug: "bad", channelsDir, max: 3 }), /go with --seed phrase/); + } finally { + await rm(tmp, { recursive: true, force: true }); + } +});