@kriya-ai/harness 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +194 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +19 -1
  5. package/src/edit/core/layout.js +24 -1
  6. package/src/edit/core/ops.js +9 -3
  7. package/src/edit/core/plan.js +36 -5
  8. package/src/edit/core/solver.js +39 -3
  9. package/src/edit/core/transitions.js +17 -0
  10. package/src/edit/director/beats.js +335 -0
  11. package/src/edit/director/continuity.js +129 -0
  12. package/src/edit/director/graphics.js +152 -0
  13. package/src/edit/director/lookups.js +133 -0
  14. package/src/edit/director/plan.js +118 -6
  15. package/src/edit/director/playbooks.js +131 -0
  16. package/src/edit/director/revise.js +49 -5
  17. package/src/edit/engine/captions.js +32 -0
  18. package/src/edit/engine/found-media.js +64 -0
  19. package/src/edit/engine/graphics.js +178 -0
  20. package/src/edit/engine/motion.js +24 -3
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/gates/copy.js +25 -5
  23. package/src/edit/gates/index.js +16 -5
  24. package/src/edit/gates/picture.js +11 -3
  25. package/src/edit/gates/text.js +20 -4
  26. package/src/edit/graph/scheduler.js +1 -1
  27. package/src/edit/host/deliver.js +8 -1
  28. package/src/edit/host/main.js +8 -5
  29. package/src/edit/host/paths.js +15 -2
  30. package/src/edit/host/projects.js +229 -12
  31. package/src/edit/host/server.js +72 -3
  32. package/src/edit/index/views.js +9 -0
  33. package/src/edit/loop/make.js +25 -6
  34. package/src/edit/recipes/graphic-clips.js +57 -0
  35. package/src/edit/recipes/montage.js +74 -0
  36. package/src/edit/recipes/programme.js +24 -0
  37. package/src/edit/recipes/reel.js +65 -14
  38. package/src/edit/recipes/scene-clips.js +127 -0
  39. package/src/edit/runtime/fetch.js +33 -0
  40. package/studio/dist/studio.css +15 -0
  41. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,133 @@
1
+ // What the speech names that the footage doesn't show (DP4, DP6, EDD-52, EDD-57): one slot picks the
2
+ // lines where viewers would want to see a real place or thing and the hard terms worth defining;
3
+ // code places them, the server searches licensed sources, and the person approves each on the card.
4
+ // Search words leave the computer, so this runs only with editing.mediaSearch on.
5
+
6
+ import { paperEdit } from "../index/views.js"
7
+ import { phrasesOf } from "./beats.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const OPENING = 3 * FLICKS
11
+ const MIN = 2.5 * FLICKS
12
+ const MAX = 12 * FLICKS
13
+ const GAP = 1 * FLICKS
14
+ export const MAX_PICTURES = 8
15
+ export const MAX_TERMS = 4
16
+
17
+ const LOOKUPS_SCHEMA = {
18
+ type: "object",
19
+ properties: {
20
+ pictures: { type: "array", maxItems: MAX_PICTURES, items: { type: "object", properties: { from: { type: "string", maxLength: 64 }, to: { type: "string", maxLength: 64 }, query: { type: "string", maxLength: 80 } }, required: ["from", "to", "query"], additionalProperties: false } },
21
+ terms: { type: "array", maxItems: MAX_TERMS, items: { type: "object", properties: { at: { type: "string", maxLength: 64 }, term: { type: "string", maxLength: 60 } }, required: ["at", "term"], additionalProperties: false } },
22
+ },
23
+ required: ["pictures", "terms"],
24
+ additionalProperties: false,
25
+ }
26
+
27
+ const SAID_OFF = /\b(?:no|without|skip|don't (?:want|add|use)|do not (?:want|add|use))\s+(?:any\s+|the\s+)?(?:images?|photos?|pictures?|footage from|stock|internet)\b/i
28
+
29
+ /** Where the person said no pictures. */
30
+ export const picturesRefused = (text) => SAID_OFF.test(text)
31
+
32
+ /** The id a term's definition is kept under. */
33
+ export const termId = (term) => `term:${lower(term)}`
34
+
35
+ const lower = (text) => String(text).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N} ]+/gu, " ").replace(/\s+/g, " ").trim()
36
+
37
+ /**
38
+ * A slot's picks, on phrase edges, clear of the scenes and each other; a term only where its words are said.
39
+ * @returns {{ pictures: { from: string, to: string, query: string }[], terms: { at: string, term: string }[] }}
40
+ */
41
+ export function arrangeLookups({ pictures = [], terms = [] }, { index, asset, scenes = [], cuts = [] }) {
42
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
43
+ const position = new Map(words.map((w, i) => [w.id, i]))
44
+ const phrases = phrasesOf(index, asset)
45
+ const phraseAt = (i) => phrases.findIndex((p) => i >= p.first && i <= p.last)
46
+ const trimmed = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
47
+ const taken = scenes.flatMap((s) => (position.has(s.from) && position.has(s.to) ? [{ start: words[position.get(s.from)].start, end: words[position.get(s.to)].end }] : []))
48
+ const out = []
49
+ const spans = pictures.map((p) => ({ p, i: phraseAt(position.get(p.from) ?? -1), k: phraseAt(position.get(p.to) ?? -1) })).filter(({ i, k }) => i >= 0 && k >= i).sort((a, b) => a.i - b.i)
50
+ for (const { p, i, k: asked } of spans) {
51
+ let k = asked
52
+ while (k + 1 < phrases.length && phrases[k].end - phrases[i].start < MIN) k++
53
+ const start = phrases[i].start
54
+ const end = phrases[k].end
55
+ const query = String(p.query ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 80)
56
+ if (query.length < 2 || start - words[0].start < OPENING || end - start > MAX || end - start < MIN) continue
57
+ if (words.some((w) => w.start >= start && w.end <= end && trimmed(w))) continue
58
+ if ([...taken, ...out].some((t) => start < t.end + GAP && t.start < end + GAP)) continue
59
+ out.push({ start, end, from: words[phrases[i].first].id, to: words[phrases[k].last].id, query })
60
+ }
61
+ const shown = new Set()
62
+ const keptTerms = terms.flatMap((t) => {
63
+ const at = position.get(t.at)
64
+ const term = String(t.term ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 60)
65
+ const said = lower(words.slice(Math.max(0, (at ?? 0) - 1), (at ?? 0) + 6).map((w) => w.text).join(" "))
66
+ const key = lower(term)
67
+ if (at === undefined || term.length < 3 || trimmed(words[at]) || shown.has(key) || !said.includes(key)) return []
68
+ if ([...taken, ...out].some((s) => words[at].start >= s.start - GAP && words[at].start <= s.end + GAP)) return []
69
+ shown.add(key)
70
+ return [{ at: t.at, term }]
71
+ })
72
+ return { pictures: out.slice(0, MAX_PICTURES).map(({ from, to, query }) => ({ from, to, query })), terms: keptTerms.slice(0, MAX_TERMS) }
73
+ }
74
+
75
+ // Clinical photographs nobody asked to see in an explainer (found live: "human pancreas" gave a skull with lesions)
76
+ const GRAPHIC = /metasta|lesion|carcinoma|tumou?r|cancer|autops|cadaver|corpse|necro|gangren|wound|surgery|surgical|dissect|injur|blood ?stain|dead body|execution/i
77
+
78
+ /**
79
+ * Search engines drift. A picture must be named for what was asked, the closest title first: every word
80
+ * asked for, then the fewest others. The person still sees each one before anything is downloaded.
81
+ */
82
+ export function rankPictures(query, items) {
83
+ const wanted = lower(query).split(" ").filter((w) => w.length > 2)
84
+ const main = [...wanted].sort((a, b) => b.length - a.length)[0]
85
+ const score = (item) => {
86
+ const title = lower(item.title.replace(/\.[a-z0-9]{3,4}$/i, ""))
87
+ const hits = wanted.filter((w) => title.includes(w)).length
88
+ return hits * 10 - title.split(" ").length
89
+ }
90
+ return items.filter((item) => !GRAPHIC.test(item.title) && (!main || lower(item.title).includes(main))).sort((a, b) => score(b) - score(a))
91
+ }
92
+
93
+ /**
94
+ * @param {{ ask: Function, index: object, asset: string, text: string, scenes?: object[], cuts?: object[], search: (queries: string[]) => Promise<object[]>, define: (terms: string[]) => Promise<object[]>, wantTerms?: boolean, wantPictures?: boolean, signal?: AbortSignal }} input
95
+ * @returns {Promise<{ pictures: object[], terms: object[], items: object[], definitions: object[] }>} items, definitions: everything found, for the Host to keep
96
+ */
97
+ export async function planLookups({ ask, index, asset, text, scenes = [], cuts = [], search, define, wantTerms = true, wantPictures = true, signal }) {
98
+ const none = { pictures: [], terms: [], items: [], definitions: [] }
99
+ const sentences = (index.sentences ?? []).filter((s) => s.asset === asset)
100
+ if (!sentences.length) return none
101
+ const answer = await ask({
102
+ task: "lookups",
103
+ tier: "budget",
104
+ schema: LOOKUPS_SCHEMA,
105
+ view: paperEdit({ ...index, sentences, takes: [] }, { assets: [asset] }),
106
+ request: [
107
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 800))}`,
108
+ wantPictures ? `pictures: the moments where the speaker names a real place, building, object, animal or event the viewer would want to see and the footage doesn't show. \`from\` and \`to\` are word ids covering about 3 to 10 seconds; \`query\` is 2 to 6 English words naming that exact thing for an encyclopaedia image search. Never a private person, never a generic mood. Leave it empty if nothing is named.` : "pictures: leave empty.",
109
+ wantTerms ? "terms: up to 4 hard technical terms a general viewer wouldn't know, exactly as spoken, with `at`, the id of the term's first word. Leave it empty if there are none." : "terms: leave empty.",
110
+ ].join("\n"),
111
+ maxOutput: 900,
112
+ fallback: () => ({ pictures: [], terms: [] }),
113
+ signal,
114
+ priority: 0,
115
+ })
116
+ const arranged = arrangeLookups(answer.value, { index, asset, scenes, cuts })
117
+ const results = arranged.pictures.length ? await search([...new Set(arranged.pictures.map((p) => p.query))].slice(0, 6)) : []
118
+ const definitions = arranged.terms.length ? await define(arranged.terms.map((t) => t.term)) : []
119
+ const byQuery = new Map(results.map((r) => [r.query, r.items ?? []]))
120
+ const used = new Set()
121
+ const pictures = arranged.pictures.flatMap((p) => {
122
+ const items = rankPictures(p.query, byQuery.get(p.query) ?? []).filter((item) => !used.has(item.id))
123
+ if (!items.length) return []
124
+ used.add(items[0].id)
125
+ return [{ ...p, id: items[0].id, options: items.slice(0, 4).map(({ id, title, licence, creator, kind }) => ({ id, title, licence, creator, kind })) }]
126
+ })
127
+ const byTerm = new Map(definitions.map((d) => [d.term, d]))
128
+ const terms = arranged.terms.flatMap((t) => {
129
+ const d = byTerm.get(t.term)
130
+ return d ? [{ at: t.at, term: t.term, id: termId(t.term), quote: d.quote, source: d.source }] : []
131
+ })
132
+ return { pictures, terms, items: results.flatMap((r) => r.items ?? []), definitions }
133
+ }
@@ -7,11 +7,19 @@
7
7
 
8
8
  import { FORMATS, GRADES } from "../recipes/reel.js"
9
9
  import { MOODS } from "../engine/music-bed.js"
10
+ import { LOOKS } from "../engine/captions.js"
10
11
  import { SFX } from "../engine/sfx.js"
11
12
  import { paperEdit, shotDigest } from "../index/views.js"
13
+ import { planScenes, visualsIn } from "./beats.js"
14
+ import { graphicLine, graphicsIn, planGraphics } from "./graphics.js"
15
+ import { picturesRefused, planLookups } from "./lookups.js"
16
+ import { applyPlaybook, footageFacts, GENRES, PLAYBOOKS, playbookPrompt } from "./playbooks.js"
12
17
  import { timesIn } from "./revise.js"
18
+ import { TRANSITIONS } from "../core/transitions.js"
13
19
 
14
20
  const FLICKS = 705_600_000
21
+ // The highlight colours a plan may choose; hex stays in code
22
+ export const ACCENTS = { yellow: "#ffd23f", amber: "#ffb347", teal: "#4fd1c5", pink: "#ff7ab6", white: "#ffffff" }
15
23
  const ID = { type: "string", maxLength: 64 }
16
24
 
17
25
  export const PLAN_SCHEMA = {
@@ -45,6 +53,26 @@ export const PLAN_SCHEMA = {
45
53
  additionalProperties: false,
46
54
  }
47
55
 
56
+ // Transitions in the person's words: a kind, "no transitions", and whether every cut gets one
57
+ const TRANSITION_CUES = [
58
+ ["slide", /\b(?:slide|push)\b/i],
59
+ ["wipe", /\bwipe\b/i],
60
+ ["zoom", /\bzoom\b/i],
61
+ ["flash", /\bflash\b/i],
62
+ ["dip", /\bdip\b|\bto black\b/i],
63
+ ["fade", /\b(?:cross ?fade|dissolve|fade)\b/i],
64
+ ]
65
+ /** @returns {{ transition?: string, transitionAll?: boolean }} empty when the words say nothing of transitions */
66
+ export function transitionIn(text) {
67
+ const said = String(text ?? "")
68
+ // The clause that speaks of transitions, so "zoom in on the price" elsewhere doesn't choose a zoom
69
+ const clause = said.split(/[.;!?\n]+/).find((part) => /\btransitions?\b|\bcross ?fade|\bdissolve/i.test(part))
70
+ if (!clause) return {}
71
+ if (/\b(?:no|without|skip|remove(?: the| all)?|drop the)\s+(?:any\s+)?transitions?\b/i.test(clause)) return { transition: "none" }
72
+ const kind = TRANSITION_CUES.find(([, cue]) => cue.test(clause))?.[0] ?? "fade"
73
+ return { transition: kind, ...(/\b(?:every|each|all)\s+(?:the\s+|of the\s+)?cuts?\b|\beverywhere\b/i.test(clause) ? { transitionAll: true } : {}) }
74
+ }
75
+
48
76
  /** What the plan's settings ask of a make job, as the make route takes them. */
49
77
  export function briefOf(settings = {}) {
50
78
  return {
@@ -64,6 +92,16 @@ export function briefOf(settings = {}) {
64
92
  ...(settings.titles ? { titles: true } : {}),
65
93
  ...(settings.ramps ? { ramps: true } : {}),
66
94
  ...(Array.isArray(settings.cuts) && settings.cuts.length ? { cuts: mergeCuts(settings.cuts) } : {}),
95
+ ...(typeof settings.song === "string" ? { music: settings.song } : {}),
96
+ ...(settings.montage ? { montage: true } : {}),
97
+ ...(settings.multicam ? { multicam: settings.multicam } : {}),
98
+ ...(settings.captionStyle ? { captionStyle: settings.captionStyle } : {}),
99
+ ...(settings.pictures?.length ? { pictures: settings.pictures.map(({ from, to, id }) => ({ from, to, id })) } : {}),
100
+ ...(settings.terms?.length ? { terms: settings.terms.map(({ at, id, term }) => ({ at, id, term })) } : {}),
101
+ ...(Number.isInteger(settings.soundEvery) && settings.soundEvery > 1 ? { soundEvery: settings.soundEvery } : {}),
102
+ ...(Array.isArray(settings.scenes) && settings.scenes.length ? { scenes: settings.scenes, sceneSound: settings.sceneSound !== false } : {}),
103
+ ...(Array.isArray(settings.graphics) && settings.graphics.length ? { graphics: settings.graphics } : {}),
104
+ ...(Object.hasOwn(TRANSITIONS, settings.transition ?? "") ? { transition: settings.transition, ...(settings.transitionAll ? { transitionAll: true } : {}) } : {}),
67
105
  }
68
106
  }
69
107
 
@@ -240,10 +278,12 @@ export function planProblems(settings, index) {
240
278
  }
241
279
 
242
280
  /**
243
- * @param {{ ask: Function, project: object, index: object, text: string, history?: object[], previous?: object, references?: { name: string, lines: string[] }[], choices?: object, signal?: AbortSignal }} input
281
+ * @param {{ ask: Function, project: object, index: object, text: string, history?: object[], previous?: object, references?: { name: string, lines: string[] }[], choices?: object, visuals?: boolean, playbooks?: boolean, signal?: AbortSignal }} input
282
+ * visuals, playbooks, motion: the server's editing.visuals, editing.playbooks and editing.motion; off, this plan is what it always was
283
+ * lookups: { search, define, keep } with editing.mediaSearch on; null, no search word leaves the computer
244
284
  * @returns {Promise<{ say: string, steps: string[], settings: object, source: string, reason?: string }>}
245
285
  */
246
- export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, signal }) {
286
+ export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, visuals = false, playbooks = false, motion = false, lookups = null, signal }) {
247
287
  const assets = project.assets.filter((a) => a.kind === "video" || a.kind === "audio").map((a) => a.id)
248
288
  const refs = references.length ? `References the person added, measured by code:\n${references.map((r) => `- ${r.name}: ${r.lines.join("; ")}`).join("\n")}` : "No references added."
249
289
  const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), refs, `The person's current choices in the Studio: ${JSON.stringify(choices)}`].join("\n\n")
@@ -254,12 +294,18 @@ export async function planCut({ ask, project, index, text, history = [], previou
254
294
  const kept = Array.isArray(previous?.settings?.cuts) ? previous.settings.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to)) : []
255
295
  const cuts = take ? mergeCuts([...kept, ...[...history.filter((h) => h.who === "you").map((h) => h.text), text].flatMap((said) => trimsIn(said, length))], length / FLICKS) : []
256
296
  const at = (n) => `${Math.floor(n / 60)}:${(n % 60).toFixed(1).padStart(4, "0")}`
297
+ // The scenes first, so the pitch can speak for them; each is checked by code, and the person swaps them on the card
298
+ const planned = visuals && take ? await planScenes({ ask, index, asset: take.id, text, history, previous, cuts, signal }) : null
299
+ const scenes = planned?.scenes ?? []
300
+ const { scenes: _shownOnTheCard, graphics: _alsoOnTheCard, ...previousSettings } = previous?.settings ?? {}
257
301
  const earlier = history.length ? `Earlier in this chat:\n${history.map((h) => `${h.who === "you" ? "Person" : "Kriya"}: ${JSON.stringify(h.text)}`).join("\n")}\n\n` : ""
258
302
  const request = [
259
303
  `${earlier}The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
260
304
  cuts.length ? `The person asked to trim ${cuts.map((c) => `${at(c.from)} to ${at(c.to)}`).join(", ")} of the take (${take.id}); code cuts exactly that, between words. Plan around it: no hook or cold open inside a trimmed stretch, and say the trim in your pitch.` : "",
261
305
  asked ? `The person wants the ${asked} format: settings.format is "${asked}", and your pitch says ${asked}.` : "",
262
- previous ? `Your previous plan, which they want changed: ${JSON.stringify(previous).slice(0, 3000)}. Revise it by what they say now; keep what they didn't ask to change.` : "",
306
+ previous ? `Your previous plan, which they want changed: ${JSON.stringify(previous.settings ? { ...previous, settings: previousSettings } : previous).slice(0, 3000)}. Revise it by what they say now; keep what they didn't ask to change.` : "",
307
+ scenes.length ? `Animated explainer scenes that take over the frame while the voice keeps playing are already planned on these lines: ${scenes.map((s) => `${s.from} (${s.kind}: ${s.title || s.items[0].text})`).join("; ")}. Say so in one sentence of your pitch. They're code-drawn from the speaker's words, so promise no others, and don't choose a hook or cold open on those lines.` : "",
308
+ ...(playbooks ? playbookPrompt(footageFacts(project, index, take)) : []),
263
309
  "You are the Director: plan the whole cut the way a top editor pitches it. Decide the opening (a hook sentence first, or a cold open: one strong later moment of 2 to 6 seconds played first, in black and white, before the story starts), the pacing (punch-ins), captions, the colour look, music, sound design (a sound on each cut, a riser into the story after a cold open), whether to clean background noise from the voice, the format and the length. You can also cut one camera like two (angles: wide then tight on alternate clips), lay the person's other clips over the story as B-roll (broll 'own', only if the project has other video), pop key words on screen as title cards (titles, when there are no captions), and ramp the speed out of a cold open into the story (ramps). Follow the references where they say something. Don't promise what these settings can't do: no stock footage or generated video.",
264
310
  "Answer with JSON only: `say` is your pitch in 2 to 4 plain sentences, `steps` the concrete things you'll do, and `settings` exactly what will be made: every promise in the pitch has its setting (captions, grade, music, cleanVoice, cutSound, introSound, punches, seconds, coldOpen), because only the settings are made. Use sentence ids for `hook` and word ids for `coldOpen`, only from the paper edit. Music 'reference' means follow the music reference.",
265
311
  ].filter(Boolean).join("\n")
@@ -271,10 +317,17 @@ export async function planCut({ ask, project, index, text, history = [], previou
271
317
  steps: ["Keep each line's best take and cut fillers and restarts", "Use the format, length, captions, look and music you've chosen"],
272
318
  settings: { format: choices.format ?? "9:16", ...(choices.seconds ? { seconds: choices.seconds } : {}), captions: choices.captions ?? "none", grade: choices.grade ?? "natural", music: (choices.music ?? "").replace(/^generated:/, "") || "none", cleanVoice: !!choices.cleanVoice },
273
319
  })
274
- const answer = await ask({ task: "plan", tier: "budget", schema: PLAN_SCHEMA, view, request, maxOutput: 2500, check, fallback, signal, priority: 0 })
320
+ // With playbooks the answer also names the genre; off, the schema is the same object as before
321
+ const schema = playbooks ? { ...PLAN_SCHEMA, properties: { ...PLAN_SCHEMA.properties, genre: { type: "string", enum: GENRES }, settings: { ...PLAN_SCHEMA.properties.settings, properties: { ...PLAN_SCHEMA.properties.settings.properties, captions: { type: "string", enum: ["none", ...Object.keys(LOOKS)] }, accent: { type: "string", enum: Object.keys(ACCENTS) }, song: { type: "string", maxLength: 64 } } } }, required: [...PLAN_SCHEMA.required, "genre"] } : PLAN_SCHEMA
322
+ // With editing.motion the Director may also choose a transition; off, the schema is the object it was
323
+ const asked_ = motion ? { ...schema, properties: { ...schema.properties, settings: { ...schema.properties.settings, properties: { ...schema.properties.settings.properties, transition: { type: "string", enum: ["none", ...Object.keys(TRANSITIONS)] } } } } } : schema
324
+ const answer = await ask({ task: "plan", tier: "budget", schema: asked_, view, request: motion ? `${request}\nYou may also set \`transition\` (${Object.keys(TRANSITIONS).join(", ")}): how the picture arrives where the story changes moment, such as out of a cold open or into a reordered line. Code puts it only at those joins, never on a filler cut. Choose none unless it suits the video.` : request, maxOutput: 2500, check, fallback, signal, priority: 0 })
275
325
  const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim()
276
326
  // The frame is always set, and set by what the person said, never left to a default
277
- const settings = { ...(answer.value.settings ?? {}) }
327
+ // The fallback plan keeps the person's choices: no model read the speech, so no genre was found
328
+ const genre = playbooks && answer.source !== "default" && Object.hasOwn(PLAYBOOKS, answer.value.genre ?? "") ? answer.value.genre : null
329
+ const settings = genre ? applyPlaybook(answer.value.settings ?? {}, genre, length / FLICKS) : { ...(answer.value.settings ?? {}) }
330
+ if (genre) settings.genre = genre
278
331
  settings.format = asked ?? (Object.hasOwn(FORMATS, settings.format ?? "") ? settings.format : Object.hasOwn(FORMATS, choices.format ?? "") ? choices.format : "9:16")
279
332
  // What the pitch promised and the settings left out, code fills; what the person said, code
280
333
  // sets. So the approved brief makes what the card says, not just the format
@@ -294,5 +347,64 @@ export async function planCut({ ask, project, index, text, history = [], previou
294
347
  // Said plainly when a promise can't be kept, so the card never pitches what won't be made
295
348
  const steps = (answer.value.steps ?? []).map((s) => clean(s).slice(0, 240)).filter(Boolean)
296
349
  if (promised.coldOpen && !settings.coldOpen) steps.push("No cold open: the footage has no clean 3-second stretch in its middle to open on.")
297
- return { say: clean(answer.value.say).slice(0, 900), steps: steps.slice(0, 11), settings, source: answer.source, ...(answer.reason ? { reason: answer.reason } : {}) }
350
+ // The genre decides what the plan may reach for; the person's asking outranks it
351
+ const book = genre ? PLAYBOOKS[genre] : null
352
+ const sceneList = book && !book.scenes && !visualsIn(text) ? [] : scenes
353
+ if (genre) {
354
+ const songs = project.assets.filter((a) => a.kind === "audio" && !/kriya-(?:music|sfx)-/.test(a.path ?? ""))
355
+ const wanted = songs.find((a) => a.id === answer.value.settings?.song) ?? (/\b(?:my|this|the) (?:song|track|audio file)\b/i.test(text) || genre === "montage" ? songs[0] : null)
356
+ if (wanted && person.music !== "none") {
357
+ settings.song = wanted.id
358
+ delete settings.music
359
+ } else delete settings.song
360
+ if (genre === "montage" && settings.song && project.assets.some((a) => a.kind === "video")) settings.montage = true
361
+ // Two or more cameras of a conversation: the switcher decides who's on screen
362
+ const cameras = project.assets.filter((a) => a.kind === "video")
363
+ if (genre === "podcast" && cameras.length >= 2 && take) settings.multicam = { master: take.id, angles: cameras.slice(0, 6).map((a, speaker) => ({ asset: a.id, speaker })) }
364
+ if (Object.hasOwn(ACCENTS, answer.value.settings?.accent ?? "")) settings.captionStyle = { accent: ACCENTS[answer.value.settings.accent] }
365
+ delete settings.accent
366
+ }
367
+ // Licensed pictures and cited definitions, only with their switch on and a search to ask
368
+ if (lookups && take && !picturesRefused(text)) {
369
+ const found = await planLookups({ ask, index, asset: take.id, text, scenes: sceneList, cuts, search: lookups.search, define: lookups.define, wantPictures: !book || book.scenes || genre === "documentary", wantTerms: true, signal })
370
+ lookups.keep(found)
371
+ if (found.pictures.length) {
372
+ settings.pictures = found.pictures
373
+ steps.push(`Show ${found.pictures.length} real picture${found.pictures.length === 1 ? "" : "s"} of what's named, from openly licensed sources, credited. You can swap or remove each below; nothing downloads until you approve.`)
374
+ }
375
+ if (found.terms.length) {
376
+ settings.terms = found.terms
377
+ steps.push(`Define ${found.terms.map((t) => `"${t.term}"`).join(", ")} on screen, quoted from ${[...new Set(found.terms.map((t) => t.source))].join(", ")}.`)
378
+ }
379
+ }
380
+ if (sceneList.length) {
381
+ settings.scenes = sceneList
382
+ // A sound as each scene arrives, unless the person said no sound effects
383
+ settings.sceneSound = person.cutSound !== "none"
384
+ steps.push(`Cut away to ${sceneList.length} animated scene${sceneList.length === 1 ? "" : "s"} while the voice keeps playing. You can swap or remove each one below.`)
385
+ } else if (planned && planned.source !== "person") {
386
+ const why = planned.dropped[0]?.reason
387
+ if (visualsIn(text)) steps.push(`No animated scene this time${why ? `: ${why}` : ": nothing in the speech can be drawn from the speaker's own words"}.`)
388
+ delete settings.scenes
389
+ }
390
+ // Transitions: the person's words outrank the Director's choice; a revision that says nothing keeps what was approved
391
+ const transitionSaid = motion ? [...history.filter((h) => h.who === "you").map((h) => h.text), text].map(transitionIn).reduce((all, one) => ({ ...all, ...one }), {}) : {}
392
+ const kept_ = motion && previous?.settings?.transition && Object.hasOwn(TRANSITIONS, previous.settings.transition) ? { transition: previous.settings.transition, transitionAll: !!previous.settings.transitionAll } : {}
393
+ const chosen = { ...kept_, ...(Object.hasOwn(TRANSITIONS, settings.transition ?? "") ? { transition: settings.transition } : {}), ...transitionSaid }
394
+ delete settings.transition
395
+ delete settings.transitionAll
396
+ if (motion && Object.hasOwn(TRANSITIONS, chosen.transition ?? "")) {
397
+ settings.transition = chosen.transition
398
+ if (chosen.transitionAll) settings.transitionAll = true
399
+ }
400
+ // Motion graphics from the kit, after the scenes so none is planned under one; each is checked by code
401
+ delete settings.graphics
402
+ if (motion && take) {
403
+ const planned = await planGraphics({ ask, index, asset: take.id, text, history, previous, cuts, scenes: sceneList, signal })
404
+ if (planned.graphics.length) {
405
+ settings.graphics = planned.graphics
406
+ steps.unshift(`Add ${planned.graphics.length} motion graphic${planned.graphics.length === 1 ? "" : "s"}: ${planned.graphics.map(graphicLine).join("; ")}. You can restyle or remove each below.`.slice(0, 240))
407
+ } else if (graphicsIn(text) === "on") steps.push(`No motion graphics this time${planned.dropped[0] ? `: ${planned.dropped[0].reason}` : ": the words for one must be the speaker's or yours, so say what a title or name strap should read"}.`.slice(0, 240))
408
+ }
409
+ return { say: clean(answer.value.say).slice(0, 900), steps: steps.slice(0, 13), settings, source: answer.source, ...(genre ? { genreLabel: PLAYBOOKS[genre].label } : {}), ...(answer.reason ? { reason: answer.reason } : {}) }
298
410
  }
@@ -0,0 +1,131 @@
1
+ // The Director's playbooks (DIRECTOR_PLAYBOOKS.md, EDD-56): how each kind of video is edited,
2
+ // as data a person reviewed. No command, path, URL, model or price. The Director names the
3
+ // genre from the transcript; code fills what the plan left open; the person's words outrank both.
4
+ // Numbers are starting points to tune by KriyaEditBench, not facts about any editor.
5
+
6
+ const FLICKS = 705_600_000
7
+
8
+ export const PLAYBOOKS = {
9
+ explainer: {
10
+ label: "Science or explainer",
11
+ rules: "Show what's hard to picture while the voice continues. Let a hard idea land before the next one. Keep the speaker for the hook, for anything personal and for the close.",
12
+ settings: { captions: "clean", grade: "cinematic", music: "calm", cleanVoice: true },
13
+ punchesPerMinute: 2,
14
+ soundEvery: 4,
15
+ scenes: true,
16
+ },
17
+ documentary: {
18
+ label: "Documentary or place story",
19
+ rules: "Slow, with room to look. What's named should be seen. Ambience and silence before score; few cuts, each for a reason.",
20
+ settings: { captions: "story", grade: "warm", music: "calm", cleanVoice: true },
21
+ punchesPerMinute: 0,
22
+ soundEvery: 0,
23
+ scenes: true,
24
+ },
25
+ podcast: {
26
+ label: "Podcast or interview",
27
+ rules: "Show who is talking, and sometimes who is listening. Follow the talk; don't cut on a timer. Let pauses and reactions breathe. Voice only, almost nothing else.",
28
+ settings: { captions: "minimal", grade: "natural", music: "none", cleanVoice: true },
29
+ punchesPerMinute: 1,
30
+ soundEvery: 0,
31
+ scenes: false,
32
+ },
33
+ tutorial: {
34
+ label: "Tutorial",
35
+ rules: "Tight on the action, no waiting. Show the step as it's said. Quiet sound; the viewer is following along.",
36
+ settings: { captions: "clean", grade: "natural", music: "none", cleanVoice: true },
37
+ punchesPerMinute: 2,
38
+ soundEvery: 0,
39
+ scenes: true,
40
+ },
41
+ opinion: {
42
+ label: "Opinion or talking head",
43
+ rules: "Brisk, with one real breath. Hook first. Punch in on the point, not on a timer. Numbers and names on screen. Keep every emotional beat on the face.",
44
+ settings: { captions: "karaoke", grade: "vivid", music: "none", cleanVoice: true },
45
+ punchesPerMinute: 4,
46
+ soundEvery: 3,
47
+ scenes: false,
48
+ },
49
+ promo: {
50
+ label: "Promo or ad",
51
+ rules: "One message. The offer early, an end on what to do next. Fast, led by the beat.",
52
+ settings: { captions: "pop", grade: "vivid", music: "upbeat", cleanVoice: true },
53
+ punchesPerMinute: 5,
54
+ soundEvery: 2,
55
+ scenes: true,
56
+ },
57
+ vlog: {
58
+ label: "Vlog or personal story",
59
+ rules: "Feeling first. No diagrams. Varied pace, the person's own B-roll, and quiet where the moment is quiet.",
60
+ settings: { captions: "clean", grade: "warm", music: "warm", cleanVoice: true },
61
+ punchesPerMinute: 1,
62
+ soundEvery: 0,
63
+ scenes: false,
64
+ },
65
+ montage: {
66
+ label: "Music-led montage",
67
+ rules: "The song leads. Cut on its beats, leave words out unless they matter.",
68
+ settings: { captions: "none", grade: "vivid", music: "upbeat", cleanVoice: false },
69
+ punchesPerMinute: 0,
70
+ soundEvery: 0,
71
+ scenes: false,
72
+ },
73
+ }
74
+
75
+ export const GENRES = Object.keys(PLAYBOOKS)
76
+
77
+ /**
78
+ * What the footage has and lacks, measured by code, so the Director plans from facts.
79
+ * @returns {string[]} plain lines; nothing from the media but counts
80
+ */
81
+ export function footageFacts(project, index, take) {
82
+ const lines = []
83
+ const videos = project.assets.filter((a) => a.kind === "video")
84
+ const songs = project.assets.filter((a) => a.kind === "audio" && !/kriya-(?:music|sfx)-/.test(a.path ?? ""))
85
+ const words = (index.words ?? []).filter((w) => w.asset === take?.id)
86
+ lines.push(`${videos.length} video file${videos.length === 1 ? "" : "s"}${videos.length > 1 ? ": other clips can be B-roll, or angles if they were shot together" : ": no other footage to cut to"}.`)
87
+ lines.push(songs.length ? `Sound files of the person's own in the bin, by id: ${songs.map((a) => a.id).join(", ")}; settings.song uses one.` : "No music of the person's own.")
88
+ if (words.length > 1) {
89
+ const minutes = (words.at(-1).end - words[0].start) / FLICKS / 60
90
+ const numbers = words.filter((w) => /\d/.test(w.text)).length
91
+ const pauses = words.slice(1).filter((w, i) => w.start - words[i].end > FLICKS).length
92
+ lines.push(`${Math.round(minutes * 60)} seconds of speech, about ${Math.round(words.length / Math.max(minutes, 0.01))} words a minute, ${pauses} pause${pauses === 1 ? "" : "s"} over a second, ${numbers} spoken number${numbers === 1 ? "" : "s"}.`)
93
+ }
94
+ const faces = new Set((index.faces ?? []).filter((f) => f.asset === take?.id).map((f) => f.identity))
95
+ if (faces.size) lines.push(`${faces.size} face${faces.size === 1 ? "" : "s"} seen in the take.`)
96
+ return lines
97
+ }
98
+
99
+ /** The plan slot's extra lines. */
100
+ export function playbookPrompt(facts) {
101
+ return [
102
+ "Think like a top editor. Emotion and story come before rhythm; every cut, zoom and sound needs a reason in what is being said, and over-cutting is a fault. First work out from the transcript what kind of video this is, then what it has and what it lacks.",
103
+ `What the footage has, measured: ${facts.join(" ")}`,
104
+ `Set \`genre\` to one of these, and plan by its rules:\n${GENRES.map((id) => `- ${id} (${PLAYBOOKS[id].label}): ${PLAYBOOKS[id].rules}`).join("\n")}`,
105
+ "Choose the caption look for this film in settings.captions (clean, karaoke, boxed, pop, story, minimal) and its highlight colour in settings.accent, once, for the whole film.",
106
+ "Each of your `steps` says what you'll do and why, pointing at what the speaker says. Don't apply an effect because you can.",
107
+ ]
108
+ }
109
+
110
+ const OPEN = { captions: "none", grade: "natural", music: "none", cutSound: "none" }
111
+ const isOpen = (settings, key) => settings[key] === undefined || settings[key] === null
112
+
113
+ /**
114
+ * Fills what the plan left open from the genre's playbook; what's set stays. The caller applies
115
+ * the person's words after this, so they outrank it.
116
+ * @param {object} settings the plan's settings
117
+ * @param {string} genre
118
+ * @param {number} seconds speech in the take
119
+ * @returns {object} new settings
120
+ */
121
+ export function applyPlaybook(settings, genre, seconds = 0) {
122
+ const book = PLAYBOOKS[genre]
123
+ if (!book) return settings
124
+ const out = { ...settings }
125
+ for (const [key, value] of Object.entries(book.settings)) if (isOpen(out, key)) out[key] = value
126
+ if (isOpen(out, "punches") && book.punchesPerMinute >= 0) out.punches = Math.min(8, Math.round((seconds / 60) * book.punchesPerMinute))
127
+ // Restraint: a sound on some cuts, not all. A genre with none adds none, and the plan's own stays
128
+ if (isOpen(out, "cutSound") && book.soundEvery > 0) out.cutSound = "whoosh"
129
+ if (out.cutSound && out.cutSound !== OPEN.cutSound && book.soundEvery > 1) out.soundEvery = book.soundEvery
130
+ return out
131
+ }
@@ -5,7 +5,10 @@
5
5
 
6
6
  import { apply } from "../core/ops.js"
7
7
  import { solve } from "../core/solver.js"
8
+ import { cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_KINDS, GRAPHIC_VERSION, graphicLength, SUBTITLE_MAX, TEXT_MAX } from "../engine/graphics.js"
8
9
  import { paperEdit, shotDigest } from "../index/views.js"
10
+ import { TRANSITION_LABELS, transitionLength, TRANSITIONS } from "../core/transitions.js"
11
+ import { brandIn, graphicProblems } from "./graphics.js"
9
12
 
10
13
  const FLICKS = 705_600_000
11
14
 
@@ -97,6 +100,36 @@ export const OPS_SCHEMA = {
97
100
  additionalProperties: false,
98
101
  }
99
102
 
103
+ // With editing.motion on, chat can also put a kit graphic on screen (MOTION_GRAPHICS.md). Off,
104
+ // the console's schema is the same object as before
105
+ const ITEMS = OPS_SCHEMA.properties.ops.items
106
+ const MOTION_SCHEMA = { ...OPS_SCHEMA, properties: { ...OPS_SCHEMA.properties, ops: { ...OPS_SCHEMA.properties.ops, items: { ...ITEMS, properties: { ...ITEMS.properties, op: { type: "string", enum: [...CONSOLE_OPS, "add_graphic", "transition"] }, kind: { type: "string", enum: [...Object.keys(GRAPHIC_KINDS), ...Object.keys(TRANSITIONS)] }, style: { type: "string", maxLength: 16 }, subtitle: { type: "string", maxLength: SUBTITLE_MAX } } } } } }
107
+ export const consoleSchema = (motion) => (motion ? MOTION_SCHEMA : OPS_SCHEMA)
108
+
109
+ /**
110
+ * `add_graphic` as the engine's own operation: the graphic cleaned, its words held to the
111
+ * speaker's and the person's, its length set by code. Every other operation passes through.
112
+ * @param {object[]} ops
113
+ * @param {{ index: object, person: string }} context person: the person's own messages
114
+ * @returns {{ ops: object[], problems: string[] }}
115
+ */
116
+ export function expandGraphics(ops, { index, person }) {
117
+ const problems = []
118
+ const spoken = (index.words ?? []).map((w) => w.text).join(" ")
119
+ const out = ops.map((op, i) => {
120
+ // A transition's length is code's: the default, or what was asked, inside the allowed range
121
+ if (op?.op === "transition") return Object.hasOwn(TRANSITIONS, op.kind ?? "") ? { op: "transition", clip: op.clip, kind: op.kind, duration: transitionLength(op.duration) } : (problems.push(`operation ${i + 1}: a transition's kind is one of ${Object.keys(TRANSITIONS).join(", ")}`), op)
122
+ if (op?.op !== "add_graphic") return op
123
+ const graphic = cleanGraphic({ ...op, ...brandIn(person), at: undefined })
124
+ if (!graphic) return problems.push(`operation ${i + 1}: that isn't a graphic the kit draws (a "stat" is digits; text is up to ${TEXT_MAX} characters)`), op
125
+ if (op.at === undefined) return problems.push(`operation ${i + 1}: add_graphic needs \`at\`, a word anchor or a clip edge`), op
126
+ const said = graphicProblems(graphic, { spoken, near: spoken, person })
127
+ if (said.length) return problems.push(`operation ${i + 1}: ${said[0]}; a graphic's words are the speaker's or the person's own`), op
128
+ return { op: "add_motion", block: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: graphic, at: op.at, duration: Number.isInteger(op.duration) ? Math.min(op.duration, 8 * FLICKS) : graphicLength(graphic) }
129
+ })
130
+ return { ops: out, problems }
131
+ }
132
+
100
133
  /**
101
134
  * What models often send that means nothing: every optional field present as null,
102
135
  * and empty lists or no `ops` at all. Tidied before the schema, never invented.
@@ -166,8 +199,13 @@ export function describe(op, index) {
166
199
  return `Changed caption ${op.caption} to "${op.text}"`
167
200
  case "caption_emphasis":
168
201
  return `Emphasised "${words.get(op.word)?.text ?? op.word}" in caption ${op.caption}`
202
+ case "transition":
203
+ return `Added a ${(TRANSITION_LABELS[op.kind] ?? op.kind).toLowerCase()} transition into ${op.clip}`
169
204
  case "add_title":
170
205
  return `Added the title "${op.text}" at ${place(op.at)}`
206
+ case "add_motion":
207
+ if (op.block === GRAPHIC_BLOCK) return `Added ${/^[aeiou]/i.test(GRAPHIC_KINDS[op.variables?.kind]?.label ?? "g") ? "an" : "a"} ${(GRAPHIC_KINDS[op.variables?.kind]?.label ?? "graphic").toLowerCase()} "${op.variables?.text ?? ""}"${op.variables?.subtitle ? `, "${op.variables.subtitle}"` : ""} at ${place(op.at)}`
208
+ return op.block === "scene" ? `Added an animated ${op.variables?.kind ?? ""} scene, "${op.variables?.text ?? ""}", at ${place(op.at)}` : op.op
171
209
  case "grade":
172
210
  return `Graded ${op.clip}${op.saturation !== undefined ? `, saturation ${op.saturation}` : ""}${op.gain !== undefined ? `, contrast ${op.gain}` : ""}${op.gamma !== undefined ? `, gamma ${op.gamma}` : ""}${op.lift !== undefined ? `, lift ${op.lift}` : ""}`
173
211
  case "speed_ramp":
@@ -335,7 +373,7 @@ export function timesView(text, project, index) {
335
373
  * @param {{ ask: ReturnType<import("./ask.js").createAsk>, project: object, index: object, text: string, selection?: object, signal?: AbortSignal }} input
336
374
  * @returns {Promise<{ ops: object[], changes: string[], project: object | null, source: string, reason?: string, calls: number }>}
337
375
  */
338
- export async function revise({ ask, project, index, text, selection, history = [], signal }) {
376
+ export async function revise({ ask, project, index, text, selection, history = [], motion = false, signal }) {
339
377
  const assets = project.assets.map((a) => a.id)
340
378
  // A marked range reads like a typed one: code says what it points at
341
379
  const marked = Number.isInteger(selection?.from) && Number.isInteger(selection?.to) ? ` from ${clock(selection.from)} to ${clock(selection.to)}` : ""
@@ -349,6 +387,7 @@ export async function revise({ ask, project, index, text, selection, history = [
349
387
  `${earlier}The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
350
388
  "Answer with JSON only. Put in `ops` the operations that do exactly what they ask, and nothing else.",
351
389
  "Times like 0:05 are on the cut's timeline; the lines above say which clip, words and captions each time points at. Use those ids, never compute flicks yourself. To take out a stretch the person names by time, use the exact remove_range given for it above, unchanged; for a stretch named by words, remove_range from its first word (edge start) to its last word (edge end). To change what a caption says, caption_edit with its caption id; to remove a caption, ripple_delete its caption id; to caption words, caption_style with their word ids and a look; to put a title on screen, add_title with text and a word anchor; to take background noise out of the voice, clean_voice on each picture clip; to warm or cool the picture, grade with temperature (lower is warmer, 6500 neutral), vibrance or vignette; for a speed ramp or slow motion, speed_ramp on the clip with from and to (source flicks from the lines above, or word anchors) and peak {n, d} (2/1 speeds up and back, 1/2 is eased slow motion); for a constant speed, speed; to lay other footage over a moment, place_broll with a video asset id from the project, at a word anchor or clip edge, and duration in flicks.",
390
+ ...(motion ? [`To put a motion graphic on screen, add_graphic with kind (${Object.entries(GRAPHIC_KINDS).map(([id, kind]) => `${id}: ${kind.label.toLowerCase()}`).join("; ")}), text, subtitle where the kind has a second line, and at (a word anchor). Its words must be the speaker's or the person's own from their request, never yours; a stat's text is digits the speaker says.`, `To dress a cut, transition with the clip the picture arrives in (never the first clip) and kind (${Object.keys(TRANSITIONS).join(", ")}); the cut itself doesn't move.`] : []),
352
391
  "Put one plain sentence in `say`: what you changed, or the answer if they asked a question.",
353
392
  "If they ask to fix or correct the transcript (names, misheard words), put each wrong word in `corrections` as {word: its id, text: the right word}, only where you are confident from the context.",
354
393
  "If they ask for the whole video to be made, directed, edited or improved (not one part of it), set `direct` to an object (with `seconds` and a caption look if they say so) and leave `ops` empty: the Director makes the whole cut.",
@@ -356,13 +395,18 @@ export async function revise({ ask, project, index, text, selection, history = [
356
395
  ].join("\n")
357
396
  const words = new Map((index.words ?? []).map((w) => [w.id, w]))
358
397
  // Operations must apply; a correction on an unknown word is only dropped, never worth a second call
359
- const check = ({ ops }) => {
360
- if (!ops.length) return []
398
+ const person = [...history.filter((h) => h.who === "you").map((h) => h.text), text].join("\n")
399
+ const expand = (ops) => (motion ? expandGraphics(ops, { index, person }) : { ops, problems: [] })
400
+ const check = ({ ops: asked }) => {
401
+ if (!asked.length) return []
402
+ const { ops, problems } = expand(asked)
403
+ if (problems.length) return problems
361
404
  const tried = apply(project, ops, { index, author: "agent" })
362
405
  return tried.applied ? [] : tried.diagnostics.map((d) => `operation ${d.op + 1}: ${d.message}`)
363
406
  }
364
- const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 2000, check, clean: tidyConsole, fallback: () => ({ ops: [] }), signal, priority: 0 })
365
- const ops = answer.value.ops
407
+ const answer = await ask({ task: "console", tier: "budget", schema: consoleSchema(motion), view, request, maxOutput: 2000, check, clean: tidyConsole, fallback: () => ({ ops: [] }), signal, priority: 0 })
408
+ const expanded = expand(answer.value.ops)
409
+ const ops = expanded.problems.length ? [] : expanded.ops
366
410
  const tried = ops.length ? apply(project, ops, { index, author: "agent" }) : null
367
411
  // A correction that changes nothing, or isn't a known word, isn't offered
368
412
  const corrections = (answer.value.corrections ?? []).map((c) => ({ word: c.word, text: cleanWord(c.text) })).filter((c) => words.has(c.word) && c.text && c.text !== words.get(c.word).text)
@@ -21,6 +21,10 @@ export const LOOKS = {
21
21
  clean: { font: "sans", weight: 800, size: 0.042, color: "#ffffff", accent: "#ffd23f", box: null, stroke: "#000000", highlight: false },
22
22
  karaoke: { font: "sans", weight: 800, size: 0.046, color: "#ffffff", accent: "#ffd23f", box: { color: "#0a0a0a", alpha: 0.7 }, stroke: null, highlight: true },
23
23
  boxed: { font: "sans", weight: 700, size: 0.04, color: "#f2eadf", accent: "#ffb347", box: { color: "#13292b", alpha: 0.92 }, stroke: null, highlight: false },
24
+ // The playbooks' looks (DP3): bold and word by word for a promo, quieter for a story, plain for a talk
25
+ pop: { font: "rounded", weight: 800, size: 0.05, color: "#ffffff", accent: "#ffe14d", box: null, stroke: "#000000", highlight: true },
26
+ story: { font: "serif", weight: 700, size: 0.036, color: "#fff8ec", accent: "#ffd9a0", box: { color: "#14110d", alpha: 0.78 }, stroke: null, highlight: false },
27
+ minimal: { font: "sans", weight: 700, size: 0.034, color: "#ffffff", accent: "#ffffff", box: { color: "#000000", alpha: 0.72 }, stroke: null, highlight: false },
24
28
  }
25
29
 
26
30
  const HEX = /^#[0-9a-f]{6}$/i
@@ -34,6 +38,7 @@ export function lookOf(id, style = {}) {
34
38
  if (style.font in FONTS) look.font = style.font
35
39
  if (Number.isFinite(style.size) && style.size >= 0.02 && style.size <= 0.1) look.size = style.size
36
40
  if (HEX.test(style.box ?? "") && look.box) look.box = { ...look.box, color: style.box }
41
+ if (style.stroke === "none") look.stroke = null
37
42
  // The repair ladder's contrast fix (QUALITY_GATES §4 rung 0): a dark scrim behind the words
38
43
  if (style.scrim === true) look.box = look.box ? { ...look.box, alpha: Math.max(look.box.alpha, 0.85) } : { color: "#000000", alpha: 0.8 }
39
44
  return look
@@ -99,6 +104,33 @@ export function scriptOf(text) {
99
104
  return "other"
100
105
  }
101
106
 
107
+ /**
108
+ * Pages a reader keeps up with: a burst of fast speech joins its neighbour, so it stays on screen
109
+ * longer, rather than flash by (found on real footage). A page that's readable is left alone.
110
+ * @param {string[][]} list pages of word ids, from pages()
111
+ * @param {{ id: string, text: string, start: number, end: number }[]} words
112
+ */
113
+ export function readablePages(list, words) {
114
+ const byId = new Map(words.map((w) => [w.id, w]))
115
+ const tooFast = (ids) => {
116
+ const script = scriptOf(ids.map((id) => byId.get(id)?.text ?? "").join(" "))
117
+ const seconds = (byId.get(ids.at(-1)).end - byId.get(ids[0]).start) / FLICKS
118
+ return seconds < 1.2 && ids.length / Math.max(seconds, 1e-3) > READING_LIMITS[script]
119
+ }
120
+ const out = list.map((p) => [...p])
121
+ for (let i = 0; i < out.length && out.length > 1; i++) {
122
+ if (!tooFast(out[i])) continue
123
+ // With the smaller neighbour, so the page stays short; never over ten words, and the gate says so if it's still fast
124
+ const before = i > 0 ? out[i - 1].length : Infinity
125
+ const after = i + 1 < out.length ? out[i + 1].length : Infinity
126
+ const into = before < after ? i - 1 : i
127
+ if (Math.min(before, after) + out[i].length > 10) continue
128
+ out.splice(into, 2, [...out[into], ...out[into + 1]])
129
+ i = into - 1
130
+ }
131
+ return out
132
+ }
133
+
102
134
  /* ─────────────────────────────── the composition ─────────────────────────────── */
103
135
 
104
136
  const ENTRANCE = { damping: 0.7, frequency: 14, ms: 320 }