@kriya-ai/harness 0.2.3 → 0.2.4

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.
@@ -0,0 +1,335 @@
1
+ // Visual beats (VISUAL_SCENES.md, EDD-51): which moments of the speech become an explainer
2
+ // scene. One model slot proposes them as typed JSON; code decides everything that can be
3
+ // decided: the words must have been said, the numbers must have been said here, and each
4
+ // scene spans whole sentences of a sensible length. With no model, code's own patterns
5
+ // find what they can, and only what they are sure of.
6
+
7
+ import { cleanScene, FLOW_MODES, SCENE_KINDS, SCENE_THEMES } from "../engine/scenes.js"
8
+ import { phraseView } from "../index/views.js"
9
+
10
+ const FLICKS = 705_600_000
11
+ const MIN_SCENE = 2.5 * FLICKS
12
+ const MAX_SCENE = 14 * FLICKS
13
+ const MIN_GAP = 1.5 * FLICKS
14
+ export const MAX_SHARE = 0.65 // of the cut under scenes: the speaker stays part of the film
15
+ export const MAX_SCENES = 10
16
+
17
+ /* ─────────────────────────────── what was said ─────────────────────────────── */
18
+
19
+ const SMALL = new Set("a an the of to in on at by for from with and or but so if as is are was were be been it its this that these those your you we our their his her they he she i my me not no do does did has have had will would can could should then than very more most into out up down over under about how what why when where which who".split(" "))
20
+ const tokens = (text) => String(text).normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}.,%]+/u).map((t) => t.replace(/^[.,]+|[.,]+$/g, "")).filter(Boolean)
21
+ // shortcut: English endings only; a label in another language must match the transcript's word as it stands
22
+ const stem = (word) => (word.length > 4 ? word.replace(/(?:ing|ed|es|s)$/, "") : word)
23
+ const isNumber = (token) => /^\d[\d.,]*%?$/.test(token)
24
+ const bare = (token) => token.replace(/%$/, "").replace(/,/g, "")
25
+
26
+ const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
27
+ const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
28
+
29
+ /** Numbers in spoken words, as digits: "seventy five" → "75", "two hundred" → "200", "a thousand" → "1000". */
30
+ export function numbersSaid(text) {
31
+ const out = new Set()
32
+ const words = tokens(text)
33
+ let current = null
34
+ const flush = () => {
35
+ if (current !== null) out.add(String(current))
36
+ current = null
37
+ }
38
+ for (const word of words) {
39
+ if (isNumber(word)) {
40
+ flush()
41
+ out.add(bare(word))
42
+ continue
43
+ }
44
+ const one = ONES.indexOf(word)
45
+ const ten = TENS.indexOf(word)
46
+ if (one >= 0) current = (current ?? 0) + one
47
+ else if (ten >= 2) current = (current ?? 0) + ten * 10
48
+ else if (word === "hundred" || word === "thousand") current = (current ?? 1) * (word === "hundred" ? 100 : 1000)
49
+ else if (!(word === "and" && current !== null)) flush()
50
+ }
51
+ flush()
52
+ return out
53
+ }
54
+
55
+ const UNITS = { "%": /percent|per cent|%/i, mg: /milligram|\bmg\b/i, g: /\bgrams?\b|\bg\b/i, kg: /kilo/i, km: /kilomet/i, m: /\bmet(?:er|re)s?\b/i, cm: /centimet/i, mm: /millimet/i, l: /lit(?:er|re)s?\b/i, ml: /millilit/i, s: /\bseconds?\b/i, min: /\bminutes?\b/i, h: /\bhours?\b/i, x: /\btimes\b/i, "₹": /rupee|₹/i, $: /dollar|\$/ }
56
+
57
+ /**
58
+ * Why a scene's words aren't the speaker's: every word on screen was said somewhere in the
59
+ * take, and every number was said in or next to this scene's own lines. Nothing else
60
+ * reaches the screen, so a model can't add a fact (a figure, a name) the person never said.
61
+ * @param {object} scene from cleanScene
62
+ * @param {{ all: string, near: string }} said the whole take's text, and this scene's lines with their neighbours
63
+ * @returns {string[]}
64
+ */
65
+ export function groundProblems(scene, { all, near }) {
66
+ const problems = []
67
+ const known = new Set(tokens(all).map(stem))
68
+ const numbers = numbersSaid(near)
69
+ const check = (text) => {
70
+ for (const token of tokens(text)) {
71
+ if (isNumber(token)) {
72
+ if (!numbers.has(bare(token))) problems.push(`the number "${token}" isn't said in this scene's lines`)
73
+ } else if (!SMALL.has(token) && !known.has(stem(token))) problems.push(`"${token}" isn't in the speaker's words`)
74
+ }
75
+ }
76
+ check(scene.title)
77
+ for (const item of scene.items) {
78
+ check(item.text)
79
+ if (item.value !== undefined && !numbers.has(item.value.replace(/,/g, ""))) problems.push(`the number "${item.value}" isn't said in this scene's lines`)
80
+ if (item.unit) {
81
+ const cue = UNITS[item.unit.toLowerCase()]
82
+ if (cue ? !cue.test(near) : !known.has(stem(item.unit.toLowerCase()))) problems.push(`the unit "${item.unit}" isn't said in this scene's lines`)
83
+ }
84
+ }
85
+ return problems
86
+ }
87
+
88
+ /* ─────────────────────────────── phrases ─────────────────────────────── */
89
+
90
+ const MAX_PHRASE = 8 * FLICKS
91
+ const MIN_PHRASE = 1.2 * FLICKS
92
+ const PAUSE = 0.35 * FLICKS
93
+ const CLAUSE = /^(?:so|but|because|where|which|as|then|when|while|resulting|despite|without|until|since|although)$/i
94
+
95
+ /**
96
+ * A take's phrases: what a scene can start and end on. Recognised speech has few sentence
97
+ * marks (found on a real take: one "sentence" of 29 s, another of 22 s), so a sentence is too
98
+ * coarse; a phrase ends at a sentence end, a pause or a new clause, and caps at 8 s.
99
+ * @returns {{ first: number, last: number, start: number, end: number, text: string }[]} first, last: positions in `words`
100
+ */
101
+ export function phrasesOf(index, asset) {
102
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
103
+ const ends = new Set((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => s.lastWord))
104
+ const out = []
105
+ let first = 0
106
+ const close = (last) => {
107
+ out.push({ first, last, start: words[first].start, end: words[last].end, text: words.slice(first, last + 1).map((w) => w.text).join(" ") })
108
+ first = last + 1
109
+ }
110
+ for (let i = 0; i < words.length; i++) {
111
+ const next = words[i + 1]
112
+ if (!next || ends.has(words[i].id)) {
113
+ close(i)
114
+ continue
115
+ }
116
+ const length = words[i].end - words[first].start
117
+ if (next.start - words[i].end >= PAUSE && length >= MIN_PHRASE) close(i)
118
+ else if (CLAUSE.test(tokens(next.text)[0] ?? "") && length >= MIN_PHRASE) close(i)
119
+ else if (next.end - words[first].start > MAX_PHRASE) close(i)
120
+ }
121
+ return out
122
+ }
123
+
124
+ /* ─────────────────────────────── placing ─────────────────────────────── */
125
+
126
+ const out = (word, cuts) => cuts.some((c) => (word.start + word.end) / 2 >= c.from * FLICKS && (word.start + word.end) / 2 < c.to * FLICKS)
127
+ const OPENING = 3 * FLICKS // the speaker is seen first
128
+ const NEAR = 6 * FLICKS // "said in or next to this scene's lines"
129
+
130
+ /**
131
+ * Scenes that may be made, in order: real words, forward, on phrase edges, a sensible length,
132
+ * room between them, under the share, words grounded. Each dropped one says why.
133
+ * @param {object[]} raw a model's or a browser's scenes; from and to are word ids or sentence ids
134
+ * @param {{ index: object, asset: string, cuts?: { from: number, to: number }[], limit?: number }} input cuts in seconds of the take
135
+ */
136
+ export function arrangeScenes(raw, { index, asset, cuts = [], limit = MAX_SCENES }) {
137
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
138
+ const total = words.length ? words.at(-1).end - words[0].start : 0
139
+ const phrases = phrasesOf(index, asset)
140
+ const position = new Map(words.map((w, i) => [w.id, i]))
141
+ const sentence = new Map((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => [s.id, s]))
142
+ const phraseAt = (i) => phrases.findIndex((p) => i >= p.first && i <= p.last)
143
+ const startOf = (id) => phraseAt(position.get(sentence.get(id)?.firstWord ?? id) ?? -1)
144
+ const endOf = (id) => phraseAt(position.get(sentence.get(id)?.lastWord ?? id) ?? -1)
145
+ const all = words.map((w) => w.text).join(" ")
146
+ const dropped = []
147
+ const placed = []
148
+ const spans = (Array.isArray(raw) ? raw : [])
149
+ .map(cleanScene)
150
+ .filter(Boolean)
151
+ .map((scene) => ({ scene, i: startOf(scene.from), k: endOf(scene.to) }))
152
+ .sort((a, b) => (a.i < 0 ? Infinity : a.i) - (b.i < 0 ? Infinity : b.i))
153
+ let used = 0
154
+ for (const { scene, i, k: asked } of spans) {
155
+ const drop = (reason) => dropped.push({ scene, reason })
156
+ if (i < 0 || asked < i) {
157
+ drop("its lines aren't in this take")
158
+ continue
159
+ }
160
+ let k = asked
161
+ // A short phrase takes the next one with it, so a scene is on screen long enough to read
162
+ while (k + 1 < phrases.length && phrases[k].end - phrases[i].start < MIN_SCENE) k++
163
+ const start = phrases[i].start
164
+ const end = phrases[k].end
165
+ const span = end - start
166
+ if (!words.length || start - words[0].start < OPENING) drop("the first line stays on the speaker, as the hook")
167
+ else if (span < MIN_SCENE) drop("its lines are too short to read a scene")
168
+ else if (span > MAX_SCENE) drop("its lines run too long for one scene")
169
+ else if (words.some((w) => w.start >= start && w.end <= end && out(w, cuts))) drop("it covers a stretch you asked to trim")
170
+ else if (placed.length && start - placed.at(-1).end < MIN_GAP) drop("it comes too soon after the last scene")
171
+ else if (placed.length >= limit) drop("there are already enough scenes")
172
+ else if (total && used + span > total * MAX_SHARE) drop("the speaker would hardly be seen")
173
+ else {
174
+ const near = words.filter((w) => w.end >= start - NEAR && w.start <= end + NEAR).map((w) => w.text).join(" ")
175
+ const wrong = groundProblems(scene, { all, near })
176
+ if (wrong.length) drop(wrong[0])
177
+ else {
178
+ used += span
179
+ placed.push({ start, end, scene: { ...scene, from: words[phrases[i].first].id, to: words[phrases[k].last].id } })
180
+ }
181
+ }
182
+ }
183
+ return { scenes: placed.map((p) => p.scene), dropped }
184
+ }
185
+
186
+ /**
187
+ * The word each label is spoken on, in order, so it lands as it's said; null where the
188
+ * label's words aren't in these words (it then comes in evenly).
189
+ * @param {object} scene
190
+ * @param {{ id: string, text: string }[]} spoken the scene's words, in order
191
+ */
192
+ export function revealWords(scene, spoken) {
193
+ let from = 0
194
+ return scene.items.map((item) => {
195
+ const wanted = new Set([...tokens(item.text), ...(item.value ? [item.value] : [])].filter((t) => !SMALL.has(t)).map(stem))
196
+ for (let i = from; i < spoken.length; i++) {
197
+ if (tokens(spoken[i].text).some((t) => wanted.has(stem(t)) || wanted.has(bare(t)))) {
198
+ from = i + 1
199
+ return spoken[i]
200
+ }
201
+ }
202
+ return null
203
+ })
204
+ }
205
+
206
+ /* ─────────────────────────────── code's own beats ─────────────────────────────── */
207
+
208
+ const LEAD = /^(?:(?:so|and|but|then|now|that|this|the|a|an|your|our|it|when|because|which|without)\s+)+/i
209
+ const HELPERS = /\s+(?:starts?|begins?|keeps?|tends?|continues?|is|are|was|were|will)(?:\s+to)?$/i
210
+ function phrase(text, words = 4) {
211
+ const cleaned = String(text).replace(/[^\p{L}\p{N}%' -]+/gu, " ").replace(/\s+/g, " ").trim().replace(LEAD, "").replace(HELPERS, "")
212
+ return cleaned.split(" ").slice(-words).join(" ").slice(0, 32).trim()
213
+ }
214
+ const CHAIN = /\s*(?:\bwhich (?:then )?(?:leads? to|causes?|makes?)\b|\bleads? to\b|\bcauses?\b|\bturns? into\b|\bresults? in\b|\band then\b|\bthen\b|→)\s*/i
215
+ const FLOW = /\b([\p{L}\p{N} '-]{3,30}?)\s+(flood|flow|mov|enter|travel|pass|go)(?:s|es|ing|ed)?\s+(?:in ?to|through|to)\s+(?:the\s+|your\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
216
+ const VERSUS = /\b([\p{L}\p{N} '-]{3,30}?)\s+(?:versus|vs\.?|compared (?:to|with)|unlike)\s+(?:the\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
217
+ const PERCENT = /\b(\d{1,3}(?:\.\d{1,2})?)\s*(?:%|percent\b|per cent\b)\s*(?:of\s+)?([\p{L}\p{N} '-]{3,40})?/iu
218
+
219
+ /**
220
+ * The beats code is sure of, from what the sentence says outright.
221
+ * shortcut: English patterns only; with no model, speech in another language gets no scene. A model reads any language.
222
+ */
223
+ export function codeBeats(index, asset) {
224
+ const out = []
225
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
226
+ for (const { first, last, text } of phrasesOf(index, asset)) {
227
+ const base = { from: words[first].id, to: words[last].id, title: "" }
228
+ const percent = PERCENT.exec(text)
229
+ const flow = FLOW.exec(text)
230
+ const versus = VERSUS.exec(text)
231
+ const chain = text.split(CHAIN).map((part) => phrase(part)).filter(Boolean)
232
+ if (percent && phrase(percent[2] ?? "")) out.push({ ...base, kind: "stat", items: [{ text: String(percent[2]).trim().split(" ").slice(0, 5).join(" ").slice(0, 32).trim(), value: percent[1], unit: "%" }] })
233
+ else if (versus && phrase(versus[1]) && phrase(versus[2])) out.push({ ...base, kind: "compare", items: [{ text: phrase(versus[1]) }, { text: String(versus[2]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
234
+ else if (flow && phrase(flow[1]) && phrase(flow[3])) out.push({ ...base, kind: "flow", mode: /flood/i.test(flow[2]) ? "floods" : /\b(?:can't|cannot|can not|blocked|stops?)\b/i.test(text) ? "blocked" : "flows", items: [{ text: phrase(flow[1]) }, { text: String(flow[3]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
235
+ else if (chain.length >= 3 && chain.length <= 5) out.push({ ...base, kind: "process", items: chain.map((text) => ({ text })) })
236
+ }
237
+ return out
238
+ }
239
+
240
+ /* ─────────────────────────────── the slot ─────────────────────────────── */
241
+
242
+ const SCENES_SCHEMA = {
243
+ type: "object",
244
+ properties: {
245
+ contentType: { type: "string", enum: ["explainer", "tutorial", "story", "opinion", "interview", "vlog", "promo", "other"] },
246
+ theme: { type: "string", enum: Object.keys(SCENE_THEMES) },
247
+ scenes: {
248
+ type: "array",
249
+ maxItems: MAX_SCENES,
250
+ items: {
251
+ type: "object",
252
+ properties: {
253
+ from: { type: "string", maxLength: 64 },
254
+ to: { type: "string", maxLength: 64 },
255
+ kind: { type: "string", enum: Object.keys(SCENE_KINDS) },
256
+ mode: { type: "string", enum: FLOW_MODES },
257
+ title: { type: "string", maxLength: 60 },
258
+ items: {
259
+ type: "array",
260
+ maxItems: 6,
261
+ items: { type: "object", properties: { text: { type: "string", maxLength: 32 }, value: { type: "string", maxLength: 12 }, unit: { type: "string", maxLength: 8 } }, required: ["text"], additionalProperties: false },
262
+ },
263
+ },
264
+ required: ["from", "to", "kind", "title", "items"],
265
+ additionalProperties: false,
266
+ },
267
+ },
268
+ },
269
+ required: ["contentType", "theme", "scenes"],
270
+ additionalProperties: false,
271
+ }
272
+
273
+ const SAID_OFF = /\b(?:no|without|skip|don't (?:want|add|use)|do not (?:want|add|use))\s+(?:any\s+|the\s+)?(?:animations?|diagrams?|visuals?|graphics|scenes|illustrations?)\b/i
274
+ const SAID_ON = /\b(?:animat\w*|diagrams?|visuals?|graphics|illustrat\w*|explainer|cutaways?)\b/i
275
+ const SAID_THEMES = [[/\bblue ?prints?\b/i, "blueprint"], [/\bchalk ?(?:board)?\b|\bblackboard\b/i, "chalk"], [/\bpaper\b|\bwhite ?board\b|\blight (?:look|theme|background)\b/i, "paper"], [/\blab\b|\bdark (?:look|theme|background)\b/i, "lab"]]
276
+ // Types of video where a diagram is usually what the viewer needs
277
+ const EXPLAINS = new Set(["explainer", "tutorial", "promo"])
278
+
279
+ /** What the person's words say about scenes: "off", "on", or null. */
280
+ export function visualsIn(text) {
281
+ return SAID_OFF.test(text) ? "off" : SAID_ON.test(text) ? "on" : null
282
+ }
283
+
284
+ const themeIn = (text) => SAID_THEMES.find(([cue]) => cue.test(text))?.[1] ?? null
285
+
286
+ /**
287
+ * The scenes for a plan. The person's words come first: "no animations" means none and no
288
+ * call. A revision that doesn't mention them keeps the ones on the card.
289
+ * @param {{ ask: Function, index: object, asset: string, text: string, history?: object[], previous?: object | null, cuts?: object[], signal?: AbortSignal }} input
290
+ * @returns {Promise<{ scenes: object[], contentType: string | null, source: string, dropped: object[] }>}
291
+ */
292
+ export async function planScenes({ ask, index, asset, text, history = [], previous = null, cuts = [], signal }) {
293
+ const said = [...history.filter((h) => h.who === "you").map((h) => h.text), text]
294
+ const verdict = said.map(visualsIn).filter(Boolean).at(-1) ?? null
295
+ if (verdict === "off") return { scenes: [], contentType: null, source: "person", dropped: [] }
296
+ const themeSaid = said.map(themeIn).filter(Boolean).at(-1) ?? null
297
+ const restyle = (scenes) => (themeSaid ? scenes.map((scene) => ({ ...scene, theme: themeSaid })) : scenes)
298
+ const kept = previous?.settings?.scenes
299
+ if (Array.isArray(kept) && !visualsIn(text)) {
300
+ const { scenes, dropped } = arrangeScenes(restyle(kept), { index, asset, cuts })
301
+ return { scenes, contentType: null, source: "kept", dropped }
302
+ }
303
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
304
+ const phrases = phrasesOf(index, asset)
305
+ const usable = words.length ? (words.at(-1).end - words[0].start) / FLICKS : 0
306
+ const limit = Math.max(1, Math.min(MAX_SCENES, Math.round(usable / 9)))
307
+ if (phrases.length < 2) return { scenes: [], contentType: null, source: "code", dropped: [] }
308
+ const hints = codeBeats(index, asset)
309
+ const kinds = Object.entries(SCENE_KINDS).map(([id, kind]) => `- ${id} (${kind.min === kind.max ? kind.min : `${kind.min} to ${kind.max}`} items): ${kind.when}`).join("\n")
310
+ const request = [
311
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 1200))}`,
312
+ "You are the Director choosing the moments where an animated explainer scene takes over the frame while the speaker's voice keeps playing, the way a top science channel cuts away from the presenter to show the idea. First decide the contentType of this video.",
313
+ verdict === "on" ? "The person asked for visuals, so propose them whatever the contentType." : "If this video isn't explaining something (a story, an opinion, a personal moment, a vlog), answer with no scenes: a diagram would get in the way.",
314
+ `Choose up to ${limit} scenes, the moments that are hard to picture from words alone: how something works, a cause and effect, a process, numbers. Keep the speaker on screen for the opening line, for anything personal or emotional and for calls to action. Let the film breathe: leave the speaker on screen between scenes.`,
315
+ `A scene covers whole phrases, about 3 to 12 seconds: \`from\` is the first word id of its first phrase, \`to\` the last word id of its last phrase. Choose lines where something can be shown, and start each scene as the idea starts. The kinds:\n${kinds}`,
316
+ "Hard rules, checked by code, which throws away a scene that breaks them: every word on the scene comes from what the speaker actually says, in the speaker's language, as short labels of 1 to 4 words; a number only if the speaker says it in those lines, as digits, in `value`, with `unit` only if they say the unit. Never add a fact, figure or name of your own, however true. List items in the order they are spoken. `title` is at most 6 of the speaker's words, or empty.",
317
+ "Use a variety of kinds, each right for its moment. Choose one theme for the whole film: lab (dark, scientific), blueprint (engineering), chalk (a lesson), paper (light).",
318
+ hints.length ? `Code found these candidates, which may help: ${JSON.stringify(hints.slice(0, 8).map((h) => ({ from: h.from, kind: h.kind })))}.` : "",
319
+ ].filter(Boolean).join("\n")
320
+ // A scene that fails is dropped below; only a whole answer with nothing usable goes back to the model
321
+ const check = ({ scenes }) => {
322
+ if (!scenes.length) return []
323
+ const tried = arrangeScenes(scenes, { index, asset, cuts, limit })
324
+ return tried.scenes.length ? [] : tried.dropped.slice(0, 3).map((d) => `scene on ${d.scene.from}: ${d.reason}`)
325
+ }
326
+ const slot = (tier) => ask({ task: "scenes", tier, schema: SCENES_SCHEMA, view: phraseView(phrases.map((p) => ({ ...p, from: words[p.first].id, to: words[p.last].id }))), request, maxOutput: 2200, check, fallback: () => ({ contentType: "other", theme: "lab", scenes: hints }), signal, priority: 0 })
327
+ let answer = await slot("balanced")
328
+ // Refused before it answered (a plan without that tier): the budget model can still do this
329
+ if (answer.source === "default" && answer.calls === 1) answer = await slot("budget")
330
+ const { value } = answer
331
+ if (answer.source !== "default" && verdict !== "on" && !EXPLAINS.has(value.contentType)) return { scenes: [], contentType: value.contentType, source: answer.source, dropped: [] }
332
+ const themed = restyle((value.scenes ?? []).map((scene) => ({ ...scene, theme: value.theme })))
333
+ const { scenes, dropped } = arrangeScenes(themed, { index, asset, cuts, limit })
334
+ return { scenes, contentType: value.contentType ?? null, source: answer.source, dropped }
335
+ }
@@ -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,17 @@
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 { picturesRefused, planLookups } from "./lookups.js"
15
+ import { applyPlaybook, footageFacts, GENRES, PLAYBOOKS, playbookPrompt } from "./playbooks.js"
12
16
  import { timesIn } from "./revise.js"
13
17
 
14
18
  const FLICKS = 705_600_000
19
+ // The highlight colours a plan may choose; hex stays in code
20
+ export const ACCENTS = { yellow: "#ffd23f", amber: "#ffb347", teal: "#4fd1c5", pink: "#ff7ab6", white: "#ffffff" }
15
21
  const ID = { type: "string", maxLength: 64 }
16
22
 
17
23
  export const PLAN_SCHEMA = {
@@ -64,6 +70,14 @@ export function briefOf(settings = {}) {
64
70
  ...(settings.titles ? { titles: true } : {}),
65
71
  ...(settings.ramps ? { ramps: true } : {}),
66
72
  ...(Array.isArray(settings.cuts) && settings.cuts.length ? { cuts: mergeCuts(settings.cuts) } : {}),
73
+ ...(typeof settings.song === "string" ? { music: settings.song } : {}),
74
+ ...(settings.montage ? { montage: true } : {}),
75
+ ...(settings.multicam ? { multicam: settings.multicam } : {}),
76
+ ...(settings.captionStyle ? { captionStyle: settings.captionStyle } : {}),
77
+ ...(settings.pictures?.length ? { pictures: settings.pictures.map(({ from, to, id }) => ({ from, to, id })) } : {}),
78
+ ...(settings.terms?.length ? { terms: settings.terms.map(({ at, id, term }) => ({ at, id, term })) } : {}),
79
+ ...(Number.isInteger(settings.soundEvery) && settings.soundEvery > 1 ? { soundEvery: settings.soundEvery } : {}),
80
+ ...(Array.isArray(settings.scenes) && settings.scenes.length ? { scenes: settings.scenes, sceneSound: settings.sceneSound !== false } : {}),
67
81
  }
68
82
  }
69
83
 
@@ -240,10 +254,12 @@ export function planProblems(settings, index) {
240
254
  }
241
255
 
242
256
  /**
243
- * @param {{ ask: Function, project: object, index: object, text: string, history?: object[], previous?: object, references?: { name: string, lines: string[] }[], choices?: object, signal?: AbortSignal }} input
257
+ * @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
258
+ * visuals, playbooks: the server's editing.visuals and editing.playbooks; off, this plan is what it always was
259
+ * lookups: { search, define, keep } with editing.mediaSearch on; null, no search word leaves the computer
244
260
  * @returns {Promise<{ say: string, steps: string[], settings: object, source: string, reason?: string }>}
245
261
  */
246
- export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, signal }) {
262
+ export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, visuals = false, playbooks = false, lookups = null, signal }) {
247
263
  const assets = project.assets.filter((a) => a.kind === "video" || a.kind === "audio").map((a) => a.id)
248
264
  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
265
  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 +270,18 @@ export async function planCut({ ask, project, index, text, history = [], previou
254
270
  const kept = Array.isArray(previous?.settings?.cuts) ? previous.settings.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to)) : []
255
271
  const cuts = take ? mergeCuts([...kept, ...[...history.filter((h) => h.who === "you").map((h) => h.text), text].flatMap((said) => trimsIn(said, length))], length / FLICKS) : []
256
272
  const at = (n) => `${Math.floor(n / 60)}:${(n % 60).toFixed(1).padStart(4, "0")}`
273
+ // The scenes first, so the pitch can speak for them; each is checked by code, and the person swaps them on the card
274
+ const planned = visuals && take ? await planScenes({ ask, index, asset: take.id, text, history, previous, cuts, signal }) : null
275
+ const scenes = planned?.scenes ?? []
276
+ const { scenes: _shownOnTheCard, ...previousSettings } = previous?.settings ?? {}
257
277
  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
278
  const request = [
259
279
  `${earlier}The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
260
280
  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
281
  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.` : "",
282
+ 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.` : "",
283
+ 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.` : "",
284
+ ...(playbooks ? playbookPrompt(footageFacts(project, index, take)) : []),
263
285
  "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
286
  "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
287
  ].filter(Boolean).join("\n")
@@ -271,10 +293,15 @@ export async function planCut({ ask, project, index, text, history = [], previou
271
293
  steps: ["Keep each line's best take and cut fillers and restarts", "Use the format, length, captions, look and music you've chosen"],
272
294
  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
295
  })
274
- const answer = await ask({ task: "plan", tier: "budget", schema: PLAN_SCHEMA, view, request, maxOutput: 2500, check, fallback, signal, priority: 0 })
296
+ // With playbooks the answer also names the genre; off, the schema is the same object as before
297
+ 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
298
+ const answer = await ask({ task: "plan", tier: "budget", schema, view, request, maxOutput: 2500, check, fallback, signal, priority: 0 })
275
299
  const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim()
276
300
  // The frame is always set, and set by what the person said, never left to a default
277
- const settings = { ...(answer.value.settings ?? {}) }
301
+ // The fallback plan keeps the person's choices: no model read the speech, so no genre was found
302
+ const genre = playbooks && answer.source !== "default" && Object.hasOwn(PLAYBOOKS, answer.value.genre ?? "") ? answer.value.genre : null
303
+ const settings = genre ? applyPlaybook(answer.value.settings ?? {}, genre, length / FLICKS) : { ...(answer.value.settings ?? {}) }
304
+ if (genre) settings.genre = genre
278
305
  settings.format = asked ?? (Object.hasOwn(FORMATS, settings.format ?? "") ? settings.format : Object.hasOwn(FORMATS, choices.format ?? "") ? choices.format : "9:16")
279
306
  // What the pitch promised and the settings left out, code fills; what the person said, code
280
307
  // sets. So the approved brief makes what the card says, not just the format
@@ -294,5 +321,45 @@ export async function planCut({ ask, project, index, text, history = [], previou
294
321
  // Said plainly when a promise can't be kept, so the card never pitches what won't be made
295
322
  const steps = (answer.value.steps ?? []).map((s) => clean(s).slice(0, 240)).filter(Boolean)
296
323
  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 } : {}) }
324
+ // The genre decides what the plan may reach for; the person's asking outranks it
325
+ const book = genre ? PLAYBOOKS[genre] : null
326
+ const sceneList = book && !book.scenes && !visualsIn(text) ? [] : scenes
327
+ if (genre) {
328
+ const songs = project.assets.filter((a) => a.kind === "audio" && !/kriya-(?:music|sfx)-/.test(a.path ?? ""))
329
+ 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)
330
+ if (wanted && person.music !== "none") {
331
+ settings.song = wanted.id
332
+ delete settings.music
333
+ } else delete settings.song
334
+ if (genre === "montage" && settings.song && project.assets.some((a) => a.kind === "video")) settings.montage = true
335
+ // Two or more cameras of a conversation: the switcher decides who's on screen
336
+ const cameras = project.assets.filter((a) => a.kind === "video")
337
+ if (genre === "podcast" && cameras.length >= 2 && take) settings.multicam = { master: take.id, angles: cameras.slice(0, 6).map((a, speaker) => ({ asset: a.id, speaker })) }
338
+ if (Object.hasOwn(ACCENTS, answer.value.settings?.accent ?? "")) settings.captionStyle = { accent: ACCENTS[answer.value.settings.accent] }
339
+ delete settings.accent
340
+ }
341
+ // Licensed pictures and cited definitions, only with their switch on and a search to ask
342
+ if (lookups && take && !picturesRefused(text)) {
343
+ 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 })
344
+ lookups.keep(found)
345
+ if (found.pictures.length) {
346
+ settings.pictures = found.pictures
347
+ 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.`)
348
+ }
349
+ if (found.terms.length) {
350
+ settings.terms = found.terms
351
+ steps.push(`Define ${found.terms.map((t) => `"${t.term}"`).join(", ")} on screen, quoted from ${[...new Set(found.terms.map((t) => t.source))].join(", ")}.`)
352
+ }
353
+ }
354
+ if (sceneList.length) {
355
+ settings.scenes = sceneList
356
+ // A sound as each scene arrives, unless the person said no sound effects
357
+ settings.sceneSound = person.cutSound !== "none"
358
+ 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.`)
359
+ } else if (planned && planned.source !== "person") {
360
+ const why = planned.dropped[0]?.reason
361
+ 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"}.`)
362
+ delete settings.scenes
363
+ }
364
+ 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
365
  }