Archilyzer · Source

archilyzer

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

commit 1e3bf96f3409104c096ceb5e97b0c3df23c9f957
parent 3464e10968c528fbd36221089596d1b42e91b4ed
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 16:57:30 -0400

umtool: the phrase finder — /tools/phrases (phrases as words or an expression, channels, prefer, exclude; one search as a job with progress; per phrase the count, by year, Rumble or other, speaker changes, ten contexts with Play and Transcript, Create montage from this search), `umtool phrases`, the scaffold seeded from a finished search

The search runs as a child process (`umtool phrases --spec --out --progress`), its answer under
CACHE_DIR/phrase-finder; Create montage posts the phrase seed's own settings plus the search's id,
and the scaffold uses that answer instead of reading the corpus again (refused when the settings
differ). A channel slug in mixed case (HasanAbiVODs3) is a channel to the phrase seed now.

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

Diffstat:
Aumtool/app/api/phrase-finder/[id]/route.ts | 17+++++++++++++++++
Aumtool/app/api/phrase-finder/context/route.ts | 18++++++++++++++++++
Aumtool/app/api/phrase-finder/route.ts | 28++++++++++++++++++++++++++++
Mumtool/app/tools/page.tsx | 8++++++--
Aumtool/app/tools/phrases/page.tsx | 33+++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/components/AppNav.tsx | 8+++++---
Mumtool/components/shell/JumpPalette.tsx | 4+++-
Aumtool/components/tools/PhraseFinder.tsx | 582++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.test.mjs | 2++
Mumtool/lib/hrefs.ts | 8++++++++
Aumtool/lib/phrase-finder.test.mjs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/phrase-finder/cli.mjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/phrase-finder/scan.d.mts | 10++++++++++
Aumtool/lib/phrase-finder/scan.mjs | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/phrase-finder/server.ts | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/phrase-finder/summary.d.mts | 7+++++++
Aumtool/lib/phrase-finder/summary.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/phrase-finder/types.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/projects/scaffold.mjs | 18++++++++++++------
Mumtool/lib/projects/scaffold.ts | 25++++++++++++++++++++++---
Mumtool/lib/scaffold-phrase.test.mjs | 23+++++++++++++++++++++++
22 files changed, 1601 insertions(+), 15 deletions(-)

diff --git a/umtool/app/api/phrase-finder/[id]/route.ts b/umtool/app/api/phrase-finder/[id]/route.ts @@ -0,0 +1,17 @@ +import { cancelPhraseScan, phraseScanView } from "@/lib/phrase-finder/server"; + +export const dynamic = "force-dynamic"; + +// One search: GET its state, progress and, once done, each phrase's numbers; +// DELETE stops it while it runs. +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + const { id } = await ctx.params; + const view = await phraseScanView(id); + if (!view) return Response.json({ error: "no such search" }, { status: 404 }); + return Response.json(view, { headers: { "cache-control": "no-store" } }); +} + +export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) { + const { id } = await ctx.params; + return Response.json({ cancelled: cancelPhraseScan(id) }, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/phrase-finder/context/route.ts b/umtool/app/api/phrase-finder/context/route.ts @@ -0,0 +1,18 @@ +import { transcriptAround } from "@/lib/phrase-finder/server"; + +export const dynamic = "force-dynamic"; + +// GET ?channel&video&at -> the cues around that second of the video's +// transcript, the hit's cue lit: where the phrase was said, read in place. +export async function GET(request: Request) { + const sp = new URL(request.url).searchParams; + const at = Number(sp.get("at")); + if (!Number.isFinite(at)) return Response.json({ error: "at is a second" }, { status: 400 }); + try { + const t = await transcriptAround(String(sp.get("channel") ?? ""), String(sp.get("video") ?? ""), at); + if (!t) return Response.json({ error: "no transcript" }, { status: 404 }); + return Response.json(t, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/phrase-finder/route.ts b/umtool/app/api/phrase-finder/route.ts @@ -0,0 +1,28 @@ +import { phraseFinderState, startPhraseScan } from "@/lib/phrase-finder/server"; + +export const dynamic = "force-dynamic"; + +// The phrase finder (release 34, /tools/phrases). GET: what the page opens +// with -- the channels, the last search's settings, the suggestions, the +// running search and the recent ones. POST {rows: [{id, text, mode}], +// channels, prefer, exclude}: start a search, a job (lib/phrase-finder/server.ts); +// a bad phrase or channel is refused here with its sentence, a second search +// while one runs with 409 and the running one's id. +export async function GET() { + return Response.json(await phraseFinderState(), { headers: { "cache-control": "no-store" } }); +} + +export async function POST(request: Request) { + let body: unknown; + try { + body = await request.json(); + } catch { + return Response.json({ error: "bad json" }, { status: 400 }); + } + try { + return Response.json(await startPhraseScan(body), { headers: { "cache-control": "no-store" } }); + } catch (e) { + const err = e as Error & { status?: number; running?: string }; + return Response.json({ error: err.message, ...(err.running ? { running: err.running } : {}) }, { status: err.status ?? 400 }); + } +} diff --git a/umtool/app/tools/page.tsx b/umtool/app/tools/page.tsx @@ -1,6 +1,6 @@ import AppShell from "@/components/shell/AppShell"; import ToolList, { PILE_WHAT, type ToolEntry } from "@/components/tools/ToolList"; -import { benchHref, facesHref, findHref, mixHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; +import { benchHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; import { TRIM_SETS } from "@/lib/trim"; export const dynamic = "force-dynamic"; @@ -24,7 +24,10 @@ export default function ToolsPage() { const articles: ToolEntry[] = [ { href: benchHref(), name: "verdict bench", what: "Could a model propose a fact-check verdict well enough to review", testid: "bench" }, ]; - const n = song.length + articles.length; + const montage: ToolEntry[] = [ + { href: phraseFinderHref(), name: "phrases", what: "How often phrases were said, by year, and a montage from one", testid: "phrases" }, + ]; + const n = song.length + articles.length + montage.length; return ( <div className="flex h-full flex-col"> <AppShell active="tools" crumbs={[{ label: "Tools" }]} meta={`${n} tools`} /> @@ -32,6 +35,7 @@ export default function ToolsPage() { <ToolList groups={[ { title: "Song", tools: song }, + { title: "Montage", tools: montage }, { title: "Articles", tools: articles }, ]} /> diff --git a/umtool/app/tools/phrases/page.tsx b/umtool/app/tools/phrases/page.tsx @@ -0,0 +1,33 @@ +import AppShell from "@/components/shell/AppShell"; +import PhraseFinder from "@/components/tools/PhraseFinder"; +import { toolsHref } from "@/lib/hrefs"; +import { phraseFinderState, phraseScanView } from "@/lib/phrase-finder/server"; + +export const dynamic = "force-dynamic"; + +// THE PHRASE FINDER (release 34): the next montage phrase, found in the UI +// with no model. Phrases (plain words or a regular expression) over the +// channels picked, in one pass, as a job; per phrase the instances once folded +// (phraseScan's rules), by year, Rumble or another channel, how many have a +// caption speaker change, ten contexts to read in place and play; and Create +// montage, the new-project form's phrase seed with these exact settings. The +// search is in the page's state, not the URL: `?scan=<id>` reopens a finished +// one and `?q=` prefills a phrase. + +type Params = Record<string, string | string[] | undefined>; +const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v) ?? ""; + +export default async function PhrasesPage({ searchParams }: { searchParams: Promise<Params> }) { + const sp = await searchParams; + const state = await phraseFinderState(); + const scanId = one(sp.scan) || state.running || null; + const initialScan = scanId ? await phraseScanView(scanId) : null; + return ( + <div className="flex h-full flex-col"> + <AppShell active="phrases" crumbs={[{ label: "Tools", href: toolsHref() }, { label: "Phrases" }]} meta={`${state.channels.length} channels`} /> + <main className="deck-main flex-1 px-4 pb-6 pt-4"> + <PhraseFinder state={state} initialScan={initialScan} prefill={one(sp.q)} /> + </main> + </div> + ); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -50,6 +50,8 @@ // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] // [--at S --dur S | --full] [--force] | --id <id> --rebuild make one take // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] +// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] +// [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass) import process from "node:process"; import { PROJECT_KINDS, @@ -718,6 +720,8 @@ function usage() { " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]", " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", + " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]", + " how often each phrase was said, by year, in one pass (the phrase finder's search)", " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", @@ -754,6 +758,8 @@ const COMMANDS = { // The take maker (release 33): lib/report/takeCli.mjs. take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), + // The phrase finder (release 34): lib/phrase-finder/cli.mjs. + phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -6,6 +6,7 @@ import { facesHref, homeHref, mixHref, + phraseFinderHref, pileHref, researchHref, sourcesHref, @@ -22,7 +23,7 @@ import RailCount from "./shell/RailCount"; // (the lit line, at rest; app/globals.css `.app-places`): "page" on the place's // own page, "true" on a page under it. // -// Tools opens into its tools while you are in one -- find, mix, the song piles +// Tools opens into its tools while you are in one -- find, mix, phrases, the song piles // (the `song ▸` group, at /tools/song/<pile>), faces, sources -- so moving // between tools is one click; /tools lists them all from anywhere. // @@ -39,6 +40,7 @@ const SONG_ITEMS = MODES.map((m) => ({ href: pileHref(m), label: m as string })) const TOOL_ITEMS = [ { href: findHref(), label: "find" }, { href: mixHref(), label: "mix" }, + { href: phraseFinderHref(), label: "phrases" }, { href: facesHref(), label: "faces" }, { href: sourcesHref(), label: "sources" }, { href: benchHref(), label: "bench" }, @@ -92,13 +94,13 @@ export default function AppNav({ active }: { active: string }) { </Link> {place === "tools" && ( <div className="app-sub" data-rail-sub="tools"> - {TOOL_ITEMS.slice(0, 2).map((it) => ( + {TOOL_ITEMS.slice(0, 3).map((it) => ( <Link key={it.href} href={it.href} prefetch={false} aria-current={it.label === active ? "page" : undefined}> {it.label} </Link> ))} <NavGroup label="song" items={SONG_ITEMS} active={active} on={songActive} /> - {TOOL_ITEMS.slice(2).map((it) => ( + {TOOL_ITEMS.slice(3).map((it) => ( <Link key={it.href} href={it.href} prefetch={false} aria-current={it.label === active ? "page" : undefined}> {it.label} </Link> diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -18,6 +18,7 @@ import { systemHref, toolsHref, workHref, + phraseFinderHref, } from "@/lib/hrefs"; import { MODES } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -44,12 +45,13 @@ const FIXED: Item[] = [ { id: "research", section: "Places", label: "Research", hint: "search the archive", href: researchHref() }, { id: "work", section: "Places", label: "Work", hint: "every piece", href: workHref() }, { id: "projects", section: "Places", label: "Projects", hint: "every project, by folder", href: projectsHref() }, - { id: "tools", section: "Places", label: "Tools", hint: "find, mix, song piles, faces, sources", href: toolsHref() }, + { id: "tools", section: "Places", label: "Tools", hint: "find, mix, phrases, song piles, faces, sources", href: toolsHref() }, { id: "system", section: "Places", label: "Settings · system", hint: "tools, disk, index, sources, recent jobs", href: systemHref() }, { id: "create", section: "Places", label: "Create", hint: "what are you making?", href: createHref() }, { id: "policy", section: "Places", label: "Settings · generation", hint: "routes, models, caps, the key, today's spend", href: generationPolicyHref() }, { id: "find", section: "Tools", label: "Find", hint: "every occurrence of a word", href: findHref() }, { id: "mix", section: "Tools", label: "Mix", hint: "the mix bench", href: mixHref() }, + { id: "phrases", section: "Tools", label: "Phrases", hint: "how often a phrase was said, by year; a montage from it", href: phraseFinderHref() }, { id: "song", section: "Tools", label: "Song piles", hint: "sort, salvage, verify, keeps", href: songToolsHref() }, ...MODES.map((m): Item => ({ id: `pile-${m}`, section: "Tools", label: `Song · ${m}`, hint: "judging pile", href: pileHref(m) })), { id: "faces", section: "Tools", label: "Faces", hint: "the face judger", href: facesHref() }, diff --git a/umtool/components/tools/PhraseFinder.tsx b/umtool/components/tools/PhraseFinder.tsx @@ -0,0 +1,582 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import CitedClip from "@/components/clips/CitedClip"; +import { Button } from "@/components/ui/button"; +import { clock } from "@/components/ui/clock"; +import { Field, Input, Select } from "@/components/ui/field"; +import { JobProgressBar } from "@/components/ui/job-progress"; +import { Panel } from "@/components/ui/panel"; +import { phraseFinderHref } from "@/lib/hrefs"; +import { montageSlug } from "@/lib/phrase-finder/summary.mjs"; +import type { PhraseFinderState, PhraseMode, PhraseSample, PhraseScanRowView, PhraseScanView, TranscriptAround } from "@/lib/phrase-finder/types"; +import { phraseSourceOf } from "yt-dlp-transcript-common/lib/montage/phraseSource.mjs"; + +// --------------------------------------------------------------------------- +// THE PHRASE FINDER (release 34), the page's one island. +// +// phrases one row each: the words (plain words, or a regular expression +// -- `auto` tells them apart by its characters), what is searched +// under it; Add phrase / ×; a suggestion (a catchphrase report's +// candidates) adds a row +// channels the ones to scan, filtered by typing; prefer (the copy to cut +// from where a stream has one) and exclude (a context that +// matches is left out) -- the phrase seed's own four settings +// Search one job for every row (POST /api/phrase-finder), its progress +// polled; Stop ends it +// results per phrase: the instances once folded, by year, Rumble or +// another, speaker changes; ten contexts, each with Play (the +// clip window or saved video on disk, else Fetch clip) and +// Transcript (the cues around it, read in place); Create montage +// (the slug prefilled) seeds a project from THIS search +// +// The data attributes are the e2e spec's handles (phrase-finder.spec.ts). +// --------------------------------------------------------------------------- + +type Row = { key: number; text: string; mode: PhraseMode; label?: string }; + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function niceDate(s: string | null): string { + const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(s ?? "")); + return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1] ?? "?"} ${m[1]}` : (s ?? "no date"); +} +const n0 = (n: number) => n.toLocaleString("en-GB"); +const scanStamp = (id: string) => { + const m = /^ps-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(id); + return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[4]}:${m[5]}` : id; +}; + +/** What a row is searched as, or why it cannot be. */ +function sourceOf(r: Row): { source: string; mode: string } | { error: string } | null { + if (!r.text.trim()) return null; + try { + return phraseSourceOf(r.text, r.mode); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } +} + +export default function PhraseFinder({ state, initialScan, prefill }: { state: PhraseFinderState; initialScan: PhraseScanView | null; prefill: string }) { + const seq = useRef(0); + const mk = (r: Omit<Row, "key">): Row => ({ ...r, key: ++seq.current }); + const [rows, setRows] = useState<Row[]>(() => { + if (prefill.trim()) return [mk({ text: prefill.trim(), mode: "auto" })]; + if (initialScan) return initialScan.spec.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label })); + if (state.last?.rows.length) return state.last.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label })); + return [mk({ text: "", mode: "auto" })]; + }); + const from = initialScan?.spec ?? state.last; + const [chosen, setChosen] = useState<Set<string>>(() => new Set(from?.channels ?? [])); + const [prefer, setPrefer] = useState(from?.prefer ?? ""); + const [exclude, setExclude] = useState(from?.exclude ?? ""); + const [filter, setFilter] = useState(""); + const [scan, setScan] = useState<PhraseScanView | null>(initialScan); + const [error, setError] = useState<string | null>(null); + const [starting, setStarting] = useState(false); + + const running = scan?.state === "running"; + const names = useMemo(() => new Map(state.channels.map((c) => [c.slug, c.name])), [state.channels]); + + // Poll the running search. + useEffect(() => { + if (!scan || scan.state !== "running") return; + let gone = false; + const t = setTimeout(async () => { + try { + const r = await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { cache: "no-store" }); + const j = await r.json(); + if (!gone && r.ok) setScan(j as PhraseScanView); + } catch { + /* the next poll */ + } + }, 800); + return () => { + gone = true; + clearTimeout(t); + }; + }, [scan]); + + const setRow = (key: number, patch: Partial<Row>) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch, ...(patch.text !== undefined ? { label: undefined } : {}) } : r))); + const addRow = (r: Omit<Row, "key"> = { text: "", mode: "auto" }) => + setRows((rs) => (rs.length === 1 && !rs[0].text.trim() ? [mk(r)] : [...rs, mk(r)])); + const removeRow = (key: number) => setRows((rs) => (rs.length > 1 ? rs.filter((r) => r.key !== key) : [mk({ text: "", mode: "auto" })])); + const toggle = (slug: string) => + setChosen((s) => { + const n = new Set(s); + if (n.has(slug)) n.delete(slug); + else n.add(slug); + return n; + }); + + const filled = rows.filter((r) => r.text.trim()); + const bad = filled.map(sourceOf).find((s) => s && "error" in s) as { error: string } | undefined; + const canSearch = !running && !starting && filled.length > 0 && !bad && (chosen.size > 0 || !!prefer); + + const search = async () => { + if (!canSearch) return; + setStarting(true); + setError(null); + try { + const body = { + rows: filled.map((r, k) => ({ id: `p${k + 1}`, text: r.text.trim(), mode: r.mode, ...(r.label ? { label: r.label } : {}) })), + channels: [...chosen], + prefer: prefer || null, + exclude: exclude.trim() || null, + }; + const r = await fetch("/api/phrase-finder", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), cache: "no-store" }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); + const v = await fetch(`/api/phrase-finder/${encodeURIComponent(j.id)}`, { cache: "no-store" }).then((x) => x.json()); + setScan(v as PhraseScanView); + window.history.replaceState(null, "", phraseFinderHref({ scan: j.id })); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setStarting(false); + } + }; + const stop = async () => { + if (!scan) return; + await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { method: "DELETE", cache: "no-store" }).catch(() => {}); + setScan({ ...scan, state: "cancelled" }); + }; + + const shown = state.channels.filter((c) => { + const f = filter.trim().toLowerCase(); + return !f || c.slug.toLowerCase().includes(f) || c.name.toLowerCase().includes(f); + }); + + return ( + <div className="grid max-w-[1180px] gap-4"> + <form + className="grid gap-4" + data-phrase-form="" + onSubmit={(e) => { + e.preventDefault(); + void search(); + }} + > + <Panel title="Phrases" aside={<span className="text-muted">{filled.length} to search</span>}> + <ul className="grid gap-2.5"> + {rows.map((r, k) => { + const s = sourceOf(r); + return ( + <li key={r.key} className="grid gap-1" data-phrase-row={k + 1}> + <div className="flex flex-wrap items-center gap-2"> + <Input + value={r.text} + onChange={(e) => setRow(r.key, { text: e.target.value })} + placeholder={k === 0 ? "slow news day" : "another phrase"} + aria-label={`phrase ${k + 1}`} + className="min-w-0 flex-1 basis-64" + data-phrase-text="" + /> + <Select value={r.mode} onChange={(e) => setRow(r.key, { mode: e.target.value as PhraseMode })} aria-label={`phrase ${k + 1}: read as`} data-phrase-mode=""> + <option value="auto">words or expression</option> + <option value="words">plain words</option> + <option value="regex">regular expression</option> + </Select> + <Button type="button" size="sm" variant="quiet" onClick={() => removeRow(r.key)} aria-label={`remove phrase ${k + 1}`} data-phrase-remove=""> + × + </Button> + </div> + {s && ( + <span className={"error" in s ? "text-[11.5px] text-reject-text" : "font-mono text-[11px] text-muted-2"} data-phrase-source=""> + {"error" in s ? s.error : `${r.label ? `${r.label} · ` : ""}${s.mode === "words" ? "as words" : "as written"}: /${s.source}/`} + </span> + )} + </li> + ); + })} + </ul> + <div className="mt-2.5 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" onClick={() => addRow()} data-phrase-add=""> + Add phrase + </Button> + {state.suggestions.length > 0 && ( + <details className="basis-full text-[12.5px]" data-phrase-suggestions=""> + <summary className="cursor-pointer text-text-2">Suggestions ({state.suggestions.length})</summary> + <div className="mt-2 flex flex-wrap gap-1.5"> + {state.suggestions.map((s) => ( + <Button + key={`${s.from}/${s.key}`} + type="button" + size="sm" + title={`/${s.regex}/ · from ${s.from}`} + onClick={() => addRow({ text: s.regex, mode: "regex", label: s.key })} + data-phrase-suggestion={s.key} + > + {s.key} + {s.instances != null && <span className="font-mono text-muted-2">{s.instances}</span>} + </Button> + ))} + </div> + </details> + )} + </div> + </Panel> + + <Panel title="Channels" aside={<span className="text-muted" data-phrase-chosen={chosen.size}>{chosen.size} picked</span>}> + {chosen.size > 0 && ( + <div className="mb-2 flex flex-wrap gap-1.5"> + {[...chosen].map((slug) => ( + <Button key={slug} type="button" size="sm" variant="pressed" onClick={() => toggle(slug)} title="leave it out" data-phrase-picked={slug}> + {names.get(slug) ?? slug} × + </Button> + ))} + </div> + )} + <Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="filter channels" aria-label="filter channels" className="mb-2 w-64" data-phrase-channel-filter="" /> + <div className="grid max-h-56 grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-x-4 gap-y-0.5 overflow-auto text-[12.5px]"> + {shown.map((c) => ( + <label key={c.slug} className="flex items-baseline gap-2 py-0.5" data-phrase-channel={c.slug}> + <input type="checkbox" checked={chosen.has(c.slug)} onChange={() => toggle(c.slug)} /> + <span className="truncate">{c.name}</span> + <span className="ml-auto font-mono text-[10.5px] text-muted-2">{n0(c.videos)}</span> + </label> + ))} + {!shown.length && <span className="text-muted">No channel matches.</span>} + </div> + <div className="mt-3 flex flex-wrap items-end gap-3"> + <Field label="Prefer" hint="cut from this channel's copy where it has the same stream"> + <Select value={prefer} onChange={(e) => setPrefer(e.target.value)} aria-label="prefer" data-phrase-prefer=""> + <option value="">none</option> + {state.channels.map((c) => ( + <option key={c.slug} value={c.slug}> + {c.name} + </option> + ))} + </Select> + </Field> + <Field label="Exclude" hint="leave out a hit whose words around it match (a regular expression)"> + <Input value={exclude} onChange={(e) => setExclude(e.target.value)} placeholder="optional" aria-label="exclude" className="w-64" data-phrase-exclude="" /> + </Field> + <Button type="submit" variant="go" disabled={!canSearch} data-phrase-search=""> + {starting ? "Starting…" : filled.length > 1 ? `Search ${filled.length} phrases` : "Search"} + </Button> + {state.recent.length > 0 && ( + <span className="text-[12px] text-muted"> + Recent:{" "} + {state.recent.slice(0, 5).map((id, k) => ( + <a key={id} href={phraseFinderHref({ scan: id })} className="ink-link" data-phrase-recent={id}> + {k ? ", " : ""} + {scanStamp(id)} + </a> + ))} + </span> + )} + </div> + {(error || bad) && ( + <p role="alert" className="mt-2 text-[12.5px] text-reject-text" data-phrase-error=""> + {error ?? bad?.error} + </p> + )} + </Panel> + </form> + + {scan && <ScanResults scan={scan} names={names} onStop={stop} />} + </div> + ); +} + +function ScanResults({ scan, names, onStop }: { scan: PhraseScanView; names: Map<string, string>; onStop: () => void }) { + const p = scan.progress; + if (scan.state === "running") { + const meter = p && p.total ? { fraction: p.done / p.total, text: `${p.done}/${p.total}` } : null; + return ( + <Panel title="Searching" data-phrase-state="running"> + <div className="grid grid-cols-[1fr_auto] items-center gap-x-3 gap-y-1.5"> + <span className="text-[12.5px] text-text-2" data-phrase-progress=""> + {p ? `${n0(p.done)} of ${n0(p.total)} transcripts · ${names.get(p.channel) ?? p.channel}` : "starting…"} + </span> + <Button type="button" size="sm" onClick={onStop} data-phrase-stop=""> + Stop + </Button> + <JobProgressBar meter={meter} /> + </div> + </Panel> + ); + } + if (scan.state !== "done" || !scan.rows) { + return ( + <Panel title="Search" data-phrase-state={scan.state}> + <p className="text-[12.5px] text-reject-text">{scan.state === "cancelled" ? "Stopped." : (scan.error ?? "The search failed.")}</p> + </Panel> + ); + } + const rows = scan.rows; + return ( + <div className="grid gap-4" data-phrase-state="done" data-phrase-scan={scan.id}> + <p className="text-[12px] text-muted" data-phrase-scanned={scan.scanned ?? 0}> + {n0(scan.scanned ?? 0)} transcripts read in {scan.seconds ?? "?"} s · {scan.spec.channels.map((c) => names.get(c) ?? c).join(", ")} + {scan.spec.prefer ? ` · cut from ${names.get(scan.spec.prefer) ?? scan.spec.prefer} where it has the stream` : ""} + </p> + {rows.length > 1 && <Compare rows={rows} />} + {rows.map((r) => ( + <PhraseResult key={r.id} scan={scan} row={r} names={names} /> + ))} + </div> + ); +} + +function Compare({ rows }: { rows: PhraseScanRowView[] }) { + const sorted = [...rows].sort((a, b) => b.summary.instances - a.summary.instances); + return ( + <Panel title="Compared" data-phrase-compare=""> + <table className="w-full text-[12.5px]"> + <thead> + <tr className="text-left text-[11px] text-muted"> + <th className="py-1 font-medium">phrase</th> + <th className="py-1 text-right font-medium">times</th> + <th className="py-1 pl-4 font-medium">by year</th> + <th className="py-1 text-right font-medium">Rumble / other</th> + <th className="py-1 text-right font-medium">speaker changes</th> + </tr> + </thead> + <tbody> + {sorted.map((r) => ( + <tr key={r.id} className="border-t border-seam" data-phrase-compare-row={r.id}> + <td className="py-1"> + <a href={`#phrase-${r.id}`} className="ink-link"> + {r.label ?? r.text} + </a> + </td> + <td className="py-1 text-right font-mono">{r.summary.instances}</td> + <td className="py-1 pl-4 font-mono text-meter" title={Object.entries(r.summary.years).map(([y, n]) => `${y}: ${n}`).join(", ")}> + {r.summary.spark} + </td> + <td className="py-1 text-right font-mono"> + {r.summary.rumble} / {r.summary.notRumble} + </td> + <td className="py-1 text-right font-mono">{r.summary.speakerChecks}</td> + </tr> + ))} + </tbody> + </table> + </Panel> + ); +} + +function YearBars({ years }: { years: Record<string, number> }) { + const entries = Object.entries(years); + const max = Math.max(1, ...entries.map(([, n]) => n)); + if (!entries.length) return null; + return ( + <div className="flex items-end gap-1" data-phrase-years=""> + {entries.map(([y, n]) => ( + <div key={y} className="flex w-7 flex-col items-center gap-0.5" data-phrase-year={y} data-count={n} title={`${y}: ${n}`}> + <span className="font-mono text-[10px] text-text-2">{n || ""}</span> + <span className="block w-4 bg-meter" style={{ height: `${n ? Math.max(2, Math.round((n / max) * 32)) : 0}px` }} /> + <span className="font-mono text-[10px] text-muted-2">&apos;{y.slice(2)}</span> + </div> + ))} + </div> + ); +} + +function PhraseResult({ scan, row, names }: { scan: PhraseScanView; row: PhraseScanRowView; names: Map<string, string> }) { + const s = row.summary; + const span = s.first ? `${String(s.first).slice(0, 4)}–${String(s.last).slice(0, 4)}` : ""; + return ( + <Panel + id={`phrase-${row.id}`} + title={row.label ?? row.text} + aside={<span className="font-mono text-muted-2">/{row.source}/</span>} + data-phrase-result={row.id} + > + <div className="flex flex-wrap items-end gap-x-8 gap-y-3"> + <div> + <div className="font-mono text-[28px] leading-none text-text" data-phrase-count={s.instances}> + {s.instances} + </div> + <div className="mt-1 text-[11.5px] text-muted"> + {s.instances === 1 ? "time" : "times"} + {span ? `, ${span}` : ""} + </div> + </div> + <YearBars years={s.years} /> + <dl className="grid grid-cols-[auto_auto] gap-x-3 gap-y-0.5 text-[12px]"> + <dt className="text-muted">Rumble</dt> + <dd className="font-mono" data-phrase-rumble={s.rumble}> + {s.rumble} + </dd> + <dt className="text-muted">other</dt> + <dd className="font-mono" data-phrase-other={s.notRumble}> + {s.notRumble} + </dd> + <dt className="text-muted">speaker changes</dt> + <dd className="font-mono" data-phrase-speaker={s.speakerChecks}> + {s.speakerChecks} + </dd> + {s.placed > 0 && ( + <> + <dt className="text-muted">placed by words</dt> + <dd className="font-mono">{s.placed}</dd> + </> + )} + {s.dropped > 0 && ( + <> + <dt className="text-muted">excluded</dt> + <dd className="font-mono">{s.dropped}</dd> + </> + )} + <dt className="text-muted">raw hits</dt> + <dd className="font-mono">{s.hits}</dd> + </dl> + </div> + {Object.keys(s.bySlug).length > 1 && ( + <p className="mt-2 text-[11.5px] text-muted"> + {Object.entries(s.bySlug) + .sort((a, b) => b[1] - a[1]) + .map(([slug, n]) => `${names.get(slug) ?? slug} ${n}`) + .join(" · ")} + </p> + )} + {s.samples.length > 0 && ( + <ol className="mt-3 grid gap-2" data-phrase-samples=""> + {s.samples.map((x) => ( + <Sample key={`${x.slug}/${x.videoId}@${x.start}`} s={x} names={names} /> + ))} + </ol> + )} + <CreateMontage scan={scan} row={row} /> + </Panel> + ); +} + +function Lit({ context, match }: { context: string; match: string }) { + const at = context.toLowerCase().indexOf(match.toLowerCase()); + if (!match || at < 0) return <>{context}</>; + return ( + <> + {context.slice(0, at)} + <b className="font-semibold text-signal-text">{context.slice(at, at + match.length)}</b> + {context.slice(at + match.length)} + </> + ); +} + +function Sample({ s, names }: { s: PhraseSample; names: Map<string, string> }) { + const [open, setOpen] = useState<"play" | "text" | null>(null); + const [ctx, setCtx] = useState<TranscriptAround | { error: string } | null>(null); + const readTranscript = useCallback(async () => { + if (open === "text") return setOpen(null); + setOpen("text"); + if (ctx && !("error" in ctx)) return; + try { + const q = new URLSearchParams({ channel: s.slug, video: s.videoId, at: String(s.start) }); + const r = await fetch(`/api/phrase-finder/context?${q}`, { cache: "no-store" }); + const j = await r.json(); + setCtx(r.ok ? (j as TranscriptAround) : { error: j.error ?? `HTTP ${r.status}` }); + } catch (e) { + setCtx({ error: e instanceof Error ? e.message : String(e) }); + } + }, [open, ctx, s.slug, s.videoId, s.start]); + return ( + <li className="rounded-[3px] border border-seam px-3 py-2" data-phrase-sample={`${s.slug}/${s.videoId}`}> + <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 text-[11.5px] text-muted"> + <span className="font-mono text-text-2">{niceDate(s.date)}</span> + <span>{names.get(s.slug) ?? s.slug}</span> + <span className="font-mono"> + {s.videoId} @ {clock(s.start)} + </span> + {s.speakerCheck && <span className="text-doubt-text">speaker change</span>} + {s.via && <span>placed from {names.get(s.via.slug) ?? s.via.slug}</span>} + <span className="ml-auto flex gap-1.5"> + <Button type="button" size="sm" variant={open === "play" ? "pressed" : "outline"} onClick={() => setOpen(open === "play" ? null : "play")} data-phrase-play=""> + Play + </Button> + <Button type="button" size="sm" variant={open === "text" ? "pressed" : "outline"} onClick={() => void readTranscript()} data-phrase-transcript=""> + Transcript + </Button> + </span> + </div> + {s.title && <div className="mt-0.5 truncate text-[11.5px] text-muted-2">{s.title}</div>} + <p className="mt-1 text-[13px] leading-snug text-text"> + <Lit context={s.context} match={s.match} /> + </p> + {open === "play" && ( + <div className="mt-2"> + <CitedClip target={{ channel: s.slug, video: s.videoId, from: s.start, to: Math.max(s.end, s.start + 1) }} reason="phrase finder" /> + </div> + )} + {open === "text" && ( + <div className="mt-2" data-phrase-cues=""> + {!ctx ? ( + <span className="text-[12px] text-muted">reading…</span> + ) : "error" in ctx ? ( + <span className="text-[12px] text-reject-text">{ctx.error}</span> + ) : ( + <ol className="grid gap-0.5 text-[12.5px]"> + {ctx.cues.map((c) => ( + <li key={c.start} className={c.lit ? "text-text" : "text-muted"} data-phrase-cue={c.lit ? "lit" : ""}> + <span className="mr-2 font-mono text-[10.5px] text-muted-2">{clock(c.start)}</span> + {c.text} + </li> + ))} + </ol> + )} + </div> + )} + </li> + ); +} + +function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRowView }) { + const router = useRouter(); + const [slug, setSlug] = useState(() => montageSlug(row.label ?? row.text)); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const empty = row.summary.instances === 0; + const create = async () => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/projects/new", { + method: "POST", + headers: { "content-type": "application/json" }, + cache: "no-store", + body: JSON.stringify({ + kind: "report-video", + slug: slug.trim(), + title: row.label ?? row.text, + seed: "phrase", + phrase: row.source, + channels: scan.spec.channels, + prefer: scan.spec.prefer, + exclude: scan.spec.exclude, + scan: { id: scan.id, row: row.id }, + }), + }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); + router.push(j.href); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(false); + } + }; + return ( + <form + className="mt-3 flex flex-wrap items-end gap-2 border-t border-seam pt-3" + data-phrase-montage={row.id} + onSubmit={(e) => { + e.preventDefault(); + void create(); + }} + > + <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=""> + {busy ? "Creating…" : "Create montage"} + </Button> + {error && ( + <span role="alert" className="text-[12px] text-reject-text" data-phrase-create-error=""> + {error} + </span> + )} + </form> + ); +} diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -83,6 +83,8 @@ test("site pages, tools and piles", () => { assert.equal(H.siteHref("jeralyzer", { ws: "w", rel: "a/b.md" }), "/sites/jeralyzer?ws=w&rel=a%2Fb.md#files"); assert.equal(H.sitesHref({ status: "draft" }), "/work?by=site&status=draft"); assert.equal(H.findHref({ q: "um" }), "/tools/find?q=um"); + assert.equal(H.phraseFinderHref(), "/tools/phrases"); + assert.equal(H.phraseFinderHref({ q: "slow news day" }), "/tools/phrases?q=slow+news+day"); assert.equal(H.facesHref({ cover: "c 1" }), "/tools/faces?cover=c+1"); assert.equal(H.sourcesHref(), "/tools/sources"); assert.equal(H.trimHref("hooks"), "/tools/trim/hooks"); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -300,6 +300,14 @@ export function findHref(q: Query = {}): string { return withQuery("/tools/find", q); } +/** + * The phrase finder (release 34): how often phrases were said, by year, and a + * montage from one. `q` prefills the first phrase. + */ +export function phraseFinderHref(q: { q?: string; scan?: string } = {}): string { + return withQuery("/tools/phrases", q); +} + /** The face judger; `cover` opens on one cover's corners. */ export function facesHref(q: { cover?: string } = {}): string { return withQuery("/tools/faces", q); diff --git a/umtool/lib/phrase-finder.test.mjs b/umtool/lib/phrase-finder.test.mjs @@ -0,0 +1,111 @@ +// The phrase finder's own parts (release 34): the spec check, the summary, +// the slug, and `umtool phrases` over a synthetic corpus — its job form +// (--spec/--out/--progress) and its terminal form. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; +import { wordsPhraseSource } from "yt-dlp-transcript-common/lib/montage/phraseSource.mjs"; +import { checkSpec } from "./phrase-finder/scan.mjs"; +import { byYear, montageSlug, sparkline, spread, summarisePhrase } from "./phrase-finder/summary.mjs"; + +const run = promisify(execFile); +const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "bin", "umtool.mjs"); + +function corpus() { + const dir = mkdtempSync(path.join(os.tmpdir(), "phrase-finder-")); + const put = (slug, id, rec) => { + const d = path.join(dir, slug, "data", id); + mkdirSync(d, { recursive: true }); + writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ id, title: `t ${id}`, ...rec })); + }; + put("rum", "r1", { uploadDate: "20200105", duration: 600, platform: "rumble", cues: [{ start: 10, end: 13, text: "what a slow news day" }, { start: 50, end: 53, text: "nobody asked for this" }] }); + put("rum", "r2", { uploadDate: "20220310", duration: 900, platform: "rumble", cues: [{ start: 5, end: 8, text: ">> slow, news days again" }] }); + put("yt", "y1", { uploadDate: "20180101", duration: 300, platform: "youtube", cues: [{ start: 1, end: 4, text: "a slow news week this is" }, { start: 90, end: 93, text: "and nobody asked" }] }); + put("yt", "y2", { uploadDate: "20220601", duration: 400, platform: "youtube", cues: [{ start: 7, end: 9, text: "no one asked" }] }); + return dir; +} + +test("checkSpec: phrases become what is searched; a bad one is refused with its sentence", () => { + const s = checkSpec({ rows: [{ id: "a", text: " slow news day ", mode: "auto" }, { text: "" }, { text: "no ?one asked", label: "nobody asked" }], channels: "yt, rum", prefer: "rum", exclude: "" }); + assert.deepEqual(s.rows, [ + { id: "a", text: "slow news day", mode: "auto", source: wordsPhraseSource("slow news day"), used: "words" }, + { id: "p3", text: "no ?one asked", label: "nobody asked", mode: "auto", source: "no ?one asked", used: "regex" }, + ]); + assert.deepEqual(s.channels, ["yt", "rum"]); + assert.equal(s.prefer, "rum"); + assert.equal(s.exclude, null); + assert.equal(checkSpec({ rows: [{ text: "x" }], channels: ["HasanAbiVODs3"] }).channels[0], "HasanAbiVODs3"); + assert.throws(() => checkSpec({ rows: [], channels: ["yt"] }), /type a phrase/); + assert.throws(() => checkSpec({ rows: [{ text: "slow (news" }], channels: ["yt"] }), /"slow \(news": not a regular expression/); + assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: [] }), /pick at least one channel/); + assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: ["../etc"] }), /is not a channel/); + assert.throws(() => checkSpec({ rows: [{ text: "x" }], channels: ["yt"], exclude: "(" }), /exclude is not a regular expression/); + assert.throws(() => checkSpec({ rows: Array.from({ length: 31 }, (_, k) => ({ text: `w${k}` })), channels: ["yt"] }), /at most 30/); +}); + +test("the summary: by year with the gaps, the split, the spread of samples", async () => { + assert.deepEqual(byYear([{ date: "20180101" }, { date: "20200105" }, { date: "20200301" }, { date: null }]), { 2018: 1, 2019: 0, 2020: 2 }); + assert.equal(sparkline({ 2018: 1, 2019: 0, 2020: 2 }), "▄ █"); + assert.deepEqual(spread([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3), [1, 6, 11]); + assert.deepEqual(spread([1, 2], 10), [1, 2]); + assert.equal(montageSlug("slow news day"), "slow-news-day-montage"); + assert.equal(montageSlug(String.raw`\b(?:no ?one|nobody) asked\b`), "no-one-nobody-asked-montage"); + assert.equal(montageSlug("!!!"), "phrase-montage"); + + const dir = corpus(); + try { + const r = await phraseScan({ channelsDir: dir, channels: ["yt"], prefer: "rum", phrase: wordsPhraseSource("slow news day") }); + const s = summarisePhrase(r, { prefer: "rum", samples: 2 }); + assert.equal(s.instances, 2); + assert.deepEqual(s.years, { 2020: 1, 2021: 0, 2022: 1 }); + assert.equal(s.rumble, 2); + assert.equal(s.notRumble, 0); + assert.equal(s.preferred, 2); + assert.equal(s.speakerChecks, 1); + assert.deepEqual(s.samples.map((x) => x.videoId), ["r1", "r2"]); + assert.equal(s.samples[1].match, "slow, news days"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("umtool phrases: the job form writes the whole answer and its progress; the terminal form prints the numbers", async () => { + const dir = corpus(); + const cache = mkdtempSync(path.join(os.tmpdir(), "phrase-finder-cache-")); + const env = { ...process.env, CHANNELS_DIR: dir, UMTOOL_CACHE_DIR: cache }; + try { + const spec = path.join(cache, "spec.json"); + const out = path.join(cache, "out.json"); + writeFileSync(spec, JSON.stringify({ rows: [{ id: "slow", text: "slow news day" }, { id: "asked", text: String.raw`\b(?:no ?one|nobody) asked\b` }], channels: ["yt", "rum"], prefer: null })); + const { stdout } = await run(process.execPath, [CLI, "phrases", "--spec", spec, "--out", out, "--progress"], { env }); + const lines = stdout.trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(lines.at(-2).progress, { done: 4, total: 4, channel: "rum", channelsDone: 2, channels: 2 }); + assert.equal(lines.at(-1).done, true); + const answer = JSON.parse(readFileSync(out, "utf8")); + assert.equal(answer.scanned, 4); + assert.deepEqual(answer.rows.map((r) => [r.id, r.used, r.result.instances.length]), [["slow", "words", 2], ["asked", "regex", 3]]); + // Each phrase's answer is phraseScan's for it alone. + const alone = await phraseScan({ channelsDir: dir, channels: ["yt", "rum"], prefer: null, phrase: answer.rows[1].source }); + assert.deepEqual(answer.rows[1].result, JSON.parse(JSON.stringify(alone))); + + const text = await run(process.execPath, [CLI, "phrases", "slow news day", "nobody asked", "--channels", "yt,rum", "--samples", "1"], { env }); + assert.match(text.stdout, /4 transcripts read/); + assert.match(text.stdout, /slow news day {2}2 time\(s\) {2}2020–2022/); + assert.match(text.stdout, /searched as \/\\bnobody\[\\s,\.\\-\]\+asked\(\?:s\|es\)\?\\b\/ \(words\)/); + const json = JSON.parse((await run(process.execPath, [CLI, "phrases", "slow news", "--channels", "yt", "--prefer", "rum", "--json"], { env })).stdout); + assert.equal(json.rows[0].instances, 3); + assert.equal(json.rows[0].preferred, 2); + const bad = await run(process.execPath, [CLI, "phrases", "slow (news", "--channels", "yt", "--regex"], { env }).catch((e) => e); + assert.equal(bad.code, 1); + assert.match(bad.stderr, /not a regular expression/); + } finally { + rmSync(dir, { recursive: true, force: true }); + rmSync(cache, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/phrase-finder/cli.mjs b/umtool/lib/phrase-finder/cli.mjs @@ -0,0 +1,101 @@ +// `umtool phrases` (release 34): the phrase finder from a terminal, and the +// page's job. Prints, per phrase, how many times it was said once folded, by +// year, from the preferred channel or another, and how many need an ear. +// +// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] +// [--words | --regex] [--samples N] [--no-cache] [--json | --full] +// umtool phrases --spec FILE --out FILE [--progress] +// +// A phrase is plain words (a tolerant pattern: any spaces, commas or hyphens +// between the words, an optional plural) unless it holds a regular +// expression's characters; --words or --regex says which for all of them. +// --json prints the summaries, --full every instance. The second form is what +// the page's job runs: the settings in a JSON file, the whole answer written to +// --out, and with --progress one JSON line of progress per few hundred videos. +import { readFile, rename, writeFile } from "node:fs/promises"; +import { runPhraseScan } from "./scan.mjs"; +import { summarisePhrase } from "./summary.mjs"; + +function parse(args) { + const o = { phrases: [], channels: [], prefer: null, exclude: null, mode: "auto", samples: 10, cache: true, json: false, full: false, spec: null, out: null, progress: false }; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + const v = () => { + const x = args[++i]; + if (x === undefined) throw new Error(`${a} needs a value`); + return x; + }; + if (a === "--channels") o.channels.push(...v().split(",")); + else if (a === "--prefer") o.prefer = v(); + else if (a === "--exclude") o.exclude = v(); + else if (a === "--words") o.mode = "words"; + else if (a === "--regex") o.mode = "regex"; + else if (a === "--samples") o.samples = Math.max(0, Number(v()) || 0); + else if (a === "--no-cache") o.cache = false; + else if (a === "--json") o.json = true; + else if (a === "--full") o.full = true; + else if (a === "--spec") o.spec = v(); + else if (a === "--out") o.out = v(); + else if (a === "--progress") o.progress = true; + else if (a === "--help" || a === "-h") o.help = true; + else if (a.startsWith("--")) throw new Error(`unknown option ${a}`); + else o.phrases.push(a); + } + return o; +} + +const USAGE = `umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] + [--words | --regex] [--samples N] [--no-cache] [--json | --full] +umtool phrases --spec FILE --out FILE [--progress]`; + +/** @param {string[]} args @returns {Promise<number>} the exit code */ +export async function phrasesCommand(args) { + let o; + try { + o = parse(args); + } catch (e) { + console.error(`${e.message}\n\n${USAGE}`); + return 2; + } + if (o.help) { + console.log(USAGE); + return 0; + } + try { + const spec = o.spec + ? JSON.parse(await readFile(o.spec, "utf8")) + : { rows: o.phrases.map((text, k) => ({ id: `p${k + 1}`, text, mode: o.mode })), channels: o.channels, prefer: o.prefer, exclude: o.exclude }; + const onProgress = o.progress ? (p) => console.log(JSON.stringify({ progress: p })) : undefined; + const answer = await runPhraseScan(spec, { ...(o.cache ? {} : { cacheDir: null }), onProgress }); + if (o.out) { + const tmp = `${o.out}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify(answer), "utf8"); + await rename(tmp, o.out); + if (o.progress) console.log(JSON.stringify({ done: true, out: o.out, seconds: answer.seconds })); + return 0; + } + if (o.full) { + console.log(JSON.stringify(answer, null, 1)); + return 0; + } + const rows = answer.rows.map((r) => ({ id: r.id, text: r.text, searched: r.source, as: r.used, ...summarisePhrase(r.result, { prefer: answer.spec.prefer, samples: o.samples }) })); + if (o.json) { + console.log(JSON.stringify({ scanned: answer.scanned, seconds: answer.seconds, spec: answer.spec, rows }, null, 2)); + return 0; + } + console.log(`${answer.scanned} transcripts read in ${answer.seconds} s`); + for (const r of rows) { + const span = r.first ? `${String(r.first).slice(0, 4)}–${String(r.last).slice(0, 4)}` : ""; + const split = answer.spec.prefer ? `${answer.spec.prefer} ${r.preferred} · other ${r.other}` : `rumble ${r.rumble} · other ${r.notRumble}`; + console.log(""); + console.log(`${r.text} ${r.instances} time(s) ${span} ${r.spark}`); + console.log(` ${split} · speaker changes ${r.speakerChecks}${r.dropped ? ` · excluded ${r.dropped}` : ""}`); + console.log(` searched as /${r.searched}/ (${r.as})`); + for (const s of r.samples) console.log(` ${s.date ?? "?"} ${s.slug}/${s.videoId} @ ${Math.round(s.start)}s ${s.context.slice(0, 100)}`); + } + return 0; + } catch (e) { + console.error(e instanceof Error ? e.message : String(e)); + return 1; + } +} diff --git a/umtool/lib/phrase-finder/scan.d.mts b/umtool/lib/phrase-finder/scan.d.mts @@ -0,0 +1,10 @@ +import type { PhraseScanSpec } from "./types"; +export const MAX_PHRASES: number; +export const CHANNEL_RE: RegExp; +export const MODES: string[]; +export function phraseTextCacheDir(): string; +export function checkSpec(spec: unknown): PhraseScanSpec; +export function runPhraseScan( + spec: unknown, + opts?: { channelsDir?: string; cacheDir?: string | null; onProgress?: (p: unknown) => void }, +): Promise<{ version: number; spec: PhraseScanSpec; startedAt: string; seconds: number; scanned: number; rows: (PhraseScanSpec["rows"][number] & { result: unknown })[] }>; diff --git a/umtool/lib/phrase-finder/scan.mjs b/umtool/lib/phrase-finder/scan.mjs @@ -0,0 +1,95 @@ +// The phrase finder's scan (release 34): several phrases over a set of +// channels in ONE pass (phraseScanMany), each typed as plain words or a +// regular expression (phraseSource.mjs), through the cue-text cache under +// umtool's CACHE_DIR. The page runs it as a job (`umtool phrases --spec … --out +// …`, lib/phrase-finder/jobs.ts) and `umtool phrases` runs it in a terminal; +// both get this. +// +// Read-only over the channels directory. Plain ESM, no server. +import { phraseScanMany, phraseSourceOf } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs"; +import { CHANNELS_DIR, cacheFile } from "../paths.mjs"; + +/** The most phrases one scan compares. */ +export const MAX_PHRASES = 30; +/** A channel directory's name: no separators, no dot first. */ +export const CHANNEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +export const MODES = ["auto", "words", "regex"]; + +/** Where the joined cue text is cached (cueTextCache.mjs), under CACHE_DIR. */ +export const phraseTextCacheDir = () => cacheFile("phrase-text"); + +/** + * A scan's settings, checked: `{rows: [{id, text, mode, label?}], channels, + * prefer, exclude}` → the same with each row's `source` (what is searched) + * and `used` (`words` | `regex`); `label` names a phrase given as an + * expression (a suggestion's "nobody asked"). Throws a sentence naming what is wrong. + */ +export function checkSpec(spec) { + const rowsIn = Array.isArray(spec?.rows) ? spec.rows : []; + const rows = []; + const seen = new Set(); + for (const [k, r] of rowsIn.entries()) { + const text = String(r?.text ?? "").trim(); + if (!text) continue; + const mode = MODES.includes(r?.mode) ? r.mode : "auto"; + let id = String(r?.id ?? `p${k + 1}`).trim() || `p${k + 1}`; + if (!/^[A-Za-z0-9_-]{1,40}$/.test(id) || seen.has(id)) id = `p${k + 1}`; + if (seen.has(id)) throw new Error(`two phrases share the id "${id}"`); + seen.add(id); + let src; + try { + src = phraseSourceOf(text, mode); + } catch (e) { + throw new Error(`"${text}": ${e instanceof Error ? e.message : String(e)}`); + } + const label = String(r?.label ?? "").trim().slice(0, 80); + rows.push({ id, text, ...(label ? { label } : {}), mode, source: src.source, used: src.mode }); + } + if (!rows.length) throw new Error("type a phrase to search for"); + if (rows.length > MAX_PHRASES) throw new Error(`at most ${MAX_PHRASES} phrases in one search`); + const list = (v) => (Array.isArray(v) ? v : String(v ?? "").split(",")).map((c) => String(c).trim()).filter(Boolean); + const channels = [...new Set(list(spec?.channels))]; + const prefer = String(spec?.prefer ?? "").trim() || null; + for (const c of [...channels, ...(prefer ? [prefer] : [])]) if (!CHANNEL_RE.test(c)) throw new Error(`"${c}" is not a channel`); + if (!channels.length && !prefer) throw new Error("pick at least one channel"); + const exclude = String(spec?.exclude ?? "").trim() || null; + if (exclude) { + try { + new RegExp(exclude, "i"); + } catch (e) { + throw new Error(`exclude is not a regular expression: ${e instanceof Error ? e.message : String(e)}`); + } + } + return { rows, channels, prefer, exclude }; +} + +/** + * Run a checked spec: `{version, spec, startedAt, seconds, scanned, rows: + * [{id, text, mode, used, source, result}]}`, `result` being phraseScan's + * answer for that phrase alone. `cacheDir: null` reads every cue file. + */ +export async function runPhraseScan(spec, { channelsDir = CHANNELS_DIR, cacheDir = phraseTextCacheDir(), onProgress } = {}) { + const s = checkSpec(spec); + const t0 = Date.now(); + const results = await phraseScanMany({ + channelsDir, + channels: s.channels, + prefer: s.prefer, + exclude: s.exclude, + phrases: s.rows.map((r) => ({ id: r.id, phrase: r.source })), + cacheDir, + onProgress, + }); + const byId = new Map(results.map((r) => [r.id, r])); + return { + version: 1, + spec: s, + startedAt: new Date(t0).toISOString(), + seconds: Math.round((Date.now() - t0) / 100) / 10, + scanned: results[0]?.scanned ?? 0, + rows: s.rows.map((r) => { + const { id: _id, phrase: _phrase, ...result } = byId.get(r.id); + return { ...r, result }; + }), + }; +} diff --git a/umtool/lib/phrase-finder/server.ts b/umtool/lib/phrase-finder/server.ts @@ -0,0 +1,336 @@ +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { CHANNELS_DIR, REPORTS_ROOT, cacheFile } from "@/lib/paths"; +import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; +import { CHANNEL_RE, checkSpec } from "./scan.mjs"; +import { summarisePhrase } from "./summary.mjs"; +import type { PhraseChannel, PhraseFinderState, PhraseScanRowView, PhraseScanSpec, PhraseScanView, PhraseSuggestion } from "./types"; + +// --------------------------------------------------------------------------- +// THE PHRASE FINDER's server half (release 34; the page is /tools/phrases). +// +// a scan runs as a CHILD PROCESS, `umtool phrases --spec … --out … +// --progress` (lib/phrase-finder/cli.mjs), never inside a request: +// over a big corpus it reads tens of thousands of cue files, and +// a request that waited would time out, and a server that read +// them itself would hold their memory. Its progress lines are +// read off its stdout; its answer is a file. One scan at a time. +// the store CACHE_DIR/phrase-finder/: scans/<id>.json (the whole answer, +// what Create montage seeds a project from), specs/<id>.json, and +// last.json (the channels, prefer, exclude and phrases of the last +// search, the page's defaults). A cache: delete it at any time. +// suggestions candidates.json files of a catchphrase report: the paths in +// UMTOOL_PHRASE_CANDIDATES (":"-separated), else every +// <REPORTS_ROOT>/<dir>/candidates.json with the report's shape +// (`{scanned: [{key, regex, instances, …}]}`). +// +// SERVER ONLY. Every path here carries the Turbopack opt-out (lib/paths.mjs, +// findRepoRoot): CHANNELS_DIR and the cache are the user's, not the app's. +// --------------------------------------------------------------------------- + +const STORE = () => cacheFile("phrase-finder"); +// A video directory's name: a YouTube id may start with a dash or an underscore; never a dot. +const VIDEO_RE = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/; +const SCAN_ID_RE = /^ps-\d{14}-[0-9a-f]{6}$/; +const scanFile = (id: string) => path.join(/* turbopackIgnore: true */ STORE(), "scans", `${id}.json`); +const specFile = (id: string) => path.join(/* turbopackIgnore: true */ STORE(), "specs", `${id}.json`); +const LAST = () => path.join(/* turbopackIgnore: true */ STORE(), "last.json"); +/** Finished scans kept on disk; older ones are removed when a scan starts. */ +const KEEP_SCANS = 20; + +export const isScanId = (id: unknown): id is string => typeof id === "string" && SCAN_ID_RE.test(id); + +type Job = { + id: string; + state: "running" | "done" | "failed" | "cancelled"; + startedAt: number; + endedAt: number | null; + spec: PhraseScanSpec; + progress: PhraseScanView["progress"]; + error: string | null; + pid: number | null; + log: string[]; +}; +type Registry = { jobs: Map<string, Job> }; +const g = globalThis as typeof globalThis & { __umtoolPhraseScans?: Registry }; +const reg: Registry = (g.__umtoolPhraseScans ??= { jobs: new Map() }); + +const runningScan = () => [...reg.jobs.values()].find((j) => j.state === "running") ?? null; + +async function writeAtomic(file: string, text: string) { + await mkdir(path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(/* turbopackIgnore: true */ tmp, text, "utf8"); + await rename(/* turbopackIgnore: true */ tmp, file); +} + +async function readJsonFile<T>(file: string): Promise<T | null> { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")) as T; + } catch { + return null; + } +} + +function newScanId(): string { + const d = new Date(); + const p = (n: number, w = 2) => String(n).padStart(w, "0"); + const stamp = `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`; + return `ps-${stamp}-${randomBytes(3).toString("hex")}`; +} + +async function pruneScans() { + const dir = path.join(/* turbopackIgnore: true */ STORE(), "scans"); + const names = (await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[])).filter((n) => /^ps-.*\.json$/.test(n)).sort(); + for (const n of names.slice(0, Math.max(0, names.length - KEEP_SCANS))) { + await rm(path.join(/* turbopackIgnore: true */ dir, n), { force: true }); + await rm(path.join(/* turbopackIgnore: true */ STORE(), "specs", n), { force: true }); + } +} + +/** + * Start a scan of `spec` (checked first: a bad phrase is refused here, in the + * request, with its sentence). Refuses while another scan runs. + */ +export async function startPhraseScan(raw: unknown): Promise<{ id: string }> { + const spec = checkSpec(raw) as PhraseScanSpec; + const running = runningScan(); + if (running) throw Object.assign(new Error("a search is already running"), { status: 409, running: running.id }); + await pruneScans(); + const id = newScanId(); + await writeAtomic(specFile(id), JSON.stringify(spec)); + await writeAtomic(LAST(), JSON.stringify({ channels: spec.channels, prefer: spec.prefer, exclude: spec.exclude, rows: spec.rows.map((r) => ({ text: r.text, mode: r.mode, ...(r.label ? { label: r.label } : {}) })) })); + const job: Job = { id, state: "running", startedAt: Date.now(), endedAt: null, spec, progress: null, error: null, pid: null, log: [] }; + reg.jobs.set(id, job); + + const cli = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + const child = spawn(process.execPath, [cli, "phrases", "--spec", specFile(id), "--out", scanFile(id), "--progress"], { + cwd: UMTOOL_DIR, + env: process.env, + stdio: ["ignore", "pipe", "pipe"], + detached: true, + }); + job.pid = child.pid ?? null; + let buf = ""; + child.stdout.on("data", (b: Buffer) => { + buf += b.toString(); + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + try { + const m = JSON.parse(line); + if (m?.progress) job.progress = m.progress; + } catch { + job.log.push(line); + } + } + }); + child.stderr.on("data", (b: Buffer) => { + job.log.push(...b.toString().split("\n").filter((l) => l.trim())); + if (job.log.length > 50) job.log.splice(0, job.log.length - 50); + }); + const end = (state: Job["state"], error: string | null) => { + if (job.state !== "running") return; + job.state = state; + job.error = error; + job.endedAt = Date.now(); + }; + child.on("error", (e) => end("failed", e.message)); + child.on("close", (code) => { + if (job.state !== "running") return; + if (code === 0) end("done", null); + else end("failed", job.log.at(-1) ?? `the search exited ${code}`); + }); + return { id }; +} + +/** Stop a running scan (its whole process group). */ +export function cancelPhraseScan(id: string): boolean { + const job = reg.jobs.get(id); + if (!job || job.state !== "running") return false; + job.state = "cancelled"; + job.endedAt = Date.now(); + if (job.pid) { + try { + process.kill(-job.pid, "SIGTERM"); + } catch { + /* gone */ + } + } + return true; +} + +type ScanAnswer = { + version: number; + spec: PhraseScanSpec; + startedAt: string; + seconds: number; + scanned: number; + rows: (PhraseScanSpec["rows"][number] & { result: { instances: unknown[]; hits: unknown[]; dropped: unknown[]; scanned: number } })[]; +}; + +// One answer file is a few MB; the page polls the view, so the last few are kept parsed. +const answers = new Map<string, { at: number; answer: ScanAnswer }>(); +async function readAnswer(id: string): Promise<ScanAnswer | null> { + if (!isScanId(id)) return null; + const st = await stat(/* turbopackIgnore: true */ scanFile(id)).catch(() => null); + if (!st) return null; + const kept = answers.get(id); + if (kept && kept.at === st.mtimeMs) return kept.answer; + const answer = await readJsonFile<ScanAnswer>(scanFile(id)); + if (!answer) return null; + answers.set(id, { at: st.mtimeMs, answer }); + while (answers.size > 4) answers.delete(answers.keys().next().value as string); + return answer; +} + +/** What the page shows of a scan: its state and progress, and once done each phrase's numbers. */ +export async function phraseScanView(id: string): Promise<PhraseScanView | null> { + if (!isScanId(id)) return null; + const job = reg.jobs.get(id) ?? null; + const spec = job?.spec ?? (await readJsonFile<PhraseScanSpec>(specFile(id))); + if (!spec) return null; + const answer = !job || job.state === "done" ? await readAnswer(id) : null; + const state = job?.state ?? (answer ? "done" : "failed"); + const rows: PhraseScanRowView[] | null = answer + ? answer.rows.map((r) => ({ + id: r.id, + text: r.text, + ...(r.label ? { label: r.label } : {}), + mode: r.mode, + used: r.used, + source: r.source, + summary: summarisePhrase(r.result, { prefer: answer.spec.prefer }) as PhraseScanRowView["summary"], + })) + : null; + return { + id, + state, + spec, + startedAt: job ? new Date(job.startedAt).toISOString() : (answer?.startedAt ?? null), + seconds: answer?.seconds ?? (job ? Math.round(((job.endedAt ?? Date.now()) - job.startedAt) / 100) / 10 : null), + progress: job?.progress ?? null, + error: job?.error ?? (answer ? null : "this search's answer is gone (the cache was cleared): search again"), + scanned: answer?.scanned ?? null, + rows, + }; +} + +/** + * One phrase of a finished scan, whole — for Create montage. Refuses a scan + * whose settings are not the ones given, so a project is seeded only from + * the search it says it is. + */ +export async function scanRowFor(id: string, row: string, want: { phrase: string; channels: string[]; prefer: string | null; exclude: string | null }) { + const answer = await readAnswer(id); + if (!answer) throw new Error("that search is gone: search again"); + const r = answer.rows.find((x) => x.id === row); + if (!r) throw new Error(`that search has no phrase "${row}"`); + const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]); + if (r.source !== want.phrase || !same(answer.spec.channels, want.channels) || (answer.spec.prefer ?? null) !== (want.prefer ?? null) || (answer.spec.exclude ?? null) !== (want.exclude ?? null)) { + throw new Error("the search does not match these settings: search again"); + } + return r.result; +} + +// ── the page's defaults ───────────────────────────────────────────────────── + +let channelsCache: { at: number; list: PhraseChannel[] } | null = null; + +/** The channels with transcripts (a social channel has none), by name. Cached a minute. */ +export async function phraseChannels(): Promise<PhraseChannel[]> { + if (channelsCache && Date.now() - channelsCache.at < 60_000) return channelsCache.list; + const out: PhraseChannel[] = []; + const dirs = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR, { withFileTypes: true }).catch(() => []); + for (const d of dirs) { + if (!d.isDirectory() || !CHANNEL_RE.test(d.name)) continue; + const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, d.name); + const cfg = await readJsonFile<{ name?: string; platform?: string; sourceKind?: string }>(path.join(/* turbopackIgnore: true */ dir, "config.json")); + if (cfg?.sourceKind === "social") continue; + const videos = (await readdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "data")).catch(() => [] as string[])).length; + if (!videos) continue; + out.push({ slug: d.name, name: cfg?.name || d.name, platform: cfg?.platform ?? null, videos }); + } + out.sort((a, b) => a.name.localeCompare(b.name)); + channelsCache = { at: Date.now(), list: out }; + return out; +} + +/** The suggestions: each candidates file's phrases, as the report ranked them. */ +export async function phraseSuggestions(): Promise<PhraseSuggestion[]> { + const env = (process.env.UMTOOL_PHRASE_CANDIDATES ?? "").split(":").map((s) => s.trim()).filter(Boolean); + let files = env; + if (!files.length) { + const dirs = await readdir(/* turbopackIgnore: true */ REPORTS_ROOT, { withFileTypes: true }).catch(() => []); + files = dirs.filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => path.join(/* turbopackIgnore: true */ REPORTS_ROOT, d.name, "candidates.json")); + } + const out: PhraseSuggestion[] = []; + for (const f of files.sort()) { + const doc = await readJsonFile<{ scanned?: { key?: string; regex?: string; instances?: number; perYear?: Record<string, number>; spark?: string }[] }>(f); + if (!Array.isArray(doc?.scanned)) continue; + const from = path.basename(path.dirname(/* turbopackIgnore: true */ f)); + for (const c of doc.scanned) { + if (typeof c?.regex !== "string" || !c.regex.trim()) continue; + try { + new RegExp(c.regex, "i"); + } catch { + continue; + } + out.push({ key: String(c.key ?? c.regex), regex: c.regex, instances: Number(c.instances) || null, spark: typeof c.spark === "string" ? c.spark : null, from }); + } + } + return out; +} + +/** Everything the page opens with. */ +export async function phraseFinderState(): Promise<PhraseFinderState> { + const [channels, suggestions, last] = await Promise.all([phraseChannels(), phraseSuggestions(), readJsonFile<PhraseFinderState["last"]>(LAST())]); + const running = runningScan(); + const dir = path.join(/* turbopackIgnore: true */ STORE(), "scans"); + const recent = (await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[])) + .filter((n) => /^ps-.*\.json$/.test(n)) + .map((n) => n.replace(/\.json$/, "")) + .sort() + .reverse() + .slice(0, 8); + const known = new Set(channels.map((c) => c.slug)); + return { + channels, + suggestions, + last: last + ? { + channels: (last.channels ?? []).filter((c) => known.has(c)), + prefer: last.prefer && known.has(last.prefer) ? last.prefer : null, + exclude: last.exclude ?? null, + rows: Array.isArray(last.rows) ? last.rows.slice(0, 30) : [], + } + : null, + running: running?.id ?? null, + recent, + }; +} + +// ── the transcript position ───────────────────────────────────────────────── + +/** The cues around a second of a video (`span` either side), for reading a hit where it was said. */ +export async function transcriptAround(channel: string, video: string, at: number, span = 5) { + if (!CHANNEL_RE.test(channel) || !VIDEO_RE.test(video)) throw new Error("not a video"); + const doc = await readJsonFile<{ title?: string; uploadDate?: string; cues?: { start: number; end?: number; text?: string }[] }>( + path.join(/* turbopackIgnore: true */ CHANNELS_DIR, channel, "data", video, "transcript.cues.json"), + ); + if (!doc || !Array.isArray(doc.cues)) return null; + const cues = doc.cues.filter((c) => c && Number.isFinite(Number(c.start))); + let k = cues.findIndex((c) => Number(c.start) >= at - 0.01); + if (k < 0) k = cues.length - 1; + const lo = Math.max(0, k - span); + return { + title: doc.title ?? null, + date: doc.uploadDate ?? null, + at, + cues: cues.slice(lo, Math.min(cues.length, k + span + 1)).map((c) => ({ start: Number(c.start), end: Number(c.end ?? c.start), text: String(c.text ?? ""), lit: Number(c.start) === Number(cues[k]?.start) })), + }; +} diff --git a/umtool/lib/phrase-finder/summary.d.mts b/umtool/lib/phrase-finder/summary.d.mts @@ -0,0 +1,7 @@ +import type { PhraseSummary } from "./types"; +export function yearOf(date: unknown): string | null; +export function byYear(instances: { date?: string | null }[]): Record<string, number>; +export function sparkline(years: Record<string, number>): string; +export function spread<T>(list: T[], n: number): T[]; +export function summarisePhrase(result: unknown, opts?: { prefer?: string | null; samples?: number }): PhraseSummary; +export function montageSlug(text: string): string; diff --git a/umtool/lib/phrase-finder/summary.mjs b/umtool/lib/phrase-finder/summary.mjs @@ -0,0 +1,97 @@ +// The phrase finder's numbers (release 34), from one phrase's scan +// (common/lib/montage/phraseScan.mjs: phraseScan or phraseScanMany): how many +// times it was said once folded, by year, from the preferred (Rumble) copy or +// another channel, how many need an ear for who says it, and a handful of +// contexts spread over the years to read and play. +// +// Pure, so the page, its API and `umtool phrases` print the same numbers. + +/** `YYYYMMDD…` → `YYYY`, or null. */ +export const yearOf = (date) => (/^(\d{4})/.exec(String(date ?? ""))?.[1] ?? null); + +/** `{year: count}` over the instances, in year order, every year between the first and the last present (0 for a gap). */ +export function byYear(instances) { + const n = new Map(); + for (const i of instances) { + const y = yearOf(i.date); + if (y) n.set(y, (n.get(y) ?? 0) + 1); + } + const ys = [...n.keys()].map(Number).sort((a, b) => a - b); + const out = {}; + if (!ys.length) return out; + for (let y = ys[0]; y <= ys[ys.length - 1]; y++) out[String(y)] = n.get(String(y)) ?? 0; + return out; +} + +const BARS = " ▁▂▃▄▅▆▇█"; +/** A one-line bar row of `byYear`: one character per year. */ +export function sparkline(years) { + const vals = Object.values(years); + const max = Math.max(0, ...vals); + if (!max) return ""; + return vals.map((v) => (v ? BARS[Math.max(1, Math.round((v / max) * 8))] : BARS[0])).join(""); +} + +/** Pick `n` of `list` spread evenly from first to last (all of them when there are fewer). */ +export function spread(list, n) { + if (list.length <= n) return list.slice(); + if (n <= 1) return list.slice(0, Math.max(0, n)); + const out = []; + for (let k = 0; k < n; k++) out.push(list[Math.round((k * (list.length - 1)) / (n - 1))]); + return out; +} + +/** + * One phrase's summary. `prefer` is the preferred channel (the Rumble copy): + * an instance there counts as `preferred`, every other as `other`; `rumble` + * counts by platform, whatever the channel. `samples` contexts (10) are spread + * over the chronological instances. + */ +export function summarisePhrase(result, { prefer = null, samples = 10 } = {}) { + const instances = Array.isArray(result?.instances) ? result.instances : []; + const bySlug = {}; + for (const i of instances) bySlug[i.slug] = (bySlug[i.slug] ?? 0) + 1; + const years = byYear(instances); + return { + instances: instances.length, + hits: Array.isArray(result?.hits) ? result.hits.length : 0, + dropped: Array.isArray(result?.dropped) ? result.dropped.length : 0, + scanned: Number(result?.scanned) || 0, + years, + spark: sparkline(years), + rumble: instances.filter((i) => i.platform === "rumble").length, + notRumble: instances.filter((i) => i.platform !== "rumble").length, + preferred: prefer ? instances.filter((i) => i.slug === prefer).length : 0, + other: prefer ? instances.filter((i) => i.slug !== prefer).length : instances.length, + placed: instances.filter((i) => i.via).length, + speakerChecks: instances.filter((i) => i.speakerCheck).length, + bySlug, + first: instances[0]?.date ?? null, + last: instances[instances.length - 1]?.date ?? null, + samples: spread(instances, samples).map((i) => ({ + slug: i.slug, + videoId: i.videoId, + date: i.date ?? null, + title: i.title ?? null, + platform: i.platform ?? null, + start: i.start, + end: i.end, + match: i.match, + context: String(i.context ?? "").slice(0, 300), + speakerCheck: Boolean(i.speakerCheck), + ...(i.via ? { via: { slug: i.via.slug, videoId: i.via.videoId } } : {}), + })), + }; +} + +/** A phrase as a project slug: `slow news day` → `slow-news-day-montage`; a regex keeps its letters. */ +export function montageSlug(text) { + const base = String(text ?? "") + .toLowerCase() + .replace(/\\[bswd]/g, " ") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 48) + .replace(/-+$/g, ""); + return `${base || "phrase"}-montage`; +} diff --git a/umtool/lib/phrase-finder/types.ts b/umtool/lib/phrase-finder/types.ts @@ -0,0 +1,79 @@ +// The phrase finder's shapes (release 34), shared by its server +// (lib/phrase-finder/server.ts, the /api/phrase-finder routes) and the page +// (components/tools/PhraseFinder.tsx). Types only. + +export type PhraseMode = "auto" | "words" | "regex"; + +/** A checked search (lib/phrase-finder/scan.mjs checkSpec). */ +export type PhraseScanSpec = { + rows: { id: string; text: string; label?: string; mode: PhraseMode; source: string; used: "words" | "regex" }[]; + channels: string[]; + prefer: string | null; + exclude: string | null; +}; + +export type PhraseSample = { + slug: string; + videoId: string; + date: string | null; + title: string | null; + platform: string | null; + start: number; + end: number; + match: string; + context: string; + speakerCheck: boolean; + via?: { slug: string; videoId: string }; +}; + +/** One phrase's numbers (lib/phrase-finder/summary.mjs summarisePhrase). */ +export type PhraseSummary = { + instances: number; + hits: number; + dropped: number; + scanned: number; + years: Record<string, number>; + spark: string; + rumble: number; + notRumble: number; + preferred: number; + other: number; + placed: number; + speakerChecks: number; + bySlug: Record<string, number>; + first: string | null; + last: string | null; + samples: PhraseSample[]; +}; + +export type PhraseScanRowView = { id: string; text: string; label?: string; mode: PhraseMode; used: "words" | "regex"; source: string; summary: PhraseSummary }; + +export type PhraseScanView = { + id: string; + state: "running" | "done" | "failed" | "cancelled"; + spec: PhraseScanSpec; + startedAt: string | null; + seconds: number | null; + progress: { done: number; total: number; channel: string; channelsDone: number; channels: number } | null; + error: string | null; + scanned: number | null; + rows: PhraseScanRowView[] | null; +}; + +export type PhraseChannel = { slug: string; name: string; platform: string | null; videos: number }; +export type PhraseSuggestion = { key: string; regex: string; instances: number | null; spark: string | null; from: string }; + +export type PhraseFinderState = { + channels: PhraseChannel[]; + suggestions: PhraseSuggestion[]; + last: { channels: string[]; prefer: string | null; exclude: string | null; rows: { text: string; mode: PhraseMode; label?: string }[] } | null; + running: string | null; + recent: string[]; +}; + +export type TranscriptAround = { + title: string | null; + date: string | null; + at: number; + cues: { start: number; end: number; text: string; lit: boolean }[]; +}; diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -11,6 +11,8 @@ import { instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/monta import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs"; export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; +// A channel's directory name: mixed case is a channel too (HasanAbiVODs3); no separators, no dot first. +export const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; export const SEEDS = ["chapters", "frames", "phrase"]; /** @@ -222,11 +224,14 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po * regular expression, case-insensitive) was said in `channels`, cut from the * `prefer` channel's copy where one exists (common/lib/montage/phraseScan.mjs), * chronological; a context matching `exclude` is left out. The scan's whole - * answer is written beside the manifest as `phrase-scan.json`. + * answer is written beside the manifest as `phrase-scan.json`. `scan` (release + * 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. * - * @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 }} 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 }} 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 }) { +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 }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -255,8 +260,9 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site } const list = [...(channels ?? []), ...(prefer ? [prefer] : [])].map((c) => String(c).trim()).filter(Boolean); if (!list.length) throw new Error("--seed phrase needs --channels (and optionally --prefer)"); - for (const c of list) if (!SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`); - } else if (phrase || channels?.length || prefer || exclude) { + 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"); } if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); @@ -323,7 +329,7 @@ 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 = await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null }); + const scan = given ?? (await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null })); doc.timeline = instancesAsClips(scan.instances); doc.render.transition = 0; // The window already carries its margin (2.5 s each side), and the editor diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts @@ -4,6 +4,7 @@ import { ScaffoldError, scaffoldSong } from "./scaffold-song"; import { scaffoldReportVideo } from "./scaffold.mjs"; import { kindById } from "./kinds.mjs"; import { invalidateProjects } from "../projects"; +import { scanRowFor } from "../phrase-finder/server"; export { ScaffoldError }; @@ -24,6 +25,9 @@ export type NewProjectBody = { channels?: string[] | string | null; prefer?: string | null; exclude?: string | null; + // 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; }; /** @@ -38,6 +42,22 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str const slug = String(body.slug ?? "").trim().toLowerCase(); let result: { href: string; [k: string]: unknown }; + const channelList = (Array.isArray(body.channels) ? body.channels : String(body.channels ?? "").split(",")) + .map((c) => String(c).trim()) + .filter(Boolean); + let scan: Awaited<ReturnType<typeof scanRowFor>> | null = null; + if (body.seed === "phrase" && body.scan?.id && body.scan.row) { + try { + scan = await scanRowFor(String(body.scan.id), String(body.scan.row), { + phrase: String(body.phrase ?? ""), + channels: channelList, + prefer: body.prefer || null, + exclude: body.exclude || null, + }); + } catch (e) { + throw new ScaffoldError(e instanceof Error ? e.message : String(e), 400); + } + } if (kind === SONG_KIND) { result = await scaffoldSong({ slug, title: body.title }); } else { @@ -53,11 +73,10 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str ...(body.seed === "phrase" ? { phrase: body.phrase ?? null, - channels: (Array.isArray(body.channels) ? body.channels : String(body.channels ?? "").split(",")) - .map((c) => String(c).trim()) - .filter(Boolean), + channels: channelList, prefer: body.prefer || null, exclude: body.exclude || null, + ...(scan ? { scan } : {}), } : {}), ...(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 @@ -64,3 +64,26 @@ test("--seed phrase refuses what it cannot scan", async () => { await rm(tmp, { recursive: true, force: true }); } }); + +test("--seed phrase with a finished scan (release 34, the phrase finder): the same project, the corpus not read again", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-phrase-seed-")); + try { + const channelsDir = path.join(tmp, "channels"); + await video(channelsDir, "synth-rumble", "r1", { uploadDate: "20230102", duration: 1000, platform: "rumble", cues: [{ start: 100, end: 103, text: "kind of a slow news day today" }] }); + await video(channelsDir, "Synth-YT", "y0", { uploadDate: "20190502", duration: 600, platform: "youtube", cues: [{ start: 4, end: 6, text: "a slow" }, { start: 6, end: 8, text: "news week indeed" }] }); + const { phraseScanMany } = await import("yt-dlp-transcript-common/lib/montage/phraseScan.mjs"); + const phrase = String.raw`slow[\s,]+news`; + const [{ id: _id, phrase: _p, ...scan }] = await phraseScanMany({ channelsDir, channels: ["Synth-YT"], prefer: "synth-rumble", phrases: [{ id: "a", phrase }] }); + const args = { root: path.join(tmp, "reports"), seed: "phrase", phrase, channels: ["Synth-YT"], prefer: "synth-rumble" }; + const fresh = await scaffoldReportVideo({ ...args, slug: "fresh", channelsDir }); + // An empty channels dir: only the given scan can seed it. + const given = await scaffoldReportVideo({ ...args, slug: "given", channelsDir: path.join(tmp, "nothing"), scan }); + assert.equal(given.seeded, 2); + const read = async (dir, f) => (await readFile(path.join(dir, f), "utf8")).replaceAll("given", "fresh"); + for (const f of ["video.manifest.json", "phrase-scan.json", "README.md"]) assert.equal(await read(given.dir, f), await read(fresh.dir, f), f); + await assert.rejects(scaffoldReportVideo({ ...args, slug: "bad", channelsDir, scan: { instances: "no" } }), /a phrase scan is/); + await assert.rejects(scaffoldReportVideo({ root: args.root, slug: "bad2", channelsDir, scan }), /go with --seed phrase/); + } finally { + await rm(tmp, { recursive: true, force: true }); + } +});