Archilyzer · Source

archilyzer

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

commit e1ce4c91f7e4444cf8d301fc7268ceefbb56fd4e
parent e7651e36816e234e287516d0fde7ba0b454247ea
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 13:06:08 -0400

Merge r31/respell: an article corrects what the transcripts mishear in its quotes (archilyzer reports respell: preview, then --apply; bracketing per respelling), and every quote check applies the respellings to both sides

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

Diffstat:
MCOMMANDS.md | 1+
MREPORT.md | 1+
Mcommon/bin/archilyzer.ts | 15+++++++++++++++
Mcommon/bin/reports-check.ts | 8++++----
Acommon/bin/reports-respell.test.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/reports-respell.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/citations/respell.d.mts | 28++++++++++++++++++++++++++++
Acommon/lib/citations/respell.mjs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/citations/respell.test.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/citations/verify.ts | 38++++++++++++++++++++++++++++----------
Acommon/lib/report/respellArticle.ts | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/respellManifest.d.mts | 9+++++++++
Acommon/lib/report/respellManifest.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/respellReport.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/respellReport.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/schema.ts | 11+++++++++++
Mcommon/package.json | 2++
Mcommon/publish/composeReports.ts | 10++++++----
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 21+++++++++++++++++++++
Aplans/release-31/respell.md | 28++++++++++++++++++++++++++++
Mumtool/app/api/report/cut/route.ts | 8++++++--
Mumtool/report-to-video/cut-to-quote.test.mjs | 17+++++++++++++++++
Mumtool/report-to-video/resolve-windows.mjs | 15+++++++++++----
24 files changed, 1053 insertions(+), 24 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -36,6 +36,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster &lt;image&gt;\] \[--caption &lt;line&gt;\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) | | `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/&lt;id&gt;/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) | | `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | +| `archilyzer reports respell` | `<articleId> --heard <form,…> --reads <word> [--bracket] [--note <text>] [--iteration <n>] [--apply] [--json]` | correct what the transcripts mishear across an article's quotes: each heard form (words, case-insensitive, a plural s carried) reads as --reads in the quotes of iteration n's report.json (default: the iteration the current report came from), the article's report.json when it is that report, and the iteration's video manifest (burned-in quotes, flip cards) — plainly, or bracketed (\[K-Cup\]) with --bracket; the report's own words plainly. Each file gains `respellings`, which every quote check (compose, verify-quotes, the video's cut-to-quote) applies to the transcript before comparing, so a corrected quote verifies as its original did. A dry run printing every change as before → after unless --apply, which backs each file up to the project's revisions/ first (exit 1 when nothing would change; 2 for usage, or no such article or iteration) | | `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | | `archilyzer frames rederive` | `<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json]` | work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.&lt;profile&gt;.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` checks that (exit 1 when there is no sidecar; 2 for usage) | diff --git a/REPORT.md b/REPORT.md @@ -40,6 +40,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `citations` | no | The report's citations, by id — see [CITATIONS.md](CITATIONS.md). A citation is cited from markdown with `[label](cite:<id>)` and listed under the claims that rest on it. Absent = none. | | `sections` | yes | The report's sections, in order. | | `entries` | no | The report's timeline: dated entries, appended over time and shown newest first under "Timeline", before the claims — see `entries[]` below. With entries and a public `siteUrl`, the report publishes feeds of them (`feed.xml`, RSS 2.0; `feed.json`, JSON Feed 1.1). Absent = none. | +| `respellings` | no | What the transcripts mishear, corrected where the report quotes them: `[{ "heard": ["cake cup", "cakeup"], "reads": "K-Cup", "bracket": false }]`. Each heard form (words, case-insensitive, a plural `s` carried) reads as `reads` in the report's quotes — bracketed, `[K-Cup]`, when `bracket` is true — and every quote check applies the same respellings to the transcript before comparing, so a corrected quote verifies as its verbatim original did. Written by `archilyzer reports respell`. Absent = none. | | `slides` | no | How the report reads as slides (its page's Slides and Overview views, `slides.html`, `slides.pdf`) — see `slides` below. Absent = slides derived from its text. | #### `sections[]` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -414,6 +414,21 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["reports", "respell"], + usage: + "<articleId> --heard <form,…> --reads <word> [--bracket] [--note <text>] [--iteration <n>] [--apply] [--json] correct what the transcripts mishear across an article's quotes: each heard form (words, case-insensitive, a plural s carried) reads as --reads in the quotes of iteration n's report.json (default: the iteration the current report came from), the article's report.json when it is that report, and the iteration's video manifest (burned-in quotes, flip cards) — plainly, or bracketed ([K-Cup]) with --bracket; the report's own words plainly. Each file gains `respellings`, which every quote check (compose, verify-quotes, the video's cut-to-quote) applies to the transcript before comparing, so a corrected quote verifies as its original did. A dry run printing every change as before → after unless --apply, which backs each file up to the project's revisions/ first (exit 1 when nothing would change; 2 for usage, or no such article or iteration)", + flags: { heard: "string", reads: "string", bracket: "boolean", note: "string", iteration: "string", apply: "boolean", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [article] = positionals; + if (!article) { + console.error("reports respell: give <articleId>"); + return 2; + } + return (await import("./reports-respell")).respellRow(article, flags as Parameters<typeof import("./reports-respell").respellRow>[1]); + }, + }, + { path: ["reports", "bench-verdicts"], usage: "--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage)", diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -255,8 +255,8 @@ export async function verifyReportQuotes( results.push({ ...base, status: "missing-post", message: `no post ${c.id} in the posts archive of "${c.channel}"` }); continue; } - const v = quoteVerification(c.quote, postText, now); - const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText); + const v = quoteVerification(c.quote, postText, now, report.respellings); + const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText, report.respellings); const frag = fragmentOf(c.quote); const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : frag ? "fragment" : "ok"; const sentence = status === "fragment" ? fullSentenceFor(frag!.part, [{ start: 0, end: 1, text: postText }], 0) : null; @@ -286,7 +286,7 @@ export async function verifyReportQuotes( results.push({ ...base, status: "no-cues", message: `${c.channel}/${c.id} has no transcript cues to check the quote against` }); continue; } - const checked = checkSpanQuote(record, c, now); + const checked = checkSpanQuote(record, c, now, report.respellings); const score = checked.verification.quoteScore ?? 0; const best = checked.tracks.reduce<{ name: string; score: number } | null>( (b, t) => (!b || t.score > b.score ? t : b), @@ -302,7 +302,7 @@ export async function verifyReportQuotes( if (!quoteDrifted(checked.verification)) { const tracks = record.tracks.length ? record.tracks.map((t) => t.cues) : [record.cues]; for (const cues of tracks) { - const r = strictQuoteCheck(c.quote, cues, c.start); + const r = strictQuoteCheck(c.quote, cues, c.start, { respellings: report.respellings }); if (!strict || r.ok) strict = r; if (r.ok) { strictCues = cues; diff --git a/common/bin/reports-respell.test.ts b/common/bin/reports-respell.test.ts @@ -0,0 +1,108 @@ +// `archilyzer reports respell`: a dry run that writes nothing, then --apply through the +// registry and the iterations store, with backups; a temp store. +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { writeArticle } from "../lib/report/registry"; +import { createIteration, makeCurrent, updateIteration, writeIterationFile } from "../lib/report/iterations"; +import { respellMain } from "./reports-respell"; + +const ROOTS: string[] = []; +after(() => { + for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); +}); + +function setup() { + const root = mkdtempSync(path.join(tmpdir(), "reports-respell-")); + ROOTS.push(root); + const paths = { articlesDir: path.join(root, "reports"), exportIndexDir: path.join(root, ".export-index") }; + return { paths, projectsRoot: path.join(root, "projects") }; +} + +const doc = (id: string) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "Coffee", body: 'He said [“my own cakeup machine”](cite:a).' }], + citations: { a: { kind: "video", channel: "ch", id: "v1", start: 1, end: 2, quote: "my own cakeup machine" } }, +}); + +function capture() { + const lines: string[] = []; + const errors: string[] = []; + return { out: { log: (s: string) => lines.push(s), error: (s: string) => errors.push(s) }, lines, errors }; +} + +const FLAGS = { heard: "cake cup, cakeup", reads: "K-Cup" }; + +test("dry by default: every change listed, nothing written; --apply writes the iteration, the article and the manifest, backed up", async () => { + const s = setup(); + await writeArticle(doc("cb"), { paths: s.paths }); + await createIteration("cb", { kind: "sweep", model: "claude-code", question: "Q?" }, s.paths); + await writeIterationFile("cb", 1, "report.json", doc("cb"), s.paths); + await updateIteration("cb", 1, { status: "done" }, s.paths); + await makeCurrent("cb", 1, s.paths); + const project = path.join(s.projectsRoot, "cb", "i1"); + mkdirSync(project, { recursive: true }); + const manifestFile = path.join(project, "video.manifest.json"); + writeFileSync(manifestFile, JSON.stringify({ slug: "cb", timeline: [{ id: "c", quote: "my own cakeup machine" }] })); + const articleFile = path.join(s.paths.articlesDir, "cb", "report.json"); + const iterFile = path.join(s.paths.articlesDir, "cb", "iterations", "1", "report.json"); + const before = readFileSync(articleFile, "utf8"); + + const dry = capture(); + assert.equal(await respellMain("cb", FLAGS, s, dry.out), 0); + assert.equal(readFileSync(articleFile, "utf8"), before); + const text = dry.lines.join("\n"); + assert.match(text, /«cakeup» → «K-Cup»/); + assert.match(text, /iteration-report .*: 2 change\(s\)/); + assert.match(text, /article-report .*: 2 change\(s\)/); + assert.match(text, /video-manifest .*: 1 change\(s\)/); + assert.match(text, /dry run: nothing written/); + + const run = capture(); + assert.equal(await respellMain("cb", { ...FLAGS, apply: true }, s, run.out), 0); + for (const f of [articleFile, iterFile]) { + const r = JSON.parse(readFileSync(f, "utf8")); + assert.equal(r.citations.a.quote, "my own K-Cup machine"); + assert.match(r.sections[0].body, /my own K-Cup machine/); + assert.deepEqual(r.respellings, [{ heard: ["cake cup", "cakeup"], reads: "K-Cup" }]); + } + assert.equal(JSON.parse(readFileSync(manifestFile, "utf8")).timeline[0].quote, "my own K-Cup machine"); + const backups = readdirSync(path.join(project, "revisions")); + assert.equal(backups.length, 3); + assert.ok(backups.some((b) => b.endsWith("-before-respell.article-report.json"))); + // The backup is the file as it was. + const ab = backups.find((b) => b.endsWith("article-report.json"))!; + assert.equal(readFileSync(path.join(project, "revisions", ab), "utf8"), before); + + // Again: nothing left to change. + const again = capture(); + assert.equal(await respellMain("cb", { ...FLAGS, apply: true }, s, again.out), 1); + assert.equal(readdirSync(path.join(project, "revisions")).length, 3); +}); + +test("an article with no iterations: its report only, backed up outside the store", async () => { + const s = setup(); + await writeArticle(doc("solo"), { paths: s.paths }); + const run = capture(); + assert.equal(await respellMain("solo", { ...FLAGS, bracket: true, apply: true }, s, run.out), 0); + const r = JSON.parse(readFileSync(path.join(s.paths.articlesDir, "solo", "report.json"), "utf8")); + assert.equal(r.citations.a.quote, "my own [K-Cup] machine"); + assert.deepEqual(readdirSync(path.join(s.paths.articlesDir, "solo")).sort(), ["report.json"]); + assert.ok(existsSync(path.join(s.projectsRoot, "solo", "revisions"))); +}); + +test("usage and unknowns: no --heard or --reads, a bad --iteration, no such article", async () => { + const s = setup(); + await writeArticle(doc("x"), { paths: s.paths }); + assert.equal(await respellMain("x", { reads: "K-Cup" }, s, capture().out), 2); + assert.equal(await respellMain("x", { heard: "cake cup" }, s, capture().out), 2); + assert.equal(await respellMain("x", { ...FLAGS, iteration: "zero" }, s, capture().out), 2); + assert.equal(await respellMain("x", { ...FLAGS, iteration: "3" }, s, capture().out), 2); + assert.equal(await respellMain("nope", FLAGS, s, capture().out), 2); +}); diff --git a/common/bin/reports-respell.ts b/common/bin/reports-respell.ts @@ -0,0 +1,81 @@ +// `archilyzer reports respell <articleId> --heard <a,b,…> --reads <word> [--bracket] +// [--note <text>] [--iteration <n>] [--apply] [--json]` — correct a transcript's +// mis-hearing across an article's quotes (lib/report/respellArticle.ts). +// +// DRY RUN BY DEFAULT: it prints every change, file by file, as before → after, and +// writes nothing. `--apply` writes (each file backed up first to its project's +// revisions/). Exit 0 when the plan is clean (and applied); 1 when it changes nothing +// anywhere; 2 for usage, or no such article or iteration. + +import type { Paths } from "../lib/paths"; +import { ArticleRegistryError } from "../lib/report/registry"; +import { applyRespell, formatRespellPlan, planRespell } from "../lib/report/respellArticle"; +import { projectsRootOf } from "./reports-delete"; + +type Out = { log: (s: string) => void; error: (s: string) => void }; + +export type RespellFlags = { + heard?: string; + reads?: string; + bracket?: boolean; + note?: string; + iteration?: string; + apply?: boolean; + json?: boolean; +}; + +export async function respellMain( + article: string, + flags: RespellFlags, + env: { projectsRoot: string; paths: Pick<Paths, "articlesDir" | "exportIndexDir"> }, + out: Out = console, +): Promise<number> { + const heard = (flags.heard ?? "").split(",").map((h) => h.trim()).filter(Boolean); + const reads = (flags.reads ?? "").trim(); + if (!heard.length || !reads) { + out.error('reports respell: give --heard "<form>[,<form>…]" and --reads "<word>"'); + return 2; + } + let iteration: number | undefined; + if (flags.iteration !== undefined) { + iteration = Number(flags.iteration); + if (!Number.isInteger(iteration) || iteration < 1) { + out.error(`reports respell: --iteration takes an iteration number (1, 2, …), not "${flags.iteration}"`); + return 2; + } + } + const respellings = [{ heard, reads, ...(flags.bracket ? { bracket: true } : {}), ...(flags.note ? { note: flags.note } : {}) }]; + const opts = { ...(iteration !== undefined ? { iteration } : {}), ...env }; + try { + if (!flags.apply) { + const plan = await planRespell(article, respellings, opts); + if (flags.json) out.log(JSON.stringify({ applied: false, plan }, null, 2)); + else { + for (const l of formatRespellPlan(plan)) out.log(l); + out.log("dry run: nothing written — run again with --apply to write it"); + } + return plan.total ? 0 : 1; + } + const { plan, backups } = await applyRespell(article, respellings, opts); + if (flags.json) out.log(JSON.stringify({ applied: true, plan, backups }, null, 2)); + else { + for (const l of formatRespellPlan(plan)) out.log(l); + for (const b of backups) out.log(`backup ${b}`); + out.log(`applied: ${plan.total} change(s); the old files are the backups above`); + } + return plan.total ? 0 : 1; + } catch (err) { + if (err instanceof ArticleRegistryError) { + out.error(`reports respell: ${err.message}`); + for (const p of (err as { problems?: string[] }).problems ?? []) out.error(` ${p}`); + return 2; + } + throw err; + } +} + +export async function respellRow(article: string, flags: RespellFlags): Promise<number> { + const { getPaths } = await import("../lib/paths"); + const { getSettings } = await import("../lib/settings"); + return respellMain(article, flags, { projectsRoot: projectsRootOf(getSettings().generation), paths: getPaths() }); +} diff --git a/common/lib/citations/respell.d.mts b/common/lib/citations/respell.d.mts @@ -0,0 +1,28 @@ +// Types for respell.mjs (the module's comments say what a respelling is). + +export type Respelling = { + // What the transcript says, one or more forms (words, not patterns). + heard: string[]; + // What was said. + reads: string; + // Show the reading bracketed, as an altered quote is marked. Off by default: an + // obvious correction reads plainly. + bracket?: boolean; + note?: string; +}; + +// "display": each respelling as it says (bracketed or plain) — what a reader sees. +// "plain": every reading unbracketed — what the checks compare. +export type RespellMark = "display" | "plain"; + +export function applyRespellings( + text: string, + respellings: readonly Respelling[] | undefined, + mark?: RespellMark, +): string; +export function countRespellings(text: string, respellings: readonly Respelling[] | undefined): number; +export function cleanRespellings(input: unknown): Respelling[]; +export function mergeRespellings( + existing: readonly Respelling[] | undefined, + added: readonly Respelling[], +): Respelling[]; diff --git a/common/lib/citations/respell.mjs b/common/lib/citations/respell.mjs @@ -0,0 +1,107 @@ +// RESPELLINGS — a transcript's mis-hearing, corrected where an article quotes it. +// +// Transcripts are machine-made and mishear brand names and coinages ("cake cup" for +// K-Cup). A quote is verbatim from the transcript, so it carries the mis-hearing. An +// article may declare, once, what the transcript hears and what was said: +// +// "respellings": [{ "heard": ["cake cake cup", "cake cup", "cakeup"], "reads": "K-Cup" }] +// +// and its quotes then show the proper word — plainly for an obvious correction, or +// bracketed as an altered quote is ("because [K-Cup] machines are…") when the respelling +// says `bracket: true`. Every check of a quote against the record applies +// the same respellings to BOTH sides before comparing (lib/citations/verify.ts), so a +// corrected quote verifies exactly as its verbatim original did and nothing else does. +// +// Matching: each heard form on word boundaries, case-insensitive, longest form first +// (so "cake cake cup" wins over "cake cup"), a trailing plural "s" carried onto the +// reading ("cake cups" → "K-Cups"). Text already corrected is left alone, so applying +// twice changes nothing. +// +// Pure, no imports: the export site, the browser and umtool's .mjs scripts can use it. +// Types: respell.d.mts. + +const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// One regex over every heard form of every respelling, longest first, with the reading +// of each form beside it. +function compile(respellings) { + const readsOf = new Map(); + for (const r of respellings) { + const reads = r.reads.trim(); + if (!reads) continue; + for (const h of r.heard) { + const key = h.trim().replace(/\s+/g, " ").toLowerCase(); + if (key && !readsOf.has(key)) readsOf.set(key, { reads, bracket: r.bracket === true }); + } + } + if (readsOf.size === 0) return null; + const forms = [...readsOf.keys()].sort((a, b) => b.length - a.length); + // A heard form's spaces match any run of whitespace; the form must stand on word + // boundaries (letters/digits on neither side), with an optional plural "s". + const alt = forms.map((f) => f.split(" ").map(escapeRe).join("\\s+")).join("|"); + const re = new RegExp(`(?<![\\p{L}\\p{N}])(${alt})(s?)(?![\\p{L}\\p{N}])`, "giu"); + return { re, readsOf }; +} + +// `text` with every heard form replaced by its reading — as each respelling says +// ("display": bracketed when it asks) or all plain ("plain", for the checks). +export function applyRespellings(text, respellings, mark = "display") { + if (!respellings?.length || !text) return text; + const c = compile(respellings); + if (!c) return text; + return text.replace(c.re, (_m, form, plural, offset, whole) => { + const hit = c.readsOf.get(form.replace(/\s+/g, " ").toLowerCase()); + const word = (hit?.reads ?? form) + plural; + if (mark === "plain" || !hit?.bracket) return word; + // Already inside brackets ("[cake cup]" written by hand): do not double them. + const before = whole[offset - 1]; + const after = whole[offset + form.length + plural.length]; + return before === "[" && after === "]" ? word : `[${word}]`; + }); +} + +// How many places `text` would change. +export function countRespellings(text, respellings) { + if (!respellings?.length || !text) return 0; + const c = compile(respellings); + return c ? [...text.matchAll(c.re)].length : 0; +} + +// The respellings a document declares, cleaned: blank forms and readings dropped, a +// reading that is itself one of its heard forms dropped (it would never settle). +export function cleanRespellings(input) { + if (!Array.isArray(input)) return []; + const out = []; + for (const r of input) { + if (!r || typeof r !== "object") continue; + const reads = typeof r.reads === "string" ? r.reads.trim() : ""; + const heard = Array.isArray(r.heard) + ? r.heard.filter((h) => typeof h === "string" && h.trim() !== "").map((h) => h.trim()) + : []; + if (!reads || heard.length === 0) continue; + if (heard.some((h) => h.toLowerCase() === reads.toLowerCase())) continue; + const note = typeof r.note === "string" ? r.note : undefined; + const bracket = r.bracket === true; + out.push({ heard, reads, ...(bracket ? { bracket } : {}), ...(note ? { note } : {}) }); + } + return out; +} + +// Respellings joined: one per reading, its heard forms merged (a later `bracket` or +// `note` wins). +export function mergeRespellings(existing, added) { + const byReads = new Map(); + for (const r of [...cleanRespellings(existing ?? []), ...cleanRespellings(added)]) { + const prev = byReads.get(r.reads); + if (!prev) { + byReads.set(r.reads, { ...r, heard: [...r.heard] }); + continue; + } + const heard = [...prev.heard]; + for (const h of r.heard) if (!heard.some((x) => x.toLowerCase() === h.toLowerCase())) heard.push(h); + const bracket = r.bracket !== undefined ? r.bracket === true : prev.bracket === true; + const note = r.note ?? prev.note; + byReads.set(r.reads, { heard, reads: r.reads, ...(bracket ? { bracket } : {}), ...(note ? { note } : {}) }); + } + return [...byReads.values()]; +} diff --git a/common/lib/citations/respell.test.ts b/common/lib/citations/respell.test.ts @@ -0,0 +1,93 @@ +// respell.mjs: a transcript's mis-hearing, corrected where a quote shows it — and the +// quote checks, which apply the same respellings to both sides. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { applyRespellings, cleanRespellings, countRespellings, mergeRespellings } from "./respell.mjs"; +import { quoteVerification, quoteDrifted, strictQuoteCheck, strictTextCheck } from "./verify"; + +const KCUP = [{ heard: ["cake cake cup", "cake cup", "cakeup"], reads: "K-Cup" }]; + +test("plain by default: every heard form, case-insensitive, on word boundaries, a plural carried", () => { + assert.equal(applyRespellings("because cake cup machines are expensive", KCUP), "because K-Cup machines are expensive"); + assert.equal(applyRespellings("I bought my own cakeup machine", KCUP), "I bought my own K-Cup machine"); + assert.equal(applyRespellings("Cake Cups everywhere", KCUP), "K-Cups everywhere"); + assert.equal(applyRespellings("a pancake cupboard and cakeupper", KCUP), "a pancake cupboard and cakeupper"); +}); + +test("the longest heard form wins, so a stutter is one correction", () => { + assert.equal(applyRespellings("our own cake cake cup machine", KCUP), "our own K-Cup machine"); +}); + +test("bracketed only when the respelling asks; 'plain' never brackets; no double brackets", () => { + const b = [{ ...KCUP[0], bracket: true }]; + assert.equal(applyRespellings("my own cakeup machine", b), "my own [K-Cup] machine"); + assert.equal(applyRespellings("my own cakeup machine", b, "plain"), "my own K-Cup machine"); + assert.equal(applyRespellings("my own [cakeup] machine", b), "my own [K-Cup] machine"); +}); + +test("applying twice changes nothing; no respellings is the text unchanged", () => { + const once = applyRespellings("cake cup and cakeup", KCUP); + assert.equal(applyRespellings(once, KCUP), once); + assert.equal(applyRespellings("cake cup", undefined), "cake cup"); + assert.equal(applyRespellings("cake cup", []), "cake cup"); + assert.equal(countRespellings("cake cup, cakeups and cake cake cup", KCUP), 3); +}); + +test("clean drops blanks, a reading that is one of its heard forms, and non-objects", () => { + assert.deepEqual( + cleanRespellings([ + { heard: [" cake cup ", ""], reads: " K-Cup " }, + { heard: ["k-cup"], reads: "K-Cup" }, + { heard: [], reads: "X" }, + "nope", + { heard: ["kay cup"], reads: "K-Cup", bracket: true, note: "brand" }, + ]), + [ + { heard: ["cake cup"], reads: "K-Cup" }, + { heard: ["kay cup"], reads: "K-Cup", bracket: true, note: "brand" }, + ], + ); +}); + +test("merge joins heard forms per reading; a later bracket or note wins", () => { + const m = mergeRespellings([{ heard: ["cake cup"], reads: "K-Cup", note: "a" }], [ + { heard: ["Cake Cup", "cakeup"], reads: "K-Cup", bracket: true }, + { heard: ["stix"], reads: "Styx" }, + ]); + assert.deepEqual(m, [ + { heard: ["cake cup", "cakeup"], reads: "K-Cup", bracket: true, note: "a" }, + { heard: ["stix"], reads: "Styx" }, + ]); +}); + +const cues = [ + { start: 10, end: 14, text: "because cake cup machines are very very expensive" }, + { start: 14, end: 18, text: "so we pay somebody with a cake cup machine" }, +]; +const said = cues.map((c) => c.text).join(" "); + +test("a respelled quote verifies as its verbatim original did — recall and strict", () => { + const quote = applyRespellings(said, KCUP); + const v = quoteVerification(quote, said, "t", KCUP); + assert.equal(v.quoteScore, 1); + assert.equal(strictQuoteCheck(quote, cues, 10, { respellings: KCUP }).ok, true); + assert.equal(strictTextCheck(quote, said, KCUP).ok, true); + // Bracketed reads the same to the checks. + const bracketed = applyRespellings(said, [{ ...KCUP[0], bracket: true }]); + assert.equal(strictQuoteCheck(bracketed, cues, 10, { respellings: KCUP }).ok, true); +}); + +test("without the respelling declared the corrected quote is not verbatim", () => { + const quote = applyRespellings(said, KCUP); + assert.equal(strictQuoteCheck(quote, cues, 10).ok, false); + assert.ok((quoteVerification(quote, said, "t").quoteScore ?? 1) < 1); +}); + +test("a respelling never makes an unrelated quote pass", () => { + const v = quoteVerification("the K-Cup machines are cheap and free", said, "t", KCUP); + assert.equal(strictQuoteCheck("K-Cup machines are cheap", cues, 10, { respellings: KCUP }).ok, false); + assert.ok((v.quoteScore ?? 1) < 1); + // A short corrected quote drifts without its respelling, and passes with it. + assert.equal(quoteDrifted(quoteVerification("K-Cup machine", "cake cup machine", "t")), true); + assert.equal(quoteDrifted(quoteVerification("K-Cup machine", "cake cup machine", "t", KCUP)), false); +}); diff --git a/common/lib/citations/verify.ts b/common/lib/citations/verify.ts @@ -25,10 +25,19 @@ // (lib/citations/schema.ts verificationSchema), and nothing here can vouch for // a voice, so `voiceChecked` is never written. // -// Pure, no imports but types: the export site and the browser can use it. +// RESPELLINGS (lib/citations/respell.ts): a document may declare what the transcript +// mishears; every check here applies them, plain, to BOTH the quote and the record's +// text before comparing, so a quote showing the corrected word scores as its verbatim +// original did. +// +// Pure, no imports but types and the pure respell module: the export site and the +// browser can use it. +import { applyRespellings, type Respelling } from "./respell.mjs"; import type { CitationVerification } from "./schema"; +const plain = (text: string, respellings?: readonly Respelling[]) => applyRespellings(text, respellings, "plain"); + export const QUOTE_WINDOW_SLACK_SECONDS = 5; export const QUOTE_DRIFT_THRESHOLD = 0.6; @@ -84,9 +93,14 @@ export function roundScore(score: number): number { } // The verification block for a quote checked against `text` at `checkedAt`. -export function quoteVerification(quote: string, text: string, checkedAt: string): CitationVerification { +export function quoteVerification( + quote: string, + text: string, + checkedAt: string, + respellings?: readonly Respelling[], +): CitationVerification { return { - quoteScore: roundScore(tokenRecall(quote, text)), + quoteScore: roundScore(tokenRecall(plain(quote, respellings), plain(text, respellings))), quoteCheckedAt: checkedAt, method: QUOTE_CHECK_METHOD, }; @@ -156,11 +170,11 @@ function containsWords(hay: string, needle: string): boolean { return needle.length > 0 && ` ${hay} `.includes(` ${needle} `); } -function strictAgainst(quote: string, text: string): StrictQuoteResult { - const hay = strictNormalize(text); +function strictAgainst(quote: string, text: string, respellings?: readonly Respelling[]): StrictQuoteResult { + const hay = strictNormalize(plain(text, respellings)); const fragments = quoteFragments(quote).map((fragment) => ({ fragment, - ok: containsWords(hay, strictNormalize(fragment)), + ok: containsWords(hay, strictNormalize(plain(fragment, respellings))), })); const failed = fragments.find((f) => !f.ok)?.fragment; return { @@ -186,12 +200,16 @@ export function strictQuoteCheck( quote: string, cues: readonly TimedText[], second: number, - opts: { windowSeconds?: number } = {}, + opts: { windowSeconds?: number; respellings?: readonly Respelling[] } = {}, ): StrictQuoteResult { - return strictAgainst(quote, strictWindowText(cues, second, opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS)); + return strictAgainst( + quote, + strictWindowText(cues, second, opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS), + opts.respellings, + ); } // A post quote, strictly: each fragment verbatim in the post's text. -export function strictTextCheck(quote: string, text: string): StrictQuoteResult { - return strictAgainst(quote, text); +export function strictTextCheck(quote: string, text: string, respellings?: readonly Respelling[]): StrictQuoteResult { + return strictAgainst(quote, text, respellings); } diff --git a/common/lib/report/respellArticle.ts b/common/lib/report/respellArticle.ts @@ -0,0 +1,232 @@ +// RESPELL AN ARTICLE — plan, then apply, a transcript mis-hearing's correction across +// an article's quotes (`archilyzer reports respell`; lib/citations/respell.mjs says +// what a respelling is). +// +// The files, for iteration n (default: the iteration the article's current report +// came from): +// - reports/<id>/iterations/<n>/report.json — through writeIterationFile; +// - reports/<id>/report.json — when it is n's report (the article is current on n, +// or has no iterations), through writeArticle (audience and video kept); +// - <projectsRoot>/<id>/i<n>/video.manifest.json — the iteration's video project, +// when it has one. +// Each report gains `respellings`, the manifest too (every quote check, and the +// video's cut-to-quote, apply them from then on). Before a write, the file as it was +// is copied to the project's `revisions/<stamp>-before-respell.<name>` (beside the +// manifest's other revisions; an article with no iterations: <projectsRoot>/<id>/ +// revisions/), so a respell is undone by copying it back. +// +// A respelled video shows the new words only once it is rebuilt: the plan says so. + +import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { cleanRespellings, type Respelling } from "../citations/respell.mjs"; +import type { Paths } from "../paths"; +import { currentIteration, iterationFile, projectOf, readIteration, writeIterationFile } from "./iterations"; +import { articleFile, ArticleRegistryError, writeArticle } from "./registry"; +import { respellManifest } from "./respellManifest.mjs"; +import { respellReport, type RespellChange } from "./respellReport"; +import type { Report } from "./schema"; +import { parseReport } from "./validate"; + +type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">; + +export type RespellTarget = { + kind: "iteration-report" | "article-report" | "video-manifest"; + file: string; + changes: RespellChange[]; +}; + +export type RespellPlan = { + article: string; + iteration: number | null; + respellings: Respelling[]; + targets: RespellTarget[]; + // Places changed, all files. + total: number; + notes: string[]; +}; + +export type RespellOptions = { + iteration?: number; + projectsRoot: string; + paths: StorePaths; +}; + +const readJson = async (file: string): Promise<unknown | null> => { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; + throw new ArticleRegistryError(`${file} is not readable JSON: ${(err as Error).message}`); + } +}; + +const asReport = (raw: unknown, id: string, file: string): Report => { + const parsed = parseReport(raw, { id }); + if (!parsed.ok) throw new ArticleRegistryError(`${file} is not a report`, parsed.problems.map((p) => p.message)); + return parsed.value; +}; + +type Computed = { + plan: RespellPlan; + writes: { target: RespellTarget; data: unknown; projectDir: string | null }[]; +}; + +async function compute(id: string, input: readonly Respelling[], o: RespellOptions): Promise<Computed> { + const respellings = cleanRespellings(input); + if (respellings.length === 0) throw new ArticleRegistryError("no respelling: give at least one heard form and a reading"); + const notes: string[] = []; + const current = await currentIteration(id, o.paths); + const n = o.iteration ?? current.reportFrom ?? current.report ?? null; + if (n !== null && !(await readIteration(id, n, o.paths))) { + throw new ArticleRegistryError(`"${id}" has no iteration i${n}`); + } + const writes: Computed["writes"] = []; + const projectDir = n !== null ? projectOf(o.projectsRoot, id, n) : null; + + if (n !== null) { + const file = iterationFile(o.paths, id, n, "report.json"); + const raw = await readJson(file); + if (raw) { + asReport(raw, id, file); + // The raw document, not the parsed one: the file keeps its own key order. + const r = respellReport(raw as Report, respellings); + writes.push({ target: { kind: "iteration-report", file, changes: r.changes }, data: r.report, projectDir }); + } else notes.push(`i${n} has no report.json of its own`); + } + const articleIsN = n === null || current.reportFrom === n || current.report === n; + const aFile = articleFile(o.paths, id); + const aRaw = await readJson(aFile); + if (aRaw && articleIsN) { + asReport(aRaw, id, aFile); + const r = respellReport(aRaw as Report, respellings); + writes.push({ target: { kind: "article-report", file: aFile, changes: r.changes }, data: r.report, projectDir }); + } else if (aRaw) { + notes.push(`the article's report.json is another iteration's (i${current.reportFrom ?? current.report}); not changed`); + } else if (n === null) { + throw new ArticleRegistryError(`"${id}" has no report.json and no iterations`); + } + if (projectDir) { + const file = path.join(projectDir, "video.manifest.json"); + const raw = await readJson(file); + if (raw && typeof raw === "object" && !Array.isArray(raw)) { + const r = respellManifest(raw as Record<string, unknown>, respellings); + writes.push({ target: { kind: "video-manifest", file, changes: r.changes }, data: r.manifest, projectDir }); + if (r.changes.length) notes.push("the video shows the new words once it is rebuilt (its burned-in quotes and cards)"); + } + } + const targets = writes.map((w) => w.target); + return { + plan: { article: id, iteration: n, respellings, targets, total: targets.reduce((s, t) => s + t.changes.length, 0), notes }, + writes, + }; +} + +export async function planRespell(id: string, respellings: readonly Respelling[], o: RespellOptions): Promise<RespellPlan> { + return (await compute(id, respellings, o)).plan; +} + +const stampOf = (d: Date) => d.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z"); + +// Apply: the plan is computed again (the files may have moved since the preview), +// every changed file backed up, then written. Answers the plan applied and the backups. +export async function applyRespell( + id: string, + respellings: readonly Respelling[], + o: RespellOptions, + now: Date = new Date(), +): Promise<{ plan: RespellPlan; backups: string[] }> { + const { plan, writes } = await compute(id, respellings, o); + const backups: string[] = []; + const stamp = stampOf(now); + for (const w of writes) { + // A target with no change still gains `respellings` (the checks need them), so + // every target is written; a target that already carries them and changes + // nothing is left alone. + const before = await readFile(w.target.file, "utf8"); + const after = `${JSON.stringify(w.data, null, 2)}\n`; + if (before === after || JSON.stringify(JSON.parse(before)) === JSON.stringify(w.data)) continue; + // Never beside the article in the store (a stray file there is the export's to + // trip on): the iteration's project, or the article's folder under the projects root. + const backupDir = path.join(w.projectDir ?? path.join(o.projectsRoot, id), "revisions"); + await mkdir(backupDir, { recursive: true }); + const name = w.target.kind === "video-manifest" ? "manifest.json" : `${w.target.kind}.json`; + const backup = path.join(backupDir, `${stamp}-before-respell.${name}`); + await copyFile(w.target.file, backup); + backups.push(backup); + if (w.target.kind === "iteration-report") { + await writeIterationFile(id, plan.iteration!, "report.json", w.data as object, o.paths); + } else if (w.target.kind === "article-report") { + await writeArticle(w.data, { paths: o.paths, keepAudience: true, keepVideo: true }); + } else { + await writeFile(w.target.file, after, "utf8"); + } + } + return { plan, backups }; +} + +// The plan as lines a person reads: per file, each changed field, and in it each +// changed run of words with a few words either side, «before» → «after». +export function formatRespellPlan(plan: RespellPlan): string[] { + const out: string[] = []; + const rs = plan.respellings.map((r) => `${r.heard.map((h) => `"${h}"`).join(", ")} → "${r.reads}"${r.bracket ? " (bracketed)" : ""}`); + out.push(`respell "${plan.article}"${plan.iteration !== null ? ` i${plan.iteration}` : ""}: ${rs.join("; ")}`); + for (const t of plan.targets) { + out.push(""); + out.push(`${t.kind} ${t.file}: ${t.changes.length} change(s)${t.changes.length ? "" : " (gains respellings only)"}`); + for (const c of t.changes) { + out.push(` ${c.at}`); + for (const h of wordHunks(c.before, c.after)) out.push(` ${h}`); + } + } + for (const n of plan.notes) out.push(`note: ${n}`); + out.push(""); + out.push(`${plan.total} change(s) in ${plan.targets.filter((t) => t.changes.length).length} file(s)`); + return out; +} + +const CONTEXT_WORDS = 5; + +// Each run of words that differs, as "…context «old» → «new» context…" (a word-level +// longest common subsequence: the texts are a field each, a few hundred words at most). +export function wordHunks(before: string, after: string): string[] { + const a = before.split(/\s+/).filter(Boolean); + const b = after.split(/\s+/).filter(Boolean); + const L: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) + for (let j = b.length - 1; j >= 0; j--) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]); + // Walk: equal words, or a hunk of removed/added words. + type Op = { eq: true; w: string; i: number } | { eq: false; del: string[]; add: string[]; i: number }; + const ops: Op[] = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + ops.push({ eq: true, w: a[i], i }); + i++; + j++; + continue; + } + const del: string[] = []; + const add: string[] = []; + const at = i; + while ((i < a.length || j < b.length) && !(i < a.length && j < b.length && a[i] === b[j])) { + if (j >= b.length || (i < a.length && L[i + 1][j] >= L[i][j + 1])) del.push(a[i++]); + else add.push(b[j++]); + } + ops.push({ eq: false, del, add, i: at }); + } + const hunks: string[] = []; + ops.forEach((op, k) => { + if (op.eq) return; + const left: string[] = []; + for (let x = k - 1; x >= 0 && left.length < CONTEXT_WORDS && ops[x].eq; x--) left.unshift((ops[x] as { w: string }).w); + const right: string[] = []; + for (let x = k + 1; x < ops.length && right.length < CONTEXT_WORDS && ops[x].eq; x++) right.push((ops[x] as { w: string }).w); + const more = (n: number) => (n > 0 ? "…" : ""); + hunks.push( + `${more(k - left.length)}${left.join(" ")} «${op.del.join(" ")}» → «${op.add.join(" ")}» ${right.join(" ")}${more(ops.length - 1 - k - right.length)}`.replace(/\s+/g, " ").trim(), + ); + }); + return hunks; +} diff --git a/common/lib/report/respellManifest.d.mts b/common/lib/report/respellManifest.d.mts @@ -0,0 +1,9 @@ +// Types for respellManifest.mjs. +import type { Respelling } from "../citations/respell.mjs"; + +export type ManifestRespellChange = { at: string; before: string; after: string }; + +export function respellManifest<T extends Record<string, unknown>>( + manifest: T, + respellings: readonly Respelling[], +): { manifest: T & { respellings?: Respelling[] }; changes: ManifestRespellChange[] }; diff --git a/common/lib/report/respellManifest.mjs b/common/lib/report/respellManifest.mjs @@ -0,0 +1,52 @@ +// RESPELL A VIDEO MANIFEST — the video side of `archilyzer reports respell` +// (lib/citations/respell.mjs says what a respelling is; lib/report/respellReport.ts +// is the report side). +// +// Every string in the manifest is walked: +// - under a QUOTE key (`quote` — a clip's verbatim words, burned into its frames; +// `words` — a flip card's quoted line): the respelling as it says (bracketed when +// it asks); +// - under a key that names a thing (ids, slugs, sources, paths, urls, dates — SKIP_KEYS) +// or a value that looks like a path or url: untouched; +// - anything else (titles, subtitles, narration, card text — the author's words): plain. +// `respellings` is merged in at the top, so resolve-windows' cut-to-quote applies the +// same respellings to the cues (a respelled quote still finds its span). +// +// Pure: the caller reads and writes the file. Types: respellManifest.d.mts. + +import { applyRespellings, cleanRespellings, mergeRespellings } from "../citations/respell.mjs"; + +const QUOTE_KEYS = new Set(["quote", "words"]); +const SKIP_KEYS = new Set([ + "id", "entry", "slug", "src", "source", "file", "path", "url", "href", "link", "siteOrigin", "siteChannel", + "siteVideo", "channel", "video", "videoId", "cite", "citeUrl", "kind", "type", "status", "date", "when", + "generatedOn", "schemaVersion", "model", "voice", "preset", "layout", "theme", "accent", "color", "font", + "respellings", "drafted", "provenance", +]); +const looksLikeRef = (v) => /^(https?:|file:|\/|\.{1,2}\/|~\/)/.test(v) || /\.[a-z0-9]{2,4}$/i.test(v); + +export function respellManifest(manifest, respellings) { + const rs = cleanRespellings(respellings); + const changes = []; + const out = structuredClone(manifest); + const walk = (node, at, key) => { + if (typeof node === "string") { + if (SKIP_KEYS.has(key) || looksLikeRef(node)) return node; + const after = applyRespellings(node, rs, QUOTE_KEYS.has(key) ? "display" : "plain"); + if (after !== node) changes.push({ at, before: node, after }); + return after; + } + if (Array.isArray(node)) return node.map((v, i) => walk(v, `${at}[${i}]`, key)); + if (node && typeof node === "object") { + for (const [k, v] of Object.entries(node)) { + if (SKIP_KEYS.has(k) && typeof v === "object") continue; + node[k] = walk(v, at ? `${at}.${k}` : k, k); + } + return node; + } + return node; + }; + walk(out, "", ""); + if (rs.length) out.respellings = mergeRespellings(out.respellings, rs); + return { manifest: out, changes }; +} diff --git a/common/lib/report/respellReport.test.ts b/common/lib/report/respellReport.test.ts @@ -0,0 +1,87 @@ +// respellReport.ts and respellManifest.mjs: which strings a respelling changes, and how. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { respellMarkdown, respellReport } from "./respellReport"; +import { respellManifest } from "./respellManifest.mjs"; +import type { Report } from "./schema"; + +const KCUP = [{ heard: ["cake cup", "cakeup"], reads: "K-Cup" }]; +const KCUP_B = [{ ...KCUP[0], bracket: true }]; + +const report = (): Report => + ({ + format: "archilyzer-report", + version: 1, + id: "demo", + kind: "sweep", + title: "The cake cup story", + summary: 'He said [“my own cakeup machine”](cite:a), and [a cake cup page](https://example.com/cake-cup "cake cup").', + sections: [ + { + id: "s1", + title: "Coffee", + claims: [{ id: "c1", text: "The cakeup machine.", findings: "[“a cake cup machine”](cite:b)", gist: "cake cup", slide: { points: ["cakeup"] } }], + }, + ], + sources: { doc: { kind: "web", title: "A cake cup review", url: "https://example.com" } }, + citations: { + a: { kind: "video", channel: "ch", id: "v1", start: 1, end: 2, quote: "my own cakeup machine" }, + b: { kind: "video", channel: "ch", id: "v1", start: 3, end: 4, quote: "a cake cup machine" }, + }, + }) as unknown as Report; + +test("quotes take the respelling as it says; the report's own words read plainly", () => { + const { report: r, changes } = respellReport(report(), KCUP_B); + assert.equal(r.title, "The K-Cup story"); + assert.match(r.summary!, /\[“my own \[K-Cup\] machine”\]\(cite:a\)/); + // A link that is not a citation: its label is the report's words (plain), its href untouched. + assert.match(r.summary!, /\[a K-Cup page\]\(https:\/\/example\.com\/cake-cup "cake cup"\)/); + const c = r.sections[0].claims![0]; + assert.equal(c.text, "The K-Cup machine."); + assert.equal(c.findings, "[“a [K-Cup] machine”](cite:b)"); + assert.equal(c.gist, "K-Cup"); + assert.deepEqual(c.slide?.points, ["K-Cup"]); + assert.equal((r.citations!.a as { quote: string }).quote, "my own [K-Cup] machine"); + // Sources are the document's own words. + assert.equal((r.sources!.doc as { title: string }).title, "A cake cup review"); + assert.deepEqual(r.respellings, KCUP_B); + assert.ok(changes.some((ch) => ch.at === "citations.b.quote")); +}); + +test("plain respellings mark nothing; the input is not mutated; a second pass changes nothing", () => { + const input = report(); + const { report: once } = respellReport(input, KCUP); + assert.equal((once.citations!.a as { quote: string }).quote, "my own K-Cup machine"); + assert.equal((input.citations!.a as { quote: string }).quote, "my own cakeup machine"); + const { changes } = respellReport(once, KCUP); + assert.deepEqual(changes, []); +}); + +test("markdown: a cite label is a quote, another label and the text around are the author's", () => { + assert.equal( + respellMarkdown("cake cup [“cake cup”](cite:x) [cake cup](https://a.b/c)", KCUP_B), + "K-Cup [“[K-Cup]”](cite:x) [K-Cup](https://a.b/c)", + ); +}); + +test("a manifest: quotes and flip words take the respelling, titles plain, ids and paths untouched", () => { + const m = { + slug: "cake-cup", + title: "The cake cup story", + render: { chrome: { flips: { pairs: [{ id: "p", then: { entry: "cake cup", when: "2022", words: "my own cakeup machine" } }] } } }, + timeline: [{ type: "clip", id: "c1", src: "clips/cake cup.mp4", quote: "a cake cup machine", onscreen: { title: "The cakeup machine" } }], + provenance: { siteOrigin: "https://x", note: "cake cup" }, + }; + const { manifest: out, changes } = respellManifest(m, KCUP_B); + assert.equal(out.title, "The K-Cup story"); + assert.equal(out.slug, "cake-cup"); + assert.equal(out.render.chrome.flips.pairs[0].then.words, "my own [K-Cup] machine"); + assert.equal(out.render.chrome.flips.pairs[0].then.entry, "cake cup"); + assert.equal(out.timeline[0].quote, "a [K-Cup] machine"); + assert.equal(out.timeline[0].src, "clips/cake cup.mp4"); + assert.equal(out.timeline[0].onscreen.title, "The K-Cup machine"); + assert.equal(out.provenance.note, "cake cup"); + assert.deepEqual(out.respellings, KCUP_B); + assert.equal(m.timeline[0].quote, "a cake cup machine"); + assert.equal(changes.length, 4); +}); diff --git a/common/lib/report/respellReport.ts b/common/lib/report/respellReport.ts @@ -0,0 +1,104 @@ +// RESPELL A REPORT — the edit `archilyzer reports respell` plans and applies +// (lib/citations/respell.ts says what a respelling is). +// +// What changes, and how a reading shows: +// - a citation's `quote` and the label of every `[…](cite:<id>)` link: the +// respelling as it says (bracketed when it asks) — these are the quotes; +// - the rest of the report's own words (title, subtitle, summary, method, a +// section's title and body, a claim's text, findings and gist, a timeline +// entry's title and body, slide points and lines): plain — the report's words +// are not a quote, so nothing is marked; +// - `respellings`: the new ones merged in (same reading: heard forms joined), so +// every quote check applies them from now on. +// What does not: ids, links, sources (a document's words as the source has them), a +// claim's `sourceQuote`, verdicts, dates. +// +// Pure: the caller reads and writes the files. + +import { applyRespellings, cleanRespellings, mergeRespellings, type Respelling } from "../citations/respell.mjs"; + +export { mergeRespellings }; +import type { Report } from "./schema"; + +export type RespellChange = { + // Where, as a path into the document ("sections[2].claims[0].findings"). + at: string; + before: string; + after: string; +}; + +// The same one-level-of-brackets link shape convertShared reads. +const LINK_RE = /\[((?:[^[\]]|\[[^[\]]*\])*)\]\(\s*(<?[^)\s>]+>?(?:\s+"[^"]*")?)\s*\)/g; + +// Markdown: link labels of `cite:` links as quotes ("display"), everything else plain. +export function respellMarkdown(md: string, respellings: readonly Respelling[]): string { + let out = ""; + let last = 0; + for (const m of md.matchAll(LINK_RE)) { + const at = m.index ?? 0; + out += applyRespellings(md.slice(last, at), respellings, "plain"); + const href = m[2]; + const isCite = /^<?cite:/.test(href); + out += `[${applyRespellings(m[1], respellings, isCite ? "display" : "plain")}](${href})`; + last = at + m[0].length; + } + return out + applyRespellings(md.slice(last), respellings, "plain"); +} + +// The report with the respellings applied, and every string that changed. +export function respellReport( + report: Report, + respellings: readonly Respelling[], +): { report: Report; changes: RespellChange[] } { + const rs = cleanRespellings(respellings); + const changes: RespellChange[] = []; + const out: Report = structuredClone(report); + const fix = (at: string, value: string | undefined, how: "markdown" | "quote" | "plain"): string | undefined => { + if (typeof value !== "string" || value === "") return value; + const after = + how === "markdown" + ? respellMarkdown(value, rs) + : applyRespellings(value, rs, how === "quote" ? "display" : "plain"); + if (after !== value) changes.push({ at, before: value, after }); + return after; + }; + + out.title = fix("title", out.title, "plain")!; + out.subtitle = fix("subtitle", out.subtitle, "plain"); + out.summary = fix("summary", out.summary, "markdown"); + out.method = fix("method", out.method, "markdown"); + type Slide = { title?: string; points?: string[] }; + const fixSlide = (at: string, sl: Slide | undefined) => { + if (!sl) return; + if (sl.title !== undefined) sl.title = fix(`${at}.title`, sl.title, "plain"); + sl.points = sl.points?.map((p, k) => fix(`${at}.points[${k}]`, p, "markdown")!); + }; + if (out.slides) { + fixSlide("slides", out.slides); + if (out.slides.closing !== undefined) out.slides.closing = fix("slides.closing", out.slides.closing, "markdown"); + } + out.sections.forEach((s, i) => { + s.title = fix(`sections[${i}].title`, s.title, "plain")!; + fixSlide(`sections[${i}].slide`, s.slide); + if (s.body !== undefined) s.body = fix(`sections[${i}].body`, s.body, "markdown"); + s.claims?.forEach((c, j) => { + const at = `sections[${i}].claims[${j}]`; + if (c.title !== undefined) c.title = fix(`${at}.title`, c.title, "plain"); + c.text = fix(`${at}.text`, c.text, "markdown")!; + fixSlide(`${at}.slide`, c.slide); + if (c.findings !== undefined) c.findings = fix(`${at}.findings`, c.findings, "markdown"); + if (c.gist !== undefined) c.gist = fix(`${at}.gist`, c.gist, "markdown"); + }); + }); + out.entries?.forEach((e, i) => { + e.title = fix(`entries[${i}].title`, e.title, "plain")!; + e.body = fix(`entries[${i}].body`, e.body, "markdown")!; + }); + for (const [id, c] of Object.entries(out.citations ?? {})) { + if ("quote" in c && typeof c.quote === "string") { + (c as { quote: string }).quote = fix(`citations.${id}.quote`, c.quote, "quote")!; + } + } + if (rs.length) out.respellings = mergeRespellings(out.respellings, rs); + return { report: out, changes }; +} diff --git a/common/lib/report/schema.ts b/common/lib/report/schema.ts @@ -107,6 +107,14 @@ export const entrySchema = z.strictObject({ const verdictOverride = z.strictObject({ label: text.optional(), color: text.optional() }); +// A transcript's mis-hearing the report's quotes correct (lib/citations/respell.ts). +export const respellingSchema = z.strictObject({ + heard: z.array(text).min(1), + reads: text, + bracket: z.boolean().optional(), + note: text.optional(), +}); + export const reportSchema = z.strictObject({ format: z.literal(REPORT_FORMAT), version: z.literal(REPORT_VERSION), @@ -128,6 +136,7 @@ export const reportSchema = z.strictObject({ sections: z.array(sectionSchema), entries: z.array(entrySchema).optional(), slides: reportSlidesSchema.optional(), + respellings: z.array(respellingSchema).optional(), }); export type Claim = z.infer<typeof claimSchema>; @@ -174,6 +183,8 @@ export const REPORT_FIELD_DOCS: FieldDocs<Report> = { sections: "The report's sections, in order.", entries: "The report's timeline: dated entries, appended over time and shown newest first under \"Timeline\", before the claims — see `entries[]` below. With entries and a public `siteUrl`, the report publishes feeds of them (`feed.xml`, RSS 2.0; `feed.json`, JSON Feed 1.1). Absent = none.", + respellings: + "What the transcripts mishear, corrected where the report quotes them: `[{ \"heard\": [\"cake cup\", \"cakeup\"], \"reads\": \"K-Cup\", \"bracket\": false }]`. Each heard form (words, case-insensitive, a plural `s` carried) reads as `reads` in the report's quotes — bracketed, `[K-Cup]`, when `bracket` is true — and every quote check applies the same respellings to the transcript before comparing, so a corrected quote verifies as its verbatim original did. Written by `archilyzer reports respell`. Absent = none.", slides: "How the report reads as slides (its page's Slides and Overview views, `slides.html`, `slides.pdf`) — see `slides` below. Absent = slides derived from its text.", }; diff --git a/common/package.json b/common/package.json @@ -31,11 +31,13 @@ "./components/urlState": "./components/urlState.ts", "./components/virtualizer": "./components/virtualizer.ts", "./components/*": "./components/*.tsx", + "./lib/citations/respell.mjs": "./lib/citations/respell.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", + "./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs", "./lib/report/panels.mjs": "./lib/report/panels.mjs", "./lib/report/social.mjs": "./lib/report/social.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -102,6 +102,7 @@ import type { Post } from "../lib/posts"; import { readJsonFile } from "../lib/jsonFile-server"; import { momentKeyOf, momentPath, parseMomentKey, type SpanMoment } from "../lib/citations/moments"; import { CITATIONS_VERSION, type Citation, type PostCitation, type SpanCitation } from "../lib/citations/schema"; +import type { Respelling } from "../lib/citations/respell.mjs"; import { cueWindowText, quoteDrifted, quoteVerification, QUOTE_DRIFT_THRESHOLD } from "../lib/citations/verify"; import { buildCitedIn } from "../lib/report/citedIn"; import { renderReportJsonFeed, renderReportRss, reportFeedUrls } from "../lib/report/feeds"; @@ -370,17 +371,18 @@ export function checkSpanQuote( record: Pick<CitedRecord, "cues" | "tracks">, c: { quote: string; start: number; end: number }, now: string, + respellings?: readonly Respelling[], ): SpanQuoteCheck { let best: { name: string; cues: Cue[]; v: ReturnType<typeof quoteVerification> } | null = null; const tracks: SpanQuoteCheck["tracks"] = []; for (const t of record.tracks) { - const v = quoteVerification(c.quote, cueWindowText(t.cues, c.start, c.end), now); + const v = quoteVerification(c.quote, cueWindowText(t.cues, c.start, c.end), now, respellings); tracks.push({ name: t.name, score: v.quoteScore ?? 0 }); if (!best || (v.quoteScore ?? 0) > (best.v.quoteScore ?? 0)) best = { name: t.name, cues: t.cues, v }; } return best ? { verification: { ...best.v, method: `${best.v.method}; text: ${best.name}` }, cues: best.cues, tracks } - : { verification: quoteVerification(c.quote, cueWindowText(record.cues, c.start, c.end), now), cues: null, tracks }; + : { verification: quoteVerification(c.quote, cueWindowText(record.cues, c.start, c.end), now, respellings), cues: null, tracks }; } // The sentence compose fails a drifted quote with. @@ -636,7 +638,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol problems.push({ kind: "missing-post", citation: ref, report: report.id, message: `no post ${c.id} in the posts archive of "${c.channel}"` }); continue; } - c.verification = quoteVerification(c.quote, post.text, now); + c.verification = quoteVerification(c.quote, post.text, now, report.respellings); } else { const record = await recordOf(c.channel, c.id); if (!record) { @@ -647,7 +649,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol problems.push({ kind: "no-cues", citation: ref, report: report.id, message: `${c.channel}/${c.id} has no transcript cues to check the quote against` }); continue; } - const checked = checkSpanQuote(record, c, now); + const checked = checkSpanQuote(record, c, now, report.respellings); c.verification = checked.verification; const mk = momentKeyOf(c); if (checked.cues && mk && !momentCues.has(mk)) momentCues.set(mk, checked.cues); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **An article can correct what the transcripts mishear in its quotes.** `archilyzer reports respell <article> --heard "cake cup,cakeup" --reads K-Cup` previews every change — the article's quotes and citations, its report's own words, and its video's burned-in quotes and flip cards — as before → after, and writes nothing; `--apply` writes it, each file backed up first. `--bracket` shows the correction as an altered quote, `[K-Cup]`. The article records the respelling, and every quote check applies it to the transcript before comparing, so a corrected quote still verifies exactly; the transcript itself is untouched. A video shows the new words once it is rebuilt. - **`pnpm ops audio-audit` checks the audio already on disk, file by file.** `pnpm ops audio-audit --json '{"platform":"odysee"}'` (or `{"slug":"<channel>"}`; `"scope":"all"` for transcribed videos too, `"max"` to cap the files) decodes each audio file a channel holds with error tolerance — one file at a time, at the lowest CPU and disk priority — and writes what it found beside the file in `audio-integrity.json`: clean, damaged (part of it will not decode) or undecodable, with how much decodes and where the gaps are. Audio downloaded before the audio check existed, or on a channel without it, was never checked. The same command again skips the files already checked. A drive that stops answering ends that channel's run with a sentence that says so instead of hanging. - **Damaged held audio has its own bucket, and its Retry downloads again.** The channel's Download stage has a **Damaged held audio** card (and the report a `corruptHeldAudio` bucket) for files the audit found damaged; they are no longer handed to the transcription lane. **Retry** (or `pnpm ops retry-bucket --json '{"slug":"<channel>","bucket":"corruptHeldAudio"}'`) sets the file aside and downloads again with the audio check on: a clean copy replaces it, a copy that is malformed too keeps whichever decodes longer, and a failed download puts the file back. Transcribing such a file decodes what it can and keeps the gaps as silence. **/review**'s media scan shows the audit's verdict beside its own, and lists a file it reads as fine but the audit found damaged. - **A poker frame scan finds the moments a highlight reel is made of.** Besides the double-ups, busts and big pots, the derivation now marks: every pot the streamer's player takes (a pot of 25 big blinds or more is a big pot; the same log line read twice with a digit off is one pot), the player's all-ins with how they ended (doubled, won, lost, busted, or not read), each blind level going up (from the client's "Blinds are now" line; a misread line that a later one contradicts is ignored, in the big blind too), and the field falling under 100, 50, 27 and 18 players and to the final table (from the client's "position N of M" only, once each). Each of these says which rule made it, what it read, and whether a second reading backs it (`confirmed`) or not; a reading flagged against a spoken number still makes nothing. An all-in banner the model reads is the player's only when the player's chips are all in the middle. The new moments appear on an existing scan by re-deriving it, with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`. Needs a restart of the editor. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9878,3 +9878,24 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri right length) whose record is damaged is a finding of verdict `damaged` (totals `damaged?`). No decode for it. - **e2e fixtures**: `fake-ffmpeg.mjs` answers `-version`, and `-f framecrc pipe:1` with 100 frames over fake-ffprobe's duration (`__DUR=<s>__`, else 100000) — half of it for a file carrying `__CORRUPT__`. + +## Respellings: a transcript's mis-hearing corrected in an article's quotes (verified 2026-10-16, branch `r31/respell`) + +- **The shape** (`lib/citations/respell.mjs` + `.d.mts`, pure, shared with umtool): `{heard: string[], reads, bracket?, + note?}`. `applyRespellings(text, rs, "display" | "plain")`: each heard form on word boundaries, case-insensitive, + longest first (a stutter "cake cake cup" is one), a plural `s` carried; "display" brackets only a respelling with + `bracket: true`; "plain" never does. Idempotent. `mergeRespellings` joins heard forms per reading. +- **Where they live**: a report's top-level `respellings` (schema, REPORT.md) and a video manifest's top-level + `respellings` (no strict manifest schema). +- **Every quote check applies them, plain, to BOTH sides** — `quoteVerification(q, text, at, rs)`, + `strictQuoteCheck(q, cues, s, {respellings})`, `strictTextCheck(q, text, rs)`, `checkSpanQuote(record, c, now, rs)`; + compose and `reports verify-quotes` pass `report.respellings`; umtool `cutToQuote(…, {respellings})` (resolve-windows + and `/api/report/cut`) passes the manifest's. Undeclared, a corrected quote is `inexact` (strict) and may drift. +- **The writer** `lib/report/respellArticle.ts` (`archilyzer reports respell`): iteration n's report.json via + `writeIterationFile`, the article's report.json via `writeArticle` (keepAudience, keepVideo) when it is n's, and + `<projectsRoot>/<id>/i<n>/video.manifest.json`; the raw JSON is respelled (key order kept). What is respelled: + `respellReport` — cite-link labels and `citations.*.quote` "display"; the report's own words plain; sources, a claim's + `sourceQuote`, ids and links never. `respellManifest` — `quote`/`words` "display", other prose plain, SKIP_KEYS (ids, + paths, urls, provenance, drafted) and path/url-looking values never. Backups: `<project>/revisions/<stamp>-before- + respell.{iteration-report,article-report,manifest}.json` (no iterations: `<projectsRoot>/<id>/revisions/`). + diff --git a/plans/release-31/respell.md b/plans/release-31/respell.md @@ -0,0 +1,28 @@ +# Release 31 — respellings: a transcript's mis-hearing corrected in an article's quotes (as shipped) + +Operator ask (2026-10-16): the cornbreadman article's quotes carry "cake cup"/"cakeup" for K-Cup; correct the text in +the article as an operation that can be previewed. Ruling: bracketing is per respelling and OFF by default (an obvious +correction reads plainly); `--bracket` marks an altered quote `[K-Cup]`. + +## What + +- `archilyzer reports respell <article> --heard <a,b,…> --reads <word> [--bracket] [--note] [--iteration n] [--apply] + [--json]`: a dry run listing every change per file as word hunks (`«cakeup» → «K-Cup»`); `--apply` backs each file + up and writes it through the registry / iterations store; exit 1 when nothing would change. +- Reports and video manifests gain `respellings`; every quote check (compose, verify-quotes recall + strict, umtool's + cut-to-quote) applies them to both sides, so a corrected quote verifies exactly and an undeclared one does not. + +## Files + +`common/lib/citations/respell.mjs` (+ `.d.mts`), `common/lib/citations/verify.ts`, `common/publish/composeReports.ts`, +`common/bin/reports-check.ts`, `common/lib/report/{schema.ts, respellReport.ts, respellManifest.mjs (+ .d.mts), +respellArticle.ts}`, `common/bin/{reports-respell.ts, archilyzer.ts}`, `common/package.json` (exports), +`umtool/report-to-video/resolve-windows.mjs`, `umtool/app/api/report/cut/route.ts`; COMMANDS.md, REPORT.md. + +## Gates + +tsc clean (all packages); common 4443, editor 322, mcp 377, export 117, umtool 33, scripts 1042 (+3 skipped); docs +files/env/cli and settings example checks clean. New: `respell.test.ts` (9), `respellReport.test.ts` (4), +`reports-respell.test.ts` (3), a cut-to-quote case. Live dry run on `cornbreadman-then-and-now`: 16 changes in 3 +files; `reports verify-quotes` on the respelled report 58/58 ok (the four K-Cup quotes score 1, strict ok); the same +report without `respellings` flags them `inexact`. diff --git a/umtool/app/api/report/cut/route.ts b/umtool/app/api/report/cut/route.ts @@ -1,5 +1,6 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, updateClip } from "@/lib/report/manifest.mjs"; +import { cleanRespellings } from "yt-dlp-transcript-common/lib/citations/respell.mjs"; import { cuesInWindow } from "@/lib/projects/report.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { cutToQuote } from "umtool-report-to-video/resolve-windows"; @@ -27,7 +28,7 @@ export async function POST(request: Request) { const r = await resolveClip(projectId, clipId); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); - const { project, clip } = r; + const { project, clip, manifest } = r; if (!String(clip.quote ?? "").trim()) { return Response.json( @@ -45,7 +46,10 @@ export async function POST(request: Request) { } const minMatch = Number.isFinite(Number(body.minMatch)) ? Number(body.minMatch) : 0.6; - const hit = cutToQuote(doc.cues, clip.quote, { start: clip.start, end: clip.end }, { minMatch }) as + const hit = cutToQuote(doc.cues, clip.quote, { start: clip.start, end: clip.end }, { + minMatch, + respellings: cleanRespellings((manifest as { respellings?: unknown }).respellings), + }) as | { ok: true; cutStart: number; cutEnd: number; score: number; matched: string } | { ok: false; score: number; why: string; matched: string }; diff --git a/umtool/report-to-video/cut-to-quote.test.mjs b/umtool/report-to-video/cut-to-quote.test.mjs @@ -130,3 +130,20 @@ test("a citeUrl naming ANOTHER recording is not ours to move", () => { const e = entryOf({ cite: 100, citeUrl: "https://anilyzer.pages.dev/?v=other%2Fvid9&t=100" }); assert.deepEqual(citeForCut(e, { cutStart: 138.2, cutEnd: 157.9 }), { cite: 139 }); }); + +test("a manifest's respellings: a quote showing the corrected word finds the cues that mishear it", () => { + const heard = [ + { start: 0, end: 4, text: "Something before the part we want." }, + { start: 4, end: 8, text: "Because cake cup machines are very expensive." }, + { start: 8, end: 12, text: "And something after it, unrelated." }, + ]; + const quote = "because K-Cup machines are very expensive"; + const rs = [{ heard: ["cake cup"], reads: "K-Cup" }]; + const with_ = cutToQuote(heard, quote, { start: 0, end: 12 }, { respellings: rs }); + assert.equal(with_.ok, true); + assert.equal(with_.score, 1); + assert.equal(with_.cutStart, 4); + assert.equal(with_.cutEnd, 8); + const without = cutToQuote(heard, quote, { start: 0, end: 12 }); + assert.ok(without.score < 1); +}); diff --git a/umtool/report-to-video/resolve-windows.mjs b/umtool/report-to-video/resolve-windows.mjs @@ -55,6 +55,7 @@ import { clipLabel, createLocalMedia, hasLocalMedia } from "./local-media.mjs"; // with the report converters, which widen a citation's one second into a span. // This file re-exports it. import { CUE_EPS as EPS, widen } from "yt-dlp-transcript-common/lib/cueWiden.mjs"; +import { applyRespellings } from "yt-dlp-transcript-common/lib/citations/respell.mjs"; export { widen }; @@ -132,18 +133,24 @@ function bestRun(cueToks, frag) { /** * Where inside [start,end] the quote actually is. * + * @param {any[]} cues + * @param {string | null | undefined} quote + * @param {{start:number,end:number}} extent + * @param {{minMatch?:number,maxLead?:number,maxTail?:number,respellings?:import("yt-dlp-transcript-common/lib/citations/respell.mjs").Respelling[]}} [opts] * @returns {{ok:true,cutStart:number,cutEnd:number,score:number,matched:string} * | {ok:false,score:number,why:string,matched:string}} */ -export function cutToQuote(cues, quote, extent, { minMatch = 0.6, maxLead = 8, maxTail = 12 } = {}) { - const frags = quoteFragments(quote); +export function cutToQuote(cues, quote, extent, { minMatch = 0.6, maxLead = 8, maxTail = 12, respellings } = {}) { + // A manifest's respellings (lib/citations/respell.mjs) apply, plain, to both sides: + // a quote showing "K-Cup" finds the cues that say "cake cup". + const frags = quoteFragments(applyRespellings(quote ?? "", respellings, "plain")); if (!frags.length) return { ok: false, score: 0, why: "no quote", matched: "" }; const inside = cues.filter((c) => c.end > extent.start + EPS && c.start < extent.end - EPS); if (!inside.length) { return { ok: false, score: 0, why: "no cues inside the window", matched: "" }; } - const cueToks = inside.map((c) => normaliseWords(c.text).split(" ").filter(Boolean)); + const cueToks = inside.map((c) => normaliseWords(applyRespellings(String(c.text ?? ""), respellings, "plain")).split(" ").filter(Boolean)); let hits = 0; let total = 0; @@ -298,7 +305,7 @@ async function cutPass(manifest, { cuesOf, slug, opts, write, force }) { continue; } const cues = await cuesOf(e); - const r = cutToQuote(cues, e.quote, { start: e.start, end: e.end }, opts); + const r = cutToQuote(cues, e.quote, { start: e.start, end: e.end }, { ...opts, respellings: manifest.respellings }); const extent = `${e.start.toFixed(1)}–${e.end.toFixed(1)}`; if (!r.ok) { unmatched += 1;