Archilyzer · Source

archilyzer

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

commit 934ff4d4954ec7e8625df05e530c42809b71e9cc
parent 5ad64ba2e3311b53191d2f544331a495c3e08956
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 25 Oct 2026 22:17:04 -0400

archilyzer corpus grep: a regex over the live corpus's transcripts off disk, no index and no editor, dated by upload_date, with the videos in range that have no transcript yet

--regex <re> [--channels a,b] [--since/--until YYYY-MM-DD] [--window 30]
[--limit N] [--case-sensitive] [--json]. Each held video's cues are read as
the ops transcript route reads them (readCuesInVideoDir, split out of
readVideoCues: a fresh cues.json, else the caption-track rule, en-orig before
en, rolling repeats collapsed). A channel whose text is unreadable is skipped
and named (assertChannelTextReadable); social channels are left out. A
metadata mtime two days before --since rules a video out with one stat.

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

Diffstat:
Mcommon/bin/archilyzer.ts | 16++++++++++++++++
Acommon/bin/corpus-grep.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/corpusGrep.test.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/corpusGrep.ts | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/videoCues.ts | 20++++++++++++++++++--
5 files changed, 583 insertions(+), 2 deletions(-)

diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -902,6 +902,22 @@ export const COMMANDS: Command[] = [ json: flags.json === true, }), }, + { + path: ["corpus", "grep"], + usage: + "--regex <re> [--channels a,b] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json] search the LIVE corpus's transcripts off disk, no index and no editor: each held video's cues (transcript.cues.json, else its best caption track, en-orig before en, rolling repeats collapsed), dated by metadata.info.json upload_date; prints date, channel, id, start second, title and the window's text (case-insensitive unless --case-sensitive), then the videos in range with no transcript yet; a channel whose text is unreadable is skipped and named; default every channel that is not social; TRANSCRIPTS_DIR picks the corpus; writes nothing", + flags: { + regex: "string", + channels: "string", + since: "string", + until: "string", + window: "string", + limit: "string", + "case-sensitive": "boolean", + json: "boolean", + }, + run: async ({ flags }) => (await import("./corpus-grep")).main(flags), + }, script(["storage", "migrate-tier"], "migrate-media-tier.ts", "<slug>…|--all [--order smallest] [--include-large] [--dry-run] [--reclaim] bring a channel off the retired whole-directory layout onto the media tier, its text home to the corpus disk (editor stopped; --all stops before the three big-text channels)"), { diff --git a/common/bin/corpus-grep.ts b/common/bin/corpus-grep.ts @@ -0,0 +1,123 @@ +// `archilyzer corpus grep --regex <re> [--channels a,b] [--since YYYY-MM-DD] +// [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json]` +// +// A regex over the LIVE corpus's transcripts (controller/corpusGrep.ts): every +// held video of the named channels (default: every channel that is not social), +// dated by metadata.info.json's upload_date, its cues read as the ops +// transcript route reads them. Prints each hit's date, channel, id, start +// second, title and window text, then how many videos in range have no +// transcript yet, and lists them. Needs no editor and no index; writes nothing. +// The corpus is TRANSCRIPTS_DIR, else the checkout's transcripts/ (from a +// worktree, point TRANSCRIPTS_DIR at the primary checkout's). + +import { getPaths } from "../lib/paths"; +import { corpusGrep, parseGrepDate, type CorpusGrepResult } from "../controller/corpusGrep"; +import type { FlagValue } from "./_parseFlags"; + +function str(v: FlagValue | undefined): string | undefined { + return typeof v === "string" ? v : undefined; +} + +function clock(s: number): string { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + const mm = String(m).padStart(2, "0"); + const ss = String(sec).padStart(2, "0"); + return h ? `${h}:${mm}:${ss}` : `${m}:${ss}`; +} + +export function formatCorpusGrep(r: CorpusGrepResult): string { + const lines: string[] = []; + for (const h of r.hits) { + lines.push(`${h.date || "undated"} ${h.slug} ${h.id} ${h.start}s (${clock(h.start)}) ${h.title}`); + lines.push(` ${h.text}`); + } + const range = + r.since || r.until ? ` uploaded ${r.since ? `from ${r.since}` : ""}${r.since && r.until ? " " : ""}${r.until ? `to ${r.until}` : ""}` : ""; + lines.push(""); + lines.push( + `${r.totalHits} hit${r.totalHits === 1 ? "" : "s"}${r.hits.length < r.totalHits ? ` (${r.hits.length} shown)` : ""} ` + + `for /${r.pattern}/ in ${r.videosSearched} transcribed video${r.videosSearched === 1 ? "" : "s"}${range} ` + + `across ${r.channels.length} channel${r.channels.length === 1 ? "" : "s"} (${r.windowSeconds} s windows).`, + ); + if (r.since || r.until) { + if (r.undated) lines.push(`${r.undated} video${r.undated === 1 ? "" : "s"} with no metadata.info.json (no date) left out.`); + } + lines.push(`${r.noTranscript.length} video${r.noTranscript.length === 1 ? "" : "s"} in range with no transcript yet${r.noTranscript.length ? ":" : "."}`); + for (const p of r.noTranscript) { + const dur = p.duration !== undefined ? ` ${clock(Math.round(p.duration))}` : ""; + lines.push(` ${p.date || "undated"} ${p.slug} ${p.id}${dur} ${p.title}`); + } + for (const s of r.skippedChannels) lines.push(`skipped ${s.slug}: ${s.reason}`); + for (const e of r.errors) lines.push(`unreadable ${e.slug}/${e.id}: ${e.error}`); + return lines.join("\n"); +} + +export async function main(flags: Record<string, FlagValue>): Promise<number> { + const source = str(flags.regex); + if (!source) { + console.error("corpus grep: --regex <pattern> is required"); + return 2; + } + let pattern: RegExp; + try { + pattern = new RegExp(source, flags["case-sensitive"] === true ? "" : "i"); + } catch (err) { + console.error(`corpus grep: --regex does not parse: ${(err as Error).message}`); + return 2; + } + const dates: Record<"since" | "until", string | undefined> = { since: undefined, until: undefined }; + for (const key of ["since", "until"] as const) { + const raw = flags[key]; + if (raw === undefined) continue; + const day = typeof raw === "string" ? parseGrepDate(raw) : null; + if (!day) { + console.error(`corpus grep: --${key} is a date, YYYY-MM-DD`); + return 2; + } + dates[key] = day; + } + const num = (key: string, min: number): number | undefined | null => { + const raw = flags[key]; + if (raw === undefined) return undefined; + const n = typeof raw === "string" ? Number(raw) : NaN; + return Number.isInteger(n) && n >= min ? n : null; + }; + const windowSeconds = num("window", 1); + if (windowSeconds === null) { + console.error("corpus grep: --window is a whole number of seconds, 1 or more"); + return 2; + } + const limit = num("limit", 0); + if (limit === null) { + console.error("corpus grep: --limit is a whole number"); + return 2; + } + const channelsRaw = flags.channels; + if (channelsRaw === true) { + console.error("corpus grep: --channels takes a comma-separated list of slugs"); + return 2; + } + const channels = channelsRaw + ?.split(",") + .map((s) => s.trim()) + .filter(Boolean); + let result: CorpusGrepResult; + try { + result = await corpusGrep({ + paths: getPaths(), + pattern, + ...(channels?.length ? { channels } : {}), + ...(dates.since ? { since: dates.since } : {}), + ...(dates.until ? { until: dates.until } : {}), + ...(windowSeconds !== undefined ? { windowSeconds } : {}), + ...(limit !== undefined ? { limit } : {}), + }); + } catch (err) { + console.error(`corpus grep: ${(err as Error).message}`); + return 1; + } + console.log(flags.json === true ? JSON.stringify(result, null, 2) : formatCorpusGrep(result)); + return 0; +} diff --git a/common/controller/corpusGrep.test.ts b/common/controller/corpusGrep.test.ts @@ -0,0 +1,123 @@ +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/corpusGrep.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { corpusGrep, grepCues, parseGrepDate } from "./corpusGrep"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "corpus-grep-")); +const paths = { transcriptsDir: ROOT, channelsDir: path.join(ROOT, "channels") } as Paths; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const vtt = (cues: [number, number, string][]) => + "WEBVTT\n\n" + + cues + .map(([a, b, t]) => { + const ts = (s: number) => `00:${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; + return `${ts(a)} --> ${ts(b)}\n${t}\n`; + }) + .join("\n"); + +async function channel(slug: string, config: Record<string, unknown> = {}) { + const dir = path.join(paths.channelsDir, slug); + await mkdir(path.join(dir, "data"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "youtube", name: slug, ...config })); +} + +async function video( + slug: string, + id: string, + opts: { date?: string; title: string; files?: Record<string, string>; old?: boolean }, +) { + const dir = path.join(paths.channelsDir, slug, "data", id); + await mkdir(dir, { recursive: true }); + if (opts.date) { + const meta = path.join(dir, "metadata.info.json"); + await writeFile(meta, JSON.stringify({ id, title: opts.title, upload_date: opts.date, duration: 600, webpage_url: `https://example.com/${id}` })); + if (opts.old) { + const t = new Date("2020-01-01T00:00:00Z"); + await utimes(meta, t, t); + } + } + for (const [name, body] of Object.entries(opts.files ?? {})) await writeFile(path.join(dir, name), body); +} + +await channel("show"); +// en-orig is the speaker's words; en a rewrite. The rule reads en-orig. +await video("show", "a1", { + date: "20261022", + title: "Episode one", + files: { + "transcript.en-orig.vtt": vtt([ + [0, 5, "hello and welcome"], + [10, 15, "my dog Huck went to the vet"], + [40, 45, "nothing here"], + [70, 75, "Huck is doing better"], + ]), + "transcript.en.vtt": vtt([[0, 5, "a rewritten track that says Huck"]]), + }, +}); +await video("show", "a2", { date: "20261023", title: "No transcript yet" }); +await video("show", "a3", { + date: "20251001", + title: "Old one", + old: true, + files: { "transcript.en.vtt": vtt([[0, 5, "Huck in the old days"]]) }, +}); +await channel("posts", { sourceKind: "social", platform: "twitter" }); +await channel("gone", { dataDir: "/nonexistent/archilyzer-corpus-grep" }); + +test("parseGrepDate takes both spellings and refuses a day that does not exist", () => { + assert.equal(parseGrepDate("2026-10-21"), "20261021"); + assert.equal(parseGrepDate("20261021"), "20261021"); + assert.equal(parseGrepDate("2026-02-30"), null); + assert.equal(parseGrepDate("yesterday"), null); +}); + +test("grepCues: one hit per moment, at the cue the match begins in", () => { + const cues = [ + { start: 0, end: 5, text: "a" }, + { start: 12, end: 15, text: "the word\nhere" }, + { start: 20, end: 25, text: "b" }, + { start: 50, end: 55, text: "word again" }, + ]; + const hits = grepCues(cues, /word/i, 30); + assert.deepEqual( + hits.map((h) => h.start), + [12, 50], + ); + assert.equal(hits[0].text, "a the word here b"); +}); + +test("corpus grep: date floor, caption-track rule, pending videos, guards", async () => { + const r = await corpusGrep({ paths, pattern: /\bhuck\b/i, since: "20261021" }); + assert.deepEqual(r.channels, ["show"]); + // The legacy channel is skipped and named; the social one is left out. + assert.deepEqual(r.skippedChannels.map((s) => s.slug), ["gone"]); + assert.deepEqual( + r.hits.map((h) => [h.date, h.slug, h.id, h.start, h.title]), + [ + ["2026-10-22", "show", "a1", 10, "Episode one"], + ["2026-10-22", "show", "a1", 70, "Episode one"], + ], + ); + assert.equal(r.hits[0].url, "https://example.com/a1"); + assert.equal(r.videosInRange, 2); + assert.equal(r.videosSearched, 1); + assert.deepEqual(r.noTranscript.map((p) => [p.id, p.title, p.duration]), [["a2", "No transcript yet", 600]]); +}); + +test("corpus grep: no date bound searches the old video too; --until bounds; limit counts all", async () => { + const all = await corpusGrep({ paths, pattern: /huck/i, channels: ["show"], limit: 1 }); + assert.equal(all.totalHits, 3); + assert.equal(all.hits.length, 1); + assert.equal(all.hits[0].id, "a3"); + const until = await corpusGrep({ paths, pattern: /huck/i, channels: ["show"], until: "20251231" }); + assert.deepEqual(until.hits.map((h) => h.id), ["a3"]); + await assert.rejects(corpusGrep({ paths, pattern: /x/, channels: ["nope"] }), /Channel "nope" not found/); + const named = await corpusGrep({ paths, pattern: /x/, channels: ["posts"] }); + assert.match(named.skippedChannels[0].reason, /social/); +}); diff --git a/common/controller/corpusGrep.ts b/common/controller/corpusGrep.ts @@ -0,0 +1,303 @@ +// CORPUS GREP — a regex over the LIVE corpus's transcripts, off disk, with no +// index and no editor (`archilyzer corpus grep`). +// +// The published shards and the MCP (TRANSCRIPT_LOCAL_DIR is a composed public +// dir) only know what the last publish built. A video downloaded an hour ago, +// a private channel, or a channel no site carries is invisible to them. This +// reads `transcripts/channels/<slug>/data/<id>/` itself: each video's cues the +// way the ops transcript route reads them (readCuesInVideoDir — a fresh +// transcript.cues.json, else what normalize would write: the caption-track +// rule, en-orig before en, YouTube's rolling-caption repeats collapsed by +// parseVtt), dated by metadata.info.json's upload_date. +// +// A WINDOW is `windowSeconds` (30) of cues starting at a cue, stepped by half a +// window; a window is a hit when the pattern matches its text, and the next hit +// in the same video starts after that window ends, so one moment is one hit. +// Each hit names the start second of the cue the match begins in. +// +// Read-only. A channel whose text is not readable (its drive is not answering, +// a legacy layout, a move in flight — assertChannelTextReadable) is skipped +// with its reason, never read as "no videos". A social channel holds posts, +// not transcripts, and is left out. +// +// Reference: an agent's hand-written ~/reports/quartering-huck/search/since.py +// (2026-10-25), which this replaces. + +import path from "node:path"; +import { readFile, stat } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import type { Cue } from "../lib/vtt"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { isSocialChannel } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { mapConcurrent } from "../lib/concurrency"; +import { listChannelConfigs, readChannelConfig } from "./channels"; +import { heldVideoIds, readCuesInVideoDir } from "./videoCues"; + +export type CorpusGrepHit = { + // YYYY-MM-DD, or "" for an undated video (searched only with no date bound). + date: string; + slug: string; + id: string; + // The start second of the cue the match begins in. + start: number; + title: string; + // The whole window's text. + text: string; + url?: string; +}; + +export type CorpusGrepPending = { + date: string; + slug: string; + id: string; + title: string; + duration?: number; +}; + +export type CorpusGrepResult = { + pattern: string; + since: string | null; + until: string | null; + windowSeconds: number; + channels: string[]; + skippedChannels: { slug: string; reason: string }[]; + // Videos in range (by upload date) and how many of them had a transcript. + videosInRange: number; + videosSearched: number; + // In range with no transcript yet: still to download or transcribe. + noTranscript: CorpusGrepPending[]; + // No metadata.info.json (so no date): left out when a date bound is set. + undated: number; + // Every hit, before `limit`. + totalHits: number; + hits: CorpusGrepHit[]; + // Videos whose transcript could not be read, with the error. + errors: { slug: string; id: string; error: string }[]; +}; + +export type CorpusGrepOptions = { + paths: Paths; + pattern: RegExp; + // Absent: every channel that is not social. + channels?: readonly string[]; + // YYYYMMDD, inclusive. + since?: string; + until?: string; + windowSeconds?: number; + // Hits returned (all are counted in totalHits). Absent: all. + limit?: number; + onNote?: (line: string) => void; +}; + +const DAY_MS = 24 * 60 * 60 * 1000; + +// "2026-10-21" or "20261021" -> "20261021"; anything else null. +export function parseGrepDate(raw: string): string | null { + const m = /^(\d{4})-?(\d{2})-?(\d{2})$/.exec(raw.trim()); + if (!m) return null; + const [, y, mo, d] = m; + const t = Date.UTC(Number(y), Number(mo) - 1, Number(d)); + const back = new Date(t); + if (back.getUTCMonth() !== Number(mo) - 1 || back.getUTCDate() !== Number(d)) return null; + return `${y}${mo}${d}`; +} + +function dashed(day: string): string { + return day.length === 8 ? `${day.slice(0, 4)}-${day.slice(4, 6)}-${day.slice(6)}` : day; +} + +// The windows of one video's cues that the pattern matches (see the header). +export function grepCues( + cues: readonly Cue[], + pattern: RegExp, + windowSeconds = 30, +): { start: number; text: string }[] { + const re = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")); + const half = windowSeconds / 2; + const out: { start: number; text: string }[] = []; + const n = cues.length; + let i = 0; + let blockedUntil = -Infinity; + while (i < n) { + const t0 = cues[i].start; + if (t0 >= blockedUntil) { + let text = ""; + const offsets: { at: number; cue: number }[] = []; + for (let j = i; j < n && cues[j].start < t0 + windowSeconds; j++) { + const piece = cues[j].text.replace(/\s+/g, " ").trim(); + if (!piece) continue; + if (text) text += " "; + offsets.push({ at: text.length, cue: j }); + text += piece; + } + const m = text ? re.exec(text) : null; + if (m) { + let cue = offsets[0].cue; + for (const o of offsets) { + if (o.at <= m.index) cue = o.cue; + else break; + } + out.push({ start: Math.floor(cues[cue].start), text }); + blockedUntil = t0 + windowSeconds; + } + } + let k = i + 1; + while (k < n && cues[k].start < t0 + half) k++; + i = k; + } + return out; +} + +type Meta = { + upload_date?: unknown; + release_date?: unknown; + timestamp?: unknown; + title?: unknown; + fulltitle?: unknown; + duration?: unknown; + webpage_url?: unknown; +}; + +function metaDay(m: Meta): string { + for (const v of [m.upload_date, m.release_date]) { + if (typeof v === "string" && /^\d{8}$/.test(v)) return v; + } + if (typeof m.timestamp === "number" && Number.isFinite(m.timestamp)) { + return new Date(m.timestamp * 1000).toISOString().slice(0, 10).replace(/-/g, ""); + } + return ""; +} + +async function grepChannel( + opts: CorpusGrepOptions, + slug: string, + config: ChannelConfig, + result: CorpusGrepResult, +): Promise<void> { + const dataDir = path.join(opts.paths.channelsDir, slug, "data"); + const ids = [...(await heldVideoIds(dataDir))].sort(); + const since = opts.since ?? null; + const until = opts.until ?? null; + const dated = since !== null || until !== null; + // A video uploaded on or after `since` cannot have had its metadata written + // before that day: an mtime two days earlier (timezone slack) rules it out + // with one stat and no parse. Only false positives get through, and the + // upload_date check below settles those. + const floorMs = since + ? Date.UTC(Number(since.slice(0, 4)), Number(since.slice(4, 6)) - 1, Number(since.slice(6))) - 2 * DAY_MS + : null; + const windowSeconds = opts.windowSeconds ?? 30; + await mapConcurrent(ids, 8, async (id) => { + const videoDir = path.join(dataDir, id); + const metaPath = path.join(videoDir, "metadata.info.json"); + const st = await stat(metaPath).catch(() => null); + let meta: Meta | null = null; + if (st) { + if (floorMs !== null && st.mtimeMs < floorMs) return; + try { + meta = JSON.parse(await readFile(metaPath, "utf8")) as Meta; + } catch { + meta = null; + } + } + const day = meta ? metaDay(meta) : ""; + if (!day) { + result.undated++; + if (dated) return; + } else { + if (since && day < since) return; + if (until && day > until) return; + } + result.videosInRange++; + const titleOf = (m: Meta | null) => + typeof m?.title === "string" ? m.title : typeof m?.fulltitle === "string" ? m.fulltitle : ""; + let read; + try { + read = await readCuesInVideoDir({ slug, id, videoDir, configName: config.name }); + } catch (err) { + result.errors.push({ slug, id, error: (err as Error).message }); + return; + } + if (!read || read.cues.length === 0) { + result.noTranscript.push({ + date: dashed(day), + slug, + id, + title: titleOf(meta), + ...(typeof meta?.duration === "number" ? { duration: meta.duration } : {}), + }); + return; + } + result.videosSearched++; + const title = read.title ?? titleOf(meta); + const url = read.webpageUrl ?? (typeof meta?.webpage_url === "string" ? meta.webpage_url : undefined); + for (const w of grepCues(read.cues, opts.pattern, windowSeconds)) { + result.hits.push({ date: dashed(day), slug, id, start: w.start, title, text: w.text, ...(url ? { url } : {}) }); + } + }); +} + +export async function corpusGrep(opts: CorpusGrepOptions): Promise<CorpusGrepResult> { + const result: CorpusGrepResult = { + pattern: opts.pattern.source, + since: opts.since ? dashed(opts.since) : null, + until: opts.until ? dashed(opts.until) : null, + windowSeconds: opts.windowSeconds ?? 30, + channels: [], + skippedChannels: [], + videosInRange: 0, + videosSearched: 0, + noTranscript: [], + undated: 0, + totalHits: 0, + hits: [], + errors: [], + }; + let targets: { slug: string; config: ChannelConfig }[]; + if (opts.channels && opts.channels.length) { + targets = []; + for (const slug of opts.channels) { + const config = await readChannelConfig(opts.paths, slug); + if (!config) throw new Error(`Channel "${slug}" not found in ${opts.paths.channelsDir}`); + targets.push({ slug, config }); + } + } else { + targets = await listChannelConfigs(opts.paths); + } + for (const { slug, config } of targets) { + if (isSocialChannel(config)) { + if (opts.channels?.length) { + result.skippedChannels.push({ slug, reason: "a social channel: posts, not transcripts" }); + } + continue; + } + try { + await assertChannelTextReadable(opts.paths, slug, config); + } catch (err) { + const reason = (err as Error).message; + result.skippedChannels.push({ slug, reason }); + opts.onNote?.(`skipped ${slug}: ${reason}`); + continue; + } + result.channels.push(slug); + try { + await grepChannel(opts, slug, config, result); + } catch (err) { + // data/ could not be listed (not ENOENT — that is a channel holding + // nothing): say so rather than count it as empty. + result.channels.pop(); + result.skippedChannels.push({ slug, reason: (err as Error).message }); + opts.onNote?.(`skipped ${slug}: ${(err as Error).message}`); + } + } + const order = (a: { date: string; slug: string; id: string }, b: typeof a) => + a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id); + result.hits.sort((a, b) => order(a, b) || a.start - b.start); + result.noTranscript.sort(order); + result.totalHits = result.hits.length; + if (opts.limit !== undefined && result.hits.length > opts.limit) { + result.hits = result.hits.slice(0, opts.limit); + } + return result; +} diff --git a/common/controller/videoCues.ts b/common/controller/videoCues.ts @@ -131,6 +131,22 @@ export async function readVideoCues( const st = await stat(videoDir).catch(() => null); if (!st?.isDirectory()) return { error: `Channel "${slug}" holds no video "${id}"`, status: 404 }; + const read = await readCuesInVideoDir({ slug, id, videoDir, configName: config.name }); + if (read) return read; + return { error: `${slug}/${id} has no transcript to read (no transcript.json and no English VTT)`, status: 404 }; +} + +// The read itself, for a caller that has already found the channel and passed +// its text guard (corpus grep walks every video of a channel through this): +// a fresh transcript.cues.json, else what normalize would write, else the +// English VTT alone. null when the video has no transcript to read. +export async function readCuesInVideoDir(opts: { + slug: string; + id: string; + videoDir: string; + configName?: string; +}): Promise<VideoCues | null> { + const { slug, id, videoDir } = opts; const files = await readVideoFiles(videoDir); const freshness = await isCuesJsonFresh(videoDir); const cuesJson: VideoCues["cuesJson"] = files.entries.includes(CUES_JSON_FILENAME) @@ -142,11 +158,11 @@ export async function readVideoCues( const t = await readNormalizedTranscript(freshness.cuesPath); if (t) return fromNormalized(slug, id, t, "cues.json", cuesJson); } - const built = await buildNormalizedTranscript({ videoDir, channelSlug: slug, configName: config.name }, files); + const built = await buildNormalizedTranscript({ videoDir, channelSlug: slug, configName: opts.configName }, files); if (built.status === "built") return fromNormalized(slug, id, built.transcript, "built", cuesJson); if (built.reason === "no-metadata") { const read = await readEnglishVttCues(videoDir, files.entries); if (read) return { slug, id, source: "vtt", cuesJson, file: read.filename, cues: read.cues }; } - return { error: `${slug}/${id} has no transcript to read (no transcript.json and no English VTT)`, status: 404 }; + return null; }