@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,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
+ }
@@ -168,6 +168,8 @@ export function describe(op, index) {
168
168
  return `Emphasised "${words.get(op.word)?.text ?? op.word}" in caption ${op.caption}`
169
169
  case "add_title":
170
170
  return `Added the title "${op.text}" at ${place(op.at)}`
171
+ case "add_motion":
172
+ return op.block === "scene" ? `Added an animated ${op.variables?.kind ?? ""} scene, "${op.variables?.text ?? ""}", at ${place(op.at)}` : op.op
171
173
  case "grade":
172
174
  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
175
  case "speed_ramp":
@@ -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 }
@@ -0,0 +1,64 @@
1
+ // Licensed media the person approved on the Plan Card (EDD-52): downloaded by the Host, only over
2
+ // HTTPS, only from the hosts the server's search reads, with no redirects and a size limit. A still
3
+ // becomes a short clip with a slow move, so it goes through the same render as any B-roll.
4
+
5
+ import { createWriteStream, renameSync, rmSync } from "node:fs"
6
+ import { Readable } from "node:stream"
7
+ import { pipeline } from "node:stream/promises"
8
+
9
+ import { EngineFailure } from "./tool.js"
10
+
11
+ export const MEDIA_HOSTS = ["upload.wikimedia.org", "thumb.wikimedia.org", "images-assets.nasa.gov", "live.staticflickr.com"]
12
+ export const MEDIA_TYPES = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "video/webm": ".webm", "video/mp4": ".mp4", "video/ogg": ".ogv", "application/ogg": ".ogv" }
13
+ const MAX_BYTES = 100 * 1024 * 1024
14
+ const TIMEOUT_MS = 120_000
15
+
16
+ export function allowedMediaUrl(url) {
17
+ try {
18
+ const parsed = new URL(String(url))
19
+ return parsed.protocol === "https:" && !parsed.username && !parsed.password && !parsed.port && MEDIA_HOSTS.includes(parsed.hostname)
20
+ } catch {
21
+ return false
22
+ }
23
+ }
24
+
25
+ /**
26
+ * @param {string} url
27
+ * @param {string} base the file's path without its extension; the type the server states picks it
28
+ * @returns {Promise<{ file: string, type: string }>}
29
+ */
30
+ export async function downloadMedia(url, base, { signal, maxBytes = MAX_BYTES, get = fetch } = {}) {
31
+ if (!allowedMediaUrl(url)) throw new EngineFailure("input", "bad_media_url", "That picture isn't from a source Kriya may download from.")
32
+ const limit = AbortSignal.timeout(TIMEOUT_MS)
33
+ const response = await get(url, { redirect: "error", headers: { "user-agent": "KriyaEditingStudio/1.0 (https://github.com/zuko14/kriya-harness)" }, signal: signal ? AbortSignal.any([signal, limit]) : limit })
34
+ if (!response.ok) throw new EngineFailure("environment", "media_download", `The source answered ${response.status}.`)
35
+ const type = String(response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase()
36
+ const extension = MEDIA_TYPES[type]
37
+ if (!extension) throw new EngineFailure("input", "bad_media_type", "That file isn't a picture or video Kriya can use.")
38
+ if (Number(response.headers.get("content-length") ?? 0) > maxBytes) throw new EngineFailure("input", "media_too_big", "That file is too big.")
39
+ const file = `${base}${extension}`
40
+ const part = `${file}.${process.pid}.part`
41
+ let seen = 0
42
+ const counted = async function* (source) {
43
+ for await (const chunk of source) {
44
+ seen += chunk.length
45
+ if (seen > maxBytes) throw new EngineFailure("input", "media_too_big", "That file is too big.")
46
+ yield chunk
47
+ }
48
+ }
49
+ try {
50
+ await pipeline(Readable.fromWeb(response.body), counted, createWriteStream(part))
51
+ renameSync(part, file)
52
+ } catch (error) {
53
+ rmSync(part, { force: true })
54
+ throw error
55
+ }
56
+ return { file, type }
57
+ }
58
+
59
+ /** FFmpeg's arguments for a still as a clip: filling the frame, moving slowly in or out. No sound. */
60
+ export function stillClipArgs({ image, output, width, height, seconds, fps = 30, inward = true }) {
61
+ const frames = Math.max(1, Math.round(seconds * fps))
62
+ const zoom = inward ? `1+0.1*on/${frames}` : `1.1-0.1*on/${frames}`
63
+ return ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", image, "-vf", `scale=${width * 2}:${height * 2}:force_original_aspect_ratio=increase,crop=${width * 2}:${height * 2},zoompan=z='${zoom}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${width}x${height}:fps=${fps},format=yuv420p`, "-frames:v", String(frames), "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-an", "-y", output]
64
+ }
@@ -9,6 +9,7 @@ import { join } from "node:path"
9
9
 
10
10
  import { childEnv } from "../runtime/setup.js"
11
11
  import { confine, confinement, installOf } from "./confine.js"
12
+ import { buildScene, SCENE_VERSION } from "./scenes.js"
12
13
  import { EngineFailure, runTool } from "./tool.js"
13
14
 
14
15
  const FLICKS = 705_600_000
@@ -118,6 +119,22 @@ export const BLOCKS = {
118
119
  animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 6), scale: 0.8, opacity: 0 }, to: { y: 0, scale: 1, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
119
120
  }),
120
121
  },
122
+ // A hard term, its definition quoted with its source (EDD-57). The words are never edited
123
+ term: {
124
+ version: 1,
125
+ build: ({ variables, area, size, output }) => {
126
+ const floor = Math.ceil(output.height * 0.0205)
127
+ const quote = Math.max(floor, Math.round(size * 0.72))
128
+ const cite = Math.max(floor, Math.round(size * 0.6))
129
+ return {
130
+ css: `#a{position:absolute;left:${area.x}px;top:${area.y}px;width:${area.w}px;height:${area.h}px;display:flex;align-items:flex-end}#t{width:100%;box-sizing:border-box;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;background:#13292b;color:#f2eadf;padding:${Math.round(size * 0.4)}px ${Math.round(size * 0.55)}px;border-left:${Math.round(size * 0.18)}px solid #ffb347;border-radius:${Math.round(size * 0.2)}px}#t b,#t q,#t small{display:block;background:#13292b}#t b{font-size:${Math.round(size * 1.05)}px;font-weight:800}#t q{font-size:${quote}px;line-height:1.2;margin:${Math.round(size * 0.15)}px 0;quotes:'“' '”'}#t small{font-size:${cite}px;color:#ffb347}`,
131
+ body: `<div id="a"><div id="t"><b data-text>${escapeText(textVar(variables, "text", 60))}</b><q data-text>${escapeText(textVar(variables, "quote", 120))}</q><small data-text>${escapeText(textVar(variables, "source", 40))}</small></div></div>`,
132
+ animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 2), opacity: 0 }, to: { y: 0, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
133
+ }
134
+ },
135
+ },
136
+ // An explainer scene (VISUAL_SCENES.md): an opaque cutaway; `placement` is its content box
137
+ scene: { version: SCENE_VERSION, build: (parts) => buildScene(parts, springKeyframes) },
121
138
  }
122
139
 
123
140
  /** A block tile's composition. An unknown block or version is refused, never drawn as something else. */
@@ -129,7 +146,7 @@ export function blockComposition(node, { output, canvas }) {
129
146
  const box = node.placement ?? { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * 0.4), w: Math.round(canvas.width * 0.8), h: Math.round(canvas.height * 0.12) }
130
147
  const area = { x: Math.round(box.x * sx), y: Math.round(box.y * sy), w: Math.round(box.w * sx), h: Math.round(box.h * sy) }
131
148
  const size = Math.round(output.height * 0.03)
132
- return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size }) })
149
+ return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size, output, duration: node.duration }) })
133
150
  }
134
151
 
135
152
  /* ─────────────────────────────── model-written code ─────────────────────────────── */
@@ -293,7 +310,7 @@ function readBoxes(times) {
293
310
  const r = el.getBoundingClientRect()
294
311
  const style = getComputedStyle(el)
295
312
  const colours = new Set([style.color, ...[...el.querySelectorAll("span")].map((span) => getComputedStyle(span).color)])
296
- return { x: r.x, y: r.y, w: r.width, h: r.height, text: el.textContent, size: parseFloat(style.fontSize), colours: [...colours], plate: style.backgroundColor, clipped: el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1 }
313
+ return { x: r.x, y: r.y, w: r.width, h: r.height, text: el.textContent, size: parseFloat(style.fontSize), colours: [...colours], plate: style.backgroundColor, stroke: style.webkitTextStrokeColor, strokeWidth: parseFloat(style.webkitTextStrokeWidth) || 0, clipped: el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1 }
297
314
  })
298
315
  })
299
316
  }