mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b70c8c868d | ||
|
|
1e559373fc |
No files matched your search
@@ -50,11 +50,6 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
||||
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
|
||||
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
|
||||
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
|
||||
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
|
||||
COPY deploy/git deploy/git
|
||||
COPY deploy/fly/start.sh image/fly-start.sh
|
||||
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
|
||||
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
|
||||
// stop unless all the goals pass").
|
||||
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
||||
import * as cp from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
|
||||
/** where a goal's critic verdict is kept, relative to the brief */
|
||||
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
|
||||
export const TIMEOUT = 300
|
||||
/** folders that aren't the work: what the job writes about itself, and what tools keep */
|
||||
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
|
||||
|
||||
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
|
||||
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
|
||||
* as older than the work (12-01) */
|
||||
const READING = /\.(check|words|scene|floor|montage)\.json$/
|
||||
|
||||
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
|
||||
export function newest(dir: string): number | null {
|
||||
let best: number | null = null
|
||||
const stack = [dir]
|
||||
let seen = 0
|
||||
while (stack.length) {
|
||||
const d = stack.pop()!
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(d)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const name of names) {
|
||||
if (++seen > 20_000) return best
|
||||
const p = path.join(d, name)
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (st.isDirectory()) {
|
||||
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
|
||||
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
|
||||
export function verdict(dir: string, g: Contract): Verdict | null {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const goalOf = (j: Job): Contract | null => j.contract
|
||||
|
||||
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
|
||||
for (const r of goalOf(j)?.rules ?? []) {
|
||||
if (!r.run) continue
|
||||
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
|
||||
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
|
||||
const says = saysOf(goalOf(j) ?? null)
|
||||
if (!says.length) return
|
||||
let v = verdict(j.root, j.contract!)
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
|
||||
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
|
||||
// judges by hand), where this session has a critic to ask
|
||||
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
|
||||
try {
|
||||
v = await judge(j.contract!, j.root)
|
||||
} catch (e) {
|
||||
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
|
||||
return
|
||||
}
|
||||
}
|
||||
const fresh = freshOf(v)
|
||||
for (const r of says) {
|
||||
const one = v?.rules?.[r.id]
|
||||
const fix = NO_CRITIC
|
||||
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
|
||||
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
|
||||
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
|
||||
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
|
||||
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
|
||||
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
|
||||
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
|
||||
}
|
||||
|
||||
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
|
||||
export function lastVerdict(text: string): Verdict | null {
|
||||
const key = text.lastIndexOf('"rules"')
|
||||
if (key < 0) return null
|
||||
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
|
||||
let depth = 0
|
||||
let inStr = false
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const ch = text[i]
|
||||
if (inStr) {
|
||||
if (ch === "\\") i++
|
||||
else if (ch === '"') inStr = false
|
||||
continue
|
||||
}
|
||||
if (ch === '"') inStr = true
|
||||
else if (ch === "{") depth++
|
||||
else if (ch === "}" && --depth === 0) {
|
||||
try {
|
||||
const v = JSON.parse(text.slice(open, i + 1))
|
||||
if (v && typeof v.rules === "object") return v
|
||||
} catch {}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
|
||||
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
|
||||
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
|
||||
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
|
||||
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
|
||||
/** whether every rule here can be judged in this session */
|
||||
export function hasCritic(dir: string, rules: Said[]): boolean {
|
||||
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
|
||||
}
|
||||
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
||||
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
||||
/** the videos under out/, newest first */
|
||||
function made(dir: string): string[] {
|
||||
const out: { f: string; at: number }[] = []
|
||||
const walk = (d: string) => {
|
||||
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
|
||||
const f = path.join(d, e.name)
|
||||
if (e.isDirectory()) walk(f)
|
||||
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
|
||||
}
|
||||
}
|
||||
walk(path.join(dir, "out"))
|
||||
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
|
||||
}
|
||||
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
|
||||
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
|
||||
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
|
||||
const CLEF_PIECES = 12
|
||||
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
|
||||
function piecesOf(r: Said, dir: string): string[] {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
|
||||
}
|
||||
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
|
||||
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
|
||||
export const CLEF_AT_ONCE = 6
|
||||
|
||||
/** `f` on each item, at most `n` at once, the answers in the items' order */
|
||||
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of only) {
|
||||
const files = piecesOf(r, dir)
|
||||
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
|
||||
pieces.set(r.id, files)
|
||||
for (const file of files) {
|
||||
const key = [file, w?.[1], w?.[2]].join("\u001f")
|
||||
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
|
||||
at.rules.push(r)
|
||||
groups.set(key, at)
|
||||
}
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = ask === askClef && !asyncSpawn()
|
||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
||||
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
}
|
||||
const rules: Verdict["rules"] = {}
|
||||
for (const r of only) {
|
||||
const a = got.get(r.id) ?? []
|
||||
const open = a.filter((x) => !x.pass)
|
||||
rules[r.id] = !pieces.get(r.id)?.length
|
||||
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
|
||||
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||
}
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
||||
* its 10.5 minutes) */
|
||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
||||
if (!jobs.length) return []
|
||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
||||
mkdirSync(tmp, { recursive: true })
|
||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
||||
try {
|
||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
||||
return jobs.map((k, i) => {
|
||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
||||
return rows
|
||||
})
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
const args = askArgs(file, says, from, to)
|
||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
||||
if (!asyncSpawn()) {
|
||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
||||
const rows = rowsOf(String(r.stdout ?? ""))
|
||||
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
|
||||
return Promise.resolve(rows)
|
||||
}
|
||||
return new Promise((ok, no) => {
|
||||
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = rowsOf(out)
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
||||
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
|
||||
* it judged counts as changed after) */
|
||||
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
|
||||
const all = saysOf(g)
|
||||
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
||||
const read = all.filter((r) => !watched.includes(r))
|
||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
||||
const [heard, said] = await Promise.all([
|
||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
||||
])
|
||||
const rules: Verdict["rules"] = { ...heard }
|
||||
if (said !== null) {
|
||||
const v = lastVerdict(said)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
||||
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
|
||||
}
|
||||
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
|
||||
}
|
||||
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
|
||||
async function askAgent(cwd: string, p: string): Promise<string> {
|
||||
const url = criticUrl()
|
||||
if (!url) throw new Error(NO_CRITIC)
|
||||
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
|
||||
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
|
||||
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
|
||||
return j.text
|
||||
}
|
||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
||||
const file = path.join(dir, verdictPath(g))
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
||||
return out
|
||||
}
|
||||
|
||||
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
|
||||
+66
-3
@@ -9,14 +9,19 @@ import type { Contract } from "./contract.ts"
|
||||
import * as media from "./media.ts"
|
||||
import type { Faces, Levels, Word } from "./media.ts"
|
||||
import type { Scene } from "./packs/place.ts"
|
||||
import { outOf, planScene, said } from "./plan.ts"
|
||||
import type { Project } from "./project.ts"
|
||||
|
||||
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
|
||||
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
|
||||
/** a text on a frame, in render pixels: its layout box and its ink */
|
||||
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
|
||||
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
|
||||
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||||
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number; lines?: number }
|
||||
/** a video on a frame, in render pixels: its source and the source second it shows, its box (and what of it a box it's
|
||||
* in leaves showing, `clip`), its object-fit and object-position ([x px, x share of the free space, y px, y share]) */
|
||||
export type ManifestVideo = { src: string; at: number; box: number[]; clip?: number[]; fit?: string; position?: number[]; opacity?: number }
|
||||
/** `raea render --manifest`: the frames with their texts and videos, and the sound's clips; `plan`: written by `raea
|
||||
* render --plan`, which draws nothing (every frame laid out, no picture) */
|
||||
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; plan?: boolean; frames?: { frame: number; text?: ManifestText[]; videos?: ManifestVideo[]; pictures?: { kind?: string; box?: number[]; opacity?: number }[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||||
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
|
||||
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
|
||||
|
||||
@@ -37,6 +42,9 @@ export interface FileFacts {
|
||||
height: number | null
|
||||
fps: number
|
||||
manifest: Manifest | null
|
||||
/** a cut checked on its plan, before it's drawn (plan.ts): `manifest` is the plan, `path` and `abs` name the export
|
||||
* it's of (which may not be there yet), and its words and scene are what its takes say and its sources show */
|
||||
plan: boolean
|
||||
moment: Moment
|
||||
contract: Contract | null
|
||||
/** what it says, word by word */
|
||||
@@ -125,6 +133,7 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
|
||||
height: shape?.height ?? manifest?.height ?? null,
|
||||
fps: manifest?.fps ?? shape?.fps ?? 30,
|
||||
manifest,
|
||||
plan: false,
|
||||
moment,
|
||||
contract,
|
||||
words: once(() => media.words(abs)),
|
||||
@@ -167,3 +176,57 @@ export function runIn(dir: string) {
|
||||
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
|
||||
}
|
||||
}
|
||||
|
||||
/** a composition checked on a plan of one of its cuts (`raea goal check --at edit --manifest OUT.plan.json EDIT.tsx`):
|
||||
* the facts of the export the plan is of (OUT.mp4 beside the plan), known before it's drawn. Its words are its voice
|
||||
* clips' takes' words where the clips put them, its scene its videos' source frames' (plan.ts); its own level, sheet
|
||||
* and look wait for the export */
|
||||
export function planFacts(plan: Manifest, planAbs: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
|
||||
const abs = `${outOf(planAbs)}.mp4`
|
||||
const roots = [root, path.dirname(planAbs)]
|
||||
const fps = Number(plan.fps) || 30
|
||||
const takeWords = new Map<string, Promise<Word[]>>()
|
||||
const take = (src: string) => onMachine(src, roots)
|
||||
const wordsOfTake = (src: string) => {
|
||||
const f = take(src)
|
||||
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
|
||||
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
|
||||
return takeWords.get(f)!
|
||||
}
|
||||
const st = statSync(planAbs)
|
||||
return {
|
||||
path: path.relative(root, abs),
|
||||
abs,
|
||||
root,
|
||||
kind: "other",
|
||||
made: true,
|
||||
stamp: `${Math.round(st.mtimeMs)} ${st.size}`,
|
||||
seconds: (Number(plan.length) || plan.frames?.length || 0) / fps,
|
||||
width: Number(plan.width) || null,
|
||||
height: Number(plan.height) || null,
|
||||
fps,
|
||||
manifest: plan,
|
||||
plan: true,
|
||||
moment,
|
||||
contract,
|
||||
words: once(async () => {
|
||||
const clips = plan.sounds?.clips ?? []
|
||||
const got = new Map<string, Word[]>()
|
||||
for (const c of clips) {
|
||||
if (got.has(c.src)) continue
|
||||
try {
|
||||
got.set(c.src, await wordsOfTake(c.src))
|
||||
} catch {}
|
||||
}
|
||||
return said(clips, plan.sounds?.fps ?? fps, (src) => got.get(src) ?? null)
|
||||
}),
|
||||
take,
|
||||
takeWords: wordsOfTake,
|
||||
levels: (a, b, src) => (src ? media.levels(take(src) ?? src, a, b) : { start: a ?? 0, db: [] }),
|
||||
scene: once(() => planScene(root, plan, take)),
|
||||
sheet: () => {
|
||||
throw new media.Unmet("a plan has no picture to make a sheet of: render it")
|
||||
},
|
||||
seen: () => null,
|
||||
}
|
||||
}
|
||||
+31
-18
@@ -233,24 +233,7 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
|
||||
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
|
||||
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
|
||||
const faces: Faces[] = []
|
||||
const scenes: Scene[] = []
|
||||
for (let i = 0; i < jpgs.length; i += 300) {
|
||||
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
|
||||
const r = await post("/v1/scene", body, "application/json")
|
||||
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
|
||||
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
|
||||
if (!g) {
|
||||
faces.push(null)
|
||||
scenes.push(null)
|
||||
continue
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
}
|
||||
const { faces, scenes } = await readScenes(jpgs.map((n) => readFileSync(path.join(dir, n))))
|
||||
if (whole && scenes.length) {
|
||||
try {
|
||||
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
|
||||
@@ -262,6 +245,36 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
}
|
||||
}
|
||||
|
||||
/** frames (JPEGs, a null where there's none) read by the farm's scene reader, 300 a request: each one's faces and seams,
|
||||
* and its scene (people, faces, things, words in the shot) */
|
||||
export async function readScenes(jpgs: (Buffer | null)[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
|
||||
if (!farm()) throw new Unmet("no scene reader on this machine (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)")
|
||||
const faces: Faces[] = []
|
||||
const scenes: Scene[] = []
|
||||
const real = jpgs.flatMap((j, i) => (j ? [i] : []))
|
||||
const got = new Map<number, Record<string, any> | null>()
|
||||
for (let i = 0; i < real.length; i += 300) {
|
||||
const part = real.slice(i, i + 300)
|
||||
const body = JSON.stringify({ frames: part.map((k) => jpgs[k]!.toString("base64")) })
|
||||
const r = await post("/v1/scene", body, "application/json")
|
||||
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
|
||||
;(JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames.forEach((g, n) => got.set(part[n], g))
|
||||
}
|
||||
for (let i = 0; i < jpgs.length; i++) {
|
||||
const g = got.get(i)
|
||||
if (!g) {
|
||||
faces.push(null)
|
||||
scenes.push(null)
|
||||
continue
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
return { faces, scenes }
|
||||
}
|
||||
|
||||
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
|
||||
export function sheet(file: string): string {
|
||||
const out = `${stem(file)}.sheet.jpg`
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import { RATE, type Word } from "../media.ts"
|
||||
import { samples, textFrames } from "../plan.ts"
|
||||
import type { TextLine } from "./place.ts"
|
||||
|
||||
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
|
||||
@@ -235,13 +236,15 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
// a cut's plan (plan.ts): what it shows is its own text, as laid out, and what it says its takes' words where its
|
||||
// clips put them; an export's is what the reader reads and hears in it
|
||||
const sc = f.plan && f.manifest ? { rate: RATE, scenes: [] } : await f.scene()
|
||||
const frames: Frame[] = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
|
||||
const shown = captionsOf(frames, sc.rate || 2, heard)
|
||||
const rate = sc.rate || 2
|
||||
|
||||
@@ -10,6 +10,7 @@ import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RAEA, stem } from "../media.ts"
|
||||
import { textRules, ZONE_FIX } from "../plan.ts"
|
||||
import { bookkeeping } from "./naming.ts"
|
||||
|
||||
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
|
||||
@@ -53,7 +54,13 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
|
||||
|
||||
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
|
||||
|
||||
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["edit", "render", "publish", "done"] }, async (f) => {
|
||||
// a cut's plan (plan.ts): the text rules raea check holds a manifest to, on every frame, before it's drawn; what only
|
||||
// the picture and the mix show (contrast, freezes, flashing, loudness, blotching) waits for the export
|
||||
if (f.plan && f.manifest) {
|
||||
for (const x of textRules(f.manifest)) found({ level: x.level, says: x.says, fix: x.rule === "safe-area" ? ZONE_FIX : undefined, seconds: x.at })
|
||||
return
|
||||
}
|
||||
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
|
||||
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
|
||||
for (const x of floorOf(f.abs, m, f.root)) say(x)
|
||||
|
||||
@@ -13,6 +13,7 @@ import { existsSync, readFileSync } from "node:fs"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RATE, stem, type Faces } from "../media.ts"
|
||||
import { PLAN_SOFT } from "../plan.ts"
|
||||
|
||||
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
|
||||
export const FACE_MIN = 0.05
|
||||
@@ -141,13 +142,17 @@ export const despite = (abs: string) => {
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
// at edit only a cut's plan (plan.ts): its faces are its sources' frames, mapped into the cut's
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
|
||||
// the text's sizes are said even where the faces wait for a scene reader
|
||||
const why = despite(f.abs)
|
||||
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
|
||||
// on a plan a face cut by the edge is a warning (plan.ts ON_PLAN_WARNS): its source frames are read without the cut's
|
||||
// text over them, and the render's check holds it
|
||||
for (const x of cutFaces((await f.scene()).faces, RATE))
|
||||
say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : f.plan && x.kind === "face-cut" && x.level === "error" ? { ...x, level: "warn", says: `${x.says}${PLAN_SOFT}` } : x)
|
||||
},
|
||||
)
|
||||
@@ -5,11 +5,8 @@
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
||||
import * as cp from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { spawn } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
@@ -201,9 +198,7 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = ask === askClef && !asyncSpawn()
|
||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
||||
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
const heard = await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
@@ -220,51 +215,16 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
||||
* its 10.5 minutes) */
|
||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
||||
if (!jobs.length) return []
|
||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
||||
mkdirSync(tmp, { recursive: true })
|
||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
||||
try {
|
||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
||||
return jobs.map((k, i) => {
|
||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
||||
return rows
|
||||
})
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
const args = askArgs(file, says, from, to)
|
||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
||||
if (!asyncSpawn()) {
|
||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
||||
const rows = rowsOf(String(r.stdout ?? ""))
|
||||
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
|
||||
return Promise.resolve(rows)
|
||||
}
|
||||
return new Promise((ok, no) => {
|
||||
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = rowsOf(out)
|
||||
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
|
||||
@@ -294,9 +294,9 @@ export function placeReport(file: string, scenes: Scene[], size: [number, number
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
|
||||
if (!f.made || (f.kind !== "video" && !f.plan) || !f.manifest?.frames?.length) return
|
||||
const { scenes } = await f.scene()
|
||||
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
},
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
// editor holds (and the skill's end card rule: few words, held long enough).
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import { RATE, type Word } from "../media.ts"
|
||||
import { samples, textFrames } from "../plan.ts"
|
||||
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
|
||||
|
||||
export type Block = { text: string; words: number; from: number; to: number; size?: number }
|
||||
@@ -105,11 +106,14 @@ export function reading(blocks: Block[]): Finding[] {
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!f.made || (f.kind !== "video" && !f.plan)) return
|
||||
// a cut's plan (plan.ts): its own text as laid out (a sign in the footage isn't meant to be read); an export's,
|
||||
// what the reader reads in it
|
||||
const planned = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : null
|
||||
const sc = planned ? { rate: RATE, scenes: [] } : await f.scene()
|
||||
const frames: Frame[] = planned ?? sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((x) => x.lines.length)) return
|
||||
const rate = sc.rate || 2
|
||||
const heard = await f.words()
|
||||
|
||||
@@ -229,9 +229,10 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (f.kind !== "video" && f.kind !== "audio") return
|
||||
// at edit only a cut's plan (plan.ts), whose clips are the export's
|
||||
if (f.kind !== "video" && f.kind !== "audio" && !f.plan) return
|
||||
if (!f.made) return
|
||||
if (!f.manifest) {
|
||||
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
// A cut checked before it's drawn (12-04, round 22: every run missed its budget the same way, a full render of every cut
|
||||
// and only then dozens of errors, fixed, and everything rendered again). `raea render EDIT.tsx --composition ID --plan
|
||||
// -o OUT.plan.json` runs each frame through React and layout and gathers the sound, drawing nothing: its plan is a render
|
||||
// manifest of every frame. `raea goal check --at edit --manifest OUT.plan.json EDIT.tsx` holds the plan to what can be
|
||||
// known from it:
|
||||
//
|
||||
// floor its text clipped by the frame or in the app's UI zones, and up too briefly (apps/check/text's rules)
|
||||
// frames text too small, and faces cut by the frame or a split screen's seam
|
||||
// place text over a face, a person or what the shot is about
|
||||
// sound clips cut inside a word or on sound, lines and effects at uneven levels (from each take's words and level)
|
||||
// captions what's said with no caption over it, and a caption that isn't what's said there
|
||||
// reading text up too briefly to read
|
||||
//
|
||||
// What the cut says is its voice clips' takes' words, laid where the clips put them. What its frames show is the scene of
|
||||
// each SOURCE frame a video shows there (the farm's POST /v1/scene, as for an export), mapped through the video's box,
|
||||
// fit and object-position into the cut's frame: the picture the render would draw, read without drawing it. Each
|
||||
// source frame's reading is kept under review/scenes/, so a plan checked again asks only for frames it hasn't read.
|
||||
// What only the export has (the words heard in the mix, its loudness, contrast, blotching) waits for --at render.
|
||||
//
|
||||
// A plan's errors stop the renders (raea cloud renders a batch only when every cut's plan passes), so on a plan an error
|
||||
// is only what the plan knows as exactly as the export's check: floor's text rules, text too small, sound's edit points
|
||||
// and levels. Place, captions, reading and faces cut by the edge are read from the source frames without the cut's own
|
||||
// text over them, or held against the takes' words rather than the mix, and on round 22's Body Shop each cut had one
|
||||
// such error the export's check didn't give (ON_PLAN_WARNS): on a plan they're warnings, and the render's check holds
|
||||
// them. The plan holds its own cut alone: the project's checks and the goals' job checks (the count, the brief's quotes)
|
||||
// don't run on it, and a check that can't run (the farm busy) waits instead of failing it.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import type { Clip, Manifest, ManifestVideo } from "./facts.ts"
|
||||
import * as media from "./media.ts"
|
||||
import type { Faces, Word } from "./media.ts"
|
||||
import { busOf } from "./packs/sound.ts"
|
||||
import type { Scene, Thing } from "./packs/place.ts"
|
||||
|
||||
/** a file a plan is checked for: a composition (the plan of one of its compositions) */
|
||||
export const COMPOSITION = /\.(tsx|jsx|ts|js|mjs)$/i
|
||||
/** the export a plan is of: OUT.plan.json (or OUT.render.json, OUT.manifest.json) is OUT's */
|
||||
export const outOf = (plan: string) => media.stem(plan).replace(/\.(plan|render|manifest)$/i, "")
|
||||
|
||||
/** checks whose errors are warnings on a plan (frames' faces cut by the edge too, in frames.ts; its text sizes stay
|
||||
* errors): each is read or heard otherwise than the export's check reads and hears it */
|
||||
export const ON_PLAN_WARNS = new Set(["place", "captions", "reading"])
|
||||
/** said after each error a plan tells and doesn't hold */
|
||||
export const PLAN_SOFT = " (on the plan a warning: the render's check holds it)"
|
||||
|
||||
/** the width the scene reader reads a frame at (media.ts SIDE), so sizes are the export's */
|
||||
const SIDE = 540
|
||||
/** a grid cell's side, as the farm's scene reader makes them (540x960: 27x48) */
|
||||
const CELL = 20
|
||||
/** a video under this opacity is fading: what's under it, or over it, is what's seen */
|
||||
const SEEN = 0.5
|
||||
/** a thing or a face with less than this share of it inside its video's visible box is out of the shot */
|
||||
const VISIBLE = 0.25
|
||||
/** a thing this much covered by a video drawn over it is hidden */
|
||||
const HIDDEN = 0.75
|
||||
|
||||
type Rect = [number, number, number, number]
|
||||
|
||||
/** the times a plan's frames are read at: RATE a second, from 0 to its end */
|
||||
export function samples(m: Manifest, rate = media.RATE): number[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const len = Number(m.length) || m.frames?.length || 0
|
||||
const n = Math.max(0, Math.ceil((len / fps) * rate - 1e-9))
|
||||
return Array.from({ length: n }, (_, i) => i / rate)
|
||||
}
|
||||
|
||||
/** where a picture sw x sh is drawn in a video's box: its fit, then its object-position ([x px, x share of the free
|
||||
* space, y px, y share], centred when unset); `native`: the picture's own size, for fit none and scale-down */
|
||||
export function drawn(v: ManifestVideo, sw: number, sh: number, native: [number, number] = [sw, sh]): Rect {
|
||||
const [bx, by, bw, bh] = v.box
|
||||
let dw = bw
|
||||
let dh = bh
|
||||
const contain = Math.min(bw / sw, bh / sh)
|
||||
const fit = v.fit ?? "fill"
|
||||
if (fit === "cover" || fit === "contain" || fit === "scale-down" || fit === "none") {
|
||||
const s = fit === "cover" ? Math.max(bw / sw, bh / sh) : fit === "contain" ? contain : fit === "none" ? native[0] / sw : Math.min(contain, native[0] / sw)
|
||||
dw = sw * s
|
||||
dh = sh * s
|
||||
}
|
||||
const p = v.position ?? [0, 0.5, 0, 0.5]
|
||||
return [bx + p[0] + p[1] * (bw - dw), by + p[2] + p[3] * (bh - dh), dw, dh]
|
||||
}
|
||||
|
||||
const meet = (a: Rect, b: Rect): Rect | null => {
|
||||
const x0 = Math.max(a[0], b[0])
|
||||
const y0 = Math.max(a[1], b[1])
|
||||
const x1 = Math.min(a[0] + a[2], b[0] + b[2])
|
||||
const y1 = Math.min(a[1] + a[3], b[1] + b[3])
|
||||
return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null
|
||||
}
|
||||
const area = (r: Rect | null) => (r ? r[2] * r[3] : 0)
|
||||
|
||||
/** what a video shows in a frame: where its picture (`size`, as decoded: rotation applied) is drawn, what of it is seen
|
||||
* in the frame (cut px), and that part of the picture as shares of it ([x, y, w, h], the `crop` read for its scene) */
|
||||
export type Layer = { v: ManifestVideo; size: [number, number]; draw: Rect; seen: Rect; crop: Rect }
|
||||
|
||||
/** the videos a frame shows, bottom first: each drawn by its box, fit and position, cut to what its box (and the box
|
||||
* clipping it) leaves showing in the frame. A fading video (under SEEN) only when nothing else shows */
|
||||
export function layersOf(videos: ManifestVideo[], W: number, H: number, sizeOf: (v: ManifestVideo) => [number, number] | null): Layer[] {
|
||||
const frame: Rect = [0, 0, W, H]
|
||||
const opaque = videos.filter((v) => (v.opacity ?? 1) >= SEEN)
|
||||
const shown = opaque.length ? opaque : [...videos].sort((a, b) => (b.opacity ?? 1) - (a.opacity ?? 1)).slice(0, 1)
|
||||
const out: Layer[] = []
|
||||
for (const v of shown) {
|
||||
if (!v.box || v.box.length < 4) continue
|
||||
const size = sizeOf(v)
|
||||
if (!size) continue
|
||||
const seen = meet(meet(v.box as Rect, (v.clip as Rect | undefined) ?? frame) ?? [0, 0, 0, 0], frame)
|
||||
if (!seen) continue
|
||||
const draw = drawn(v, size[0], size[1], size)
|
||||
const round = (x: number) => Math.round(x * 1000) / 1000
|
||||
const x0 = Math.max(0, (seen[0] - draw[0]) / draw[2])
|
||||
const y0 = Math.max(0, (seen[1] - draw[1]) / draw[3])
|
||||
const x1 = Math.min(1, (seen[0] + seen[2] - draw[0]) / draw[2])
|
||||
const y1 = Math.min(1, (seen[1] + seen[3] - draw[1]) / draw[3])
|
||||
if (x1 <= x0 || y1 <= y0) continue
|
||||
out.push({ v, size, draw, seen, crop: [round(x0), round(y0), round(x1 - x0), round(y1 - y0)] })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the scene read of the part of a source frame a layer shows (its crop, at the reader's size, as the export's reader
|
||||
* sees it: a face half out of the shot is read as the export reads it) */
|
||||
export type Source = { scene: NonNullable<Scene>; faces: NonNullable<Faces> }
|
||||
|
||||
/** what a frame of the cut shows, from the scenes of the parts of the source frames its videos show: each one's things,
|
||||
* faces and person mask mapped through its crop and its drawn box into the cut's frame (SIDE wide), and hidden where a
|
||||
* video is drawn over it. A video's edge inside the frame is a seam (a split screen, a picture in a picture). Null
|
||||
* when no video shows there */
|
||||
export function compose(all: Layer[], W: number, H: number, sourceOf: (l: Layer) => Source | null): { scene: Scene; faces: Faces } {
|
||||
const k = SIDE / Math.min(W, H)
|
||||
const w = Math.round(W * k)
|
||||
const h = Math.round(H * k)
|
||||
const layers = all.flatMap((l) => {
|
||||
const src = sourceOf(l)
|
||||
return src ? [{ ...l, src }] : []
|
||||
})
|
||||
if (!layers.length) return { scene: null, faces: null }
|
||||
type Read = (typeof layers)[number]
|
||||
// a box in a crop's scene, in the cut's pixels
|
||||
const toCut = (l: Read, t: readonly unknown[]): Rect => {
|
||||
const [x, y, bw, bh] = [0, 1, 2, 3].map((i) => Number(t[i]) || 0)
|
||||
const sx = (v: number) => (l.crop[0] + (v / l.src.scene.w) * l.crop[2]) * l.draw[2]
|
||||
const sy = (v: number) => (l.crop[1] + (v / l.src.scene.h) * l.crop[3]) * l.draw[3]
|
||||
return [l.draw[0] + sx(x), l.draw[1] + sy(y), sx(x + bw) - sx(x), sy(y + bh) - sy(y)]
|
||||
}
|
||||
const scaled = (r: Rect): [number, number, number, number] => [r[0] * k, r[1] * k, r[2] * k, r[3] * k]
|
||||
// what of a box is seen: inside its layer's visible box, and not hidden by a layer over it
|
||||
const seenOf = (i: number, b: readonly unknown[]): Rect | null => {
|
||||
const l = layers[i]
|
||||
const r = toCut(l, b)
|
||||
const vis = meet(r, l.seen)
|
||||
if (!vis || area(vis) < VISIBLE * area(r)) return null
|
||||
for (const o of layers.slice(i + 1)) if (area(meet(vis, o.seen)) >= HIDDEN * area(vis)) return null
|
||||
return vis
|
||||
}
|
||||
const things: Thing[] = []
|
||||
const faces: Thing[] = []
|
||||
layers.forEach((l, i) => {
|
||||
for (const t of l.src.scene.things) {
|
||||
const r = seenOf(i, t)
|
||||
if (r) things.push([...scaled(r), t[4], t[5]] as Thing)
|
||||
}
|
||||
for (const f of l.src.scene.faces) {
|
||||
const r = seenOf(i, f)
|
||||
if (r) faces.push([...scaled(r), "face", Number(f[5] ?? f[4]) || 0] as Thing)
|
||||
}
|
||||
})
|
||||
// the person mask: each cell's centre, in the topmost layer that shows there, read from its crop's grid
|
||||
const cols = Math.round(w / CELL)
|
||||
const rows = Math.round(h / CELL)
|
||||
const people: string[] = []
|
||||
for (let r = 0; r < rows; r++) {
|
||||
let line = ""
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const x = ((c + 0.5) / cols) * W
|
||||
const y = ((r + 0.5) / rows) * H
|
||||
const l = layers.findLast((o) => x >= o.seen[0] && x < o.seen[0] + o.seen[2] && y >= o.seen[1] && y < o.seen[1] + o.seen[3])
|
||||
if (!l) {
|
||||
line += "0"
|
||||
continue
|
||||
}
|
||||
const g = l.src.scene.grid
|
||||
const sc = Math.floor((((x - l.draw[0]) / l.draw[2] - l.crop[0]) / l.crop[2]) * g.cols)
|
||||
const sr = Math.floor((((y - l.draw[1]) / l.draw[3] - l.crop[1]) / l.crop[3]) * g.rows)
|
||||
line += g.people[sr]?.[sc] ?? "0"
|
||||
}
|
||||
people.push(line)
|
||||
}
|
||||
// a video's edge inside the frame: a seam, where it shows over a good part of the frame's other side
|
||||
const seams: media.Seam[] = []
|
||||
for (const l of layers) {
|
||||
const [x, y, sw, sh] = l.seen
|
||||
if (sw >= W * 0.5) for (const e of [y, y + sh]) if (e > H * 0.02 && e < H * 0.98) seams.push(["h", Math.round(e * k), sw / W])
|
||||
if (sh >= H * 0.5) for (const e of [x, x + sw]) if (e > W * 0.02 && e < W * 0.98) seams.push(["v", Math.round(e * k), sh / H])
|
||||
}
|
||||
const texts = layers.flatMap((l, i) => (l.src.scene.texts ?? []).flatMap((t) => {
|
||||
const r = seenOf(i, t)
|
||||
return r ? [[...scaled(r), t[4], t[5]] as [number, number, number, number, string, number]] : []
|
||||
}))
|
||||
return {
|
||||
scene: { w, h, grid: { cols, rows, people }, things, faces, texts },
|
||||
faces: { w, h, faces: faces.map((f) => [f[0], f[1], f[2], f[3], f[5]]), seams },
|
||||
}
|
||||
}
|
||||
|
||||
/** what a plan's cut says: each voice clip's take's words that fall inside it, laid where the clip puts them (a word
|
||||
* the clip cuts into is said if most of it is inside; the sound pack holds the cut itself) */
|
||||
export function said(clips: Clip[], fps: number, wordsOf: (src: string) => Word[] | null): Word[] {
|
||||
const out: Word[] = []
|
||||
for (const c of clips) {
|
||||
if (busOf(c) !== "voice") continue
|
||||
const ws = wordsOf(c.src)
|
||||
if (!ws) continue
|
||||
const a = c.at
|
||||
const b = c.at + (c.to - c.from) / fps
|
||||
for (const w of ws) {
|
||||
const inside = Math.min(b, w.end) - Math.max(a, w.start)
|
||||
// a word the clip cuts into is heard when much of it is in (a transcriber hears half a word)
|
||||
if (inside <= 0 || inside < Math.min(0.12, 0.4 * Math.max(0.01, w.end - w.start))) continue
|
||||
const shift = c.from / fps - a
|
||||
out.push({ text: w.text, start: Math.max(c.from / fps, w.start + shift), end: Math.min(c.to / fps, w.end + shift) })
|
||||
}
|
||||
}
|
||||
return out.sort((x, y) => x.start - y.start)
|
||||
}
|
||||
|
||||
/** a plan's frames by number */
|
||||
export function byFrame(m: Manifest): Map<number, NonNullable<Manifest["frames"]>[number]> {
|
||||
return new Map((m.frames ?? []).map((f) => [Number(f.frame), f]))
|
||||
}
|
||||
|
||||
type Line = [number, number, number, number, string, number]
|
||||
/** a text laid out on `n` lines, as the reader reads it: a line each, its words shared out by their letters (where
|
||||
* layout broke it isn't in the manifest, only how many lines it made) */
|
||||
export function linesOf(text: string, b: number[], n: number): Line[] {
|
||||
const words = text.split(/\s+/).filter(Boolean)
|
||||
if (n <= 1 || words.length < 2) return [[b[0], b[1], b[2], b[3], text, 1]]
|
||||
const k = Math.min(n, words.length)
|
||||
const total = words.reduce((s, w) => s + w.length + 1, 0)
|
||||
const parts: string[][] = Array.from({ length: k }, () => [])
|
||||
let at = 0
|
||||
for (const w of words) {
|
||||
// each word on the line its middle letter falls on
|
||||
parts[Math.min(k - 1, Math.floor(((at + w.length / 2) / total) * k))].push(w)
|
||||
at += w.length + 1
|
||||
}
|
||||
return parts.flatMap((p, l) => (p.length ? [[b[0], b[1] + (b[3] * l) / k, b[2], b[3] / k, p.join(" "), 1] as Line] : []))
|
||||
}
|
||||
|
||||
/** the frame nearest a time, and the text it shows, as the scene reader would read lines: [x, y, w, h, text, score] in
|
||||
* the pixels of a frame `h` high, a text laid out on several lines a line each */
|
||||
export function textFrames(m: Manifest, at: number[]): { h: number; lines: Line[] }[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const H = Number(m.height) || 1920
|
||||
const frames = byFrame(m)
|
||||
return at.map((t) => {
|
||||
const fr = frames.get(Math.round(t * fps))
|
||||
const lines = (fr?.text ?? []).filter((x) => (x.opacity ?? 1) > 0.3 && String(x.text ?? "").trim()).flatMap((x) => linesOf(String(x.text).trim(), (x.ink ?? x.box ?? [0, 0, 0, 0]) as number[], Number(x.lines) || 1))
|
||||
return { h: H, lines }
|
||||
})
|
||||
}
|
||||
|
||||
/** a frame's opaque fills over the whole frame: a cut's backgrounds are on every frame, so a frame with more than the
|
||||
* fewest any frame with a video has holds a card over its videos (an end card), which hides them. (The manifest says
|
||||
* where a fill is, not whether it's over a video or under it.) */
|
||||
const covers = (fr: NonNullable<Manifest["frames"]>[number] | undefined, W: number, H: number) =>
|
||||
(fr?.pictures ?? []).filter((p) => (p.opacity ?? 1) >= 0.9 && p.box && p.box[0] <= 1 && p.box[1] <= 1 && p.box[0] + p.box[2] >= W - 1 && p.box[1] + p.box[3] >= H - 1).length
|
||||
|
||||
// ---- the source frames' scenes, read by the farm and kept ------------------------------------------------------------
|
||||
|
||||
type Kept = { stamp: string; side: number; at: Record<string, Source> }
|
||||
/** a read's key in a source's keeping: its second and its crop */
|
||||
export const readKey = (at: number, crop: Rect) => `${at.toFixed(2)} ${crop.join(",")}`
|
||||
type Want = { file: string; at: number; crop: Rect }
|
||||
|
||||
/** parts of source frames read for a plan, each (file, second, crop) once: from review/scenes/ when read before, else
|
||||
* extracted (several ffmpeg at once where there's a shell) and read by the farm. Unmet when there's no farm here */
|
||||
export async function sourceScenes(root: string, wants: Want[]): Promise<Map<string, Source>> {
|
||||
const out = new Map<string, Source>()
|
||||
const byFile = new Map<string, Map<string, Want>>()
|
||||
for (const w of wants) byFile.set(w.file, (byFile.get(w.file) ?? new Map()).set(readKey(w.at, w.crop), w))
|
||||
const dir = path.join(root, "review", "scenes")
|
||||
for (const [file, mine] of byFile) {
|
||||
const st = statSync(file)
|
||||
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
|
||||
const keep = path.join(dir, `${path.basename(file)}.json`)
|
||||
let kept: Kept = { stamp, side: SIDE, at: {} }
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(keep, "utf8")) as Kept
|
||||
if (k.stamp === stamp && k.side === SIDE) kept = k
|
||||
} catch {}
|
||||
const need = [...mine.entries()].filter(([k]) => !kept.at[k])
|
||||
if (need.length) {
|
||||
const read = await readAt(file, need.map(([, w]) => w))
|
||||
need.forEach(([k], i) => {
|
||||
const s = read.scenes[i]
|
||||
const f = read.faces[i]
|
||||
if (s && f) kept.at[k] = { scene: s, faces: f }
|
||||
})
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true })
|
||||
// read again just before writing: a plan of another cut may have read other frames of the same file meanwhile
|
||||
try {
|
||||
const now = JSON.parse(readFileSync(keep, "utf8")) as Kept
|
||||
if (now.stamp === stamp && now.side === SIDE) kept.at = { ...now.at, ...kept.at }
|
||||
} catch {}
|
||||
const tmp = `${keep}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, JSON.stringify(kept))
|
||||
renameSync(tmp, keep)
|
||||
} catch {}
|
||||
}
|
||||
for (const k of mine.keys()) if (kept.at[k]) out.set(`${file}@${k}`, kept.at[k])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** parts of a file's frames (a second and a crop, in shares of the picture), read by the farm's scene reader at the
|
||||
* reader's size, as the export's reader reads that part of the cut's frame */
|
||||
async function readAt(file: string, wants: Want[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
|
||||
if (!process.env.RAEA_CLOUD_GPU_URL) throw new media.Unmet(`no scene reader on this machine for ${path.basename(file)}'s frames (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-plan-"))
|
||||
try {
|
||||
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
|
||||
const jpgs = wants.map((_, i) => path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`))
|
||||
const one = (w: Want, i: number) => {
|
||||
const [x, y, cw, ch] = w.crop
|
||||
const crop = `crop=iw*${cw}:ih*${ch}:iw*${x}:ih*${y}`
|
||||
return ["-v", "error", "-y", "-ss", w.at.toFixed(3), "-i", file, "-frames:v", "1", "-vf", `${crop},${scale}`, "-q:v", "4", jpgs[i]]
|
||||
}
|
||||
if (process.platform !== "win32" && spawnSync("ffmpeg", ["-version"], { encoding: "utf8" }).status === 0) {
|
||||
// eight at a time through the shell: this runtime has only spawnSync, and a plan reads 60-80 frames
|
||||
const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
|
||||
const lines = wants.map((w, i) => `ffmpeg ${one(w, i).map(q).join(" ")} &${(i + 1) % 8 === 0 ? "\nwait" : ""}`)
|
||||
spawnSync("sh", ["-c", `${lines.join("\n")}\nwait`], { encoding: "utf8", maxBuffer: 1 << 24 })
|
||||
}
|
||||
wants.forEach((w, i) => {
|
||||
if (!existsSync(jpgs[i])) media.ffmpeg(one(w, i))
|
||||
})
|
||||
return await media.readScenes(jpgs.map((j) => (existsSync(j) ? readFileSync(j) : null)))
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** a video file's picture as decoded: its width and height, swapped when it's stored rotated a quarter turn */
|
||||
export function pictureOf(file: string): [number, number] | null {
|
||||
const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_tags=rotate:stream_side_data=rotation", "-of", "json", file], { encoding: "utf8" })
|
||||
try {
|
||||
const s = JSON.parse(r.stdout ?? "").streams?.[0]
|
||||
if (s?.width) {
|
||||
const rot = Math.abs(Number(s.tags?.rotate ?? s.side_data_list?.find((d: { rotation?: number }) => d.rotation !== undefined)?.rotation ?? 0)) % 180
|
||||
return rot === 90 ? [s.height, s.width] : [s.width, s.height]
|
||||
}
|
||||
} catch {}
|
||||
const sh = media.shape(file)
|
||||
return sh ? [sh.width, sh.height] : null
|
||||
}
|
||||
|
||||
/** the scenes of a plan's frames, RATE a second: each composed from the parts of its videos' source frames it shows
|
||||
* (`file`: a source on this machine, or null) */
|
||||
export async function planScene(root: string, m: Manifest, file: (src: string) => string | null): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
|
||||
const W = Number(m.width) || 1080
|
||||
const H = Number(m.height) || 1920
|
||||
const fps = Number(m.fps) || 30
|
||||
const at = samples(m)
|
||||
const frames = byFrame(m)
|
||||
const withVideo = [...frames.values()].filter((f) => f.videos?.length)
|
||||
const backgrounds = withVideo.length ? Math.min(...withVideo.map((f) => covers(f, W, H))) : 0
|
||||
const missing = new Set<string>()
|
||||
const sizes = new Map<string, [number, number] | null>()
|
||||
const sizeOf = (v: ManifestVideo) => {
|
||||
const f = file(v.src)
|
||||
if (!f) {
|
||||
missing.add(v.src)
|
||||
return null
|
||||
}
|
||||
if (!sizes.has(f)) sizes.set(f, pictureOf(f))
|
||||
return sizes.get(f) ?? null
|
||||
}
|
||||
const shows = at.map((t) => {
|
||||
const fr = frames.get(Math.round(t * fps))
|
||||
return covers(fr, W, H) > backgrounds ? [] : layersOf((fr?.videos ?? []) as ManifestVideo[], W, H, sizeOf)
|
||||
})
|
||||
const wants = shows.flatMap((ls) => ls.map((l) => ({ file: file(l.v.src)!, at: l.v.at, crop: l.crop })))
|
||||
if (!wants.length && missing.size) throw new media.Unmet(`the plan's videos aren't on this machine (${[...missing].slice(0, 3).join(", ")}), so what its frames show can't be read`)
|
||||
const read = await sourceScenes(root, wants)
|
||||
const out = shows.map((ls) => compose(ls, W, H, (l) => read.get(`${file(l.v.src)}@${readKey(l.v.at, l.crop)}`) ?? null))
|
||||
return { rate: media.RATE, faces: out.map((o) => o.faces), scenes: out.map((o) => o.scene) }
|
||||
}
|
||||
|
||||
// ---- the floor's text rules, from the plan (apps/check/text's text_runs and text_rules) --------------------------------
|
||||
|
||||
export type Run = { text: string; from: number; to: number; box: Rect; boxes: Rect[]; size: number }
|
||||
|
||||
/** a text as it stays on screen, from the frame it comes on to the frame it leaves; typing (a text growing into the next)
|
||||
* and counting (only its digits changing) are one run, judged by its last text */
|
||||
export function textRuns(m: Manifest): Run[] {
|
||||
const fps = Number(m.fps) || 30
|
||||
const key = (s: string) => s.replace(/[0-9]/g, "").trim().toLowerCase()
|
||||
let open: Run[] = []
|
||||
const done: Run[] = []
|
||||
for (const f of [...(m.frames ?? [])].sort((a, b) => a.frame - b.frame)) {
|
||||
const t = Number(f.frame) / fps
|
||||
const next: Run[] = []
|
||||
for (const x of f.text ?? []) {
|
||||
const text = String(x.text ?? "").trim()
|
||||
if ((x.opacity ?? 1) <= 0.05 || !text) continue
|
||||
const quad = (b?: number[]): Rect | null => (b ? [0, 1, 2, 3].map((i) => Number(b[i]) || 0) as Rect : null)
|
||||
const b = quad(x.box) ?? [0, 0, 0, 0]
|
||||
const ink = quad(x.ink)
|
||||
const k = key(text)
|
||||
const i = open.findIndex((r) => {
|
||||
const rk = key(r.text)
|
||||
return rk === k || (rk !== "" && k.startsWith(rk)) || (k !== "" && rk.startsWith(k) && k.length * 2 > rk.length)
|
||||
})
|
||||
const r: Run = i >= 0 ? open.splice(i, 1)[0] : { text, from: t, to: t, box: b, boxes: [], size: 0 }
|
||||
if (text.length > r.text.length) r.boxes = []
|
||||
if (text.length >= r.text.length) {
|
||||
r.text = text
|
||||
r.box = b
|
||||
r.boxes.push(ink ?? b)
|
||||
}
|
||||
r.to = t + 1 / fps
|
||||
r.size = Number(x.size) || 0
|
||||
next.push(r)
|
||||
}
|
||||
done.push(...open)
|
||||
open = next
|
||||
}
|
||||
done.push(...open)
|
||||
return done.sort((a, b) => a.from - b.from)
|
||||
}
|
||||
|
||||
/** the zones where text can't go, [top, right, bottom, left] at the frame's width (apps/check/text zones(): default) */
|
||||
export function zones(w: number, h: number): [number, number, number, number] {
|
||||
const r = w / h
|
||||
const z: [number, number, number, number] | null = r < 0.7 ? [220, 140, 420, 60] : r < 0.9 ? [110, 60, 170, 60] : r < 1.2 ? [70, 60, 120, 60] : null
|
||||
if (!z) return [(120 * h) / 1080, (60 * w) / 1920, (120 * h) / 1080, (60 * w) / 1920]
|
||||
return z.map((v) => (v * w) / 1080) as [number, number, number, number]
|
||||
}
|
||||
|
||||
const quote = (s: string) => `“${[...s].slice(0, 40).join("")}”`
|
||||
|
||||
/** what `raea check` says of a render's text from its manifest: clipped off the frame (an error), in the app's UI zones
|
||||
* (an error), up too briefly to read (a warning, the reading pack holds it to its words) */
|
||||
export function textRules(m: Manifest): { level: "error" | "warn"; rule: string; at: number; says: string }[] {
|
||||
const w = Number(m.width) || 1080
|
||||
const h = Number(m.height) || 1920
|
||||
const [zt, zr, zb, zl] = zones(w, h)
|
||||
const out: { level: "error" | "warn"; rule: string; at: number; says: string }[] = []
|
||||
for (const r of textRuns(m)) {
|
||||
const [x, y, bw, bh] = r.box
|
||||
const q = quote(r.text)
|
||||
const boxes = r.boxes.length ? r.boxes : [r.box]
|
||||
const off = ([x, y, bw, bh]: Rect) => x < -1 || y < -1 || x + bw > w + 1 || y + bh > h + 1
|
||||
const zoned = ([x, y, bw, bh]: Rect) => y < zt || x + bw > w - zr || y + bh > h - zb || x < zl
|
||||
if (boxes.every(off)) out.push({ level: "error", rule: "clipped", at: r.from, says: `${q} runs off the frame (box ${x.toFixed(0)},${y.toFixed(0)} ${bw.toFixed(0)}x${bh.toFixed(0)} in ${w}x${h}); fit it or break the line` })
|
||||
else if (boxes.every(zoned)) {
|
||||
const [ix, iy, iw, ih] = boxes[boxes.length - 1]
|
||||
const edge = iy < zt ? `the top (keep ${zt.toFixed(0)} px clear)` : iy + ih > h - zb ? `the bottom (keep ${zb.toFixed(0)} px clear)` : ix < zl ? `the left (keep ${zl.toFixed(0)} px clear)` : `the right (keep ${zr.toFixed(0)} px clear)`
|
||||
out.push({ level: "error", rule: "safe-area", at: r.from, says: `${q} sits in the app's UI zone at ${edge}: its ${r.boxes.length && boxes[boxes.length - 1] !== r.box ? "letters" : "box"} ${ix.toFixed(0)},${iy.toFixed(0)} ${iw.toFixed(0)}x${ih.toFixed(0)} in ${w}x${h}` })
|
||||
}
|
||||
const words = r.text.split(/\s+/).filter(Boolean).length
|
||||
const need = Math.max(1, 0.3 * words)
|
||||
const held = r.to - r.from
|
||||
if (held + 0.05 < need && r.size >= 24) out.push({ level: "warn", rule: "reading", at: r.from, says: `${q} is on for ${held.toFixed(1)} s; ${words} words need ${need.toFixed(1)} s to read` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the fix a UI-zone finding asks for, said once */
|
||||
export const ZONE_FIX = "keep text inside the safe area: 220 px from the top, 420 px from the bottom, 140 px from the right and 60 px from the left of a 1080x1920 frame"
|
||||
+54
-17
@@ -3,6 +3,9 @@
|
||||
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
|
||||
//
|
||||
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
|
||||
// (EDIT.tsx --at edit --manifest OUT.plan.json: one cut of the composition checked on its plan, `raea render
|
||||
// --plan`, before it's drawn: plan.ts. Only that cut's file checks run, only what the plan knows exactly is an
|
||||
// error, and a check that can't run waits, so exit 1 always names something in the cut to fix)
|
||||
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
|
||||
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
|
||||
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
|
||||
@@ -14,12 +17,13 @@
|
||||
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
|
||||
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
|
||||
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
|
||||
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
|
||||
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
|
||||
import { fileFacts, type FileFacts, type Job, kindOf, planFacts, runIn } from "./facts.ts"
|
||||
import { COMPOSITION, ON_PLAN_WARNS, PLAN_SOFT } from "./plan.ts"
|
||||
import * as media from "./media.ts"
|
||||
import { registeredPack } from "./packs/job.ts"
|
||||
import { tastePack } from "./packs/taste.ts"
|
||||
@@ -137,13 +141,22 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
const broke: Report["broke"] = []
|
||||
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
|
||||
const fps = file?.fps ?? 30
|
||||
for (const x of r.findings)
|
||||
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
|
||||
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
|
||||
for (const x of r.findings) {
|
||||
// on a plan, what's read from the source frames or held against the takes' words is told, not held (ON_PLAN_WARNS)
|
||||
const soft = file?.plan && x.level === "error" && ON_PLAN_WARNS.has(x.check)
|
||||
findings.push({ goal, check: x.check, level: soft ? "warn" : x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: soft ? `${x.says}${PLAN_SOFT}` : x.says, fix: x.fix, by: x.by })
|
||||
}
|
||||
// on a plan, a check that couldn't run (the farm busy or down, a frame that wouldn't extract) waits: nothing in the
|
||||
// cut to fix, and the render's own check runs it again
|
||||
for (const t of r.threw) (t.waits || file?.plan ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.waits || !file?.plan ? t.says : `couldn't check the plan, so the render's check holds it: ${t.says}` })
|
||||
}
|
||||
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
|
||||
// a composition named with a manifest: one of its cuts checked on its plan (`raea render --plan`), before it's drawn
|
||||
// (plan.ts). It holds that cut alone: the project's own checks and the goals' job checks (the count, the brief's
|
||||
// quotes) are the render's and publish's to hold, never a reason not to draw one cut
|
||||
const planned = cutPlan(o.manifest, named, cwd)
|
||||
// the project's own: once, whatever its goals
|
||||
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
|
||||
const once = planned ? [] : ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
|
||||
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
|
||||
const verdicts: GoalVerdict[] = []
|
||||
const allFiles = new Set<string>()
|
||||
@@ -155,10 +168,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
: at === "publish" || at === "done"
|
||||
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
|
||||
: []
|
||||
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
|
||||
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
|
||||
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
|
||||
const checks = checksOf(contract, at, o.only)
|
||||
// a cut's plan (above), else a render's manifest kept away from its export (`raea render --manifest M`): the one
|
||||
// file named reads it
|
||||
const files: FileFacts[] = planned
|
||||
? [planFacts(planned.manifest, planned.abs, root, at, contract)]
|
||||
: wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
|
||||
if (o.manifest && !planned && files.length === 1) {
|
||||
files[0].manifest = JSON.parse(readFileSync(path.resolve(cwd, o.manifest), "utf8")) as FileFacts["manifest"]
|
||||
files[0].fps = files[0].manifest?.fps ?? files[0].fps
|
||||
}
|
||||
const checks = checksOf(contract, at, o.only).filter((c) => !planned || c.over !== "job")
|
||||
const before = findings.length
|
||||
const brokeBefore = broke.length
|
||||
const j = job(contract, deliverables, files)
|
||||
@@ -191,16 +210,32 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
|
||||
}
|
||||
}
|
||||
|
||||
/** a composition's plan: `--manifest` naming a plan (or any manifest) with one composition named */
|
||||
export function cutPlan(manifest: string | undefined, named: string[], cwd = process.cwd()): { abs: string; manifest: FileFacts["manifest"] & object } | null {
|
||||
if (!manifest || named.length !== 1 || !COMPOSITION.test(named[0])) return null
|
||||
const abs = path.resolve(cwd, manifest)
|
||||
return { abs, manifest: JSON.parse(readFileSync(abs, "utf8")) }
|
||||
}
|
||||
|
||||
/** written whole or not at all: plans of several cuts are checked at once, each writing review/goal.json */
|
||||
const writeWhole = (p: string, text: string) => {
|
||||
const tmp = `${p}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, text)
|
||||
renameSync(tmp, p)
|
||||
}
|
||||
|
||||
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
|
||||
* each file named */
|
||||
export function writeReport(r: Report, named: string[]) {
|
||||
* each file named (a plan's beside the plan: OUT.plan.check.json) */
|
||||
export function writeReport(r: Report, named: string[], plan?: string) {
|
||||
const dir = path.join(r.root, "review")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
|
||||
for (const f of named) {
|
||||
writeWhole(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
|
||||
const one = (f: string, out: string) => {
|
||||
const mine = r.findings.filter((x) => x.file === f)
|
||||
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
|
||||
writeWhole(out, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
|
||||
}
|
||||
for (const f of named) one(f, `${media.stem(path.join(r.root, f))}.check.json`)
|
||||
if (plan) for (const f of r.files) one(f, `${media.stem(plan)}.check.json`)
|
||||
}
|
||||
|
||||
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
|
||||
@@ -226,7 +261,8 @@ function flag(a: string[], name: string): string | undefined {
|
||||
}
|
||||
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
|
||||
|
||||
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
|
||||
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
|
||||
raea goal check EDIT.tsx --at edit --manifest OUT.plan.json (a cut checked on its plan, raea render --plan, before it's drawn)
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
|
||||
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
|
||||
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
|
||||
@@ -249,7 +285,8 @@ export async function main(argv: string[]): Promise<number> {
|
||||
console.error(`raea goal check: ${(e as Error).message}`)
|
||||
return 2
|
||||
}
|
||||
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
|
||||
const plan = cutPlan(flag(a, "--manifest"), files.map((n) => path.relative(r.root, path.resolve(n))))
|
||||
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))), plan?.abs)
|
||||
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
|
||||
return r.passed ? 0 : 1
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
// raea's own runtime has no async spawn, so clefVerdict asks every question through one shell (askClefMany): six at
|
||||
// once, each answer in its job's order (12-04: one after another, a stop's 18 beats took 7.7 minutes). A child with a
|
||||
// stand-in raea (a second an ask), since RAEA is read once, as goal.ts is loaded
|
||||
test("askClefMany asks every job at once, CLEF_AT_ONCE at a time, and keeps each job's answers", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
|
||||
const script = `
|
||||
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
|
||||
const jobs = Array.from({ length: 6 }, (_, i) => ({ file: "out/cut " + i + "'s.mp4", says: i % 2 ? ["one", "two"] : ["one"], from: "1", to: "2" }))
|
||||
const t0 = Date.now()
|
||||
const got = askClefMany(${JSON.stringify(dir)}, jobs)
|
||||
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file }))
|
||||
`
|
||||
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea") } })
|
||||
expect(r.stderr.trim().split("\n").filter((l) => /error/i.test(l))).toEqual([])
|
||||
const o = JSON.parse(r.stdout.trim().split("\n").at(-1)!)
|
||||
expect(o.ms).toBeLessThan(3_000)
|
||||
expect(o.n).toEqual([1, 2, 1, 2, 1, 2])
|
||||
expect(o.file).toBe("out/cut 1's.mp4")
|
||||
})
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
#!/bin/sh
|
||||
# a stand-in `raea ask FILE SAYS... --choose true,false --json`: one answer a line for each SAYS, after a second
|
||||
sleep 1
|
||||
shift; f=$1; shift
|
||||
for a in "$@"; do case "$a" in --*) break;; esac; echo "{\"answer\":\"a\",\"file\":\"$f\",\"choice\":\"true\",\"says\":\"true (0.9)\",\"problem\":null}"; done
|
||||
@@ -0,0 +1,201 @@
|
||||
// A cut checked on its plan before it's drawn (src/plan.ts): what its frames show read from its sources' frames, what it
|
||||
// says from its takes' words, and the floor's text rules on every frame
|
||||
import { expect, test } from "bun:test"
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { type Answer, useSender } from "../src/media.ts"
|
||||
import { compose, drawn, layersOf, linesOf, PLAN_SOFT, said, samples, textRules, textRuns } from "../src/plan.ts"
|
||||
import { goalCheck, text, writeReport } from "../src/run.ts"
|
||||
import { CLIP, project, put } from "./project.ts"
|
||||
|
||||
const full = (over: Record<string, unknown> = {}) => ({ src: "a.mp4", at: 1, box: [0, 0, 1080, 1920], fit: "cover", ...over })
|
||||
|
||||
test("a video is drawn by its fit and object-position, and what of it the frame shows is its crop", () => {
|
||||
// a 16:9 picture covering a 9:16 frame, centred: 3413 px wide, 1167 px of it off each side
|
||||
const c = drawn(full(), 1920, 1080)
|
||||
expect(c.map(Math.round)).toEqual([-1167, 0, 3413, 1920])
|
||||
// object-position 76% across (as `position: [0, 0.76, 0, 0.5]` says it)
|
||||
expect(Math.round(drawn(full({ position: [0, 0.76, 0, 0.5] }), 1920, 1080)[0])).toBe(Math.round(0.76 * (1080 - 3413.33)))
|
||||
// contain letterboxes it; fill stretches it
|
||||
expect(drawn(full({ fit: "contain" }), 1920, 1080).map(Math.round)).toEqual([0, 656, 1080, 608])
|
||||
expect(drawn(full({ fit: "fill" }), 1920, 1080)).toEqual([0, 0, 1080, 1920])
|
||||
const [l] = layersOf([full() as never], 1080, 1920, () => [1920, 1080])
|
||||
expect(l.crop).toEqual([0.342, 0, 0.316, 1])
|
||||
// a box clipped by its parent (`clip`) shows only that part of it
|
||||
const [h] = layersOf([full({ box: [-566, 0, 4096, 2304], clip: [0, 0, 1080, 1920] }) as never], 1080, 1920, () => [3840, 2160])
|
||||
expect(h.seen).toEqual([0, 0, 1080, 1920])
|
||||
expect(h.crop[3]).toBeCloseTo(1920 / 2304, 3)
|
||||
// a fading video is left out while another shows; alone it's what's seen
|
||||
expect(layersOf([full() as never, full({ opacity: 0.2 }) as never], 1080, 1920, () => [1920, 1080])).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("a source's scene, read of its crop, lands in the cut's frame: a face at the crop's edge is a face at the frame's", () => {
|
||||
// the reader read the crop (304x540 of a 960x540 picture) at 540 wide: a face touching its right edge, a person
|
||||
const scene = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array.from({ length: 48 }, (_, r) => (r > 20 ? "7".repeat(27) : "0".repeat(27))) }, things: [[100, 300, 300, 660, "person", 0.9]], faces: [[480, 200, 60, 80, "face", 0.9]] }
|
||||
const faces = { w: 540, h: 960, faces: [[480, 200, 60, 80, 0.9]] }
|
||||
const ls = layersOf([full() as never], 1080, 1920, () => [960, 540])
|
||||
const out = compose(ls, 1080, 1920, () => ({ scene, faces }) as never)
|
||||
expect(out.scene?.w).toBe(540)
|
||||
const [x, y, w, h] = out.faces!.faces[0]
|
||||
expect(Math.round(x + w)).toBe(540)
|
||||
expect([Math.round(y), Math.round(h)]).toEqual([200, 80])
|
||||
expect(out.scene!.grid.people[30]).toBe("7".repeat(27))
|
||||
expect(out.scene!.things[0][4]).toBe("person")
|
||||
// a video drawn over the bottom half hides what's under it there, and its top edge is a seam
|
||||
const two = layersOf([full() as never, full({ box: [0, 960, 1080, 960] }) as never], 1080, 1920, () => [960, 540])
|
||||
const low = { ...scene, things: [[100, 600, 300, 300, "dog", 0.9]] }
|
||||
const o2 = compose(two, 1080, 1920, (l) => (l.v.box[1] ? ({ scene: { ...scene, things: [], faces: [] }, faces: { ...faces, faces: [] } } as never) : ({ scene: low, faces } as never)))
|
||||
expect(o2.faces!.seams).toContainEqual(["h", 480, 1])
|
||||
expect(o2.scene!.things).toEqual([])
|
||||
})
|
||||
|
||||
test("what a plan's cut says is its voice clips' takes' words, where the clips put them", () => {
|
||||
const take = [{ text: "one", start: 10, end: 10.4 }, { text: "two", start: 10.5, end: 10.9 }, { text: "three", start: 11, end: 11.5 }, { text: "four", start: 11.6, end: 12 }]
|
||||
// frames 30-75 at 30 fps (1.0-2.5 s) show the take from 10.45 s: "one" is out, "three" whole, "four" cut a little
|
||||
const w = said([{ from: 30, to: 75, src: "media/take.mp4", at: 10.45 }], 30, () => take)
|
||||
expect(w.map((x) => x.text)).toEqual(["two", "three", "four"])
|
||||
expect(w[0].start).toBeCloseTo(1.05, 5)
|
||||
// music isn't speech
|
||||
expect(said([{ from: 0, to: 30, src: "music/bed.mp3", at: 0 }], 30, () => take)).toEqual([])
|
||||
})
|
||||
|
||||
test("the floor's text rules hold every frame of a plan: the UI zones, the frame's edges", () => {
|
||||
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, text: [
|
||||
{ text: "In the zone at the right", box: [100, 830, 900, 93], ink: [139, 830, 860, 93], size: 58 },
|
||||
{ text: "Clear of everything", box: [200, 1000, 680, 93], size: 58 },
|
||||
{ text: "Off the frame entirely here", box: [900, 1200, 600, 93], ink: [900, 1200, 600, 93], size: 58 },
|
||||
] }))
|
||||
const m = { width: 1080, height: 1920, fps: 30, length: 60, frames }
|
||||
const r = textRules(m)
|
||||
expect(r.map((x) => [x.rule, x.level])).toEqual([["safe-area", "error"], ["clipped", "error"]])
|
||||
expect(r[0].says).toMatch(/sits in the app's UI zone at the right \(keep 140 px clear\)/)
|
||||
// a typed text (growing into the next) is one run, judged by its last text
|
||||
const typed = textRuns({ fps: 30, frames: ["Hel", "Hello", "Hello there"].map((t, f) => ({ frame: f, text: [{ text: t, box: [300, 900, 400, 80], size: 60 }] })) })
|
||||
expect(typed.map((x) => x.text)).toEqual(["Hello there"])
|
||||
expect(samples(m)).toEqual([0, 0.5, 1, 1.5])
|
||||
// a text laid out on several lines is read a line each, as the export's reader reads it
|
||||
expect(linesOf("Make your Wishlist and organize your Gift Exchange", [0, 100, 600, 200], 2).map((l) => l[4])).toEqual(["Make your Wishlist and", "organize your Gift Exchange"])
|
||||
})
|
||||
|
||||
test("raea goal check --at edit --manifest PLAN EDIT.tsx: the cut's plan is checked, named for its export, before it's drawn", async () => {
|
||||
const d = project(null)
|
||||
put(d, "edit.tsx", "export default 1\n")
|
||||
put(d, "media/take.mp4", readFileSync(CLIP))
|
||||
const frames = Array.from({ length: 90 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Down in the bottom zone", box: [140, 1600, 800, 90], size: 60 }] }))
|
||||
const plan = put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 90, plan: true, frames, sounds: { fps: 30, clips: [] } }))
|
||||
// the farm's reader, standing in: every crop read has a face cut by its right edge
|
||||
const before = process.env.RAEA_CLOUD_GPU_URL
|
||||
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
|
||||
let read = 0
|
||||
useSender(async (_url, body): Promise<Answer> => {
|
||||
const n = (JSON.parse(String(body)) as { frames: string[] }).frames.length
|
||||
read += n
|
||||
const g = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [[470, 300, 70, 120, "face", 0.9]], seams: [] }
|
||||
return { status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(g) }) }
|
||||
})
|
||||
try {
|
||||
const r = await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
|
||||
const mine = r.findings.filter((x) => x.file === "out/cuts/ad_concept_v1_9x16.mp4")
|
||||
expect(mine.some((x) => x.check === "floor" && x.level === "error" && /UI zone at the bottom/.test(x.says))).toBe(true)
|
||||
// a face cut by the edge is read from the source frames: on a plan it's told, and the render's check holds it
|
||||
expect(mine.some((x) => x.check === "frames" && x.level === "warn" && /right edge/.test(x.says) && x.says.endsWith(PLAN_SOFT))).toBe(true)
|
||||
// only what the plan knows exactly holds it: floor, sound and text sizes
|
||||
expect(mine.filter((x) => x.level === "error").every((x) => x.check === "floor" || x.check === "sound" || (x.check === "frames" && /px/.test(x.says)))).toBe(true)
|
||||
expect(r.passed).toBe(false)
|
||||
expect(read).toBe(6)
|
||||
// each source frame's reading is kept: the plan checked again reads nothing
|
||||
await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
|
||||
expect(read).toBe(6)
|
||||
writeReport(r, [], plan)
|
||||
expect(existsSync(path.join(d, "out/cuts/ad_concept_v1_9x16.plan.check.json"))).toBe(true)
|
||||
} finally {
|
||||
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
|
||||
else process.env.RAEA_CLOUD_GPU_URL = before
|
||||
}
|
||||
})
|
||||
|
||||
/** a plan of one cut with nothing in it to fix: its text inside the safe area, over the test clip */
|
||||
function cleanPlan(d: string, name = "out/cuts/ad_concept_v1_9x16.plan.json") {
|
||||
put(d, "edit.tsx", "export default 1\n")
|
||||
put(d, "media/take.mp4", readFileSync(CLIP))
|
||||
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Safe in the middle", box: [140, 900, 800, 90], size: 60 }] }))
|
||||
return put(d, name, JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 60, plan: true, frames, sounds: { fps: 30, clips: [] } }))
|
||||
}
|
||||
/** the farm's reader, standing in for a test: `answer` gives each POST's reply */
|
||||
async function withFarm<T>(answer: (n: number) => Answer, run: () => Promise<T>): Promise<T> {
|
||||
const before = process.env.RAEA_CLOUD_GPU_URL
|
||||
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
|
||||
useSender(async (_url, body) => answer((JSON.parse(String(body)) as { frames: string[] }).frames.length))
|
||||
try {
|
||||
return await run()
|
||||
} finally {
|
||||
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
|
||||
else process.env.RAEA_CLOUD_GPU_URL = before
|
||||
}
|
||||
}
|
||||
const EMPTY = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [], seams: [] }
|
||||
|
||||
test("a plan holds its own cut alone: the brief's count, its quotes and the project's checks don't stop it being drawn", async () => {
|
||||
// the brief asks for 10 cuts, 1 is planned, and the open item about the count waits for a person (who answers at the
|
||||
// first stop, after the first render); the brief's text isn't in the project either
|
||||
const asked = { question: "Only 2 interviews came: cut fewer?", from: "10 total videos", about: "count" }
|
||||
const d = project({ kind: "cut", packs: { naming: false }, cut: { brief: "media/brief.txt", count: { value: 10, from: "10 total videos" }, formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }], open: [asked] } })
|
||||
const plan = cleanPlan(d)
|
||||
const r = await withFarm(
|
||||
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(EMPTY) }) }),
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
|
||||
expect(r.checks).not.toContain("count")
|
||||
expect(r.checks).not.toContain("quotes")
|
||||
expect(r.checks).not.toContain("registered")
|
||||
expect(r.passed).toBe(true)
|
||||
// the same project checked at edit without a plan still holds the count
|
||||
const whole = await goalCheck({ cwd: d, at: "edit" })
|
||||
expect(whole.findings.some((x) => x.check === "count" && x.level === "error")).toBe(true)
|
||||
})
|
||||
|
||||
test("a plan the farm can't read waits: nothing to fix, so it doesn't fail", async () => {
|
||||
const d = project(null)
|
||||
const plan = cleanPlan(d)
|
||||
let asked = 0
|
||||
const r = await withFarm(
|
||||
() => {
|
||||
asked++
|
||||
return { status: 503, ok: false, text: "busy" }
|
||||
},
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
expect(asked).toBeGreaterThan(0)
|
||||
expect(r.broke).toEqual([])
|
||||
expect(r.waits.map((w) => w.check)).toContain("frames")
|
||||
expect(r.waits.find((w) => w.check === "frames")?.says).toMatch(/render's check holds it.*503/)
|
||||
expect(r.errors).toBe(0)
|
||||
expect(r.passed).toBe(true)
|
||||
expect(text(r)).toMatch(/^PASSED .*waiting/m)
|
||||
})
|
||||
|
||||
test("on a plan, text over a face and talking with no captions are warnings: the render's check holds them", async () => {
|
||||
const d = project({ kind: "cut", packs: { naming: false }, cut: { formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }] } })
|
||||
// a caption with nothing said under it, straight over a face the farm reads in every frame
|
||||
const plan = cleanPlan(d)
|
||||
const m = JSON.parse(readFileSync(plan, "utf8"))
|
||||
m.length = 240
|
||||
m.frames = Array.from({ length: 240 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: (f % 90) / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: f < 60 ? [{ text: "Nobody says this at all", box: [140, 300, 800, 300], size: 60 }] : [] }))
|
||||
// ... and from 5 s, past a text hook's opening, the take talks with no caption up
|
||||
put(d, "media/take.words.json", JSON.stringify("so this is what we said".split(" ").map((t, i) => ({ text: t, start: 0.3 + i * 0.4, end: 0.6 + i * 0.4 }))))
|
||||
m.sounds.clips = [{ key: "v", from: 150, to: 240, src: "media/take.mp4", at: 0 }]
|
||||
put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify(m))
|
||||
const face = { ...EMPTY, faces: [[170, 150, 200, 200, "face", 0.95]] }
|
||||
const r = await withFarm(
|
||||
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(face) }) }),
|
||||
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
|
||||
)
|
||||
const soft = r.findings.filter((x) => x.says.endsWith(PLAN_SOFT))
|
||||
expect(soft.length).toBeGreaterThan(0)
|
||||
expect(soft.every((x) => x.level === "warn" && ["place", "captions", "reading", "frames"].includes(x.check))).toBe(true)
|
||||
expect(soft.some((x) => x.check === "place" && /covers a face/.test(x.says))).toBe(true)
|
||||
expect(soft.some((x) => x.check === "captions" && /no captions over the talking/.test(x.says))).toBe(true)
|
||||
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
|
||||
expect(r.passed).toBe(true)
|
||||
})
|
||||
Reference in new issue
Block a user