// TASK teaser — the lines of the cut's teaser card (release 28 M3). A STEP on // a done iteration (./media.ts): one unit per teaser entry, the field `lines`. // // The evidence is the report as a whole: its title and subtitle, its section // titles, each claim's gist (its words, the quoted ones taken out) and the // days its sources are from. The lines are TEASER_MIN_LINES to // TEASER_MAX_LINES, each one line of at most TEASER_LINE_MAX characters; the // first is drawn as the overline, the middle ones as titles and the last as // the kicker (a date, or the turn), and each must fit its role's row — which // the build's own `validateTeaser` judges (umtool's deck.mjs, through // `TaskDeps.deckChecks`; a teaser it cannot check is not written). No line // reads a quote out: no quotation marks, and no run of TEASER_QUOTE_RUN words // from any citation's quote. No name or number the evidence does not have. // // A cut with no teaser gets one: an entry `{type: "teaser", id: "teaser"}` // after its last clip, its lines written through applyDraft as any empty // field — the operator deletes it like any entry. import { strictNormalize } from "../../../citations/verify"; import { applyDraft, entriesWithId } from "../../drafted.mjs"; import { titleLineGrounding } from "./onscreen"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import type { DeckChecks } from "./deckChecks"; import { runMediaTask, type MediaContext, type MediaReport, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import type { TaskDeps, TaskResult } from "./types"; export const TEASER_MIN_LINES = 3; export const TEASER_MAX_LINES = 5; export const TEASER_LINE_MAX = 70; // A run this long copied from a quote is the quote read out. export const TEASER_QUOTE_RUN = 5; // The row each role fits (deck.mjs TEASER_LIMITS.fit): the prompt's rule; the // build's validator is the check. const ROLE_FIT = { overline: 64, title: 34, kicker: 56 }; // A `break` (the line's end, drawn as the smaller second tier) fits this row. const SUB_FIT = 66; export type TeaserLine = string | { text: string; break: string }; /** * The lines as the card draws them: a line longer than its role's row (roles * follow position: with three or more lines the first is the overline, the * last the kicker, the rest titles; two are an overline and a title; one is a * title) becomes `{ text, break }`, its end set as the second tier at the last * word boundary where the first tier fits the role and the end fits the * second tier's row. A line that cannot be split so stays as written, and the * build's check refuses it. Code fits the rows; the model only writes words. */ export function fitTeaserLines(lines: string[]): TeaserLine[] { const roleOf = (i: number): keyof typeof ROLE_FIT => lines.length >= 3 ? (i === 0 ? "overline" : i === lines.length - 1 ? "kicker" : "title") : lines.length === 2 && i === 0 ? "overline" : "title"; return lines.map((line, i) => { const fit = ROLE_FIT[roleOf(i)]; if (line.length <= fit) return line; const words = line.split(/\s+/); for (let k = words.length - 1; k >= 1; k--) { const head = words.slice(0, k).join(" "); const tail = words.slice(k).join(" "); if (head.length <= fit && tail.length <= SUB_FIT) return { text: line, break: tail }; } return line; }); } export const NEW_TEASER_ID = "teaser"; export type TeaserInput = MediaTaskInput; type TeaserUnit = MediaUnit & { // The teaser entry as it is (null: the cut has none, and the task adds it). entry: ManifestEntry | null; evidence: string; quotes: string[]; deck: DeckChecks | null; }; type Obj = Record; const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’|(^|\s)'[^']+'(?=[\s.,;:!?]|$)/; /** A claim's gist: its words with every quoted part (and the colon before it) taken out. */ export function claimGist(text: string): string { return stripCites(text) .replace(/:?\s*("[^"]*"|“[^”]*”)/g, "") .replace(/\s+/g, " ") .replace(/[\s:,;]+$/, "") .trim(); } const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; /** The report as the teaser may use it: titles, section titles, claim gists, the days of its sources. */ export function teaserEvidence(report: MediaReport, manifest: VideoManifest): string { const lines = [`Report: ${String(report.title ?? "")}`]; if (report.subtitle) lines.push(`Subtitle: ${String(report.subtitle)}`); for (const s of Array.isArray(report.sections) ? report.sections : []) { const gists = (Array.isArray(s?.claims) ? s.claims : []).map((c: Obj) => claimGist(String(c?.text ?? ""))).filter(Boolean); if (!gists.length) continue; lines.push(`Section: ${String(s.title ?? "")}`); for (const g of gists.slice(0, 8)) lines.push(`- ${g}`); } const days = new Set(); for (const c of Object.values(isObj(report.citations) ? report.citations : {})) if (typeof (c as Obj)?.date === "string") days.add((c as Obj).date.slice(0, 10)); for (const e of manifest.timeline) if (typeof e.date === "string") days.add(e.date.slice(0, 10)); const sorted = [...days].filter((d) => /^\d{4}-\d{2}/.test(d)).sort(); if (sorted.length) { const month = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1] ?? ""} ${d.slice(0, 4)}`.trim(); lines.push(`Sources dated: ${month(sorted[0]!)}${sorted.length > 1 && month(sorted.at(-1)!) !== month(sorted[0]!) ? ` to ${month(sorted.at(-1)!)}` : ""}`); } return lines.join("\n"); } /** The quote words a line repeats in a run of TEASER_QUOTE_RUN or more, or null. */ export function quoteRunIn(line: string, quotes: readonly string[]): string | null { const said = ` ${strictNormalize(line)} `; for (const q of quotes) { const w = strictNormalize(q).split(" ").filter(Boolean); for (let k = 0; k + TEASER_QUOTE_RUN <= w.length; k++) { const run = w.slice(k, k + TEASER_QUOTE_RUN).join(" "); if (said.includes(` ${run} `)) return run; } } return null; } /** The teaser entry these lines would make. */ export const teaserEntryOf = (u: Pick, lines: string[]): ManifestEntry => ({ ...(u.entry ?? { type: "teaser", id: u.id }), lines: fitTeaserLines(lines) }) as ManifestEntry; /** Every code check of a teaser's lines: `hard` refuses them. */ export function checkTeaser(lines: string[], u: Pick): { hard: string[]; soft: string[] } { const hard: string[] = []; const soft: string[] = []; if (lines.length < TEASER_MIN_LINES || lines.length > TEASER_MAX_LINES) hard.push(`${lines.length} lines (${TEASER_MIN_LINES} to ${TEASER_MAX_LINES})`); lines.forEach((l, i) => { const n = `line ${i + 1}`; if (!l.trim()) hard.push(`${n} is empty`); if (/[\r\n]/.test(l)) hard.push(`${n} is more than one line`); if (l.trim().length > TEASER_LINE_MAX) hard.push(`${n} is ${l.trim().length} characters (at most ${TEASER_LINE_MAX})`); if (QUOTE_MARKS_RE.test(l)) hard.push(`${n} has quotation marks: a teaser reads no quote out`); const run = quoteRunIn(l, u.quotes); if (run) hard.push(`${n} repeats a quote ("${run}"): the clips say it; the teaser does not read it out`); const g = titleLineGrounding(l, u.evidence, "the report"); for (const p of g.hard) hard.push(`${n}: ${p}`); for (const p of g.soft) soft.push(`${n}: ${p}`); }); if (!hard.length) { if (!u.deck) hard.push("the build's teaser check (deck.mjs validateTeaser) is not available, so the lines are not written"); else for (const e of u.deck.validateTeaser(teaserEntryOf(u, lines), `teaser ${u.id}`)) hard.push(`it would not build: ${e}`); } return { hard, soft }; } export function teaserSystem(): string { const rules = [ `Write ${TEASER_MIN_LINES} to ${TEASER_MAX_LINES} short lines, each one line of plain words.`, `The first line is the overline (at most ${ROLE_FIT.overline} characters): who or what the video is about.`, `The middle lines are titles (each at most ${ROLE_FIT.title} characters): the questions or findings the video turns on, without giving the answers away.`, `The last line is the kicker (at most ${ROLE_FIT.kicker} characters): when, or the turn the video ends on.`, "Read no quote out: no quotation marks, and do not repeat the speakers' words.", "Use only names, numbers and dates that appear in the evidence.", "Write in the third person.", ]; return ( "You write the teaser card that closes a short evidence video: a few lines that slam in one after another. " + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + 'Answer with "lines": the lines in order.' ); } const SCHEMA = { type: "object", properties: { lines: { type: "array", items: { type: "string" } } }, required: ["lines"] }; /** The model's answer to lines (a throw is a hard failure). */ export function parseTeaser(answer: unknown): string[] { const a = isObj(answer) ? answer : {}; if (!Array.isArray(a.lines)) throw new Error('no "lines" in the answer'); return a.lines.map((l: unknown) => (typeof l === "string" ? l : isObj(l) && typeof l.text === "string" ? l.text : String(l ?? "")).trim()).filter((l: string) => l !== ""); } // A free id for a new teaser: "teaser", else "teaser-2", … function freeId(manifest: VideoManifest): string { const ids = new Set(manifest.timeline.map((e) => e.id)); if (!ids.has(NEW_TEASER_ID)) return NEW_TEASER_ID; for (let i = 2; ; i++) if (!ids.has(`${NEW_TEASER_ID}-${i}`)) return `${NEW_TEASER_ID}-${i}`; } async function teaserUnits(ctx: MediaContext): Promise { const { manifest, report } = ctx; let deck: DeckChecks | null = null; try { deck = (await ctx.handle.deps.deckChecks?.()) ?? null; } catch (e) { ctx.handle.log(` the build's teaser check is not loaded (${(e as Error).message})`); } const evidence = teaserEvidence(report, manifest); const quotes = Object.values(isObj(report.citations) ? report.citations : {}) .map((c) => String((c as Obj)?.quote ?? "")) .concat(manifest.timeline.map((e) => String(e.quote ?? ""))) .filter(Boolean); const seen = new Set(); const teasers = manifest.timeline.filter((e) => e.type === "teaser" && !seen.has(e.id) && seen.add(e.id)); const base = { evidence, quotes, deck }; if (!teasers.length) { const id = freeId(manifest); return [{ id, target: { entry: id, field: "lines" }, label: "a new teaser after the last clip", entry: null, ...base }]; } return teasers.map((e) => ({ id: e.id, target: { entry: e.id, field: "lines" }, entry: e, ...base })); } /** The teaser as a media task (./media.ts): one unit per teaser entry, or one new teaser. */ export const TEASER_SPEC: MediaTaskSpec = { task: "teaser", noun: "teaser", verb: "drafted", progressMetric: "entries", units: (ctx) => teaserUnits(ctx), schema: () => SCHEMA, system: () => teaserSystem(), user: (u) => `Evidence (the only facts you may use):\n${u.evidence}\n\nWrite the teaser's lines.`, parse: (answer) => parseTeaser(answer), check: (lines, u) => checkTeaser(lines, u), apply(manifest, u, value, provenance, force) { // No teaser yet: add one after the last clip, then write its lines as any // empty field. if (!u.entry && !entriesWithId(manifest, u.id).length) { let at = -1; manifest.timeline.forEach((e, i) => { if (e.type === "clip") at = i; }); manifest.timeline.splice(at < 0 ? manifest.timeline.length : at + 1, 0, { type: "teaser", id: u.id } as ManifestEntry); } return applyDraft(manifest, { entry: u.id, field: "lines", value: fitTeaserLines(value as string[]), provenance, force }); }, describe: (lines) => lines.join(" / "), }; export async function teaser(input: TeaserInput, deps: TaskDeps): Promise { return runMediaTask(TEASER_SPEC, input, deps); }