// TASK onscreen — each clip's on-screen title and subtitle (release 28 M2). // A STEP on a done iteration (./media.ts): one unit per clip entry (or the // `entries` asked for), the field `onscreen.{title, subtitle}`. // // The evidence of a clip is what the report says of it: the claim it cites // (its text and verdict), its section, its quote, its source and date. Several // clips are asked in one call (`batch`), as many as fit the local model's // prompt cap (at most ONSCREEN_BATCH_MAX); a re-ask carries only the clips // refused. Code checks every line: the title at most 60 characters, the // subtitle at most 90, one line each; the title quotes nothing, and the // subtitle quotes only words of the clip's own quote, verbatim (inside // quotation marks); no name or number the evidence does not have; and the // narrator's third person outside a quotation. The better of two attempts is // kept; a clip whose on-screen text is the operator's is never replaced. import { strictNormalize } from "../../../citations/verify"; import { CHARS_PER_TOKEN, ollamaConfigOf, promptCapOf, providerOf, structuredPromptEstimate } from "../../../llm"; import { firstPersonProblems, groundedProblems } from "../grounding"; import type { ManifestEntry } from "../videoOps"; import { cutCandidates } from "./cut"; import { runMediaTask, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import type { TaskDeps, TaskResult } from "./types"; export const ONSCREEN_TITLE_MAX = 60; export const ONSCREEN_SUBTITLE_MAX = 90; // The most clips one ask carries (an API model too: a review reads them as a set). export const ONSCREEN_BATCH_MAX = 8; // The room a re-ask's words take on top of a batch's prompt. const RETRY_ROOM_CHARS = 1500; export type OnscreenInput = MediaTaskInput; export type OnscreenValue = { title: string; subtitle?: string }; type OnscreenUnit = MediaUnit & { entry: ManifestEntry; // The clip's own words: what the subtitle may quote. quote: string; // The evidence block shown to the model; names and numbers are grounded in it. evidence: string; }; type Obj = Record; const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); // A quotation: double marks (straight or curly), guillemets, or curly singles. const QUOTED_RE = /"([^"]*)"|“([^”]*)”|«([^»]*)»|‘([^’]*)’/g; const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’/; /** The quoted parts of a line, and whether its marks pair up. */ export function quotedParts(text: string): { parts: string[]; balanced: boolean } { const parts: string[] = []; for (const m of text.matchAll(QUOTED_RE)) parts.push((m[1] ?? m[2] ?? m[3] ?? m[4] ?? "").trim()); const rest = text.replace(QUOTED_RE, " "); return { parts, balanced: !/["“”«»„‟]/.test(rest) && !/‘/.test(rest) }; } /** Is `part` the quote's own words, in order (punctuation and case aside)? */ export function isVerbatimOf(part: string, quote: string): boolean { const p = strictNormalize(part); return !!p && ` ${strictNormalize(quote)} `.includes(` ${p} `); } // The words a Title Case title leaves small, or capitalises with the rest: // neither is ever a name. const TITLE_SMALL = new Set( `a an the and but or nor for so yet of to in on at by up as is it its from with into onto off out over under than that this these those be been being was were are am has have had do does did not no never ever all any each every more most much many some such own same other only just very too again once still also even then now here there when where why how what who whom which whose while if after before about against between through during without within upon via per vs`.split(/\s+/), ); // Ordinary words a headline capitalises (say, deny, sell, …): never read as a // name in a Title Case title, in the evidence or not. Kept short: a word not // here and not in the evidence is a name's candidate, as before. const TITLE_ORDINARY = new Set( `say said says tell told claim claims claimed admit admits admitted deny denies denied refuse refuses refused want wants wanted will would won't can can't could should must may might need needs get gets got make makes made take takes took give gives gave go goes went come comes came keep keeps kept see sees saw know knows knew think thinks thought call calls called ask asks asked answer answers answered change changes changed turn turns turned back sell sells sold sale buy buys bought pay pays paid win wins won lose loses lost start starts started stop stops stopped stay stays plan plans planned promise promises promised deal deals story stories question questions answer truth lie lies side sides vote votes rule rules line lines word words first last next new old big small long short true false real fake whole half day days week weeks month months year years time times later earlier late early again here yes no never always often sometimes nobody everybody somebody anyone everyone someone nothing everything something one two three four five six seven eight nine ten`.split(/\s+/), ); const TITLE_WORD_RE = /[A-Za-z][A-Za-z'’-]*/g; const stemOf = (w: string) => w.toLowerCase().replace(/['’]s$/, "").replace(/(ing|ed|es|s|ly)$/, ""); /** A title whose words (the small ones aside) all start with a capital, two at least. */ export function isTitleCase(title: string): boolean { const big = (title.match(TITLE_WORD_RE) ?? []).filter((w) => !TITLE_SMALL.has(w.toLowerCase())); return big.length >= 2 && big.every((w) => /^[A-Z]/.test(w)); } /** * A Title Case title as the sentence it would be: past its first word, a word * is lowercased when it is small, an ordinary headline word, or a word the * evidence has in any case (by its stem); any other keeps its capital — a * name's candidate, which the grounding then looks for. Any other title is * returned as it is. */ export function titleAsSentence(title: string, evidence: string): string { if (!isTitleCase(title)) return title; const known = new Set((evidence.match(TITLE_WORD_RE) ?? []).map(stemOf)); let first = true; return title.replace(TITLE_WORD_RE, (w) => { if (first) { first = false; return w; } const low = w.toLowerCase(); return TITLE_SMALL.has(low) || TITLE_ORDINARY.has(low) || known.has(stemOf(w)) ? low : w; }); } /** * The names-and-numbers check of one short line (an on-screen title, a teaser * line). A Title Case line is checked in its sentence case (titleAsSentence), * and what is left capitalised and absent from the evidence is SOFT: without a * lexicon code cannot tell an ordinary headline word ("Expansion") from a name * the evidence lacks, so it is said to the reviewer (the drafts review holds a * final build until the line is approved) rather than refused. Numbers, and * names in a line that is not Title Case, stay hard. */ export function titleLineGrounding(text: string, evidence: string, where: string): { hard: string[]; soft: string[] } { if (!isTitleCase(text)) return { hard: groundedProblems(text, evidence, where), soft: [] }; const hard: string[] = []; const soft: string[] = []; for (const p of groundedProblems(titleAsSentence(text, evidence), evidence, where)) { (p.startsWith("name ") ? soft : hard).push(p.startsWith("name ") ? `${p} (a Title Case word — check it is not a name)` : p); } return { hard, soft }; } /** Every code check of one clip's on-screen text: `hard` refuses it. */ export function checkOnscreen(v: OnscreenValue, u: Pick): { hard: string[]; soft: string[] } { const hard: string[] = []; const title = v.title; const sub = v.subtitle ?? ""; if (!title.trim()) hard.push("no title"); for (const [name, text, max] of [["title", title, ONSCREEN_TITLE_MAX], ["subtitle", sub, ONSCREEN_SUBTITLE_MAX]] as const) { if (/[\r\n]/.test(text)) hard.push(`the ${name} is more than one line`); if (text.trim().length > max) hard.push(`the ${name} is ${text.trim().length} characters (at most ${max})`); } if (QUOTE_MARKS_RE.test(title)) hard.push("the title has quotation marks: a title quotes nobody"); const { parts, balanced } = quotedParts(sub); if (!balanced) hard.push("the subtitle's quotation marks do not pair up"); for (const part of parts) { if (!isVerbatimOf(part, u.quote)) hard.push(`the subtitle quotes “${part}”, which is not the clip's quote word for word`); } // Names and numbers: in the evidence (a quoted part is the quote's own). A // Title Case title is checked in its sentence case (titleAsSentence): its // capitals are not a name's signal, so an ordinary word is lowercased and an // unknown name still stands out. const t = titleLineGrounding(title, u.evidence, "the clip's evidence"); hard.push(...t.hard); hard.push(...groundedProblems(sub.replace(QUOTED_RE, " "), u.evidence, "the clip's evidence")); hard.push(...firstPersonProblems(`${title}. ${sub}`)); return { hard: [...new Set(hard)], soft: [...new Set(t.soft)] }; } const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); function unitsOf(ctx: MediaContext): OnscreenUnit[] { const { manifest, report } = ctx; const byEntry = new Map(cutCandidates(manifest, report).map((c) => [c.entry, c])); const out: OnscreenUnit[] = []; const seen = new Set(); let chapter = ""; for (const e of manifest.timeline) { if (e.type === "card" && e.style === "chapter") chapter = String(e.heading ?? ""); if (e.type !== "clip" || seen.has(e.id)) continue; seen.add(e.id); const c = byEntry.get(e.id); const verdict = c?.claim?.verdict ?? (isObj(e.claim) ? e.claim.verdict : undefined); const quote = String(e.quote ?? c?.quote ?? ""); const lines = [ `Report: ${String(report.title ?? "")}`, chapter ? `Section: ${chapter}` : "", c?.claim ? `Claim${verdict ? ` [${verdict}]` : ""}: ${stripCites(c.claim.text)}` : verdict ? `Verdict: ${verdict}` : "", quote ? `Quote: "${quote}"` : "", [c?.label, c?.date || e.date].filter(Boolean).length ? `Source: ${[c?.label, c?.date || e.date].filter(Boolean).join(", ")}` : "", ].filter(Boolean); out.push({ id: e.id, target: { entry: e.id, field: "onscreen" }, label: chapter || undefined, entry: e, quote, evidence: lines.join("\n") }); } return out; } export function onscreenSystem(): string { const rules = [ "For each clip, write the text shown on screen while it plays: a title that says what the clip shows, in plain words, and a subtitle that adds who, when or what is at stake.", `The title is one line of at most ${ONSCREEN_TITLE_MAX} characters, and it has no quotation marks.`, `The subtitle is one line of at most ${ONSCREEN_SUBTITLE_MAX} characters. It may quote the speaker only with words from that clip's quote, exactly as they are, inside double quotation marks.`, "Use only names and numbers that appear in that clip's evidence.", "Write in the third person, in sentence case: no I, me, my, we or our outside a quotation.", "Say what the clip shows; do not add facts, and do not put the verdict in the speaker's mouth.", ]; return ( "You write on-screen text for the clips of a short evidence video. " + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + 'Answer with "entries": one {"id", "title", "subtitle"} per clip, its id exactly as given.' ); } const SCHEMA = { type: "object", properties: { entries: { type: "array", items: { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, subtitle: { type: "string" } }, required: ["id", "title", "subtitle"], }, }, }, required: ["entries"], }; const userOf = (units: OnscreenUnit[]) => `${units.map((u) => `### Clip ${u.id}\n${u.evidence}`).join("\n\n")}\n\nWrite the on-screen title and subtitle of ${units.length === 1 ? "this clip" : `each of these ${units.length} clips`}.`; /** The units in asks: as many per ask as fit the local prompt cap, at most ONSCREEN_BATCH_MAX. */ export function onscreenBatches(units: OnscreenUnit[], ctx: Pick, "input" | "handle">): OnscreenUnit[][] { const local = providerOf(ctx.input.model) === "local"; const cap = local ? promptCapOf(ollamaConfigOf(ctx.handle.deps.llm, ctx.input.model)) - Math.ceil(RETRY_ROOM_CHARS / CHARS_PER_TOKEN) : Number.POSITIVE_INFINITY; const system = onscreenSystem(); const out: OnscreenUnit[][] = []; let cur: OnscreenUnit[] = []; for (const u of units) { const next = [...cur, u]; const fits = next.length <= ONSCREEN_BATCH_MAX && (!local || structuredPromptEstimate({ system, user: userOf(next), schema: SCHEMA }) <= cap); if (fits || !cur.length) cur = next; else { out.push(cur); cur = [u]; } } if (cur.length) out.push(cur); return out; } /** One clip's answer to its value (a throw is a hard failure). */ export function parseOnscreen(raw: unknown): OnscreenValue { const o = isObj(raw) ? raw : {}; const title = typeof o.title === "string" ? o.title.trim() : ""; const subtitle = typeof o.subtitle === "string" ? o.subtitle.trim() : ""; if (!title && !subtitle) throw new Error("no title and no subtitle"); return { title, ...(subtitle ? { subtitle } : {}) }; } /** On-screen text as a media task (./media.ts): one unit per clip, asked in batches. */ export const ONSCREEN_SPEC: MediaTaskSpec = { task: "onscreen", noun: "clip", verb: "titled", progressMetric: "entries", units: (ctx) => unitsOf(ctx), schema: () => SCHEMA, system: () => onscreenSystem(), user: (u) => userOf([u]), batch: { group: (units, ctx) => onscreenBatches(units, ctx), schema: () => SCHEMA, system: () => onscreenSystem(), user: (units) => userOf(units), split(answer) { const list = isObj(answer) && Array.isArray(answer.entries) ? answer.entries : []; const out: Record = {}; for (const e of list) if (isObj(e) && typeof e.id === "string" && !(e.id.trim() in out)) out[e.id.trim()] = e; return out; }, }, parse: (raw) => parseOnscreen(raw), check: (v, u) => checkOnscreen(v, u), toField: (v) => ({ title: v.title, ...(v.subtitle ? { subtitle: v.subtitle } : {}) }), describe: (v) => `${v.title}${v.subtitle ? ` — ${v.subtitle}` : ""}`, }; export async function onscreen(input: OnscreenInput, deps: TaskDeps): Promise { return runMediaTask(ONSCREEN_SPEC, input, deps); }