Compare commits

..
Author SHA1 Message Date
shinyobjectz 95b867d0ad A video's montage findings are kept beside it, measured again when it or its beats change
Reading a 35 s cut's frames took 7 s each time the goal was checked, on files that hadn't changed.
2026-12-01 21:26:15 -08:00
shinyobjectz 494905d9ee The montage pack reads a video's frames from a file, not down a pipe
13 MB of small frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box; into a file, 4.6 s.
2026-12-01 21:19:27 -08:00
shaneandshinyobjectz 7b8317764a A made video's floor report is kept beside it, measured again only for cause (#300)
The measure took 26 s a cut and ran again on the same file at publish and at done. A kept report with an error is always measured again: what it names can be put right without the video changing.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:59:21 -08:00
shaneandshinyobjectz c69e28fac3 A box says when its agent's turn has ended: its transcript ended a step and nothing of its own still runs (#299)
Gemini wrote its last message without answering session/prompt, and the run stayed open 45 minutes until the idle agent was ended, read as cut off and started again. A step with no tool call is also how it waits on a job in the background (123 of 131 in one run), so the agent's processes are read with it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:39:50 -08:00
shaneandshinyobjectz 83da71b62d A video's scene reading is kept beside it, and a kept reading isn't the work changing (#298)
A cut checked at its render was read again at publish and again at done, 30 s a file each time: a done check of 11 files took 334 s. And a done check that heard a cut's words wrote them beside it, so the critic's verdict of a minute before read as older than the work and every says rule failed again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 19:01:29 -08:00
shaneandshinyobjectz 4d896d2b2f One size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still (#297)
Told by pixels alone, an ad named _9x16 beside its own 1080x1920 renders and a 540x960 still read as three sizes, and an agent with one size made couldn't stop for its sign-off.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:43:59 -08:00
shaneandshinyobjectz d4d13925fa Farm: scene frames in parallel, 32 warm containers a video (#296)
* The farm reads a cut's scene frames on containers of their own, side by side

They went through the API's one core one after another inside its event loop: 70 frames of a 35 s ad took 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow). A whole goal check on a 35 s cut: 34 s, from 77-98.

* The farm draws a video on up to 32 containers, kept warm a minute, and says where a slow job's end went

A 35 s 1080x1920 cut: 80 s from the box's call to its file, from 104-160. At 8 containers its parts ran two after another on each; at 2 s idle every render's containers started cold.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:58 -08:00
shaneandshinyobjectz a8d7263235 A caption over a person's body is a warning; over a face or what the shot shows it stays an error (#295)
Two people fill a 9:16 interview frame, and each caption's clearest place is a different one: an agent spent hours cropping shots and rendering again to clear errors that a steady caption position can't. The warning still names the clear place.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:53 -08:00
11 changed files with 297 additions and 50 deletions

No files matched your search

+77 -33
View File
@@ -32,6 +32,7 @@ import re
import resource
import shutil
import subprocess
import threading
import time
import uuid
@@ -81,8 +82,10 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -168,6 +171,8 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# one reading at a time a container: the models aren't safe to run from two threads
SCENE_LOCK = threading.Lock()
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
@@ -228,6 +233,10 @@ class Log:
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
# about five times their GPUs' working seconds
SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
def on(gpus, job):
@@ -291,7 +300,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
@@ -434,7 +443,9 @@ def coordinate(id: str, args: list[str], opts: dict):
except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True)
code = 1
t_end = [time.time()]
vol.commit()
t_end.append(time.time())
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
@@ -448,7 +459,9 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else:
time.sleep(pause)
t_end.append(time.time())
after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"):
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
@@ -460,10 +473,66 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
vol.commit()
t_end.append(time.time())
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
if t_end[-1] - t_end[0] > 5:
d = [b - a for a, b in zip(t_end, t_end[1:])]
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
log.end(code)
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
def read_scenes(frames):
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
import base64
import cv2
import numpy as np
import farm_scene
global SCENE
with SCENE_LOCK:
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return out
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
SCENE_HERE = 4
SCENE_PART = 6
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
def scene_run(frames: list[str]) -> list:
return read_scenes(frames)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
@modal.concurrent(max_inputs=32)
@modal.asgi_app()
@@ -548,19 +617,6 @@ def api():
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/scene")
async def scene(req: Request):
@@ -569,11 +625,6 @@ def api():
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
@@ -581,18 +632,11 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
if len(frames) <= SCENE_HERE:
out = await asyncio.to_thread(read_scenes, frames)
else:
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
out = [r async for part in scene_run.map.aio(parts) for r in part]
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")
+18
View File
@@ -208,10 +208,23 @@ export async function words(file: string, anyAge = false): Promise<Word[]> {
/** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */
export const RATE = 2
const SIDE = 540
/** a video's scene reading, kept beside it */
export const SCENE_EXT = "scene.json"
/** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene
* (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */
export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
// a video's whole reading is kept beside it, as its words are, and read again only when the file is newer: a cut
// checked at its render was read again at publish and again at done, 30 s a file each time, so a done check of 11
// files took 334 s (12-01)
const whole = !at?.length && !/\.(png|jpe?g|webp)$/i.test(file)
if (whole) {
const kept = freshBeside(file, SCENE_EXT)
try {
const k = kept ? (JSON.parse(readFileSync(kept, "utf8")) as { rate: number; side: number; faces: Faces[]; scenes: Scene[] }) : null
if (k && k.rate === RATE && k.side === SIDE && Array.isArray(k.scenes) && k.scenes.length) return { rate: k.rate, faces: k.faces, scenes: k.scenes }
} catch {}
}
if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
try {
@@ -238,6 +251,11 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
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)
}
}
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
} catch {}
}
return { rate: at?.length ? 0 : RATE, faces, scenes }
} finally {
rmSync(dir, { recursive: true, force: true })
+27 -3
View File
@@ -4,7 +4,7 @@
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
// the text rules and the person's text taste on them; what it can't see waits for the export's floor
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
@@ -12,7 +12,7 @@ import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts"
type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
/** raea's measure of a file, its findings as it wrote them (-o) */
function measure(args: string[], cwd: string): Measured[] {
@@ -27,12 +27,36 @@ function measure(args: string[], cwd: string): Measured[] {
}
}
/** a video's floor report, kept beside it */
export const FLOOR_EXT = "floor.json"
let version: string | undefined
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
const kept = `${stem(abs)}.${FLOOR_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
} catch {}
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
try {
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
} catch {}
return findings
}
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) => {
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 measure([f.abs, ...(m ? ["--manifest", m] : [])], f.root)) say(x)
for (const x of floorOf(f.abs, m, f.root)) say(x)
})
export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => {
+6 -1
View File
@@ -19,6 +19,11 @@ 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
@@ -43,7 +48,7 @@ export function newest(dir: string): number | null {
}
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" && !name.endsWith(".check.json")) best = Math.max(best ?? 0, st.mtimeMs)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
+41 -8
View File
@@ -13,6 +13,9 @@
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
import { spawnSync } from "node:child_process"
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
@@ -42,9 +45,18 @@ export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye"
export function read(file: string, fps: number, width: number, height: number): Read {
const w = READ_W
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
const buf = r.stdout as Buffer
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
// 4.6 s into a file (12-01)
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
let buf: Buffer
try {
const raw = path.join(dir, "frames.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
buf = readFileSync(raw)
} finally {
rmSync(dir, { recursive: true, force: true })
}
const size = w * h * 3
const frames: Frame[] = []
for (let o = 0; o + size <= buf.length; o += size) {
@@ -235,6 +247,25 @@ export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?:
return out
}
/** a video's montage findings, kept beside it */
export const MONTAGE_EXT = "montage.json"
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
} catch {}
const findings = measure()
try {
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
} catch {}
return findings
}
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
export default check<FileFacts>(
@@ -244,9 +275,6 @@ export default check<FileFacts>(
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
const plan = c ? cutOf(c, f.path) : null
const beats = plan?.plan.beats ?? []
const r = read(f.abs, f.fps, f.width, f.height)
if (r.frames.length < 2) return
const cuts = cutsOf(r)
let faces: Faces[] | undefined
let rate = 0
try {
@@ -258,7 +286,12 @@ export default check<FileFacts>(
if (!(e instanceof Unmet)) throw e
}
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] })
for (const x of pace(beats, cuts, r.fps, r.frames.length / r.fps)) say(x)
for (const x of acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })) say(x)
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
const r = read(f.abs, f.fps, f.width!, f.height!)
if (r.frames.length < 2) return []
const cuts = cutsOf(r)
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
}))
say(x)
},
)
+7 -2
View File
@@ -7,6 +7,7 @@
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said.
// Over a face or a thing it's an error; over a person's body alone, a warning.
//
// raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
@@ -257,8 +258,12 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) {
const face = under.includes("a face")
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
// an error only for what a shot can't lose: a face, or the thing it shows (the product, the dog, a phone held
// up). A caption over someone's coat with clearer ground elsewhere is a warning with the place said (12-01: two
// people fill a 9:16 interview frame, each caption's clearest place is a different one, and an agent spent
// hours cropping shots and rendering again to clear errors a steady caption position can't)
const hard = under.some((u) => u !== "a person in the shot")
out.push({ level: hard ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
} else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) {
+14 -1
View File
@@ -11,11 +11,24 @@ import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
/** The size a made file is in, as a name says one (9x16): its name's, else a video's own shape (1080x1920 is 9x16).
* A picture with no size in its name is a still of the work, a sheet or a strip, not a size of an ad. Told by pixels
* alone, an ad named _9x16 beside its own 1080x1920 renders and one 540x960 still read as three sizes, and an agent
* with one size made couldn't stop for its sign-off (12-01). */
export function shapeOf(f: { path: string; kind?: string; width?: number; height?: number }): string | null {
const named = sizeOf(f.path)
if (named) return named
if (f.kind !== "video" || !f.width || !f.height) return null
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
const g = gcd(f.width, f.height)
return `${f.width / g}x${f.height / g}`
}
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
const sizes = new Map<string, string[]>()
for (const f of made) {
const s = sizeOf(f.path) ?? (f.width && f.height ? `${f.width}x${f.height}` : null)
const s = shapeOf(f)
if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path])
}
if (sizes.size < 2) return
+52
View File
@@ -0,0 +1,52 @@
// A made video's floor report is kept beside it and measured again only for cause (packs/floor.ts)
import { expect, test } from "bun:test"
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { floorOf, type Measured } from "../src/packs/floor.ts"
import { keptOr } from "../src/packs/montage.ts"
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
let out: Measured[] = [{ level: "warn", says: "quiet" }]
const by = () => (runs++, out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(runs).toBe(1)
// the video made again
const later = new Date(Date.now() + 60_000)
utimesSync(v, later, later)
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 120_000), new Date(Date.now() + 120_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
// an error isn't kept as an answer
utimesSync(v, new Date(Date.now() + 180_000), new Date(Date.now() + 180_000))
out = [{ level: "error", says: "a placeholder brand kit" }]
floorOf(v, undefined, d, by)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 240_000), new Date(Date.now() + 240_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(4)
rmSync(d, { recursive: true, force: true })
})
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
keptOr(v, "a", by)
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
expect(runs).toBe(1)
keptOr(v, "b", by)
expect(runs).toBe(2)
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
keptOr(v, "b", by)
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
+13 -1
View File
@@ -1,7 +1,7 @@
// The rule packs (MK29, ported from Rust's goal gate tests): run rules pass or say why, says rules need a fresh critic;
// any goal carries rules.
import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
@@ -80,3 +80,15 @@ test("clef judges a rule on the file it names, else on every video made, and say
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
})
test("a reading kept beside a file isn't the work changing", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-newest-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
writeFileSync(cut, "x")
utimesSync(cut, 1000, 1000)
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
expect(newest(d)).toBe(1_000_000)
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)
})
+31 -1
View File
@@ -1,6 +1,9 @@
import { test } from "bun:test"
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { RATE, scene, SCENE_EXT, useSender } from "../src/media.ts"
import { placeReport, textOver } from "../src/packs/place.ts"
test("the place pack's model", async () => {
@@ -42,4 +45,31 @@ test("the place pack's model", async () => {
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning")
// a: a caption across the woman's body with clear ground above her: a warning that names the place, never an error
// (12-01: errors here had an agent cropping interview shots and rendering again for hours)
for (const y of [300, 400, 500]) {
const d = textOver(man([t("Did you know you", 480, y, 536, 88)]), [sc.a], 1).filter((x) => /covers a person in the shot (at|from)/.test(x.says))
assert.ok(d.length === 1 && d[0].level === "warn", JSON.stringify(d))
}
assert.match(textOver(man([t("Did you know you", 480, 400, 536, 88)]), [sc.a], 1)[0].says, /covers a person in the shot at 0\.0 s: move it to left \d+ px, top \d+ px/)
ok("a caption over a body with clearer ground elsewhere is a warning with the place said")
})
test("a video's scene reading is kept beside it and read again only when the video is newer", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-scene-kept-"))
const cut = path.join(d, "a_b_c_v1_9x16.mp4")
writeFileSync(cut, "not a real video")
const kept = { rate: RATE, side: 540, faces: [null], scenes: [{ w: 540, h: 960, grid: { cols: 1, rows: 1, people: ["0"] }, things: [], faces: [] }] }
writeFileSync(path.join(d, `a_b_c_v1_9x16.${SCENE_EXT}`), JSON.stringify(kept))
let asked = 0
useSender(async () => (asked++, { status: 500, ok: false, text: "" }))
delete process.env.RAEA_CLOUD_GPU_URL
// no farm here at all, and the reading still comes back: from beside the file
const r = await scene(cut)
assert.equal(r.scenes.length, 1)
assert.equal(r.rate, RATE)
assert.equal(asked, 0)
// a reading at named seconds is never the whole file's
await assert.rejects(scene(cut, [1, 2]), /no scene reader/)
})
+11
View File
@@ -4,6 +4,7 @@ import { beforeAll, expect, test } from "bun:test"
import { goalCheck } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs"
import { shapeOf } from "../src/packs/sizes.ts"
beforeAll(() => {
process.env.RAEA_REAL = "/usr/bin/false"
@@ -31,3 +32,13 @@ test("every size of the newest version passes; a person's answer can say fewer",
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
})
test("one size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still", () => {
expect(shapeOf({ path: "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka_small.mp4", kind: "video", width: 540, height: 960 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1350 })).toBe("4x5")
expect(shapeOf({ path: "out/stills/a1_38.jpg", kind: "image", width: 540, height: 960 })).toBe(null)
expect(shapeOf({ path: "out/stills/strip.png", kind: "image", width: 1080, height: 480 })).toBe(null)
expect(shapeOf({ path: "out/stills/dutch_vetbill_end_v1_1x1.png", kind: "image", width: 1080, height: 1080 })).toBe("1x1")
})