Compare commits

..
Author SHA1 Message Date
shinyobjectz 559b23482f Safe defaults: text keeps out of the app's UI zones, talking clips move off words
Round 22's ad cuts spent most of their render passes on two kinds of error that the goal check found only after a
full render: text in the app's UI zones (the floor's safe-area rule) and clips whose in or out cut a word (the sound
pack's edit points). This makes the SDK's defaults avoid both.

Text: uiZones(width, height, {platform, shape}) is the floor's own table (apps/check/text/src/lib.rs zones), and
useUiZones() reads it for the composition. <SafeArea> is a layer over the frame inset by the zones, for text placed by
hand. <Region> now keeps its bands out of the zones by default: its edges were 0.08 H and 0.80 H, inside the 9:16 top
and bottom zones, and its sides a symmetric 65 px, inside the 140 px right-hand zone. keepOut={false} gives the old
bands for a part placed there on purpose, and platform picks a platform's zones.

Clips: a <Video> placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a take
with its words beside it (TAKE.words.json, or footage/TAKE.words.json for a take in media/) moves in its take by the
least amount within 0.4 s that leaves neither end inside a word, judged as the sound pack judges it. In and out move
together, so its place and length in the edit stay and nothing freezes. Clips of one take that play on from each other
(a take split only to reframe it) move together, so the take plays on unbroken where they join; this is why the move
is made where the clips are placed (AbsoluteFill and Series look through their children) rather than by each Video,
which can't see the clips it joins. Each move is written to the render's log once, and the element carries
data-raea-snapped. snap={false} keeps a clip where it is; snap={true} moves a Video on its own where the tree doesn't
reach it.

Tested: bun test conformance (776 pass; the 6 that fail fail the same on main), with new tests in
safe-defaults.test.tsx and the Region tests updated to the new bands. On the three round 22 projects' render manifests
and take words, the clip snapping takes the real cut ends inside words from 24 to 8, 22 to 6 and 2 to 2, and keeps all
65 joins between continuous clips unbroken. On a Fly box, raea 0.1.17-rc4 with this sdk/video overlaid (its files were
identical to main's before the change) rendered a test edit: the caption row placed on the frame is flagged in the
right-hand zone and the same row inside SafeArea is not, a Region's bands are clear, the clip whose in cut a word
plays 300 ms earlier (sounds.clips at 10.2) with the move in the render's log, and the reframed pair is left alone.
The SDK reference pages are regenerated for the new exports only.
2026-12-04 10:21:13 -08:00
119 changed files with 2166 additions and 4454 deletions

No files matched your search

+2 -2
View File
@@ -52,7 +52,7 @@ pub fn stop(v: &Value) -> Option<String> {
let cwd = PathBuf::from(v["cwd"].as_str()?);
let brief = brief_with_job(&cwd)?;
let exe = std::env::current_exe().ok()?;
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let out = std::process::Command::new(exe).args(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
let home = raea_io_home::user_home()?;
let session = v["session_id"].as_str().unwrap_or("");
@@ -67,7 +67,7 @@ pub fn stop(v: &Value) -> Option<String> {
}
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
Some(format!("Not done ({open}{}): {items}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
}
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
+37 -6
View File
@@ -3,10 +3,10 @@
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
//! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
//! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
//! every harness hands its agent; what was sent goes back in the shape each one reads.
//! file is saved: `raea goal check --at edit` on a composition, or on a file under a brief. As a turn ends: `raea
//! goal check --at done` on the brief's goals (apps/check/make). After any tool, and as a turn ends: what the person sent from
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit
//! moment's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -114,6 +114,23 @@ pub fn steer(files: &[String]) -> String {
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
}
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
/// adds or updates (Codex).
fn saved(v: &Value) -> Vec<String> {
let i = &v["tool_input"];
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
return vec![p.to_string()];
}
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Whether a saved file is held at the edit moment: a composition (a .tsx that registers a root), or any file under a
/// brief.ts
fn held_at_edit(p: &Path) -> bool {
(p.extension().is_some_and(|e| e == "tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) || p.parent().is_some_and(|d| raea_app_check_make::brief_with_job(d).is_some())
}
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
/// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String {
@@ -161,8 +178,20 @@ pub fn hook(args: &[String]) -> R<String> {
}
return Ok(String::new());
}
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
// the edit moment of the loop (docs/goal.feature MK33): `raea goal check FILE --at edit` on a saved composition, or
// on any file under a brief; a save that passes says nothing
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
if out.status.code() == Some(1) {
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
}
}
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
}
#[cfg(test)]
@@ -188,6 +217,8 @@ mod tests {
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
assert_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
+1 -20
View File
@@ -192,10 +192,6 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
}
}
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
pub const RAIL: f64 = 0.45;
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
let r = w / h;
@@ -228,8 +224,7 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
let [x, y, bw, bh] = r.box_;
let q = quote(&r.text);
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
if r.boxes.iter().all(off) {
clipped += 1;
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
@@ -318,20 +313,6 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
#[cfg(test)]
mod tests {
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
/// down was an error); the same card over the buttons isn't.
#[test]
fn the_right_zone_starts_where_the_apps_buttons_do() {
let right = |y: f64| {
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
let (mut issues, mut passed) = (vec![], vec![]);
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
};
assert_eq!(right(682.0), "");
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
}
use super::*;
use serde_json::json;
-60
View File
@@ -1,60 +0,0 @@
Feature: one check (12-04, Shane: "fix how every agent checks its work ... removing ask and judge completely and all
that exists is check as the overarching method")
Round 26's agents met about nine ways to check their work (raea goal check, goal seen, goal judge, raea ask, raea
check's taste, the old frames command, a lines.txt words check, raea cloud's stop critic and run eval, and the render and
publish tools' own copies), two of them broken on the boxes, and 183 findings on 10 cuts of which about 10 were real
faults. Every agent, on raea cloud, in the desktop app or with the raea skill, now has one: `raea check`.
Rule: every rule lives in one of three places, or nowhere (12-04, Shane)
Built in: a component or an SDK default that can't produce the fault (captions from the words file, in the safe area;
a Region that keeps text off faces and the app's buttons; raea cut, which cuts only in pauses). Its check is a
backstop that shouldn't fire.
A check, hard or soft: hard is an error (a fault in the deliverable), soft a warning (a note for the person, never a
reason to render again).
Context the agent retrieves while it makes the work: craft and taste (how captions read, pacing, a hook, a brand's
fingerprint, the person's past notes) live in the skill, the guides and memory. Nothing grades the work against them.
A rule that fits none of these isn't a rule: no ritual (the agent saying it looked: `seen`) and no model's opinion
of the work (taste, a critic, a judge, an ask).
Scenario: CK0 one verb
Given any project
When an agent or a person runs `raea check [FILE...] [--at edit|render|publish|done]`
Then it runs every rule the project's goal holds at that moment, and nothing else checks the work
And `raea goal check` still runs as `raea check`, for boxes and tools on an older raea
And `raea ask`, `raea goal judge`, `raea judge` and `raea goal seen` are gone: raea says so, and names `raea check`
Scenario: CK1 run once, after the render
Given a render that wrote OUT.mp4 (on this machine, or on raea cloud's farm and checked by the box that sent it)
When it ends
Then `raea check OUT.mp4 --at render` runs once and keeps OUT.check.json beside it
And publish and done read OUT.check.json while it's no older than OUT.mp4 or its manifest, and never run its rules again
Scenario: CK2 only real faults, one line a rule
Given a cut
Then it is held to: a word clipped or missing (words, sound), a face cut by the frame edge (frames), text over a face,
a sign or the app's buttons (place, floor), captions over talking (captions), the brief's must-say, never-say and
CTA (say, never, cta), its size, length and name (shape, sizes, naming), the brief's count and open items, and what
the render itself found (render)
And a 3D scene, kit or shot is held to its deliverables and what its render found: clipping, a part out of place or
under its detail, light that jumps
And each rule says at most one line a file: its first finding and how many more like it
Scenario: CK3 our own text from the manifest
Given a render manifest beside a video
Then captions, placement and size read the texts raea drew from it, never by reading the frames
And text in the source footage (a sign, a phone's screen) is never counted as the edit's
Scenario: CK4 no critic, no ritual in the loop
Then no check asks a model to judge the work, and no check waits for the agent to say it looked
And a check that can't run on a machine (Mac, Linux, Windows, a raea cloud box) is removed, not left waiting
Scenario: CK5 a brief that can't break the check
Given brief.ts with `goal: [steps, cut({...})]`, `goal: steps` or `goal: cut({...})`
Then `raea check` reads every goal in it, and never crashes on what an agent wrote
And a cut's beats are the agent's plan, never a rule it is checked against
Scenario: CK6 one set of instructions
Then raea's skill, its guides, `raea help`, the AGENTS.md raea writes, raea cloud's method, workflows and skills, and
the desktop app all name `raea check` as the one way to check, and none names ask, judge, seen, frames check or a
lines.txt words check
-34
View File
@@ -124,37 +124,3 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
back, a second container handing its render to the first, an ACP turn round-tripped
And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file
comes back through /v1/files
Rule: a box edits on light copies, the farm renders from originals (12-05)
Scenario: CL17. Nothing on the box takes a light copy's place
Given raea cloud brought a run's footage as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt)
Then every look the agent takes (a still, a frame, a probe, a check of its words) reads the light copy
And no file ever replaces footage/NAME.mp4 on the box, before a render or after one
Scenario: CL18. A farm render reads each light copy as its original, fetched by the farm
Given .raea-cloud/originals.json names a light copy's original: its hash, size and a link that hasn't ended
When a render that reads the light copy goes to the farm (server/offload.ts)
Then its media manifest names the original under the light copy's path, with its link, and the light copy's own
bytes go nowhere
And the farm fetches the original from the library into its cache, checks it against its hash, and keeps it for
every later render; the box never downloads it, hashes it or sends it
And a light copy the render doesn't read is left out, its original included
And a size raea cloud doesn't know goes as 0, which the farm takes with a link and never without one
Scenario: CL19. An original with no link goes from the box
Given a light copy whose original has no hash, or whose link ends within 5 minutes
When its original is in footage/originals/ under the light copy's name (any extension)
Then the render sends that file by its own hash, under the light copy's path
And only a farm with its media cache gets an original by its file (by LFS or in the tar it would go as the light
copy), and only that farm an original of unknown size: for any other the take is rendered as its light copy
And .raea-cloud/proxies/ never goes in a render's tar, and an original no source names stays on the box
Scenario: CL20. A render that read a light copy says so
Given a light copy with no original either way
Then the render prints NO ORIGINAL with its name, and is rendered from the light copy
And its manifest records {"originals": {"read": [...], "light": [...]}} (a still's in OUT.render.json beside it),
checked or not, from which raea cloud marks it a draft that is never shown or published
And the farm's media list holds each original by its link in its light copy's place, with everything else that
went (12-05 review: the farm-cache path dropped the links while the manifest said they were read)
And an original of unknown size over 40 GB is refused as it downloads, before it fills the farm's volume
And test/originals.ts and test/farm_media.py check CL17-CL20
+134 -6
View File
@@ -38,13 +38,14 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
```
`raea` exports 21 components, 9 hooks, 65 functions, 11 values, 109 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
`raea` exports 22 components, 10 hooks, 68 functions, 12 values, 117 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
## Components
### `AbsoluteFill`
A box over the whole of its parent, laid out as a flex column; `style` is merged over that.
A box over the whole of its parent, laid out as a flex column; `style` is merged over that. The talking clips placed
in it are moved off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -209,6 +210,7 @@ component, whose box it can't reach, or a part with a mask, is placed inside a f
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](video.md#mediaprops).
@@ -229,10 +231,26 @@ A box at the band its name stands for, clear of the face perception found at thi
| --- | --- | --- |
| `name` | `RegionName` | the band: "auto" (default) takes the larger of top and bottom; top and bottom stay clear of the face; center is the middle third; full is the safe area |
| `margin` | `number` | the gap kept from the face and the sides, as a share of the width (0.06) |
| `keepOut` | `boolean` | keep the band out of the app's UI zones (true): its edges and sides clear the strips a social app draws its buttons and captions over (uiZones). false places it there on purpose: the older bands, 0.08 H from the top to 0.80 H down, inset by `margin` alone |
| `platform` | `UiPlatform` | the platform whose UI it keeps out of (tiktok, reels, shorts); none: the strictest, as the floor checks |
| `style` | `CSSProperties` | merged under the box's own placement |
| `className` | `string` | Tailwind or CSS classes |
| `children` | `ReactNode` | what goes in the band; `useRegion()` reads its box |
### `SafeArea`
A layer over the whole frame but the app's UI zones: text and captions placed inside it (absolutely, or in its
flex column) are clear of them. Its top, right, bottom and left are the zones, as CSS custom properties --ui-top,
--ui-right, --ui-bottom and --ui-left on it.
| Prop | Type | What it does |
| --- | --- | --- |
| `style` | `CSSProperties` | merged over the layer's own placement |
| `className` | `string` | Tailwind or CSS classes |
| `children` | `ReactNode` | what goes inside: placed in the layer, which keeps clear of the app's UI |
Also takes the props of [`UiZoneOptions`](#uizoneoptions) (`platform`, `shape`).
### `Sequence`
Shifts time by `from` and shows its children only for `durationInFrames` frames.
@@ -253,7 +271,8 @@ Used in: [manual: hello](https://github.com/shinyobjectz/raea/blob/main/docs/man
### `Series`
Plays its Series.Sequence children back to back, each shifted by its own offset.
Plays its Series.Sequence children back to back, each shifted by its own offset; the talking clips in them are moved
off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -291,13 +310,15 @@ Its children, coming in over the part's first frames, going out over its last, a
### `Video`
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show.
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. On a talking take its
ends are moved off words (`snap`).
| Prop | Type | What it does |
| --- | --- | --- |
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](video.md#mediaprops).
@@ -376,6 +397,14 @@ the map bound to the composition's fps as `song`.
function useSong(map: SongMap, options?: UseSongOptions): SongMoment & { song: Song; }
```
### `useUiZones`
The app's UI zones of the composition being rendered (its width and height).
```ts
function useUiZones(o?: UiZoneOptions): UiZones
```
### `useVideoConfig`
The settings of the composition being rendered (inside a Sequence, its width, height and length win).
@@ -697,10 +726,12 @@ function random(seed: string | number | null): number
### `regionBand`
Works out the vertical band each name stands for, given perception and the composition size.
Works out the vertical band each name stands for, given perception and the composition size. Its edges are the
platform's safe area when perception gives one, else clear of the app's UI zones (`keepOut`: uiZones of the frame);
with keepOut false, 0.08 H from the top and 0.80 H (0.92 H landscape) down, which reach into them.
```ts
function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin?: number): Band
function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin?: number, keepOut?: false | UiZones): Band
```
### `registerRoot`
@@ -788,6 +819,18 @@ arrives from a side: `distance` px (30) over `frames` (7), fading in over 5. `fr
function slide(o?: { from?: Dir; distance?: number; frames?: number; ease?: Curve; }): Move
```
### `snapClip`
The clip [tin, tout] of a take (seconds in the take; tout Infinity when it plays to the take's end or its length isn't
known) moved by the least amount, within SNAP_NEAR, that leaves neither end inside a word, as the sound pack's edit
points judge it (a cut on a boundary where words run together is tight, not a cut word): in a gap if one is near, else
on such a boundary. Failing that, the move that leaves the fewest ends inside words. Never moved before the take's
start.
```ts
function snapClip(words: readonly TakeWord[], tin: number, tout: number): Snap
```
### `song`
A song map bound to a frame rate (and where frame 0 sits in the song): frames from song times, and the reverse.
@@ -882,6 +925,15 @@ a strike-through line drawn: width 0 to 100% over `frames` (8).
function strike(o?: { frames?: number; ease?: Curve; }): Move
```
### `takeWords`
The words of the take `src`, read once from the first words file found (takeWordsFiles); null when there is none or
this isn't the engine (plain bun has no files to read).
```ts
function takeWords(src: string): TakeWord[] | null
```
### `tick`
a number counting from `from` (0) to `to` over `frames` (24), written as the element's text: `digits` decimals,
@@ -936,6 +988,15 @@ sees states (a playtest over a game's pure fold) recovers the TransitionRecord a
function transitionOf(m: AnyMachine, before: Snapshot<string> | undefined, after: Snapshot<string>): TransitionRecord | null
```
### `uiZones`
The app's UI zones of a `width` x `height` frame: how far in from each edge its text keeps, in px. The floor's
numbers (apps/check/text/src/lib.rs `zones`), scaled with the width.
```ts
function uiZones(width: number, height: number, o?: UiZoneOptions): UiZones
```
### `wipe`
a reveal wiping across from `from` (left) over `frames` (8), in-out-cubic, by clipping.
@@ -1003,6 +1064,10 @@ Where the space's media folder is served from.
The named moves by name, as `enter="rise"` finds them.
### `SNAP_NEAR`
the most a clip is moved to clear its ends (s): the sound pack's NEAR, where it looks for a gap
### `SPACE_KEY`
The prefix of the key the app holds on the stage for each panel that publishes (`data-feed-publish` on an element):
@@ -1637,6 +1702,10 @@ A control as a registered composition holds it: its cost said.
type RegisteredControl = Control & { cost: ControlCost }
```
### `SafeAreaProps`
The props of [`SafeArea`](#safearea), tabled there.
### `SequenceLayout`
```ts
@@ -1660,6 +1729,22 @@ The props of [`Sequence`](#sequence), tabled there.
| `width` | `number` | the width its children see, px (the parent's by default) |
| `durationInFrames` | `number` | how many frames it shows its children (forever by default) |
### `Snap`
What snapping a clip did: `by` seconds (0 when it stays), the ends it moved off words, and the ends it couldn't.
```ts
type Snap = { by: number; moved: SnapMove[]; left: { edge: "in" | "out"; at: number; word: string }[] }
```
### `SnapMove`
One move of a clip's end: where it was, where it went, and the word it cut.
```ts
type SnapMove = { edge: "in" | "out"; from: number; to: number; word: string; wordFrom: number; wordTo: number }
```
### `Snapshot`
The machine's runtime state, kept in the context it drives. `path` is the active states outermost first ([] before
@@ -1933,6 +2018,14 @@ On or off: a boolean.
| `cost` | `ControlCost` | how a change reaches the picture: "live" unless said |
| `about` | `string` | one line on what it changes, for the panel's tooltip and an agent reading the code |
### `TakeWord`
a word of a take, in seconds
```ts
type TakeWord = { text: string; start: number; end: number }
```
### `TextControl`
A string: a title, a caption, a name.
@@ -2024,6 +2117,41 @@ A target's name alone, one transition, or several checked in order.
type Transitions = | NoInfer<N> | TransitionConfig<C, E, N> | readonly (NoInfer<N> | TransitionConfig<C, E, N>)[]
```
### `UiPlatform`
The platform the cut is for: each draws its UI in a different place. None: the strictest of them, which is what the
floor checks when the brief names no platform.
```ts
type UiPlatform = "tiktok" | "reels" | "shorts"
```
### `UiShape`
The frame's shape; by default the nearest to its width over height.
```ts
type UiShape = "9:16" | "4:5" | "1:1" | "16:9"
```
### `UiZoneOptions`
| Field | Type | What it is |
| --- | --- | --- |
| `platform` | `UiPlatform` | the platform's own zones (tiktok, reels, shorts); none: the strictest |
| `shape` | `UiShape` | the shape to take the zones of; by default the nearest to width / height |
### `UiZones`
How far in from each edge of the frame the app's UI reaches, in the composition's px.
| Field | Type | What it is |
| --- | --- | --- |
| `top` (required) | `number` | the status bar and the app's top tabs |
| `right` (required) | `number` | the like, comment and share buttons |
| `bottom` (required) | `number` | the app's own caption, sound name and bar |
| `left` (required) | `number` | the edge's margin |
### `UseSongOptions`
| Field | Type | What it is |
+5 -2
View File
@@ -79,7 +79,8 @@ Shifts time by `from` and shows its children only for `durationInFrames` frames.
### `Series`
Plays its Series.Sequence children back to back, each shifted by its own offset.
Plays its Series.Sequence children back to back, each shifted by its own offset; the talking clips in them are moved
off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -87,13 +88,15 @@ Plays its Series.Sequence children back to back, each shifted by its own offset.
### `Video`
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show.
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. On a talking take its
ends are moved off words (`snap`).
| Prop | Type | What it does |
| --- | --- | --- |
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](#mediaprops).
-80
View File
@@ -1,80 +0,0 @@
// pace.ts on made-up words and levels: a short run between two long pauses joins a neighbour; level evening measures
// only clips with a second of speech and gives a short clip its own take's gain
import { expect, test } from "bun:test";
import { evenLevels, linesIn, pace, unsqueezed, type Levels } from "../src/pace";
/** levels at 10 ms: speech (-20 dB) inside each word, quiet (-70 dB) elsewhere, over `seconds` */
function levels(ws: { from: number; to: number }[], seconds: number): Levels {
const db = Array.from({ length: Math.round(seconds * 100) }, (_, i) => (ws.some((w) => i / 100 >= w.from && i / 100 < w.to) ? -20 : -70));
return { start: 0, db };
}
test("a word alone between two long pauses joins a neighbour instead of flicking by", () => {
const ws = [
{ text: "Sounds", from: 0.5, to: 0.9 },
{ text: "great.", from: 0.95, to: 1.4 },
// 0.7 s pause
{ text: "Available", from: 2.1, to: 2.55 },
// 0.6 s pause
{ text: "times", from: 3.15, to: 3.5 },
{ text: "the", from: 3.55, to: 3.7 },
{ text: "same", from: 3.75, to: 4.0 },
{ text: "day.", from: 4.05, to: 4.5 },
];
const { pieces, trims } = pace(ws, levels(ws, 6), [[0, 6]], { hook: 0 });
expect(pieces.length).toBe(2);
for (const p of pieces) expect(ws[p.words[1]].to - ws[p.words[0]].from).toBeGreaterThanOrEqual(0.8);
// the shorter pause (after "Available") is the one kept; the longer one is still cut
expect(pieces[1].words[0]).toBe(2);
expect(trims.filter((t) => t.kind === "pause").length).toBe(1);
});
test("a clip too short to measure takes its own take's gain, and gain stays within 9 dB", () => {
const clips = [
{ take: "A", file: "A.mp4", from: 0, to: 3, line: "a" },
{ take: "A", file: "A.mp4", from: 4, to: 4.5, line: "b" },
{ take: "B", file: "B.mp4", from: 0, to: 3, line: "c" },
{ take: "C", file: "C.mp4", from: 0, to: 3, line: "d" },
];
const lv: Record<string, { db: number; seconds: number }> = { a: { db: -30, seconds: 2.5 }, b: { db: -45, seconds: 0.4 }, c: { db: -18, seconds: 2.5 }, d: { db: -18, seconds: 2.5 } };
const out = evenLevels(clips, (c) => lv[c.line]);
expect(out[0].gainDb).toBe(9);
expect(out[1].gainDb).toBe(9);
expect(out[2].gainDb).toBeUndefined();
});
test("a line stopping mid-sentence with no pause runs on to its sentence's end; a tight seam never crosses a word", () => {
const ws = [
{ text: "get", from: 0.5, to: 0.66 },
{ text: "them", from: 0.66, to: 0.82 },
{ text: "delivered", from: 0.82, to: 1.06 },
{ text: "for", from: 1.06, to: 1.22 },
{ text: "free?", from: 1.22, to: 1.46 },
// a pause, then the next sentence
{ text: "Uh", from: 2.0, to: 2.3 },
{ text: "sounds", from: 2.3, to: 2.6 },
];
// the sound of "for" starts 60 ms after its transcript time, so halfway between the sounds would be inside it
const l = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 1.46 }, { from: 2.0, to: 2.6 }], 3.5);
const { pieces } = pace(ws, l, [[0, 2]], { hook: 0 });
expect(pieces.length).toBe(1);
expect(pieces[0].words).toEqual([0, 4]);
expect(pieces[0].to).toBeGreaterThanOrEqual(1.46);
// a line ending where the sentence goes on for more than three words is cut at the boundary, not inside the next word
const long = [...ws.slice(0, 3), { text: "for", from: 1.06, to: 1.22 }, { text: "all", from: 1.22, to: 1.4 }, { text: "your", from: 1.4, to: 1.55 }, { text: "pets", from: 1.55, to: 1.8 }, { text: "today.", from: 1.8, to: 2.2 }];
const l2 = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 2.2 }], 3);
const r = pace(long, l2, [[0, 2]], { hook: 0 });
expect(r.pieces[0].to).toBeLessThanOrEqual(1.06 + 1 / 30);
});
test("a phrase a transcriber heard twice and squeezed into one instant is dropped, and the line is found where it was said", () => {
// 12-05, run 28: "Sign up for the news, sign up for the newsletter", with "up for the news sign" all at 10.32-10.34 s
const w = (text: string, a: number, b: number) => ({ text, from: a / 1000, to: b / 1000 });
const heard = [w("for", 9280, 9360), w("the", 9360, 9440), w("newsletter.", 9440, 9460), w("Sign", 10080, 10320), w("up", 10320, 10340), w("for", 10320, 10340), w("the", 10320, 10340), w("news", 10320, 10340), w("sign", 10320, 10340), w("up", 10320, 10400), w("for", 10400, 10560), w("the", 10560, 10640), w("newsletter", 10640, 10960)];
const ws = unsqueezed(heard);
expect(ws.map((x) => x.text).join(" ")).toBe("for the newsletter. Sign up for the newsletter");
const { spans } = linesIn(ws, ["sign up for the newsletter"]);
expect(ws[spans[0][0]].from).toBe(10.08);
// two short words together are speech, kept
expect(unsqueezed([w("a", 0, 20), w("cat", 20, 40), w("sat", 300, 500)]).length).toBe(3);
});
-38
View File
@@ -255,44 +255,6 @@ ${Array.from({ length: 40 }, (_, i) => `.u${i} { margin: ${i}px; }`).join("\n")}
}
});
// a take's jump cuts read through the ffmpeg CLI (cutplan.ts ffmpegCuts): where raea media cuts finds them
test.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)("raea cut reads a take's jump cuts through ffmpeg, where the engine finds them", async () => {
const { ffmpegCuts } = await import("../src/cutplan.ts");
const dir = mkdtempSync(join(tmpdir(), "raea-ffcuts-"));
try {
const color = (c: string) => ["-f", "lavfi", "-i", `color=c=${c}:s=320x180:r=30:d=2`];
spawnSync("ffmpeg", ["-v", "error", "-y", ...color("red"), ...color("blue"), ...color("green"), "-filter_complex", "[0][1][2]concat=n=3:v=1:a=0", "-c:v", "libx264", "-pix_fmt", "yuv420p", join(dir, "t.mp4")]);
expect(ffmpegCuts(join(dir, "t.mp4"), 0.08)).toEqual([2, 4]);
expect(ffmpegCuts(join(dir, "missing.mp4"), 0.08)).toBeNull();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// raea cloud's footage/faces.json (prep's faces, found on its farm): perception.json takes each clip's face from it,
// with no still and no raea-perceive (a box has none). A made clip and made-up faces, never real footage
test.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)("raea cut takes each clip's face from footage/faces.json", () => {
const dir = mkdtempSync(join(tmpdir(), "raea-cut-faces-"));
const run = (...a: string[]) => spawnSync("bun", [join(here, "src/native.ts"), bin, ...a], { cwd: dir, encoding: "utf8", env: { ...process.env, RAEA_PERCEIVE: "/nonexistent/raea-perceive" } });
try {
mkdirSync(join(dir, "media"));
mkdirSync(join(dir, "footage"));
spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x120:r=30:d=4", "-c:v", "libx264", "-pix_fmt", "yuv420p", join(dir, "media/take01.mp4")]);
const said: [string, number, number][] = [["Hello", 200, 600], ["there.", 650, 1000], ["This", 1500, 1700], ["is", 1750, 1850], ["the", 1900, 2000], ["second", 2100, 2500], ["line.", 2550, 2900]];
writeFileSync(join(dir, "media/take01.words.json"), JSON.stringify(said.map(([text, start_ms, end_ms]) => ({ text, start_ms, end_ms }))));
// no face by the first clip's middle (0.6 s, nearest 1 s); two at 2 s, by the second's (2.4 s): the larger is kept
const face = [0.25, 0.25, 0.5, 0.5, 0.9];
writeFileSync(join(dir, "footage/faces.json"), JSON.stringify({ take01: { w: 160, h: 120, t: [0, 1, 2, 3], s: [[], [], [[0.1, 0.1, 0.1, 0.1, 0.99], face], [face]] } }));
const r = run("cut", "take01", "hello there", "the second line");
expect(r.stderr).toBe("");
const band = { safe: { top: 220, bottom: 1500 } };
// 160x120 covering 1080x1920 is 16x, centred: x 0.25*160*16 - 740, y 0.25*120*16, w 0.5*160*16, h 0.5*120*16
expect(JSON.parse(readFileSync(join(dir, "perception.json"), "utf8"))).toEqual({ "0": band, "33": { ...band, face: { x: -100, y: 480, w: 1280, h: 960 } } });
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// a stock talking take (fixtures/CREDITS.md): the face branch of frame and perception.json. The footage fixtures are
// the maintainers' (tools/public-first/private.paths), so a checkout without them skips this
test.skipIf(!existsSync(join(raea, "engine/media/fixtures")))("raea frame and raea cut find the face in a talking take", () => {
+9 -21
View File
@@ -9,27 +9,13 @@ use std::path::Path;
/// `raea goal`'s verbs (docs/goal.feature): the loop's runner, sdk/goal/src/run.ts, run here on raea's JavaScriptCore
/// with Node's core. `goal gates` (the record and critic gates the packs read) is apps/make's, and `goal next` this
/// binary's own (next()).
pub const GOAL_TS: &[&str] = &["check", "tasks"];
/// Verbs that asked a model for its opinion of the work, or the agent to say it looked (docs/check.feature): gone, and
/// said so with where their part went, so an old skill or AGENTS.md that names one is set right at once.
pub fn gone(args: &[String]) -> Option<String> {
let v = |i: usize| args.get(i).map(String::as_str);
let what = match (v(0), v(1)) {
(Some("ask"), _) => "raea ask",
(Some("judge"), _) => "raea judge",
(Some("goal"), Some("seen")) => "raea goal seen",
(Some("goal"), Some("judge")) => "raea goal judge",
(Some("goal"), Some("gates")) => "raea goal gates",
(Some("check"), _) if args.iter().any(|a| a == "--taste" || a == "--quick") => "raea check --taste",
_ => return None,
};
Some(format!("{what} is gone (docs/check.feature): `raea check` is the one check, and a render checks its own output at its end. How the work should look and sound is the raea skill's and its guides', read while you make it; nothing grades it after."))
}
pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
pub const GOAL_USAGE: &str = "raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (the one check (docs/check.feature): every rule each goal of brief.ts holds at that moment, real faults only, one line a rule a file; with no goal, the floor. A render runs it on its output at its end and keeps OUT.check.json beside it; publish and done read that and never run it again. review/goal.json; exit 1 on an error. `raea goal check` is its old name)
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
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\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
@@ -56,12 +42,14 @@ pub fn render_moment(args: &[String]) -> i32 {
a.extend(["--manifest".into(), m]);
}
match goal_run(&a) {
// an ERROR is a fault in the deliverable: fix its cause in the composition before this render is handed over
Ok(1) => 1,
Ok(1) => {
println!("fix every ERROR above, then render again");
1
}
Ok(_) => 0,
// no runner (an install without the SDK): the render stands, and says so
Err(e) => {
println!("raea check: {e}");
println!("raea goal check: {e}");
0
}
}
+13 -12
View File
@@ -204,17 +204,17 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "spec" {
return spec::spec_cli(&args[1..]);
}
// `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest)
if args[0] == "check" && args.iter().any(|a| a == "--quick") {
let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?;
println!("{report}");
std::process::exit(i32::from(bad));
}
// `hook [AGENT]`: every agent harness's tool hooks (A5d): raea show over Preview, the quick check after a save (SK10)
if args[0] == "hook" { return raea_app_check::hook::hook(&args[1..]); }
// `check [FILE...] [--at MOMENT]`: the one check (docs/check.feature), sdk/goal/src/run.ts; a model's opinion
// (`--taste`, `ask`, `judge`, `goal seen|judge`) is no check, and refused with where its part went
if let Some(why) = gone(args) { return Err(why); }
// `check EDIT.tsx|NAME.story.ts`: a project's own checks over a composition's frames or a story (DR4), before a
// render; the deliverables' check is the runner's
if args[0] == "check" && args[1..].iter().find(|a| !a.starts_with('-')).is_some_and(|a| a.ends_with(".tsx") || a.ends_with(".ts")) {
std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK));
}
if args[0] == "check" { return goal_ts(&[&["goal".to_string()], args].concat()); }
// `check PROJECT|EDIT.tsx`: every rule's check over the compositions' worlds (DR4); a video is the floor alone
if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) { std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK)); }
if args[0] == "check" { std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?)); }
if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)
if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)
if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)
@@ -280,12 +280,13 @@ pub fn run(args: &[String]) -> R<String> {
Some("gen") => return raea_app_tools::generate::generate(args),
// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())
Some(v) if SHELL.contains(&v) => return shell(args),
// `goal check|tasks` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal check` is `raea
// check`'s old name; `goal next` this binary's
// `goal check|tasks|seen|judge` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal gates`
// apps/make's; `goal next` this binary's
Some("goal") if args.get(1).is_some_and(|v| GOAL_TS.contains(&v.as_str())) => return goal_ts(args),
Some("make") if args.get(1).map(String::as_str) == Some("place") => return goal_ts(&[&["goal".to_string()], &args[1..]].concat()),
Some("goal") if args.get(1).map(String::as_str) == Some("gates") => return raea_app_make::cli(args),
Some("goal") if args.get(1).map(String::as_str) == Some("next") => return next(&args[2..]),
Some("goal") => return Err(format!("raea goal tasks|next (raea check checks the work)\n {GOAL_USAGE}")),
Some("goal") => return Err(format!("raea goal check|tasks|seen|judge|gates|next\n {GOAL_USAGE}")),
_ => if let Some(r) = raea_app_solid::verb(args) { return r }, // `solid info|view FILE.ts`, `judge DIR`, `ask FILE` (apps/solid)
}
// `master-gain BUNDLE.js DIR`: the gain and ceiling a composition's render masters its sound with, as JSON (live
-124
View File
@@ -1,124 +0,0 @@
// How raea cut times a take's lines: the take's light copy when raea cloud keeps one, its jump cuts (kept in raea's
// cache) and sound level, and pace.ts's timing, kept off the take's own jump cuts. native.ts gives it the engine.
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { basename, dirname } from "node:path";
import { levelsOf, linesIn, pace, wavSamples, type Levels, type PaceOptions, type Piece, type Trim, type Word } from "./pace";
/** what timing needs of the engine: a take's path, raea's commands (text and JSON), and whether a file is sound alone */
export type TakeIO = { at: (p: string) => string; engineRun: (a: string[]) => string; engineJson: (a: string[]) => any; isAudio: (f: string) => boolean };
const ms = (s: number) => Math.round(s * 1000) / 1000;
/** A take's jump cuts read through the ffmpeg CLI where there is one: its luma at 160x90, every frame, scored as raea
* media cuts scores them (ffmpeg's select scene: each frame's mean absolute difference from the last, less the
* difference before it, over 100). ffmpeg decodes on every core; the engine's own decoder on a Linux box is openh264 on
* one (12-05: 38 s for a 3.5-minute light copy, 66 s for a 6-minute one, against 4 s for ffmpeg), and a box step has
* 3 minutes. The small picture leaves a hard cut's score where it was and a frame's grain out. null where ffmpeg
* can't read it: the engine reads it then. */
export function ffmpegCuts(file: string, threshold: number): number[] | null {
const [w, h] = [160, 90];
const r = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-an", "-vf", `scale=${w}:${h}:flags=area,format=gray,showinfo`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 });
if (r.error || r.status !== 0 || !r.stdout?.length) return null;
// each frame's time, from showinfo's lines in order
const times = [...String(r.stderr).matchAll(/\bn:\s*\d+\s+pts:\s*-?\d+\s+pts_time:(-?[\d.]+)/g)].map((m) => Number(m[1]));
const n = w * h;
const frames = Math.floor(r.stdout.length / n);
if (!frames || times.length !== frames) return null;
const y = r.stdout as Buffer;
const out: number[] = [];
let prev = 0;
for (let f = 1; f < frames; f++) {
let sad = 0;
for (let i = f * n, j = (f - 1) * n, e = i + n; i < e; i++, j++) sad += Math.abs(y[i] - y[j]);
const mafd = sad / n;
const score = Math.min(Math.max(Math.min(mafd, Math.abs(mafd - prev)) / 100, 0), 1);
prev = mafd;
if (score > threshold) out.push(ms(times[f]));
}
return out;
}
/** cutPlan and takeLevels over `io`, each take's levels kept for the run */
export function timing({ at, engineRun, engineJson, isAudio }: TakeIO) {
/** The take to read for timing: its light copy when raea cloud keeps one (.raea-cloud/proxies/NAME.mp4 in the project,
* where the light copy goes once a render brings the original into footage/). Its words, pauses, level and jump cuts
* are the original's, read in a fraction of the time (12-05: a 4K original's jump cuts took over 10 minutes of a box's
* CPU, and a fix pass's `raea cut` ran out of time). */
function lightOf(file: string): string {
const name = basename(file).replace(/\.[^.]+$/, "");
const kept = `${process.cwd()}/.raea-cloud/proxies/${name}.mp4`;
return existsSync(kept) ? kept : file;
}
/** A take's own jump cuts (raea media cuts, every frame decoded: 43 s for a 4-minute take on a box), found once per take
* and kept by its path, size and time in raea's cache, so the second `raea cut` on a take doesn't decode it again
* (12-04: three cuts on one take in a step ran past a box step's 3 minutes, and the run stopped with nothing made) */
function jumpCuts(take: string): number[] {
const file = lightOf(at(take));
let kept = "";
try {
const s = statSync(file);
const dir = `${process.env.XDG_CACHE_HOME || `${homedir()}/.cache`}/raea/cuts`;
kept = `${dir}/${createHash("sha1").update(`${realpathSync(file)}|${s.size}|${s.mtimeMs}|0.08`).digest("hex")}.json`;
if (existsSync(kept)) return JSON.parse(readFileSync(kept, "utf8")) as number[];
} catch {
kept = "";
}
const cuts = ffmpegCuts(file, 0.08) ?? (engineJson(["media", "cuts", file, "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
if (kept)
try {
mkdirSync(dirname(kept), { recursive: true });
writeFileSync(kept, JSON.stringify(cuts));
} catch {
// a cache that can't be written costs the next cut the decode, nothing else
}
return cuts;
}
/** A take's sound level every 10 ms (raea media audio, 16 kHz mono), kept for this run */
const heardLevels = new Map<string, Levels>();
function takeLevels(take: string): Levels {
const had = heardLevels.get(take);
if (had) return had;
const dir = mkdtempSync(`${tmpdir()}/raea-levels-`);
try {
const wav = `${dir}/take.wav`;
engineRun(["media", "audio", lightOf(at(take)), "--rate", "16000", "--mono", "-o", wav]);
const { pcm, rate } = wavSamples(readFileSync(wav));
const l = { start: 0, db: levelsOf(pcm, rate) };
heardLevels.set(take, l);
return l;
} catch {
// a take with no sound to read is cut on its words alone
return { start: 0, db: [] };
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
/** Where to cut a take for each line (linesIn), timed by pace.ts in the quiet around each line's sound, a breath kept,
* long pauses, fillers and false starts taken out (unless `keep`), then off the take's own jump cuts. Pieces in the
* take's seconds, on the edit's frame grid. */
function cutPlan(take: string, ws: Word[], lines: string[], o: PaceOptions, start: number): { pieces: Piece[]; trims: Trim[]; notes: string[] } {
const { spans, notes } = linesIn(ws, lines);
// a sound-only take has no jump cuts to keep off
const cuts = isAudio(take) ? [] : jumpCuts(take);
const { pieces, trims } = pace(ws, takeLevels(take), spans, o, start);
const sf = 1 / (o.fps ?? 30);
for (const p of pieces) {
const [i, j] = p.words;
// a jump cut in the take near a join: start one frame after it (or end one before), never on it, or the other
// shot's last frame can show
const ca = cuts.find((c) => Math.abs(c - p.from) <= 0.25 && c <= ws[i].from + 0.05);
if (ca !== undefined && ca + sf > p.from) p.from = ms(Math.ceil((ca + sf) / sf) * sf);
const cb = cuts.find((c) => Math.abs(c - p.to) <= 0.25 && c >= ws[j].to - 0.05);
if (cb !== undefined && cb - sf < p.to) p.to = ms(Math.floor((cb - sf) / sf) * sf);
}
return { pieces, trims, notes };
}
return { cutPlan, takeLevels };
}
-37
View File
@@ -1,37 +0,0 @@
// A take's faces from raea cloud's footage/faces.json, for raea cut's perception.json (native.ts perception)
import { readFileSync } from "node:fs";
import { basename, extname } from "node:path";
type Box = { x: number; y: number; w: number; h: number };
/** footage/faces.json in the project (raea cloud's prep: each take's faces about once a second, found on its farm, as
* shares of the take's picture, [x, y, w, h, score] each), read once. A box has no raea-perceive, so a still per clip
* found no face there and cost each `raea cut --append` every earlier clip's lookup again (12-05: a step of 13 cuts ran
* past a box's 3 minutes, and no cut on a box had a face in its perception.json) */
let facesKept: Record<string, { w?: number; h?: number; t?: number[]; s?: number[][][] }> | null | undefined;
function facesFile() {
if (facesKept === undefined)
try {
facesKept = JSON.parse(readFileSync(`${process.cwd()}/footage/faces.json`, "utf8"));
} catch {
facesKept = null;
}
return facesKept;
}
/** The largest face at the sample of faces.json nearest `t` (never one more than 1.5 s away), with the take's size: a
* face, none there (face undefined), or null when faces.json doesn't hold the take */
export function faceKept(file: string, t: number): { face?: Box; sw: number; sh: number } | null {
const take = facesFile()?.[basename(file, extname(file))];
const ts = take?.t, ss = take?.s;
if (!take || !Array.isArray(ts) || !Array.isArray(ss) || !ts.length || !take.w || !take.h) return null;
let k = 0;
ts.forEach((x, i) => {
if (Math.abs(x - t) < Math.abs(ts[k] - t)) k = i;
});
if (Math.abs(ts[k] - t) > 1.5) return null;
const faces = (ss[k] ?? []).filter((f) => Array.isArray(f) && f.length >= 4);
if (!faces.length) return { sw: take.w, sh: take.h };
const [x, y, w, h] = faces.reduce((a, b) => (b[2] * b[3] > a[2] * a[3] ? b : a));
return { face: { x, y, w, h }, sw: take.w, sh: take.h };
}
+37 -71
View File
@@ -49,54 +49,26 @@ export interface Cut {
line: string;
/** a sound-only take's clip plays as <Audio> (#89); absent means video */
kind?: "video" | "audio";
/** what brings its speech to the cut's other lines (dB): raea cut evens them */
gainDb?: number;
/** it follows a clip of the same take with time skipped (a jump cut): the edit reframes it (punchIn(i)) */
jump?: boolean;
}
/** A cutaway: a picture laid over the join after clip `after`, `l` seconds over that clip's end (an L cut: its sound runs
* on under the cutaway) and `j` over the next one's start (a J cut: that line's sound starts under it). */
export interface Cutaway extends Cut {
after: number;
l: number;
j: number;
}
/** cuts.ts from the clips: data the edit imports (each take's file as a module, so the bundler finds the media). */
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }, cutaways: Cutaway[] = []): string {
const files = [...new Set([...clips, ...cutaways].map((c) => c.file))];
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }): string {
const files = [...new Set(clips.map((c) => c.file))];
const id = (f: string) => "m_" + f.replace(/\W/g, "_");
const more = (c: Cut) => `${c.gainDb ? `, gainDb: ${c.gainDb}` : ""}${c.jump ? ", jump: true" : ""}`;
const row = (c: Cut) => `{ take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")}${more(c)} }`;
const len = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
// a cutaway's first frame in the edit: the end of the clip it lies over, less its L part
const startOf = (x: Cutaway) => Math.max(0, clips.slice(0, x.after + 1).reduce((n, c) => n + len(c), 0) - Math.round(x.l * edit.fps));
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds, timed by their sound (a breath at each join,
// long pauses, fillers and false starts out), each one's gainDb evening its level with the others, and a jump cut (the
// same take with time skipped) marked jump. Re-run raea cut to change them, or edit by hand (the edit reads only this
// file). cuts.json beside it is the same list for raea's checks.
const rows = clips.map((c) => ` { take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")} },`);
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds. Re-run raea cut to change them, or edit
// by hand (the edit reads only this file). cuts.json beside it is the same list for raea's checks.
${files.map((f) => `import ${id(f)} from ${JSON.stringify("./" + f)};`).join("\n")}
export const edit = ${JSON.stringify(edit)};
export type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio"; gainDb?: number; jump?: boolean };
export type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio" };
export const cuts: Cut[] = [
${clips.map((c) => ` ${row(c)},`).join("\n")}
];
/** pictures laid over a join, muted (the clips' sound runs under them): \`start\` is the edit's frame each begins at */
export const cutaways: (Cut & { start: number })[] = [
${cutaways.map((x) => ` { ...${row(x)}, start: ${startOf(x)} },`).join("\n")}
${rows.join("\n")}
];
/** a clip's length in the edit's frames */
export const frames = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
/** the cuts end to end, in frames */
export const total = cuts.reduce((n, c) => n + frames(c), 0);
/** how far clip i is punched in: a jump cut alternates 1 and 1.15 along a run of them, so the picture reframes at each */
export const punchIn = (i: number) => {
let k = 0;
for (let n = i; n > 0 && cuts[n]?.jump; n--) k++;
return k % 2 ? 1.15 : 1;
};
`;
}
@@ -106,17 +78,20 @@ A video edit as a React + TypeScript project, rendered by raea.
- edit.tsx: the composition. Change anything: layout, timing, which component plays when.
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing
by hand, or captions and checks lose their timing). It times each clip by its sound: a breath at each join, long
pauses, fillers and false starts out, each clip's gainDb evening the voices, a jump cut marked for punchIn(i). components/: components you added (\`raea make component add\`), yours to change.
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from its site), loaded with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
(text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
font-brand-body) or --brand-* variables; never a colour from outside it. Size, weight, layout and motion are yours,
chosen against the brand's own best work.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\` renders, then checks the export once as it ends
(\`raea check\`: real faults only, each ERROR with its fix, kept as final.check.json; nothing runs it again). Fix the
ERRORs; a warning is a note for the person. \`raea render edit.tsx --at 105 -o review/stills/\` gives frame 105 to
look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); \`raea help\` lists the rest.
by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change.
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg),
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are
a start, not a limit.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
\`raea help\` lists the rest.
## raea (everything there is; import from "raea")
@@ -124,21 +99,19 @@ Time: useCurrentFrame() (frames, from 0 inside the nearest Sequence), useVideoCo
durationInFrames}, interpolate(frame, [in...], [out...], {extrapolateLeft, extrapolateRight: "clamp", easing}),
spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...).
Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequence durationInFrames>, <Loop>, <Freeze>.
Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
through components/Framed.tsx when the project has it (<Framed src startFrom endAt at? punchIn?>: the crop on the
person's face, from footage/faces.json; at picks a face), else an objectPosition you
measured on the take, never a guess. A cut of footage is composed whole with components/Cut.tsx when the project
has it: <Cut moments={fromCuts(cuts, edit.fps, punchIn)} said={words.json} keys? hook? bed? />, each moment's show
(speaker, two, product, broll, screen, wide, end) and who, asset or cta set by you; it frames, splits, places the
product clear of faces, captions every word, lays the music bed under the voices at the level the check wants, and ends on the brand's card. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
Media: <Video src startFrom endAt volume playbackRate muted framing="face" punchIn style> (framing="face" keeps the
eyes 38% down as the speaker moves; an objectPosition or transform turns it off), <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
<Img src>. Media files import as modules: import take from
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, effects, music), and make
it as \`raea guide sound\` says; narration is <Speech text start> from raea/speech. <Mix lufs ceiling> masters the sound.
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, score, effects); music,
where there is some, in Tone.js (import * as Tone from "raea/tone"), composed for the cut (a motif, chords that move,
a part with rhythm, ending on a cut; never a pad or drone by default): instruments in a Tone.Sampler playing Parts and
Sequences, the notes from a sample library (\`raea make sounds\`, \`raea guide sources\`) or, for a timbre no library has,
Tone.tokensynth("a bowed saw, close", ["C3", "C4", "C5"]); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
Placement: <Captions said?> (said: each cut's own words) captions in the brand's style; titles go in <Region
name="top" | "bottom" | "center" | "auto" | "full">. Both keep clear of faces and the app's buttons: never type a
text's top or left.
Placement: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and
the platforms' buttons; useRegion() gives its box.
Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
Not there: React hooks come from "react" (useMemo, useState), not from raea.
`;
@@ -313,19 +286,12 @@ export function raeaHandler(host?: Host, engine?: Engine) {
if (m) spans.push([Number(m[1]), Number(m[2])]);
}
});
const num = (name: string) => {
const v = flag(args, name);
return v === undefined || !Number.isFinite(Number(v)) ? undefined : Number(v);
};
const [take, ...lines] = clean(args.slice(1), "--at", "--j", "--breath");
const cutaway = args.includes("--cutaway");
if (!take || (!lines.length && !spans.length) || (cutaway && !spans.length))
return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append] [--cutaway [--j S]] [--breath S] [--keep-pauses] [--no-gain]\n`);
// a cutaway lies over the cut there is: it always appends
const saved: { cuts?: Cut[]; cutaways?: Cutaway[] } = (args.includes("--append") || cutaway) && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")) : {};
const r = ask("cut", { take, lines, spans, keep: saved.cuts ?? [], cutaways: saved.cutaways ?? [], cutaway, j: num("--j"), breath: num("--breath"), keepPauses: args.includes("--keep-pauses"), gain: !args.includes("--no-gain") }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; cutaways: Cutaway[]; words: unknown[]; perception?: unknown; said: string };
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit, r.cutaways));
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts, ...(r.cutaways.length ? { cutaways: r.cutaways } : {}) }, null, 2) + "\n");
const [take, ...lines] = clean(args.slice(1), "--at");
if (!take || (!lines.length && !spans.length)) return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append]\n`);
const prev: Cut[] = args.includes("--append") && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")).cuts : [];
const r = ask("cut", { take, lines, spans, keep: prev }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; words: unknown[]; perception?: unknown; said: string };
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit));
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts }, null, 2) + "\n");
await c.fs.writeFile(p("words.json"), JSON.stringify(r.words) + "\n");
// where the face and the safe band are in the edit, for <Region> and the checks (a host may not see faces)
if (r.perception) await c.fs.writeFile(p("perception.json"), JSON.stringify(r.perception) + "\n");
+3 -2
View File
@@ -37,8 +37,9 @@ pub fn main() -> i32 {
}
};
match args.first().map(String::as_str) {
// `floor VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3, as raea check's floor pack reads them
Some("floor") => raea_app_check::cli_with(&args[1..], Vec::new()),
// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3
// (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: `check` here)
Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") && raea_app_direction::check::of_video(&args[1..]) => raea_app_check::cli_with(&args[1..], Vec::new()),
// `ci …`: the gates' sound measurements and lightspeed's process measurements
Some("ci") => raea_app_ci::cli(&args[1..]),
_ => {
+83 -90
View File
@@ -10,9 +10,6 @@ import { basename, delimiter, dirname, extname } from "node:path";
import { brandKit, pixelsOf } from "./brand";
import { readSite, stylesOf } from "./scrape";
import { wordsOf } from "./heard";
import { evenLevels, unsqueezed, linesIn, markJumps, speechOf, toSound, type PaceOptions } from "./pace";
import { timing } from "./cutplan";
import { faceKept } from "./faces";
import { harness, library, show, task } from "./app";
import { fromCwd } from "./show";
import { clothesHost } from "./wardrobe";
@@ -46,21 +43,17 @@ const AUDIO = ["wav", "mp3", "m4a", "aac", "flac", "aif", "aiff", "ogg", "opus"]
const extOf = (f: string) => extname(f).slice(1).toLowerCase();
const isAudio = (f: string) => AUDIO.includes(extOf(f));
/** Every take under media/ and footage/ (not footage/originals/, which the render reads in its light copies' place): its
* path from the project's root */
/** Every take under media/: its path from the project's root */
function takes(): string[] {
const out: string[] = [];
const walk = (dir: string) => {
for (const e of existsSync(at(dir)) ? readdirSync(at(dir), { withFileTypes: true }) : []) {
const p = `${dir}/${e.name}`;
if (e.isDirectory()) {
if (p !== "footage/originals") walk(p);
} else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
if (e.isDirectory()) walk(p);
else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
}
};
// media/ is a project's own; footage/ is what raea cloud fetched (its light copies: originals/ follow on their own)
walk("media");
walk("footage");
return out.sort();
}
@@ -70,7 +63,7 @@ function takeOf(name: string): string {
const all = takes();
const bare = (p: string) => p.slice(0, p.length - extname(p).length);
const found = all.find((p) => p === t || bare(p) === t) ?? all.find((p) => basename(p) === t || basename(bare(p)) === t || p.endsWith(`/${t}`) || p.includes(`${t}/`));
if (!found) throw new Error(`no take "${name}" under media/ or footage/ (${all.join(", ") || "none"})`);
if (!found) throw new Error(`no take "${name}" under media/ (${all.join(", ") || "none"})`);
return found;
}
@@ -91,11 +84,9 @@ function words(take: string, hear = false): Word[] {
if (!hear) return [];
hearTake(take, file);
}
return unsqueezed(
(JSON.parse(readFileSync(file, "utf8")) as { text: string; start_ms: number; end_ms: number }[])
.filter((w) => w.text?.trim())
.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 })),
);
return (JSON.parse(readFileSync(file, "utf8")) as { text: string; start_ms: number; end_ms: number }[])
.filter((w) => w.text?.trim())
.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 }));
}
/** A tool a clean Mac lacks, found or installed once by raea's tools/ensure.sh (docs/app.feature AP6), which sits in
@@ -127,103 +118,107 @@ function hearTake(take: string, out: string) {
}
}
// how each line is timed (cutplan.ts): the light copy, the take's jump cuts and sound level, pace.ts
const { cutPlan, takeLevels } = timing({ at, engineRun, engineJson, isAudio });
/** Where to cut a take for each line: found word for word in its transcript, in order (a line that follows the last one
* in the take joins its clip), else where 70% of its words are said in a window its length (and a note says so); each
* cut inside the pauses around it, off the take's own jump cuts, on the take's frame grid. [from, to, said] in the
* take's seconds. */
function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, number, string][]; notes: string[] } {
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "");
const toks = ws.map((w) => norm(w.text).trim());
// a sound-only take has no jump cuts to keep off, and its grid is the edit's usual 30 (a probe has no video fps)
const cuts = isAudio(take) ? [] : (engineJson(["media", "cuts", at(take), "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
let from = 0;
const spans: [number, number][] = [];
const notes: string[] = [];
lines.forEach((line, k) => {
const want = norm(line).split(/\s+/).filter(Boolean);
if (!want.length) throw new Error(`line ${k + 1} is empty`);
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
const close = () => {
const n = want.length;
if (n < 3 || toks.length < n) return undefined;
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
let best = 0;
for (let i = 1; i <= toks.length - n; i++) {
const [s, b] = [score(i), score(best)];
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
}
return score(best) * 10 >= n * 7 ? best : undefined;
};
let exact: number | undefined;
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
const i = exact ?? close();
if (i === undefined) {
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(n, n + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
}
const j = Math.min(i + want.length - 1, toks.length - 1);
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(i, j + 1).map((w) => w.text).join(" ")}"`);
from = j + 1;
const last = spans[spans.length - 1];
if (last && last[1] + 1 === i) last[1] = j;
else spans.push([i, j]);
});
const sf = 1 / fps;
const plan = spans.map(([i, j], k): [number, number, string] => {
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
// transcript word ends run early: a generous tail (more on the last line), a short lead-in, both inside the pause
let a = ws[i].from - Math.min(before * 0.6, 0.12);
let b = ws[j].to + Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22);
// a jump cut in the take near a join: start one take frame after it (or end one before), never on it, or the
// other shot's last frame can show
const ca = cuts.find((c) => Math.abs(c - a) <= 0.25 && c <= ws[i].from + 0.05);
if (ca !== undefined) a = Math.max(a, ca + sf);
const cb = cuts.find((c) => Math.abs(c - b) <= 0.25 && c >= ws[j].to - 0.05);
if (cb !== undefined) b = Math.min(b, cb - sf);
return [Math.ceil(Math.max(a, 0) * fps) / fps, Math.floor(b * fps) / fps, ws.slice(i, j + 1).map((w) => w.text).join(" ")];
});
return { plan, notes };
}
/** A clip's length in the edit's frames: cuts.ts's `frames` */
const framesOf = (from: number, to: number, fps: number) => Math.max(1, Math.round((to - from) * fps));
const ms = (s: number) => Math.round(s * 1000) / 1000;
type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
/** a cutaway: a picture laid over the join after clip `after` (its index in the cut), `l` seconds over that clip's end
* (its sound runs on under it: an L cut) and `j` over the next one's start (whose sound starts under it: a J cut) */
type Cutaway = Clip & { after: number; l: number; j: number };
type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio" };
/** how `raea cut` is asked to cut */
type CutAsk = { take: string; lines: string[]; spans: number[][]; keep: Clip[]; cutaways?: Cutaway[]; cutaway?: boolean; j?: number; breath?: number; keepPauses?: boolean; gain?: boolean };
/** A take's words with their edges on their sound (pace.ts toSound): for the timeline's words, and a clip's level */
function heardWords(file: string): Word[] {
return toSound(words(file), takeLevels(file));
}
/** `raea cut`'s host step: the clips for the lines (or --at spans) paced (pace.ts), their levels evened and jump cuts
* marked, the words in the edit's frames, and what was cut */
function cut(a: CutAsk) {
/** `raea cut`'s host step: the clips for the lines (or --at spans), the words in the edit's frames, and what was cut */
function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[] }) {
const file = takeOf(a.take);
if (!a.lines.length && !a.spans.length) throw new Error(`cut needs lines ("what's said") or spans (--at A-B, in the take's seconds)`);
const edit = shape();
const stem = basename(file, extname(file));
const kind = isAudio(file) ? "audio" as const : "video" as const;
let clips: Clip[] = [...a.keep];
const cutaways: Cutaway[] = [...(a.cutaways ?? [])];
const seconds = (cs: Clip[]) => cs.reduce((n, c) => n + framesOf(c.from, c.to, edit.fps), 0) / edit.fps;
// the breath kept at a join: 40% before a line's first sound, 60% after its last
const b = a.breath;
const o: PaceOptions = { fps: edit.fps, keepPauses: a.keepPauses, ...(b !== undefined ? { lead: b * 0.4, tail: b * 0.6, sentence: b * 0.6 + 0.08 } : {}) };
const notes: string[] = [];
let trims: Trim[] = [];
let before = 0;
const clips: Clip[] = [...a.keep];
let notes: string[] = [];
if (a.lines.length) {
const r = cutPlan(file, words(file, true), a.lines, o, seconds(clips));
notes.push(...r.notes);
trims = r.trims;
// what the lines would have run to cut as said, from each one's first word to its last
const ws = heardWords(file);
before = linesIn(ws, a.lines).spans.reduce((n, [i, j]) => n + ws[j].to - ws[i].from + 0.4, 0);
for (const p of r.pieces) {
clips.push({ take: stem, file, from: ms(p.from), to: ms(p.to), line: p.line, kind });
if (p.tight) notes.push(`"${p.line.slice(0, 40)}" has no pause at one end (its words run on): that end is cut between two words; look at it`);
}
const r = cutPlan(file, words(file, true), a.lines);
notes = r.notes;
for (const [from, to, line] of r.plan) clips.push({ take: stem, file, from: ms(from), to: ms(to), line, kind });
}
const { dur } = probeOf(file);
for (const [s, e] of a.spans) {
const [from, to] = [Math.max(s, 0), dur > 0 ? Math.min(e, dur) : e];
if (!(to > from)) throw new Error(`the span ${s}-${e} is outside ${file} (${dur.toFixed(1)} s)`);
if (a.cutaway) {
const k = clips.length - 1;
if (k < 0) throw new Error("a cutaway is laid over the cut's clips: cut a line first, then the cutaway with --append");
const j = Math.min(Math.max(a.j ?? 0, 0), to - from);
const l = ms(to - from - j);
if (l > clips[k].to - clips[k].from) throw new Error(`the cutaway runs ${l.toFixed(2)} s over the last clip's end, and it's ${(clips[k].to - clips[k].from).toFixed(2)} s long: give it less, or --j to put some over the next line`);
cutaways.push({ take: stem, file, from: ms(from), to: ms(to), line: "", kind: "video", after: k, l, j: ms(j) });
continue;
}
const line = heardWords(file).filter((w) => w.from >= from - 0.02 && w.to <= to + 0.08).map((w) => w.text).join(" ");
const line = words(file).filter((w) => w.from >= from - 0.02 && w.to <= to + 0.08).map((w) => w.text).join(" ");
clips.push({ take: stem, file, from: ms(from), to: ms(to), line, kind });
}
// a jump cut is hidden by a cutaway over its join; the rest are marked for the edit to reframe
clips = markJumps(clips, edit.fps).map((c, k) => (c.jump && cutaways.some((x) => x.after === k - 1) ? (({ jump: _, ...r }) => r)(c) : c));
if (a.gain !== false)
clips = evenLevels(clips, (c) => {
const inside = heardWords(c.file).filter((w) => w.to > c.from && w.from < c.to).map((w) => ({ ...w, from: Math.max(w.from, c.from), to: Math.min(w.to, c.to) }));
return inside.length ? { db: speechOf(takeLevels(c.file), inside), seconds: inside.reduce((n, w) => n + w.to - w.from, 0) } : null;
});
// the words in the edit's frames, for captions (useWords()): each word that sounds inside its clip
// the words in the edit's frames, for captions (useWords())
let t = 0;
const timeline: { text: string; from: number; to: number }[] = [];
const said: string[] = [];
clips.forEach((c, k) => {
const n = framesOf(c.from, c.to, edit.fps);
const f = (s: number) => t + Math.round((s - c.from) * edit.fps);
for (const w of heardWords(c.file)) if ((w.from + w.to) / 2 >= c.from && (w.from + w.to) / 2 <= c.to) timeline.push({ text: w.text, from: Math.max(f(w.from), t), to: Math.max(Math.min(f(w.to), t + n), Math.max(f(w.from), t) + 1) });
const marks = [c.jump ? "jump" : "", c.gainDb ? `${c.gainDb > 0 ? "+" : ""}${c.gainDb} dB` : ""].filter(Boolean).join(", ");
said.push(`${String(k + 1).padStart(2)} ${(t / edit.fps).toFixed(2).padStart(5)}-${((t + n) / edit.fps).toFixed(2).padStart(5)} s ${c.take} "${c.line}"${marks ? ` (${marks})` : ""}`);
for (const w of words(c.file)) if (w.from >= c.from - 0.02 && w.to <= c.to + 0.08) timeline.push({ text: w.text, from: Math.max(f(w.from), t), to: Math.max(Math.min(f(w.to), t + n), f(w.from) + 1) });
said.push(`${String(k + 1).padStart(2)} ${(t / edit.fps).toFixed(2).padStart(5)}-${((t + n) / edit.fps).toFixed(2).padStart(5)} s ${c.take} "${c.line}"`);
t += n;
});
for (const x of cutaways) said.push(` cutaway ${x.take} ${x.from.toFixed(2)}-${x.to.toFixed(2)} s over the join after clip ${x.after + 1}: ${x.l.toFixed(2)} s before it${x.j ? `, ${x.j.toFixed(2)} s after` : ""}`);
const cutOut = trims.filter((x) => x.kind !== "pause");
const pauses = trims.filter((x) => x.kind === "pause");
const paced = [
pauses.length ? `${pauses.length} long pause${pauses.length === 1 ? "" : "s"} cut to a breath (${pauses.reduce((n, x) => n + x.seconds, 0).toFixed(1)} s out)` : "",
...cutOut.map((x) => `${x.kind} "${x.said}" at ${x.at.toFixed(2)} s out`),
].filter(Boolean);
const head = `cuts.ts: ${clips.length} clips, ${(t / edit.fps).toFixed(1)} s (${t} frames at ${edit.fps} fps)${before ? `; the lines as said ran ${before.toFixed(1)} s` : ""}; words.json for captions`;
const tail = [
...(paced.length ? [`paced: ${paced.join("; ")} (--keep-pauses keeps them)`] : []),
...(clips.some((c) => c.jump) ? ["jump: a clip marked jump follows the same take with its time skipped: reframe it (punchIn(i) in cuts.ts), or lay a cutaway over the join"] : []),
];
return { edit, cuts: clips, cutaways, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...tail, ...notes.map((n) => `note: ${n}`)].join("\n") };
const head = `cuts.ts: ${clips.length} clips, ${(t / edit.fps).toFixed(1)} s (${t} frames at ${edit.fps} fps); words.json for captions`;
return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") };
}
/** raea-perceive, as `raea song` finds it (raea-io-assets perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
@@ -278,10 +273,8 @@ function perception(edit: { width: number; height: number; fps: number }, clips:
if (!seen.has(key)) {
let face: Box | undefined;
try {
// faces.json's when it holds the take, else a still of it read here
const kept = faceKept(c.file, mid);
const f = kept ? kept.face : faceAt(c.file, mid);
const { sw, sh } = kept ?? probeOf(c.file);
const f = faceAt(c.file, mid);
const { sw, sh } = probeOf(c.file);
if (f && sw && sh) {
const s = Math.max(edit.width / sw, edit.height / sh);
const [ox, oy] = [(edit.width - sw * s) / 2, (edit.height - sh * s) / 2];
-451
View File
@@ -1,451 +0,0 @@
// The timing of `raea cut` (12-05, Shane: "when we assemble the clips or video footage we should be hyper focused on
// framing and timing. both seem to go wayside or not even done ... it could be done procedurally"). The agent chooses
// the lines and their order; this times them, from the take's words and its sound level every 10 ms, as a short-form
// editor would (auto-editor's dead-space pass, a breath kept at each join, loudness matched per line):
//
// toSound each word's edges moved onto its sound: a transcriber's word times run into the pauses around it
// (parakeet's 80 ms frames: "question?" timed 2.88-4.16 s and said 2.63-3.18 s), so a cut on them keeps
// dead air, and captions show a word after it's said
// joins every cut point sits in quiet by the sound check's own measure (sdk/goal packs/sound.ts: 18 dB under the
// line's speech, or within 6 dB of a street's floor), a breath kept: ~0.06 s before a line's first sound,
// ~0.10 s after its last (0.18 s after a sentence's end), so the join between two lines is ~0.16-0.24 s
// pauses a pause inside a line longer than 0.45 s (0.3 s in the cut's first 3 s, the hook) is cut down to a breath
// fillers "um", "uh" and a false start ("I I think": the first "I") come out, only with quiet on both sides
// level each clip's gainDb brings its speech to the cut's median (the sound check errs at 6 dB apart)
// jump a clip that follows one of the same take with its time skipped is marked jump: the edit reframes it
//
// Pure: native.ts reads the words and levels and writes cuts.ts.
/** a word in its take's seconds */
export type Word = { text: string; from: number; to: number };
/** A transcript's words less the runs it squeezed: three or more words each SQUEEZED s long or less, all starting within
* 50 ms of the first. No one says three words in 50 ms; a transcriber writes them when it hears a phrase twice and
* times the copy at one instant (12-05, run 28: Body Shop's "Sign up for the news, sign up for the newsletter" came
* as "Sign up for the news sign up for the newsletter" with "up for the news sign" all at 10.32-10.34 s, raea cut took
* the line from that "sign", and the CTA clip started inside "up") */
export const SQUEEZED = 0.03;
export function unsqueezed<W extends Word>(ws: W[]): W[] {
const out: W[] = [];
for (let i = 0; i < ws.length; ) {
let j = i;
while (j < ws.length && ws[j].to - ws[j].from <= SQUEEZED && ws[j].from - ws[i].from <= 0.05) j++;
if (j - i >= 3) i = j;
else out.push(ws[i++]);
}
return out;
}
/** a take's sound level every 10 ms (dB), from `start` seconds */
export type Levels = { start: number; db: number[] };
/** a stretch of quiet in a take: from its first quiet 10 ms to the first sound after it (s) */
export type Gap = { from: number; to: number };
export interface PaceOptions {
/** the edit's frame rate: every cut point lands on its grid (30) */
fps?: number;
/** what's kept before a line's first sound (s): 0.06 */
lead?: number;
/** what's kept after a line's last sound (s): 0.10, so a join keeps ~0.16 s of breath */
tail?: number;
/** after a sentence's end (. ? !): 0.18 */
sentence?: number;
/** a pause inside a line longer than this is cut down to a breath (s): 0.45 */
pause?: number;
/** in the cut's first `hook` seconds: 0.3 */
hookPause?: number;
hook?: number;
/** pauses inside lines, fillers and false starts left as they are */
keepPauses?: boolean;
}
const DEFAULTS = { fps: 30, lead: 0.06, tail: 0.1, sentence: 0.18, pause: 0.45, hookPause: 0.3, hook: 3, keepPauses: false };
/** as the sound check measures (packs/sound.ts): speech is its loud 10 ms frames (90th percentile), a take's floor its
* quietest (10th), and quiet is 18 dB under the speech, or within 6 dB of the floor, never closer than 8 to the speech */
const SPEECH_Q = 0.9;
const FLOOR_Q = 0.1;
export const quietUnder = (floor: number, ref: number) => Math.min(ref - 8, Math.max(ref - 18, floor + 6));
/** the fewest quiet frames that make a gap: a cut point needs 20 ms of quiet either side (the check's 40 ms peak) */
const LEAST = 5;
/** a word's edge is moved onto its sound past this much quiet (s): a shorter quiet is a stop inside the word */
const TRIM = 0.12;
/** the least speech a clip cut out of a line holds (s): shorter, it joins its neighbour and keeps the pause */
const MIN_RUN = 0.8;
/** the least quiet after a word that is a pause a line can end in (s): shorter is a breath inside a sentence */
const PAUSE_MIN = 0.15;
/** the least speech a clip's level is measured on (s), and the most gain evening gives (dB) */
const MEASURE = 1;
const MOST_GAIN = 9;
export const pct = (xs: number[], q: number) => {
if (!xs.length) return -100;
const s = [...xs].sort((a, b) => a - b);
return s[Math.min(s.length - 1, Math.floor(q * s.length))];
};
const idx = (l: Levels, t: number) => Math.round((t - l.start) * 100);
const dbAt = (l: Levels, i: number) => l.db[i] ?? -100;
const span = (l: Levels, a: number, b: number) => l.db.slice(Math.max(0, idx(l, a)), Math.max(0, idx(l, b)));
/** speech's level over words: their loud frames */
export function speechOf(l: Levels, ws: Word[]): number {
return pct(ws.flatMap((w) => span(l, w.from, w.to)), SPEECH_Q);
}
/** the level under which a stretch around [a, b] is quiet, for speech at `ref` */
export function underAt(l: Levels, a: number, b: number, ref: number): number {
return quietUnder(pct(span(l, a - 0.5, b + 0.5), FLOOR_Q), ref);
}
/** the quiet stretches of LEAST frames or more in [a, b] */
export function gapsIn(l: Levels, under: number, a: number, b: number): Gap[] {
const out: Gap[] = [];
let run = -1;
const i0 = Math.max(0, idx(l, a));
const i1 = Math.min(l.db.length, idx(l, b));
for (let i = i0; i <= i1; i++) {
const quiet = i < i1 && dbAt(l, i) <= under;
if (quiet && run < 0) run = i;
if (!quiet && run >= 0) {
if (i - run >= LEAST) out.push({ from: l.start + run / 100, to: l.start + i / 100 });
run = -1;
}
}
return out;
}
const r3 = (t: number) => Math.round(t * 1000) / 1000;
/** words with their edges moved onto their sound: a word's start later past quiet it was timed into, its end earlier;
* never shorter than 80 ms (a word the levels don't hear keeps its times). Speech is each word's neighbourhood's. */
export function toSound(ws: Word[], l: Levels): Word[] {
if (!l.db.length) return ws.map((w) => ({ ...w }));
return ws.map((w) => {
const ref = pct(span(l, w.from - 1, w.to + 1), SPEECH_Q);
const under = underAt(l, w.from, w.to, ref);
const loud = (i: number) => dbAt(l, i) > under;
let a = idx(l, w.from);
let b = idx(l, w.to) - 1;
let a1 = a;
while (a1 <= b && !loud(a1)) a1++;
let b1 = b;
while (b1 >= a1 && !loud(b1)) b1--;
const at = (i: number, k: number) => ({ text: w.text, from: r3(l.start + i / 100), to: r3(l.start + k / 100) });
// under 80 ms of sound: a word timed past its sound (parakeet put "that?" at 23.68-24.40 s, said by 23.68), so it
// sits on the sound it has, or the sound it touches; a word with neither keeps its times (whispered, or masked)
if (b1 - a1 < 7) {
if (b1 >= a1) return at(Math.max(a, a1 - 2), Math.min(b + 1, Math.max(b1 + 3, a1 + 8)));
if (loud(a - 1)) return at(a, Math.min(b + 1, a + 8));
if (loud(b + 1)) return at(Math.max(a, b - 7), b + 1);
return { ...w };
}
// a stretch of quiet shorter than TRIM at an edge is the word's own (a stop, a soft consonant): kept
if ((a1 - a) / 100 >= TRIM) a = a1 - 2;
if ((b - b1) / 100 >= TRIM) b = b1 + 2;
return { text: w.text, from: r3(l.start + a / 100), to: r3(l.start + (b + 1) / 100) };
});
}
const FILLERS = new Set(["um", "umm", "uh", "uhm", "uhh", "erm", "er", "ah", "hmm", "mm", "mhm"]);
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "");
const endsSentence = (s: string) => /[.?!]["')\]]*$/.test(s.trim());
/** a stretch of a take a cut keeps: its words [first, last] (indexes into the take's words) and its in and out (s) */
export type Piece = { words: [number, number]; from: number; to: number; line: string; jump?: boolean; gainDb?: number; tight?: boolean };
/** What's cut out of a line, said: a filler or a false start, or a pause made shorter. */
export type Trim = { kind: "filler" | "false start" | "pause"; at: number; seconds: number; said: string };
/** The pieces a run of lines keeps, in order, each line given as its words [first, last] in the take, timed as above;
* `start` is where the first of them lands in the edit (s), for the hook's tighter pauses. */
export function pace(ws0: Word[], l: Levels, lines: [number, number][], o: PaceOptions = {}, start = 0): { pieces: Piece[]; trims: Trim[] } {
const p = { ...DEFAULTS, ...o };
const ws = toSound(ws0, l);
const n = ws.length;
const trims: Trim[] = [];
const pieces: Piece[] = [];
let t = start;
const grid = (x: number, lo: number, hi: number) => {
// the edit's frame nearest x that keeps inside [lo, hi], else the nearest frame
const f = x * p.fps;
const c = [Math.round(f), Math.floor(f), Math.ceil(f)].map((k) => k / p.fps).filter((v) => v >= lo - 1e-6 && v <= hi + 1e-6);
return r3(c.length ? c[0] : Math.round(f) / p.fps);
};
for (const [i, j0] of lines) {
const ref = speechOf(l, ws.slice(i, j0 + 1));
const under = underAt(l, ws[i].from, ws[j0].to, ref);
const mid = (w: Word) => Math.min(0.1, (w.to - w.from) / 2);
/** the quiet between word k and k + 1 (k = -1: before the first; k = n - 1: after the last): the longest stretch */
const gapAfter = (k: number): Gap | null => {
const a = k < 0 ? Math.max(0, ws[0].from - 1) : ws[k].to - mid(ws[k]);
const b = k + 1 >= n ? ws[n - 1].to + 1 : ws[k + 1].from + mid(ws[k + 1]);
const gs = gapsIn(l, under, a, b);
if (!gs.length) return null;
if (k < 0) return gs[gs.length - 1];
if (k + 1 >= n) return gs[0];
return gs.reduce((x, y) => (y.to - y.from > x.to - x.from ? y : x));
};
// a cut between two words with no quiet between: halfway between their sounds, never past the transcript's own
// boundary (12-05: "delivered" and "for" touched at 99.12 s, the halfway of their sounds was 99.20 s, and the clip
// ended inside "for")
const seam = (k: number) => {
if (k < 0) return r3(Math.max(0, ws[0].from - 0.02));
if (k + 1 >= n) return r3(ws[n - 1].to + 0.02);
const mid = (ws[k].to + ws[k + 1].from) / 2;
const [lo, hi] = [ws0[k].to, ws0[k + 1].from];
if (lo > hi) return r3(hi);
// the quietest 10 ms between them, the nearest the middle on a tie: two words with no pause between still dip
// somewhere, and a cut halfway can land on the first one's tail (12-05: "platform." ran on to "Yeah" with no
// quiet, and the cut halfway was 5 dB under the speech, the word's tail cut)
let best = Math.min(hi, Math.max(lo, mid));
let low = Infinity;
for (let i = idx(l, lo); i <= idx(l, hi); i++) {
const t = l.start + i / 100;
const d = dbAt(l, i);
if (d < low - 0.5 || (Math.abs(d - low) <= 0.5 && Math.abs(t - mid) < Math.abs(best - mid))) {
if (d < low - 0.5) low = d;
best = t;
}
}
return r3(Math.min(hi, Math.max(lo, best)));
};
// a line that stops mid-sentence with no quiet after it ends where its sentence does, when that's three words or
// fewer and 0.8 s away (12-05: "...and get them delivered" ran straight into "for free?")
const pausesAfter = (k: number) => {
const g = gapAfter(k);
return !!g && g.to - g.from >= PAUSE_MIN;
};
let j = j0;
if (!endsSentence(ws[j].text) && !pausesAfter(j))
for (let e = j + 1; e < n && e <= j + 3 && ws[e].to - ws[j].to <= 0.8; e++)
if (endsSentence(ws[e].text) && pausesAfter(e)) {
j = e;
break;
}
// where to cut in before word k, and out after word k: in the quiet beside it, a breath from its sound
// never into the transcript's neighbour word, on the frame grid: the check reads the transcript's word times, so a
// cut in a short quiet its words don't have lands inside a word for it (12-05: "for" at 99.12 s, the cut at 99.20 s)
// and holding its own word whole by the transcript too (12-05: "Available" 171.84-172.24 s by its words, its sound
// over by 172.0 s, the cut at 172.03 s: inside the word for the check)
const fl = (t: number) => Math.floor(t * p.fps + 1e-6) / p.fps;
const ce = (t: number) => Math.ceil(t * p.fps - 1e-6) / p.fps;
const notBefore = (k: number, at: number) => r3(Math.max(Math.min(at, fl(ws0[k].from)), k > 0 ? ce(ws0[k - 1].to) : 0));
const notAfter = (k: number, at: number) => r3(Math.min(Math.max(at, ce(ws0[k].to)), k + 1 < n ? fl(ws0[k + 1].from) : Infinity));
const cutIn = (k: number) => {
const g = gapAfter(k - 1);
if (!g) return { at: notBefore(k, grid(seam(k - 1), 0, Infinity)), tight: true };
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
return { at: notBefore(k, grid(Math.min(hi, Math.max(lo, g.to - p.lead)), lo, hi)), tight: false };
};
const cutOut = (k: number) => {
const g = gapAfter(k);
if (!g) return { at: notAfter(k, grid(seam(k), 0, Infinity)), tight: true };
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
const keep = endsSentence(ws[k].text) ? p.sentence : p.tail;
return { at: notAfter(k, grid(Math.min(hi, Math.max(lo, g.from + keep)), lo, hi)), tight: false };
};
// the words kept: fillers and false starts with quiet both sides come out
const keep = new Array<boolean>(j - i + 1).fill(true);
const quietBoth = (a: number, b: number) => (a === i || gapAfter(a - 1) !== null) && (b === j || gapAfter(b) !== null);
if (!p.keepPauses) {
for (let k = i; k <= j; k++) {
if (FILLERS.has(norm(ws[k].text)) && j > i && quietBoth(k, k)) {
keep[k - i] = false;
trims.push({ kind: "filler", at: ws[k].from, seconds: r3(ws[k].to - ws[k].from), said: ws[k].text });
}
}
for (let k = i; k <= j; k++)
for (let m = 1; m <= 3 && k + 2 * m - 1 <= j; m++) {
const same = Array.from({ length: m }, (_, q) => norm(ws[k + q].text) === norm(ws[k + m + q].text) && norm(ws[k + q].text) !== "").every(Boolean);
if (same && keep[k - i] && quietBoth(k, k + m - 1)) {
for (let q = 0; q < m; q++) keep[k + q - i] = false;
trims.push({ kind: "false start", at: ws[k].from, seconds: r3(ws[k + m - 1].to - ws[k].from), said: ws.slice(k, k + m).map((w) => w.text).join(" ") });
break;
}
}
}
// runs of kept words, split again at a long pause (shorter in the hook: the cut's first seconds)
const runs: [number, number][] = [];
const paused = new Map<number, Trim>(); // the pause after word k, cut down
for (let k = i; k <= j; k++) {
if (!keep[k - i]) continue;
const last = runs[runs.length - 1];
const cut = last && last[1] === k - 1 && !p.keepPauses ? long(k - 1, t + ws[k - 1].to - ws[i].from) : null;
if (last && last[1] === k - 1 && !cut) last[1] = k;
else {
if (cut) paused.set(k - 1, cut);
runs.push([k, k]);
}
}
// a run under MIN_RUN of speech would flick by as a clip of its own (12-05: "Available", 0.47 s between two cut
// pauses): it keeps a pause and joins its neighbour across the shorter one
for (let r = 0; r < runs.length && runs.length > 1; r++) {
const [a, b] = runs[r];
if (ws[b].to - ws[a].from >= MIN_RUN) continue;
const left = r > 0 && runs[r - 1][1] === a - 1 ? paused.get(a - 1) : undefined;
const right = r + 1 < runs.length && runs[r + 1][0] === b + 1 ? paused.get(b) : undefined;
if (!left && !right) continue;
if (left && (!right || left.seconds <= right.seconds)) {
runs[r - 1][1] = b;
runs.splice(r, 1);
paused.delete(a - 1);
r = Math.max(-1, r - 2);
} else {
runs[r][1] = runs[r + 1][1];
runs.splice(r + 1, 1);
paused.delete(b);
r -= 1;
}
}
trims.push(...paused.values());
for (const [a, b] of runs) {
const ci = cutIn(a);
const co = cutOut(b);
if (co.at <= ci.at) continue;
pieces.push({ words: [a, b], from: ci.at, to: co.at, line: ws0.slice(a, b + 1).map((w) => w.text).join(" "), ...(ci.tight || co.tight ? { tight: true } : {}) });
t += co.at - ci.at;
}
/** the pause after word k is longer than the cut keeps there (`at`: where it falls in the edit) */
function long(k: number, at: number): Trim | null {
const g = gapAfter(k);
if (!g || g.to - g.from <= (at < p.hook ? p.hookPause : p.pause)) return null;
return { kind: "pause", at: r3(g.from), seconds: r3(g.to - g.from), said: `${ws[k].text} | ${ws[k + 1].text}` };
}
}
// two lines that follow each other in the take with a short pause between are one clip: no cut where none is needed
// (two cut points in a pause shorter than the breath they keep would play its middle twice)
for (let k = pieces.length - 1; k > 0; k--) {
const [a, b] = [pieces[k - 1], pieces[k]];
const between = b.from - a.to;
const inHook = pieces.slice(0, k).reduce((s, x) => s + x.to - x.from, start) < p.hook;
if (b.words[0] === a.words[1] + 1 && between <= (inHook ? p.hookPause : p.pause) - p.lead - p.tail) {
pieces.splice(k - 1, 2, { ...a, words: [a.words[0], b.words[1]], to: b.to, line: `${a.line} ${b.line}`, ...(a.tight || b.tight ? { tight: true } : {}) });
}
}
// a pause made shorter: what was taken out of it is the pause less what the two cuts keep
for (const x of trims) if (x.kind === "pause") x.seconds = r3(Math.max(0, x.seconds - p.lead - p.tail));
return { pieces, trims };
}
/** Which words of a take each line is: found word for word in its transcript, in order, else where 70% of its words
* are said in a window its length (and a note says so), that window's ends trimmed of words the line doesn't have (a
* filler before it, the next line's first word after it). Words are compared as letters and digits, a word's digits
* apart from its letters ("about$1,200." is "about 1200"). [first, last] word of each line, in the take's words. */
export function linesIn(ws: { text: string }[], lines: string[]): { spans: [number, number][]; notes: string[] } {
const parts = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "").replace(/(\p{L})(\p{N})|(\p{N})(\p{L})/gu, "$1$3 $2$4").split(/\s+/).filter(Boolean);
// the take's words as tokens, each with the word it's part of
const toks: string[] = [];
const owner: number[] = [];
ws.forEach((w, k) => parts(w.text).forEach((t) => (toks.push(t), owner.push(k))));
let from = 0;
const spans: [number, number][] = [];
const notes: string[] = [];
lines.forEach((line, k) => {
const want = parts(line);
if (!want.length) throw new Error(`line ${k + 1} is empty`);
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
const close = () => {
const n = want.length;
if (n < 3 || toks.length < n) return undefined;
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
let best = 0;
for (let i = 1; i <= toks.length - n; i++) {
const [s, b] = [score(i), score(best)];
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
}
return score(best) * 10 >= n * 7 ? best : undefined;
};
let exact: number | undefined;
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
let i = exact ?? close();
if (i === undefined) {
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(owner[n], owner[n] + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
}
let j = Math.min(i + want.length - 1, toks.length - 1);
if (exact === undefined) {
while (i < j && !want.includes(toks[i])) i++;
while (j > i && !want.includes(toks[j])) j--;
}
const [a, b] = [owner[i], owner[j]];
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(a, b + 1).map((w) => w.text).join(" ")}"`);
from = j + 1;
spans.push([a, b]);
});
return { spans, notes };
}
/** a clip as cuts.ts holds it */
export type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
/** each clip that follows another of the same take with its time skipped (forward or back): jump, so the edit reframes it
* (a punch-in, every other one, or a cutaway over the join); the rest lose the mark */
export function markJumps<C extends Clip>(clips: C[], fps = 30): C[] {
return clips.map((c, k) => {
const prev = clips[k - 1];
const { jump: _, ...rest } = c;
const jump = !!prev && prev.file === c.file && Math.abs(c.from - prev.to) > 1.5 / fps;
return (jump ? { ...rest, jump: true } : rest) as C;
});
}
/** the gainDb that brings each voice clip's speech to the clips' median, 1 dB or more off it, within +-MOST_GAIN dB.
* A level is measured only on MEASURE s of speech or more (one word's level is mostly its edges); a shorter clip takes
* the gain of the nearest measured clip of its own take, so one take never jumps in level at a join (12-05: a 0.47 s
* "Available" was given +12 dB between two clips at 0). `levelOf` gives a clip's speech level and its seconds of words. */
export function evenLevels<C extends Clip>(clips: C[], levelOf: (c: C) => { db: number; seconds: number } | null): C[] {
const lv = clips.map((c) => {
const x = c.to - c.from >= 0.4 ? levelOf(c) : null;
return x && x.db > -90 && x.seconds >= MEASURE ? x.db : null;
});
const known = lv.filter((x): x is number => x !== null);
if (known.length < 2) return clips;
const mid = pct(known, 0.5);
const gain = (k: number) => Math.max(-MOST_GAIN, Math.min(MOST_GAIN, Math.round((mid - (lv[k] as number)) * 2) / 2));
return clips.map((c, k) => {
const { gainDb: _, ...rest } = c;
let g: number | null = lv[k] !== null ? gain(k) : null;
if (g === null) {
// the nearest measured clip of the same take, either side
for (let d = 1; d < clips.length && g === null; d++)
for (const q of [k - d, k + d]) if (q >= 0 && q < clips.length && lv[q] !== null && clips[q].file === c.file && g === null) g = gain(q);
}
if (g === null) return c;
return (Math.abs(g) >= 1 ? { ...rest, gainDb: g } : rest) as C;
});
}
/** the level every 10 ms of 16-bit PCM samples */
export function levelsOf(pcm: Int16Array, rate = 16000): number[] {
const hop = Math.round(rate / 100);
const out: number[] = [];
for (let s = 0; s + hop <= pcm.length; s += hop) {
let e = 0;
for (let k = s; k < s + hop; k++) e += (pcm[k] / 32768) ** 2;
out.push(Math.round(10 * Math.log10(e / hop + 1e-10) * 10) / 10);
}
return out;
}
/** a mono 16-bit WAV's samples and rate (`raea media audio --mono` writes one) */
export function wavSamples(buf: Uint8Array): { pcm: Int16Array; rate: number } {
const v = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
const tag = (o: number) => String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]);
if (tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error("not a WAV file");
let rate = 16000;
for (let o = 12; o + 8 <= buf.length; ) {
const id = tag(o);
const size = v.getUint32(o + 4, true);
if (id === "fmt ") {
if (v.getUint16(o + 10, true) !== 1 || v.getUint16(o + 22, true) !== 16) throw new Error("not mono 16-bit PCM");
rate = v.getUint32(o + 12, true);
}
if (id === "data") {
const n = Math.floor(Math.min(size, buf.length - o - 8) / 2);
const copy = buf.slice(o + 8, o + 8 + n * 2);
return { pcm: new Int16Array(copy.buffer, copy.byteOffset, n), rate };
}
o += 8 + size + (size % 2);
}
throw new Error("a WAV with no data");
}
+1 -1
View File
@@ -22,6 +22,6 @@ export const REGISTRY: Record<string, Record<string, string>> = {
}
};
export const TEMPLATE: Record<string, string> = {
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from \"raea\";\nimport { cutaways, cuts, edit, frames, punchIn, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />\n ) : (\n // a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\", transform: `scale(${punchIn(i)})` }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n {/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}\n {cutaways.map((c, i) => (\n <Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>\n <Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n </Sequence>\n ))}\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from \"raea\";\nimport { cuts, edit, frames, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />\n ) : (\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
"theme.css": "/* The Tailwind theme every raea project compiles with: class names (text-brand-accent, bg-brand-surface, font-brand,\n text-caption, rounded-brand) mapped onto the brand kit's variables (brand/brand.css, the --brand-* format).\n Nothing here is a colour, a font or a size of its own: change the brand, and every component follows. The kit's\n sizes are the website's, so on a 1080x1920 video they're scaled up (the kit's own note: about 2.5x). */\n@theme inline {\n --color-brand-accent: var(--brand-accent);\n --color-brand-bg: var(--brand-background);\n --color-brand-surface: var(--brand-background);\n --color-brand-on-surface: var(--brand-text);\n --color-brand-ink: var(--brand-background);\n --color-brand-on-accent: var(--brand-background);\n --color-brand-1: var(--brand-color-1);\n --color-brand-2: var(--brand-color-2);\n --color-brand-3: var(--brand-color-3);\n --font-brand: var(--brand-font-heading);\n --font-brand-body: var(--brand-font);\n --text-display: calc(var(--brand-h1-size) * 3);\n --text-title: calc(var(--brand-h2-size) * 2.5);\n --text-caption: calc(var(--brand-h2-size) * 2.5);\n --text-body: calc(var(--brand-p-size) * 2.5);\n --text-label: calc(var(--brand-h4-size) * 2.2);\n --radius-brand: var(--brand-radius);\n}\n"
};
+5
View File
@@ -83,6 +83,11 @@ pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {
})
}
/// `--taste`'s .ts files, each checked as Taste.
pub fn tastes_ts(args: &[String]) -> R<Vec<schema::Taste>> {
raea_app_direction::check::taste_files(args).iter().map(|f| read_spec(f)).collect()
}
/// `raea spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:
/// brief, script, taste or parts in it; anything else is checked as Taste, the files in
/// ~/.raea/taste being named for their kind).
-3
View File
@@ -84,9 +84,6 @@ fn a_verb_refuses_what_it_doesnt_take() {
let why = stray(&help, &a(&["render", "e.tsx", "f.tsx", "-o", "o.mp4"])).unwrap();
assert!(why.contains("\"f.tsx\": it takes 1 argument besides its flags"), "{why}");
assert!(stray(&help, &a(&["play", "g.tsx", "--full"])).unwrap().starts_with("raea play doesn't take \"--full\""));
// `goal check`, check's old name, takes check's flags (CK0)
assert_eq!(stray(&help, &a(&["goal", "check", "out/cuts/a_9x16.mp4", "--at", "render", "--manifest", "out/cuts/a_9x16.render.json"])), None);
assert!(stray(&help, &a(&["goal", "check", "--frobnicate"])).unwrap().starts_with("raea check doesn't take \"--frobnicate\""));
assert!(stray(&help, &a(&["track", "c.mp4", "--setup"])).is_some());
assert!(stray(&help, &a(&["splat", "train", "v.mp4", "-o", "o.ply", "--steps", "100"])).is_none());
}
-5
View File
@@ -143,11 +143,6 @@ use raea_cli_goal::verb_at;
/// the ones it takes. None when it is, or when the help doesn't give the verb's usage.
pub fn stray(help: &str, args: &[String]) -> Option<String> {
let verb = args.first()?;
// `goal check` is `check`'s old name (docs/check.feature CK0): its flags are check's, which the help lists under
// check alone (12-04: `raea goal check OUT --at render`, raea cloud's render tool, was refused for --at)
if verb == "goal" && args.get(1).is_some_and(|v| v == "check") {
return stray(help, &args[1..]);
}
// physics hands its subverb's arguments to the bake, the goo or the part, which check them; gen to raea-io-gen's own
if verb == "physics" || verb == "gen" {
return None;
+1 -1
View File
@@ -95,7 +95,7 @@ pub fn mezz(args: &[String]) -> R<String> {
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, gone, goal_ts, render_moment};
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, goal_ts, render_moment};
/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)
pub const SHELL: &[&str] = &["init", "cut", "words", "frame", "component", "brand", "library", "show", "clothes", "bug"];
+4 -11
View File
@@ -1,8 +1,8 @@
// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),
// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.
// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.
import { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from "raea";
import { cutaways, cuts, edit, frames, punchIn, total } from "./cuts";
import { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from "raea";
import { cuts, edit, frames, total } from "./cuts";
import { css } from "./styles.gen";
// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's
@@ -29,20 +29,13 @@ function Edit() {
{/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with
sound alone (a voice recording) plays under whatever you put in its place */}
{c.kind === "audio" ? (
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />
) : (
// a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${punchIn(i)})` }} />
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
)}
</Series.Sequence>
))}
</Series>
{/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}
{cutaways.map((c, i) => (
<Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>
<Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
</Sequence>
))}
</AbsoluteFill>
);
}
+1 -11
View File
@@ -15,7 +15,7 @@ ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
xvfb x11vnc xdotool fonts-noto-color-emoji python3-opencv > /dev/null \
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
@@ -50,16 +50,6 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS
COPY src src
COPY image image
# OpenCV's YuNet face detector (232 KB, MIT), for image/faces.py: prep finds each take's faces and components/Framed.tsx
# crops on them (12-05: agents guessed each 9:16 crop and cut the speaker off at the edge); prep also copies the cut
# components beside it (image/Cut.tsx, Shot, crop, Said, EndCard, brand, Title)
RUN curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \
&& python3 -c "import cv2; cv2.FaceDetectorYN.create('/opt/yunet.onnx', '', (640, 360))" && chmod +x image/faces.py
# 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
+13 -96
View File
@@ -4,14 +4,13 @@
#
# MODAL_PROFILE=raea modal deploy deploy/modal/farm.py
#
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X][&nv=1|0] body: the project as a tar. {id}
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X] body: the project as a tar. {id}
# GET /v1/jobs/ID?from=N {log, next, exit?}, held up to 20 s for more
# GET /v1/jobs/ID/out?as=zst|gz|tar the files the job made or changed; the job is removed
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
# left out of /out
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid],
# links: 1} (links: it fetches an original of unknown size)
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
# hashes to OID (a box's project not in raea's LFS)
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
@@ -149,20 +148,8 @@ image = (
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
)
# raea's SDK files the box image overlays on the release (image/sdk-overlay, deploy/fly/Dockerfile), here too: the farm
# bundles each composition it's sent with its own SDK, so the box's zone-aware <Region> never reached a render (12-05,
# run 17: titles through <Title> still landed at y=154, inside the app's top 220 px). Only while the release lacks them
OVERLAY = os.path.join(CLOUD, "image", "sdk-overlay")
if os.path.isdir(os.path.join(OVERLAY, "video")):
image = image.add_local_dir(OVERLAY, "/opt/sdk-overlay", copy=True).run_commands(
"set -e; S=/opt/raea/share/raea/sdk; O=/opt/sdk-overlay; if [ ! -f $S/video/src/zones.ts ]; then "
"cp $O/video/src/captions.tsx $O/video/src/index.ts $O/video/src/region.tsx $O/video/src/zones.ts "
"$O/video/src/registry.tsx $S/video/src/ && cp $O/video/package.json $S/video/package.json && "
"cp $O/raea/src/index.tsx $S/raea/src/index.tsx && echo 'overlay: zones'; fi"
)
# last: files added without copy (these) can't be followed by a build step
image = image.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
vol = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
@@ -186,11 +173,7 @@ CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VEN
# NVIDIA's shader cache and Cycles' kernels on the farm's volume, so a GPU's start reuses what an earlier one compiled
CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}/cache/nvidia", "__GL_SHADER_DISK_CACHE_SKIP_CLEANUP": "1",
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg",
# but a composition's bundle on this container's own disk (12-05, Dutch run 6: a job's 32 parts each missed the
# shared cache at once, wrote the same file and committed it, and parts that read it mid-commit got zeros:
# "bundle.js: String contained internal null bytes", up to 23 of a cut's 32 parts sent back to the 10 GPUs)
"RAEA_BUNDLE_CACHE": "/tmp/raea-bundles"}
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
# the scene reader's models, loaded once a container (/v1/scene)
@@ -214,7 +197,7 @@ def life():
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"], CACHES["RAEA_BUNDLE_CACHE"]):
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
@@ -355,43 +338,12 @@ def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
return {"code": code, "out": out[-1000:], "s": s}
def stills_run(args, frames, first, work, env, seg, man):
"""A video run drawn as stills and encoded: the run's frames from `first` (its warm-up ones dropped) at the piece's
rate (its manifest's, else 30)"""
import farm_plan
tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp, "--manifest", man], cwd=work, env=env)
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
if code or len(made) != len(frames):
return code or 1, out + f"\n{len(made)} of {len(frames)} stills drawn", s
kept = f"{tmp}/kept"
os.makedirs(kept)
n = 0
for i, name in enumerate(made):
if frames[i] >= first:
os.replace(os.path.join(tmp, name), f"{kept}/frame-{n:05d}.png")
n += 1
try:
fps = float(json.load(open(man)).get("fps") or 30)
except Exception:
fps = 30.0
c, o, _ = farm_plan.encode(kept, seg, fps, None, run, start=0, frames=n)
shutil.rmtree(tmp, ignore_errors=True)
return c, out + o, s
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload()
work = f"{JOBS}/{id}/work"
if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
# what frame 0 brought up to date in the work folder (styles.gen.ts, written by raea when it's older than the
# code), for the parts after it: uncommitted, every part's container rewrote it on the volume at once, truncating
# it under the others, and 14 of a Dutch cut's parts refused with "couldn't bundle edit.tsx: Unterminated
# string" (12-05, run 19: the cut was lost)
vol.commit()
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None:
code, out, s = run(["raea", *args], cwd=work)
@@ -406,11 +358,6 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"})
# a piece whose --at draws only stills (a game's, 12-05: "/tmp/run-00024.mp4: The file extension .mp4 was not
# recognized as an image format" on every run, and a playable's capture never came back): its frames as stills,
# encoded here into the run's H.264 part, as a Blender run's are
if code and "not recognized as an image format" in out:
code, out, s = stills_run(args, frames, first, work, env, seg, man)
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
@@ -627,22 +574,15 @@ def api():
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a
# reload waits until none of them is in it.
class Gate:
# 12-04 (one-check proof, 12 cuts in flight): blob uploads and other requests kept the volume in use without a
# break, a reload waited for none of them to be in it, and GET out sat behind it past Modal's 150 s web limit:
# 408, and Elfster's finished cut was lost. So a waiting reload holds new users back (it goes next), a reload
# that starts after a request asked for one serves that request too, and a wait has a limit (a 503, asked again)
def __init__(self):
self.users = 0
self.reloading = False
self.waiting = 0
self.begun = 0 # reloads started
self.fresh = 0 # the latest reload that worked, by its start
self.cond = asyncio.Condition()
@contextlib.asynccontextmanager
async def use(self):
async with self.cond:
await self.cond.wait_for(lambda: not self.reloading and not self.waiting)
await self.cond.wait_for(lambda: not self.reloading)
self.users += 1
try:
yield
@@ -651,36 +591,17 @@ def api():
self.users -= 1
self.cond.notify_all()
async def reload(self, wait: bool = True, within: "float | None" = None) -> bool:
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use,
and False when `within` seconds pass first"""
async def reload(self, wait: bool = True) -> bool:
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use"""
async with self.cond:
if not wait and (self.users or self.reloading or self.waiting):
if not wait and (self.users or self.reloading):
return False
want = self.begun + 1
self.waiting += 1
try:
ready = lambda: self.fresh >= want or (not self.users and not self.reloading)
if within is None:
await self.cond.wait_for(ready)
else:
await asyncio.wait_for(self.cond.wait_for(ready), within)
except asyncio.TimeoutError:
return False
finally:
self.waiting -= 1
self.cond.notify_all()
if self.fresh >= want:
return True
await self.cond.wait_for(lambda: not self.users and not self.reloading)
self.reloading = True
self.begun += 1
mine = self.begun
ok = False
try:
for pause in (0.5, 1, 2, 4, 0):
try:
await vol.reload.aio()
ok = True
return True
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
if not pause:
@@ -691,17 +612,13 @@ def api():
finally:
async with self.cond:
self.reloading = False
if ok:
self.fresh = mine
self.cond.notify_all()
gate = Gate()
# under Modal's 150 s web request limit, past which the request is lost (408) and a box can't ask again
RELOAD_WAIT_S = 100
async def reloaded():
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)"""
if not await gate.reload(within=RELOAD_WAIT_S):
if not await gate.reload():
raise HTTPException(503, "the farm's volume is busy: try again")
def check(req: Request):
@@ -814,7 +731,7 @@ def api():
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
q = req.query_params
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "nv": q.get("nv") if q.get("nv") in ("0", "1") else None, "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work"
async with gate.use():
@@ -849,7 +766,7 @@ def api():
blob = f"{ROOT}/blobs/{oid}"
if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
have.append(oid)
return {"have": have, "links": 1}
return {"have": have}
@web.put("/v1/blobs/{oid}")
async def blob_put(oid: str, req: Request):
+10 -49
View File
@@ -11,7 +11,6 @@
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
import uuid
import hashlib
import json
import os
@@ -44,21 +43,9 @@ def inside(work, rel):
return p == os.path.realpath(work) or p.startswith(os.path.realpath(work) + os.sep)
# the most an original of unknown size may be: a link that answers with more is refused before it fills the volume
UNKNOWN_MAX = 40 << 30
def get(href, header, dest, limit=None):
def get(href, header, dest):
req = urllib.request.Request(href, headers={**AGENT, **(header or {})})
with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:
if limit:
n = 0
while chunk := r.read(8 << 20):
n += len(chunk)
if n > limit:
raise ValueError(f"media: {href.split('?')[0]} is over {limit >> 30} GB, more than an original of unknown size may be")
f.write(chunk)
return
shutil.copyfileobj(r, f, CHUNK)
@@ -93,64 +80,38 @@ def fetch(work, cache, log=print, download=get, check=probe):
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
blob = os.path.join(cache, oid)
# size 0: a library original whose size raea cloud doesn't know (it comes with its link); its hash alone says
# it's the one. What the box sent (no link) is held only at its own size
held = os.path.exists(blob) and (os.path.getsize(blob) == size or (size <= 0 and bool(o.get("href"))))
if not o.get("href"):
# sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
if not held:
if not (os.path.exists(blob) and os.path.getsize(blob) == size):
raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
cached += size
elif held:
elif os.path.exists(blob) and os.path.getsize(blob) == size:
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
check(o["href"], o.get("header"))
cached += os.path.getsize(blob)
cached += size
else:
tmp = f"{blob}.part-{uuid.uuid4().hex}"
try:
download(o["href"], o.get("header"), tmp, *([UNKNOWN_MAX] if size <= 0 else []))
except Exception:
if os.path.exists(tmp):
os.remove(tmp)
raise
tmp = f"{blob}.part-{os.getpid()}"
download(o["href"], o.get("header"), tmp)
got = sha256(tmp)
if got != oid or (size > 0 and os.path.getsize(tmp) != size):
if got != oid or os.path.getsize(tmp) != size:
os.remove(tmp)
raise ValueError(f"media: {path} came back as {got[:12]}…, not {oid[:12]}…")
fetched += os.path.getsize(tmp)
os.replace(tmp, blob)
fetched += size
dest = os.path.join(work, path)
os.makedirs(os.path.dirname(dest), exist_ok=True)
if os.path.lexists(dest):
os.remove(dest)
# a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too. It ends at a
# file with the take's own name (cache/named/OID/NAME, a hard link to the blob): a bundler follows the link, and
# a composition that knows its takes by name (Framed's faces) found only a hash and framed every shot centred
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too
try:
os.symlink(named(cache, oid, path), dest)
os.symlink(blob, dest)
except OSError:
shutil.copyfile(blob, dest)
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
return {"objects": len(objects), "fetched": fetched, "cached": cached}
def named(cache, oid, path):
"""the blob under the take's own name, cache/named/OID/NAME: a hard link (the same file, no space), else the blob"""
blob = os.path.join(cache, oid)
out = os.path.join(cache, "named", oid, os.path.basename(path))
if os.path.exists(out) and os.path.getsize(out) == os.path.getsize(blob):
return out
try:
os.makedirs(os.path.dirname(out), exist_ok=True)
tmp = f"{out}.part-{uuid.uuid4().hex}"
os.link(blob, tmp)
os.replace(tmp, out)
return out
except OSError:
return blob
def is_media(path, size):
ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path) else ""
return ext in MEDIA or size >= LARGE
+4 -8
View File
@@ -365,7 +365,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
t.start()
video = out.endswith(VIDEO)
can_flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1")
can_flat = bool(video and cpu_render and not opts.get("gpu"))
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys
keyed, keys_s = farm_keys.read(rest, work, run, cpu_env, f"/tmp/{id}-keys.json") if video and opts.get("keys") else (None, 0)
@@ -409,9 +409,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
gpu_render, gpu_kind = render, kind
# a piece with 3D in it keeps its GPU, and its runs use the GPU's encoder and decoder too (CR34): on a 2D piece NVENC
# bought nothing (300 frames: 210 s against libx264's 215 s, 11% more bytes), the page and the clips are the work
# (opts nv "1" or "0" says so for the job, and "1" keeps it on GPUs: to measure what NVENC and NVDEC buy a cut)
nv = opts.get("nv") == "1" or (opts.get("nv") != "0" and bool((p.get("manifest") or {}).get("has3d")))
flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1" and (p.get("manifest") or {}).get("has3d") is False)
nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
quick = bool(flat and p.get("keys"))
@@ -541,10 +540,7 @@ def joined(probe, parts):
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = []
for c in pieces:
# the same source carried on across a run's seam, whatever its React key: each run numbers its nodes its own
# way (12-04, StreetTalk round 22: Body Shop's clips came back keyed n3 and n11 by turns, split at frames 60,
# 420, 720 and 807, and the sound check called each seam a cut inside a word)
prev = next((p for p in reversed(clips) if p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"]
if "fadeOut" in c:
+1 -4
View File
@@ -75,9 +75,6 @@ def api():
PROXY_SHORT = 540
PROXY_LIGHT_BPS = 2_500_000
PART = 64 << 20
# every proxy says what it is in its comment tag, and ffmpeg carries the tag into what's made from it: a box's renders
# and publishes read it (raea-platform harness/light.ts) so nothing made from a proxy is shown to a person as a final
LIGHT_TAG = "raea-light-copy"
AGENT = {"user-agent": "raea-ingest/1"}
@@ -163,7 +160,7 @@ def proxy_job(url: str, put: str, ticket: str) -> dict:
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
r = subprocess.run(
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-metadata", f"comment={LIGHT_TAG}", "-movflags", "+faststart", out],
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
capture_output=True, text=True, timeout=3300,
)
if r.returncode != 0 or not os.path.exists(out):
+2 -5
View File
@@ -38,10 +38,7 @@ align_image = (
ALIGNS = {"en": "English", "zh": "Chinese", "yue": "Cantonese", "fr": "French", "de": "German", "it": "Italian", "ja": "Japanese", "ko": "Korean", "pt": "Portuguese", "ru": "Russian", "es": "Spanish"}
# 12-05, run 8: three projects' 8-at-once transcriptions queued on 2 of each, and Elfster's 51 takes took 6.5 minutes
# (its wait for them ran past the fetch step's 4). Hear 4 and Align 3 hold 7 of the account's 10 GPUs at a run's start,
# before its renders, which draw on CPUs and use the GPUs only for each cut's first frame
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=3, scaledown_window=60)
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Align:
@modal.enter()
def load(self):
@@ -83,7 +80,7 @@ def aligned(heard: list, got: list) -> "list | None":
FULL_S = 180
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=4, scaledown_window=60)
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Hear:
@modal.enter()
def load(self):
-153
View File
@@ -1,153 +0,0 @@
// components/Cut.tsx: a whole cut composed from its moments. The agent says, per moment, WHAT is on screen (the speaker,
// two people, the product, a cutaway, a screen, the wide, the end card) and which take is heard; this lays each one out
// with <Shot>, places the product clear of faces, keeps the speaker talking under a cutaway, captions every word in the
// brand's style (on the seam of a split, at the bottom otherwise), holds the hook in <Title> at the top, and
// ends on the brand's <EndCard>. Every cut of a project then looks the same, and nothing is placed by a typed number.
// Put there by the box's prep beside Shot.tsx.
//
// <Cut said={words} keys={["the product"]} hook="Do you know her this well?" bed={bed} moments={[
// { show: "speaker", src: "footage/A.mp4", startFrom: 30, endAt: 120, who: "right" },
// { show: "two", src: "footage/A.mp4", startFrom: 400, endAt: 520 },
// { show: "broll", src: "footage/A.mp4", startFrom: 520, endAt: 610, asset: "footage/B.mp4", assetFrom: 300 },
// { show: "product", src: "footage/A.mp4", startFrom: 900, endAt: 1010, asset: "media/product.png" },
// { show: "end", src: "footage/H.mp4", startFrom: 0, endAt: 90, cta: "Get yours today", offer: "20% off" },
// ]} />
//
// A moment lasts its take's span (endAt - startFrom), or `frames` when it has no take. `said` is the cut's words in its
// own frames, as `raea cut` gives them for these spans in this order.
import { Audio, Sequence, useCurrentFrame } from "raea";
import EndCard from "./EndCard";
import Said from "./Said";
import Shot, { type Layout } from "./Shot";
import Title from "./Title";
type Who = number | string;
type Word = { text: string; from: number; to: number };
export type Moment = {
/** what's on screen: the speaker, two people (a split), the product (an insert), a cutaway, a screen (a stack), the
* whole wide take, or the end card */
show: "speaker" | "two" | "product" | "broll" | "screen" | "wide" | "end";
/** the take heard (and seen, but for a cutaway, a screen's top and the end card), and its span in the edit's frames */
src?: string;
startFrom?: number;
endAt?: number;
/** the length when there's no take (an end card alone) */
frames?: number;
/** who's framed (Shot's `who`), and a split's two (Shot's `pair`) */
who?: Who;
pair?: [Who, Who];
/** the product picture, the cutaway's take or the screen, and where its video starts */
asset?: string;
assetFrom?: number;
/** the product picture's width over its height */
aspect?: number;
/** the clip's level change in dB (cuts.ts's gainDb) and how far it's punched in (cuts.ts's punchIn(i): a jump cut
* reframes) */
gainDb?: number;
punchIn?: number;
/** the end card's CTA (the brief's words) and offer */
cta?: string;
offer?: string;
};
type Props = {
moments: Moment[];
/** the cut's words, in its frames; no captions without them */
said?: readonly Word[];
/** key words the captions light (Said's `keys`) */
keys?: string[];
/** emoji by word (Said's `emoji`); none unless named */
emoji?: Record<string, string>;
/** the hook, held in <Title> at the top over the first `hookFrames` (until the first sentence ends, 2 s at most);
* the captions run under it at the bottom, so no word goes uncaptioned */
hook?: string;
hookFrames?: number;
/** the music bed under the whole cut (the generate tool's), at BED_DB with fades: never a typed level */
bed?: string;
};
/** the bed's level: about 16 dB under the voices once <Mix> masters the cut, inside the check's 12-20 dB (12-05: beds
* typed at volume 0.07 or gainDb -21 sat 28-30 dB under, and the check heard no music) */
export const BED_DB = -10;
const LAYOUT: Record<Exclude<Moment["show"], "end">, Layout> = { speaker: "face", two: "split", product: "insert", broll: "broll", screen: "stack", wide: "fit" };
/** each moment's first frame on the cut and its length */
export function spans(ms: Moment[]): { from: number; len: number }[] {
let at = 0;
return ms.map((m) => {
const len = Math.max(1, m.src && m.endAt !== undefined ? m.endAt - (m.startFrom ?? 0) : (m.frames ?? 60));
const s = { from: at, len };
at += len;
return s;
});
}
/** the cut's words in its frames, from each heard take's words (footage/NAME.words.json, by the take's name): the words
* each moment's span says, in the moments' order; a word cut off by a span's edge is left out */
export function saidOf(ms: Moment[], words: Record<string, readonly { text: string; start_ms: number; end_ms: number }[]>, fps: number): Word[] {
const out: Word[] = [];
const sp = spans(ms);
ms.forEach((m, i) => {
if (!m.src) return;
const ws = words[m.src.split("/").pop()!.replace(/\.[^.]+$/, "")] ?? [];
const a = (m.startFrom ?? 0) / fps;
const b = a + sp[i].len / fps;
for (const w of ws) {
const s = w.start_ms / 1000;
const e = w.end_ms / 1000;
if (s >= a - 0.02 && e <= b + 0.05) out.push({ text: w.text, from: sp[i].from + Math.max(0, Math.round((s - a) * fps)), to: sp[i].from + Math.min(sp[i].len, Math.round((e - a) * fps)) });
}
});
return out;
}
/** cuts.ts's clips as moments, in order: each one the speaker (or `show` for clip i), its span in the edit's frames as
* cuts.ts counts them, its gainDb, and a jump cut punched in every other time (cuts.ts's punchIn). Change a moment's
* show, who or asset after; the timing stays raea cut's. */
export function fromCuts(
cuts: readonly { src: string; from: number; to: number; gainDb?: number; jump?: boolean; kind?: string }[],
fps: number,
punchIn?: (i: number) => number,
show?: (i: number) => Partial<Moment> | undefined,
): Moment[] {
return cuts.map((c, i) => {
const s = Math.round(c.from * fps);
const len = Math.max(1, Math.round((c.to - c.from) * fps));
const k = punchIn ? punchIn(i) : 1;
return { show: "speaker", src: c.src, startFrom: s, endAt: s + len, ...(c.gainDb ? { gainDb: c.gainDb } : {}), ...(k !== 1 ? { punchIn: k } : {}), ...(show?.(i) ?? {}) } as Moment;
});
}
/** the captions' band for what's on screen: over a split's or a stack's seam, else at the bottom */
const bandOf = (m?: Moment) => (m && (m.show === "two" || m.show === "screen") ? "center" : "bottom");
export default function Cut({ moments, said, keys, emoji, hook, hookFrames, bed }: Props) {
const f = useCurrentFrame();
const sp = spans(moments);
const now = sp.findIndex((s) => f >= s.from && f < s.from + s.len);
// the hook holds until the first sentence is said (2 s at most), unless told
const firstEnd = said?.find((w) => /[.?!]$/.test(w.text))?.to;
const hookLen = hookFrames ?? Math.min(60, firstEnd ?? 60);
const showHook = !!hook && f < hookLen;
return (
<>
{moments.map((m, i) => (
<Sequence key={i} from={sp[i].from} durationInFrames={sp[i].len} name={`${m.show} ${i + 1}`}>
{m.show === "end" ? (
<>
<EndCard cta={m.cta ?? ""} offer={m.offer} asset={m.asset} />
{m.src ? <Audio src={m.src} startFrom={m.startFrom} endAt={m.endAt} gainDb={m.gainDb} /> : null}
</>
) : m.src ? (
<Shot layout={LAYOUT[m.show]} src={m.src} startFrom={m.startFrom} endAt={m.endAt} who={m.who} pair={m.pair} asset={m.asset} assetFrom={m.assetFrom} aspect={m.aspect} gainDb={m.gainDb} punchIn={m.punchIn} />
) : null}
</Sequence>
))}
{bed ? <Audio src={bed} gainDb={BED_DB} fadeIn={0.3} fadeOut={1} /> : null}
{showHook ? <Title region="top">{hook}</Title> : null}
{said?.length ? <Said said={said} keys={keys} emoji={emoji} region={bandOf(moments[now])} /> : null}
</>
);
}
-65
View File
@@ -1,65 +0,0 @@
// components/EndCard.tsx: a cut's last card from the brand template (components/brand.ts): the brand's surface, its logo,
// the CTA in the brief's own words and the offer on the brand's button, every part inside the app's zones. Put there by
// the box's prep beside Shot.tsx. Change the look freely; never give a part a top or a left.
import type React from "react";
import { AbsoluteFill, Img, interpolate, useCurrentFrame, useVideoConfig } from "raea";
import { COLORS, FONTS, RADIUS, logo as brandLogo, zones } from "./brand";
type Props = {
/** the call to action, word for word from the brief */
cta: string;
/** the offer (a code, a discount), on the brand's button */
offer?: string;
/** the logo's file; the brand kit's when unset, none when it has none */
logo?: string | null;
/** a product picture above the CTA */
asset?: string;
/** merged over the card's surface */
style?: React.CSSProperties;
};
/** the offer's size: 64 px at 1080 wide, less when its line (about 0.6 em a letter in a bold face, and the button's
* padding) wouldn't fit `inner`; never under 56 px (the check calls less small print): a longer offer wraps, evenly */
export const offerSize = (offer: string, inner: number, s: number) => Math.max(56 * s, Math.min(64 * s, (inner - 96 * s) / (0.6 * Math.max(1, offer.length))));
export default function EndCard({ cta, offer, logo, asset, style }: Props) {
const f = useCurrentFrame();
const { width: W, height: H } = useVideoConfig();
const z = zones(W, H);
const s = W / 1080;
const mark = logo === undefined ? brandLogo("dark") : logo;
// the card's inner width: inside the app's zones and the card's own margin
const inner = W - z.left - Math.max(z.left, z.right) - 80 * s;
const rise = (d: number) => ({
opacity: interpolate(f, [d, d + 8], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }),
transform: `translateY(${interpolate(f, [d, d + 10], [24 * s, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })}px)`,
});
return (
<AbsoluteFill data-shot="end" style={{ background: COLORS.surface, ...style }}>
<div
style={{
position: "absolute",
left: z.left + 40 * s,
right: Math.max(z.left, z.right) + 40 * s,
top: z.top + 40 * s,
bottom: z.bottom + 40 * s,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 56 * s,
textAlign: "center",
}}
>
{mark ? <Img src={mark} style={{ maxWidth: 560 * s, maxHeight: 220 * s, objectFit: "contain", ...rise(0) }} /> : null}
{asset ? <Img src={asset} style={{ maxWidth: 620 * s, maxHeight: 520 * s, objectFit: "contain", borderRadius: RADIUS * s, ...rise(4) }} /> : null}
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: 88 * s, lineHeight: 1.08, color: COLORS.text, ...rise(6) }}>{cta}</div>
{offer ? (
// the offer on one line when it fits at 56 px or more, else wrapped evenly (12-05: "Code SAVE60 · $60 off" broke
// over two with one word alone, and shrunk to fit it was 40 px, small print)
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: offerSize(offer, inner, s), lineHeight: 1.1, maxWidth: inner, textWrap: "balance", color: COLORS.buttonText, background: COLORS.button, borderRadius: RADIUS * s * 2, padding: `${28 * s}px ${48 * s}px`, ...rise(12) }}>{offer}</div>
) : null}
</div>
</AbsoluteFill>
);
}
-148
View File
@@ -1,148 +0,0 @@
// components/Framed.tsx: a take cropped to the edit's shape around the person in it, from footage/faces.json (the
// box's prep finds every take's faces at its keyframes: image/faces.py). 12-05, Shane: "the ai fucks up the composition
// of subjects in frame all the time": each crop was a number the agent guessed (objectPosition), and a 9:16 cut showed
// a bench while the woman talking was cut off at the edge.
//
// <Framed src={c.src} startFrom={f0} endAt={f1} /> the clip's largest face, whole, eyes a third down
// <Framed ... at={0.7} /> the face nearest 70% across the take (the guest, not the host)
// <Framed ... punchIn={1.15} /> tighter, still on the face
//
// The crop holds still for the clip (an editor's locked-off reframe), and follows only when the face moves further
// than one still crop can hold, smoothed over a second. A take with no faces is centred.
import type React from "react";
import { Video, useCurrentFrame, useVideoConfig } from "raea";
import FACES from "../footage/faces.json";
type Take = { w: number; h: number; t: number[]; s: number[][][] };
const TRACKS = FACES as unknown as Record<string, Take>;
type Props = {
src: string;
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
startFrom?: number;
endAt?: number;
/** which face when several: the one nearest this share across the take (0 left, 1 right); default the largest */
at?: number;
/** 1 = the whole height of the take; above 1 = tighter, centred on the face */
punchIn?: number;
volume?: number;
/** the clip's level change in dB (cuts.ts gives it, evening the cut's voices) */
gainDb?: number;
playbackRate?: number;
muted?: boolean;
style?: React.CSSProperties;
};
const clamp = (x: number, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const median = (xs: number[]) => {
const s = [...xs].sort((a, b) => a - b);
return s.length ? s[Math.floor(s.length / 2)] : 0.5;
};
/** the face's room from the crop's edge: a third of its own width either side */
const ROOM = 1 / 3;
/** the take's face at each sample from `a` to `b` seconds: [t, cx, ey, fw], and every other face's span across the
* take ([t, left, right]) */
function path(take: Take, a: number, b: number, near?: number): { p: [number, number, number, number][]; others: [number, number, number][] } {
const out: [number, number, number, number][] = [];
const others: [number, number, number][] = [];
let last: number | undefined = near;
for (let i = 0; i < take.t.length; i++) {
const t = take.t[i];
if (t < a - 1 || t > b + 1) continue;
const fs = take.s[i];
if (!fs?.length) continue;
// the face asked for (nearest `at`), followed from sample to sample, else the largest; a sample where no face is in
// reach of them (a face width and a half, or 8% of the take) doesn't have them, and the crop holds: it never jumps
// to someone else (12-05: the host at 0.4 went undetected for a second, the guest at 0.61 was nearest, and the crop
// swung to him mid-shot, under the hook)
const g = last === undefined ? fs[0] : fs.reduce((p, q) => (Math.abs(q[0] - last!) < Math.abs(p[0] - last!) ? q : p));
const f = last === undefined || Math.abs(g[0] - last) <= Math.max(1.5 * g[2], 0.08) ? g : undefined;
for (const o of fs) if (o !== f) others.push([t, o[0] - o[2] / 2, o[0] + o[2] / 2]);
if (!f) continue;
last = f[0];
out.push([t, f[0], f[1], f[2]]);
}
return { p: out, others };
}
/** the crop's left edge nearest `ideal` that keeps the framed face (lo..hi across the take) inside it and cuts no other
* face: each other face either whole in the crop or wholly out of it (12-05, a street interview: the crop on the host cut the
* man beside her in half at the right edge). `ideal` when no such edge exists */
function cleanLeft(ideal: number, vw: number, lo: number, hi: number, others: [number, number][]): number {
const most = Math.max(0, 1 - vw);
const a = clamp(hi - vw, 0, most);
const b = clamp(lo, 0, most);
if (a > b || !others.length) return ideal;
const cuts = (l: number) => others.some(([x1, x2]) => (l > x1 && l < x2) || (l + vw > x1 && l + vw < x2));
const tries = [ideal, ...others.flatMap(([x1, x2]) => [x2 + 0.005, x1 - 0.005, x1 - vw - 0.005, x2 - vw + 0.005])];
const ok = tries.filter((l) => l >= a && l <= b && l >= 0 && l <= most && !cuts(l));
return ok.length ? ok.reduce((x, y) => (Math.abs(y - ideal) < Math.abs(x - ideal) ? y : x)) : ideal;
}
export default function Framed({ src, startFrom = 0, endAt, at, punchIn = 1, volume, gainDb, playbackRate, muted, style }: Props) {
const frame = useCurrentFrame();
const { width, height, fps } = useVideoConfig();
const name = src.split("/").pop()!.replace(/\.[^.]+$/, "");
const take = TRACKS[name];
const a = startFrom / fps;
const b = endAt !== undefined ? endAt / fps : a + 600;
const now = a + (frame / fps) * (playbackRate ?? 1);
let pos = "50% 50%";
let transform: string | undefined;
let origin: string | undefined;
if (take) {
const k = Math.max(1, punchIn);
// the share of the take the box shows across and down (object-fit: cover), before and after the punch-in
const box = width / height;
const src_ = take.w / take.h;
const vw = Math.min(1, box / src_) / k;
const vh = Math.min(1, src_ / box) / k;
const { p, others } = path(take, a, b, at);
if (p.length) {
const xs = p.map((s) => s[1]);
const fw = Math.max(...p.map((s) => s[3]));
// one still crop when every sample's face fits it with room either side; else follow, smoothed over a second
const fits = Math.max(...xs) - Math.min(...xs) + fw * (1 + 2 * ROOM) <= vw;
const near = p.filter((s) => Math.abs(s[0] - now) <= 0.5);
const cx = fits ? median(xs) : median((near.length ? near : p).map((s) => s[1]));
const ey = median((fits || !near.length ? p : near).map((s) => s[2]));
// the crop's left and top edges, in shares of the take: the face across its middle, the eyes a third down
// the framed face's span the crop must hold (every sample's when still, the nearest second's when following),
// and the other faces there, which it mustn't cut
const held = fits || !near.length ? p : near;
const lo = Math.min(...held.map((s) => s[1] - s[3] / 2));
const hi = Math.max(...held.map((s) => s[1] + s[3] / 2));
const span = (fits ? others : others.filter((o) => Math.abs(o[0] - now) <= 0.5)).map((o) => [o[1], o[2]] as [number, number]);
const left = cleanLeft(clamp(cx - vw / 2, 0, 1 - vw), vw, lo, hi, span);
const top = clamp(ey - vh / 3, 0, 1 - vh);
if (k === 1) {
pos = `${vw >= 1 ? 50 : (left / (1 - vw)) * 100}% ${vh >= 1 ? 50 : (top / (1 - vh)) * 100}%`;
} else {
// cover at 1, then scaled about the point that puts the chosen window in the box
const vw1 = vw * k;
const vh1 = vh * k;
const l1 = cleanLeft(clamp(cx - vw1 / 2, 0, 1 - vw1), vw1, lo, hi, span);
const t1 = clamp(ey - vh1 / 3, 0, 1 - vh1);
pos = `${vw1 >= 1 ? 50 : (l1 / (1 - vw1)) * 100}% ${vh1 >= 1 ? 50 : (t1 / (1 - vh1)) * 100}%`;
// the window's left edge at the box's left: scale about the point o where (o - l1)/vw1 = (o - left)/vw
const ox = vw1 === vw ? 0.5 : (left * vw1 - l1 * vw) / (vw1 - vw);
const oy = vh1 === vh ? 0.5 : (top * vh1 - t1 * vh) / (vh1 - vh);
transform = `scale(${k})`;
origin = `${clamp((ox - l1) / vw1) * 100}% ${clamp((oy - t1) / vh1) * 100}%`;
}
}
}
return (
<Video
src={src}
startFrom={startFrom}
endAt={endAt}
volume={volume}
gainDb={gainDb}
playbackRate={playbackRate}
muted={muted}
style={{ width: "100%", height: "100%", objectFit: "cover", ...style, objectPosition: pos, ...(transform ? { transform, transformOrigin: origin } : {}) }}
/>
);
}
-64
View File
@@ -1,64 +0,0 @@
// components/Said.tsx: a cut's captions in the brand's caption style with its key words lit, through raea's <Captions>
// (the cut's own words, in a safe band, marked as captions for the check and the layered export). Put there by the box's
// prep beside Shot.tsx. The word being said is lit in the accent; a key word (a number, a price, a percentage, or one of
// `keys`: the product's name, the brief's must-say) is lit from the moment it's said. An emoji goes
// after a word only where `emoji` names it: never chosen by guess.
import { Captions, type RegionName } from "raea";
import { CAPTION } from "./brand";
type Word = { text: string; from: number; to: number };
type Props = {
/** the cut's words, in its frames (`raea cut` gives them) */
said: readonly Word[];
/** the key words and phrases to light, case ignored ("the product's name", "96 hours") */
keys?: string[];
/** an emoji after a word, by the word, case ignored ({ "love": "❤️" }) */
emoji?: Record<string, string>;
/** the band (Region): "bottom" by default; "center" over a split's or a stack's seam */
region?: RegionName;
/** the size in px at 1080 wide (the brand's caption size) */
size?: number;
/** how a misheard word is written, as Captions takes it */
fix?: Record<string, string>;
};
const bare = (t: string) => t.toLowerCase().replace(/[^\p{L}\p{N}%$€£']/gu, "");
/** a word worth lighting by itself: a number, a price, a percentage */
const NUMBER = /\d|%|\$|€|£/;
/** which of `ws` are key: a number, or part of a run of words that spells one of `keys` */
export function keyed(ws: readonly Word[], keys: string[] = []): boolean[] {
const out = ws.map((w) => NUMBER.test(w.text));
const phrases = keys.map((k) => k.split(/\s+/).map(bare).filter(Boolean)).filter((k) => k.length);
for (let i = 0; i < ws.length; i++)
for (const k of phrases) if (k.every((p, j) => bare(ws[i + j]?.text ?? "") === p)) for (let j = 0; j < k.length; j++) out[i + j] = true;
return out;
}
export default function Said({ said, keys, emoji, region = "bottom", size = CAPTION.size, fix }: Props) {
const hot = keyed(said, keys);
const at = new Map(said.map((w, i) => [w, i]));
const em = Object.fromEntries(Object.entries(emoji ?? {}).map(([k, v]) => [bare(k), v]));
return (
<Captions said={said as Word[]} region={region} size={size} fix={fix}>
{(ws, saying) =>
ws.map((w, j) => {
// the caption's words are copies (spelled by `fix`): found again among the cut's by their frames
const i = at.get(said.find((x) => x.from === w.from && x.to === w.to) as Word) ?? -1;
const key = i >= 0 && hot[i];
const lit = j === saying || (key && saying >= j);
const e = em[bare(w.text)];
return (
// a key word is lit, never drawn bigger: a bigger word made the line taller than the band Captions keeps it in,
// and its letters reached the app's bottom zone (12-05, a composed street cut: 1 px into the 420 px)
<span key={j} style={{ color: lit ? CAPTION.accent : undefined }}>
{w.text}
{e ? ` ${e}` : ""}
{j < ws.length - 1 ? " " : ""}
</span>
);
})
}
</Captions>
);
}
-227
View File
@@ -1,227 +0,0 @@
// components/Shot.tsx: one moment of a cut, laid out from what the agent says is on screen, every time the same way. Put
// there by the box's prep beside Framed.tsx. 12-05, Shane: framing and timing aren't enough, "it's also composition of
// footage and assets": agents built each cut's layout by hand and by guess (a split on one face, a product card over the
// guest's face, a cutaway with nobody talking under it). The agent picks the moment and the layout; this places it.
//
// <Shot layout="face" src={take} startFrom={f0} endAt={f1} who={0.7} /> the speaker framed (Framed.tsx)
// <Shot layout="split" src={take} ... pair={["left", "right"]} /> two people of one wide take, one a half
// <Shot layout="insert" src={take} ... asset="media/product.png" /> the speaker, the product in the clear
// <Shot layout="stack" src={take} ... asset="media/screen.mp4" /> the asset on top, the speaker below
// <Shot layout="fit" src={take} ... /> the whole take over a dimmed copy
// <Shot layout="broll" src={take} ... asset="footage/broll.mp4" /> the cutaway, the take still heard (L-cut)
//
// Each falls back when the take can't hold it, from the faces prep found (footage/faces.json): a split with fewer than
// two people in the moment, or two who can't each be shown whole and alone, is the face of the first; an insert with no
// clear place off every face is a stack. Never type a crop, a top or a left: change what's on screen instead.
import type React from "react";
import { AbsoluteFill, Audio, Img, Video, interpolate, useCurrentFrame, useVideoConfig } from "raea";
import FACES from "../footage/faces.json";
import Framed from "./Framed";
import { RADIUS, zones } from "./brand";
import { type Take, type Win, css, holdsAlone, onScreen, people, pick, windowOn } from "./crop";
export type Layout = "face" | "split" | "stack" | "fit" | "insert" | "broll";
type Who = number | string;
export type ShotProps = {
layout: Layout;
/** the take this moment is heard from (and shown from, but for a cutaway) */
src: string;
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
startFrom?: number;
endAt?: number;
/** face, insert, stack: who's framed: a share across the take (0 left, 1 right), "left", "right", or the largest */
who?: Who;
/** split: the two people, top first (the leftmost on top when unset) */
pair?: [Who, Who];
/** insert: the product or logo picture; stack: what goes on top (a picture or a video); broll: the cutaway's take */
asset?: string;
/** broll and stack: where the asset's video starts, in the edit's frames */
assetFrom?: number;
/** insert: the picture's width over its height (1) and its width as a share of the frame's (0.38) */
aspect?: number;
size?: number;
/** insert: px boxes [x, y, w, h] it must keep off besides faces (the caption band is kept by default) */
keep?: [number, number, number, number][];
/** face: tighter than the take's whole height (Framed's punchIn) */
punchIn?: number;
volume?: number;
/** the clip's level change in dB (cuts.ts's gainDb) */
gainDb?: number;
muted?: boolean;
};
const TRACKS = FACES as unknown as Record<string, Take>;
/** the share of a split's span each of its two must be seen in */
const SPLIT_SEEN = 0.85;
const nameOf = (src: string) => src.split("/").pop()!.replace(/\.[^.]+$/, "");
const isVideo = (src: string) => /\.(mp4|mov|m4v|webm|mkv)$/i.test(src);
/** a take's window in a panel at x, y, w x h: the Video cropped to it, its box clipped by the panel */
function Panel({ src, win, x, y, w, h, startFrom, endAt, volume, gainDb, muted, dim }: { src: string; win: Win; x: number; y: number; w: number; h: number; startFrom?: number; endAt?: number; volume?: number; gainDb?: number; muted?: boolean; dim?: boolean }) {
const c = css(win, w, h);
return (
<div style={{ position: "absolute", left: x, top: y, width: w, height: h, overflow: "hidden", opacity: dim ? 0.45 : 1 }}>
<Video
src={src}
startFrom={startFrom}
endAt={endAt}
volume={volume}
gainDb={gainDb}
muted={muted}
style={{ position: "absolute", left: c.left, top: c.top, width: c.width, height: c.height, objectFit: "cover", objectPosition: c.objectPosition, ...(dim ? { filter: "blur(40px)" } : {}) }}
/>
</div>
);
}
/** the clearest place for a box `bw` x `bh` in a frame `W` x `H`: off every face (with a third of its width round it),
* then off `keep`, then off the bodies below the faces, inside the app's zones; null when every place covers a face */
export function clearSpot(W: number, H: number, faces: [number, number, number, number][], keep: [number, number, number, number][], bw: number, bh: number): [number, number] | null {
const z = zones(W, H);
const m = 0.04 * W;
const x0 = z.left + m;
const x1 = W - Math.max(z.right, z.left) - m - bw;
const y0 = z.top + m;
const y1 = H - z.bottom - m - bh;
if (x1 < x0 || y1 < y0) return null;
const over = (ax: number, ay: number, b: [number, number, number, number]) => Math.max(0, Math.min(ax + bw, b[0] + b[2]) - Math.max(ax, b[0])) * Math.max(0, Math.min(ay + bh, b[1] + b[3]) - Math.max(ay, b[1]));
const padded = faces.map((f) => [f[0] - f[2] / 3, f[1] - f[3] / 3, f[2] * (5 / 3), f[3] * (5 / 3)] as [number, number, number, number]);
const bodies = faces.map((f) => [f[0] - f[2] * 0.9, f[1] + f[3], f[2] * 2.8, H] as [number, number, number, number]);
let best: [number, number] | null = null;
let cost = Infinity;
const step = Math.max(8, Math.round(W / 60));
for (let y = y0; y <= y1; y += step)
for (let x = x0; x <= x1; x += step) {
if (padded.some((f) => over(x, y, f) > 0)) continue;
const c = keep.reduce((s, k) => s + over(x, y, k), 0) * 3 + bodies.reduce((s, b) => s + over(x, y, b), 0) * 0.5 + Math.abs(y + bh / 2 - H / 3) * bw * 0.02;
if (c < cost) {
cost = c;
best = [x, y];
}
}
return best;
}
export default function Shot(p: ShotProps) {
const { width: W, height: H, fps } = useVideoConfig();
const frame = useCurrentFrame();
const take = TRACKS[nameOf(p.src)];
const a = (p.startFrom ?? 0) / fps;
const b = p.endAt !== undefined ? p.endAt / fps : a + 600;
const ps = people(take, a, b);
const av = { startFrom: p.startFrom, endAt: p.endAt, volume: p.volume, gainDb: p.gainDb, muted: p.muted };
const face = () => {
const at = typeof p.who === "number" ? p.who : p.who === "left" || p.who === "right" ? pick(ps, p.who)?.cx : undefined;
// `who` beyond a place across (a person's id, "speaker") goes to Framed as it is: its take graph knows them
const extra = typeof p.who === "string" && p.who !== "left" && p.who !== "right" ? ({ who: p.who } as Record<string, unknown>) : {};
return (
<AbsoluteFill data-shot="face">
<Framed src={p.src} {...av} at={at} punchIn={p.punchIn} {...extra} />
</AbsoluteFill>
);
};
const speakerIn = (x: number, y: number, w: number, h: number, alone = false) => {
const on = pick(ps, p.who);
const win = take ? windowOn(take, w, h, on, ps.filter((q) => q !== on), alone) : { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
return { on, win, el: take ? <Panel src={p.src} win={win} x={x} y={y} w={w} h={h} {...av} /> : <Video src={p.src} {...av} style={{ position: "absolute", left: x, top: y, width: w, height: h, objectFit: "cover" }} /> };
};
const pic = (src: string, fit: "cover" | "contain", from?: number) =>
isVideo(src) ? (
<Video src={src} startFrom={from} muted style={{ width: "100%", height: "100%", objectFit: fit }} />
) : (
<Img src={src} style={{ width: "100%", height: "100%", objectFit: fit }} />
);
switch (p.layout) {
case "face":
return face();
case "split": {
const half = H / 2;
// both people in nearly the whole span: a split with one half empty for a second is the fault the check names
// (12-05: the guest's face went at 175 s, a 4 s split showed one face for its last second)
const two = ps.filter((q) => q.seen >= SPLIT_SEEN);
const [t0, t1] = p.pair ? [pick(two, p.pair[0]), pick(two, p.pair[1])] : [...two.slice(0, 2)].sort((q, r) => q.cx - r.cx);
const ok = take && t0 && t1 && t0 !== t1 && holdsAlone(take, W, half, t0, ps.filter((q) => q !== t0)) && holdsAlone(take, W, half, t1, ps.filter((q) => q !== t1));
if (!ok) return face();
const w0 = windowOn(take!, W, half, t0, ps.filter((q) => q !== t0), true);
const w1 = windowOn(take!, W, half, t1, ps.filter((q) => q !== t1), true);
return (
<AbsoluteFill data-shot="split" style={{ background: "#000" }}>
<Panel src={p.src} win={w0} x={0} y={0} w={W} h={half} {...av} />
<Panel src={p.src} win={w1} x={0} y={half} w={W} h={half} {...av} muted />
<div style={{ position: "absolute", left: 0, top: half - 3, width: W, height: 6, background: "var(--brand-background, #101010)" }} />
</AbsoluteFill>
);
}
case "insert": {
if (!p.asset) return face();
const s = speakerIn(0, 0, W, H);
const bw = Math.round((p.size ?? 0.38) * W);
const bh = Math.round(bw / (p.aspect ?? 1));
const z = zones(W, H);
const keep = p.keep ?? [[0, H - z.bottom - 0.16 * H, W, 0.16 * H] as [number, number, number, number]];
const faces = ps.map((q) => onScreen(q, s.win, 0, 0, W, H));
const at = clearSpot(W, H, faces, keep, bw, bh);
if (!at) return <Shot {...p} layout="stack" />;
const k = interpolate(frame, [0, 6], [0.92, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
const o = interpolate(frame, [0, 4], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
return (
<AbsoluteFill data-shot="insert">
{s.el}
<div style={{ position: "absolute", left: at[0], top: at[1], width: bw, height: bh, borderRadius: RADIUS * (W / 1080) * 1.4, overflow: "hidden", boxShadow: "0 18px 48px rgba(0,0,0,0.45)", background: "#fff", opacity: o, transform: `scale(${k})` }}>
{pic(p.asset, "contain", p.assetFrom)}
</div>
</AbsoluteFill>
);
}
case "stack": {
const half = Math.round(H / 2);
const s = speakerIn(0, half, W, H - half);
return (
<AbsoluteFill data-shot="stack" style={{ background: "var(--brand-background, #101010)" }}>
<div style={{ position: "absolute", left: 0, top: 0, width: W, height: half, overflow: "hidden" }}>{p.asset ? pic(p.asset, isVideo(p.asset) ? "cover" : "contain", p.assetFrom) : null}</div>
{s.el}
</AbsoluteFill>
);
}
case "fit": {
const h = Math.round((W * (take?.h ?? 9)) / (take?.w ?? 16));
const whole: Win = { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
const back = take ? windowOn(take, W, H, undefined, []) : whole;
return (
<AbsoluteFill data-shot="fit" style={{ background: "#000" }}>
<Panel src={p.src} win={back} x={0} y={0} w={W} h={H} startFrom={p.startFrom} endAt={p.endAt} muted dim />
<Panel src={p.src} win={whole} x={0} y={Math.round((H - h) / 2)} w={W} h={h} {...av} />
</AbsoluteFill>
);
}
case "broll": {
// the cutaway seen, the take heard: the speaker talks on under it (an L-cut), so a cutaway never plays in silence
const src = p.asset ?? p.src;
const own = TRACKS[nameOf(src)];
const bp = own ? people(own, (p.assetFrom ?? 0) / fps, (p.assetFrom ?? 0) / fps + (b - a)) : [];
const win = own ? windowOn(own, W, H, bp[0], bp.slice(1)) : undefined;
const push = interpolate(frame, [0, Math.max(1, (b - a) * fps)], [1, 1.06], { extrapolateRight: "clamp" });
return (
<AbsoluteFill data-shot="broll" style={{ background: "#000" }}>
{isVideo(src) && win ? (
<Panel src={src} win={win} x={0} y={0} w={W} h={H} startFrom={p.assetFrom} muted />
) : isVideo(src) ? (
<Video src={src} startFrom={p.assetFrom} muted style={{ width: "100%", height: "100%", objectFit: "cover" }} />
) : (
<Img src={src} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${push})` }} />
)}
{p.asset && !p.muted ? <Audio src={p.src} startFrom={p.startFrom} endAt={p.endAt} volume={p.volume} gainDb={p.gainDb} /> : null}
</AbsoluteFill>
);
}
}
}
-110
View File
@@ -1,110 +0,0 @@
// <Title>: a hook, a title or an offer line on a cut, placed by raea's <Region> inside the app's UI zones (the same
// zones the check holds text to) and clear of the face when the edit knows where it is. Put there by the box's prep,
// beside Framed.tsx: 12-05, agents typed each title's top (140-190 px) into the app's top 220 px, over faces, run after
// run. Change the look freely; never give it a top or left.
import type React from "react";
import { Region, useRegion, useVideoConfig } from "raea";
type Props = {
children: React.ReactNode;
/** the band: "top" (default) for a hook, "bottom" for an offer or a CTA, "center" for a card */
region?: "top" | "bottom" | "center";
/** the size in px at 1080 wide (64) */
size?: number;
/** merged over the title's own style (colour, font, a backing box); not its place */
style?: React.CSSProperties;
};
/** how tall the title's lines are in a box `w` px wide: about 0.56 em a letter in a bold face, its line height and the
* backing box's padding (`pad`, px top and bottom together) */
export function heightIn(text: string, w: number, size: number, pad = 0): number {
const perLine = Math.max(1, Math.floor(w / (0.56 * size)));
const words = text.split(/\s+/).filter(Boolean);
let lines = 1;
let at = 0;
for (const x of words) {
const n = [...x].length;
if (at && at + 1 + n > perLine) {
lines++;
at = n;
} else at += (at ? 1 : 0) + n;
}
return lines * size * 1.1 + pad;
}
/** the title's own text, for measuring */
const textOf = (c: React.ReactNode): string => (typeof c === "string" || typeof c === "number" ? String(c) : Array.isArray(c) ? c.map(textOf).join("") : "");
/** draws `children` when the band it's in has room for them (when `fits`) or when the band before had none (`else`) */
function Fit({ need, seen, children, when }: { need: number; seen: { top?: boolean }; children: React.ReactNode; when: "fits" | "else" }) {
const box = useRegion();
if (when === "fits") {
seen.top = !!box && box.h >= need;
return seen.top ? <>{children}</> : null;
}
return seen.top ? null : <>{children}</>;
}
export default function Title({ children, region = "top", size = 64, style }: Props) {
const align = (r: string) => (r === "bottom" ? "flex-end" : r === "center" ? "center" : "flex-start");
const { width } = useVideoConfig();
const px = size * (width / 1080);
const pad = 2 * (typeof style?.padding === "string" ? parseFloat(style.padding) || 0 : typeof style?.padding === "number" ? style.padding : 0);
// a hook at the top when the band over the face holds it; else in the middle, over the body and never the face
// (12-05: street takes put the face right under the app's top zone, the top band had no height, and the hook ran down
// over the face from it)
// shared by the two bands in this frame's render: the top one draws first and says whether it held the hook
const seen: { top?: boolean } = {};
const text = textOf(children);
const el = (
<div
style={{
maxWidth: "100%",
textAlign: "center",
fontFamily: "var(--brand-font-heading, var(--brand-font, inherit))",
fontWeight: 800,
fontSize: size,
lineHeight: 1.1,
color: "var(--brand-text, #fff)",
textShadow: "0 4px 24px rgba(0,0,0,0.55)",
...style,
position: undefined,
top: undefined,
left: undefined,
}}
>
{children}
</div>
);
if (region !== "top")
return (
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: align(region), alignItems: "center" }}>
{el}
</Region>
);
return (
<>
<Region name="top" style={{ display: "flex", flexDirection: "column", justifyContent: "flex-start", alignItems: "center" }}>
<FitTop text={text} px={px} pad={pad} seen={seen}>
{el}
</FitTop>
</Region>
<Region name="center" style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
<Fit need={0} seen={seen} when="else">
{el}
</Fit>
</Region>
</>
);
}
/** Fit at the top, its need measured in the band's own width */
function FitTop({ text, px, pad, seen, children }: { text: string; px: number; pad: number; seen: { top?: boolean }; children: React.ReactNode }) {
const box = useRegion();
const need = box ? heightIn(text, box.w, px, pad) : Infinity;
return (
<Fit need={need} seen={seen} when="fits">
{children}
</Fit>
);
}
-53
View File
@@ -1,53 +0,0 @@
// components/brand.ts: the brand template every composed cut takes, read from the project's brand files, never typed per
// cut: brand/brand.json (`raea brand SITE` writes it: colours by role, fonts, the CTA button, the logos in media/brand/;
// prep writes {} when there's none) and brand/brand.css's --brand-* variables, which raea loads with every page. One
// template, so every cut of a project looks the same: fonts, colours, the caption style, the logo, the end card and the
// app's safe zones.
import KIT from "../brand/brand.json";
type Logo = { file: string; type?: string; on?: "light" | "dark" | "any"; width?: number | null; height?: number | null };
type Kit = {
name?: string;
palette?: { accent?: string | null; surface?: string | null; text_on_surface?: string | null; text_on_accent?: string | null; primary?: string | null };
button?: { bg?: string | null; color?: string | null; radius?: number | null } | null;
logos?: Logo[];
radius?: number | null;
};
const kit = (KIT ?? {}) as Kit;
/** the brand's colours, as CSS: the kit's, else brand.css's variables, else neutral */
export const COLORS = {
surface: kit.palette?.surface ?? "var(--brand-background, #101010)",
text: kit.palette?.text_on_surface ?? "var(--brand-text, #ffffff)",
accent: kit.palette?.accent ?? "var(--brand-accent, #ffd23f)",
onAccent: kit.palette?.text_on_accent ?? "var(--brand-background, #101010)",
button: kit.button?.bg ?? kit.palette?.accent ?? "var(--brand-accent, #ffd23f)",
buttonText: kit.button?.color ?? kit.palette?.text_on_accent ?? "var(--brand-background, #101010)",
};
export const FONTS = {
heading: "var(--brand-font-heading, var(--brand-font, inherit))",
body: "var(--brand-font, inherit)",
};
export const RADIUS = kit.button?.radius ?? kit.radius ?? 14;
/** the brand's logo for a background: one made for it ("light" for a light one), else any; null when the kit has none */
export function logo(on: "light" | "dark" = "dark"): string | null {
const ls = kit.logos ?? [];
const l = ls.find((x) => x.on === on) ?? ls.find((x) => !x.on || x.on === "any") ?? ls[0];
return l?.file ?? null;
}
/** the caption style every cut takes: the brand's heading font, white with a shadow, the word being said and the key
* words in the accent */
export const CAPTION = { size: 84, accent: COLORS.accent, color: "var(--brand-text, #fff)" };
/** the app's UI zones (its header, buttons, caption and bar), px at this size: the same table raea's check and Region
* hold text to (the box image's sdk/video zones.ts), so nothing placed here lands where the check says it can't */
export function zones(width: number, height: number): { top: number; right: number; bottom: number; left: number } {
const r = width / height;
const s = width / 1080;
if (r < 0.7) return { top: 220 * s, right: 140 * s, bottom: 420 * s, left: 60 * s };
if (r < 0.9) return { top: 110 * s, right: 60 * s, bottom: 170 * s, left: 60 * s };
if (r < 1.2) return { top: 70 * s, right: 60 * s, bottom: 120 * s, left: 60 * s };
return { top: (120 * height) / 1080, right: (60 * width) / 1920, bottom: (120 * height) / 1080, left: (60 * width) / 1920 };
}
-136
View File
@@ -1,136 +0,0 @@
// components/crop.ts: where the people are in a take over a span, and the window of the take a panel of any shape shows
// so each one framed is whole, its eyes a third down, and no one else is cut by the panel's edge. Shot.tsx and Cut.tsx
// lay out every layout from it (a split's two halves, a stack's speaker half, an insert's shot), from the faces the
// box's prep found (footage/faces.json, image/faces.py), so no crop is a number an agent typed. Pure: no React.
//
// A take's faces: {"w", "h", "t": [seconds], "s": [[[cx, ey, fw, fh, score], ...], ...]}, shares of the picture, each
// sample's largest first (faces.py).
export type Take = { w: number; h: number; t: number[]; s: number[][][] };
/** someone in a take over a span: where their face sits (median), its largest size, and how often they're seen */
export type Person = { cx: number; ey: number; fw: number; fh: number; seen: number; left: number; right: number };
/** the part of a take a panel shows, in shares of the take: its left and top edges and its width and height */
export type Win = { left: number; top: number; vw: number; vh: number; zoom: number };
const clamp = (x: number, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const median = (xs: number[]) => {
const s = [...xs].sort((a, b) => a - b);
return s.length ? s[Math.floor(s.length / 2)] : 0.5;
};
/** a face this share of the take's height or more is someone in the shot; smaller, a passer-by */
export const IN_SHOT = 0.05;
/** room kept round the framed face, in its own widths, either side */
export const ROOM = 1 / 3;
/** the most a panel zooms into a take past cover. The render reads the originals, and a street take is a phone's 4K: 4x
* of it is 960 px across for a 1080 panel, which holds. (faces.json is measured on the light copies, so it can't say
* the original's size.) */
export const MOST_ZOOM = 4;
/** the people in a take between `a` and `b` seconds, the most seen first: each sample's faces joined to the nearest
* person already found (within a face width and a half across), so one person is one entry across the span */
export function people(take: Take | undefined, a: number, b: number): Person[] {
if (!take) return [];
const runs: { cx: number[]; ey: number[]; fw: number[]; fh: number[]; n: number }[] = [];
let samples = 0;
for (let i = 0; i < take.t.length; i++) {
if (take.t[i] < a - 0.5 || take.t[i] > b + 0.5) continue;
samples++;
for (const f of take.s[i] ?? []) {
if (f[3] < IN_SHOT) continue;
const near = runs.find((r) => Math.abs(median(r.cx) - f[0]) < 1.5 * Math.max(f[2], median(r.fw)));
const r = near ?? (runs.push({ cx: [], ey: [], fw: [], fh: [], n: 0 }), runs[runs.length - 1]);
r.cx.push(f[0]);
r.ey.push(f[1]);
r.fw.push(f[2]);
r.fh.push(f[3]);
r.n++;
}
}
return runs
.map((r) => {
const fw = Math.max(...r.fw);
return { cx: median(r.cx), ey: median(r.ey), fw, fh: Math.max(...r.fh), seen: samples ? r.n / samples : 0, left: Math.min(...r.cx) - fw / 2, right: Math.max(...r.cx) + fw / 2 };
})
.filter((p) => p.seen >= 0.3)
.sort((p, q) => q.seen * q.fw - p.seen * p.fw);
}
/** the person `who` names: a number is the face nearest that share across the take (0 left, 1 right), "left" and
* "right" the leftmost and rightmost, anything else (or nothing) the largest */
export function pick(ps: Person[], who?: number | string): Person | undefined {
if (!ps.length) return undefined;
if (typeof who === "number") return ps.reduce((p, q) => (Math.abs(q.cx - who) < Math.abs(p.cx - who) ? q : p));
if (who === "left") return ps.reduce((p, q) => (q.cx < p.cx ? q : p));
if (who === "right") return ps.reduce((p, q) => (q.cx > p.cx ? q : p));
return ps[0];
}
/** the window of `take` a panel `bw` x `bh` shows framed on `on`: the largest that holds the face whole with room and
* cuts no one else (each other face either whole inside or wholly out), zoomed in up to MOST_ZOOM to leave the others
* out when they'd be cut; the eyes a third down. With `alone`, zoomed until no one else shows, when that's possible */
export function windowOn(take: Take, bw: number, bh: number, on: Person | undefined, others: Person[], alone = false): Win {
const box = bw / bh;
const src = take.w / take.h;
// the window at zoom 1 (object-fit: cover), in shares of the take
const vw1 = Math.min(1, box / src);
const vh1 = Math.min(1, src / box);
if (!on) return { left: (1 - vw1) / 2, top: (1 - vh1) / 2, vw: vw1, vh: vh1, zoom: 1 };
const lo = on.left - on.fw * ROOM;
const hi = on.right + on.fw * ROOM;
const cuts = (l: number, vw: number) => others.some((o) => (l > o.left && l < o.right) || (l + vw > o.left && l + vw < o.right));
const shows = (l: number, vw: number) => others.some((o) => o.right > l && o.left < l + vw);
for (let zoom = 1; zoom <= MOST_ZOOM + 1e-6; zoom += 0.05) {
const vw = vw1 / zoom;
const vh = vh1 / zoom;
if (hi - lo > vw) break; // the face and its room no longer fit: the last zoom that held it is the answer below
const ideal = clamp(on.cx - vw / 2, 0, 1 - vw);
// the left edges that keep the face and its room: from hi - vw to lo, inside the take
const a = clamp(hi - vw, 0, 1 - vw);
const b = clamp(lo, 0, 1 - vw);
if (a > b) continue;
const tries = [ideal, a, b, ...others.flatMap((o) => [o.right + 0.005, o.left - vw - 0.005])].map((l) => clamp(l, a, b));
const ok = tries.filter((l) => !cuts(l, vw) && (!alone || !shows(l, vw)));
if (ok.length) {
const left = ok.reduce((x, y) => (Math.abs(y - ideal) < Math.abs(x - ideal) ? y : x));
const top = clamp(on.ey - vh / 3, 0, 1 - vh);
return { left, top, vw, vh, zoom };
}
}
// no window shows them alone: the clean one that shows others too
if (alone) return windowOn(take, bw, bh, on, others, false);
// nothing clean: the face whole at zoom 1, centred on it (the check says what it cuts)
return { left: clamp(on.cx - vw1 / 2, 0, 1 - vw1), top: clamp(on.ey - vh1 / 3, 0, 1 - vh1), vw: vw1, vh: vh1, zoom: 1 };
}
/** whether a window can show `on` alone (no one else in it), for a split's halves */
export function holdsAlone(take: Take, bw: number, bh: number, on: Person, others: Person[]): boolean {
const w = windowOn(take, bw, bh, on, others, true);
return !others.some((o) => o.right > w.left && o.left < w.left + w.vw) && on.left >= w.left - 1e-3 && on.right <= w.left + w.vw + 1e-3;
}
/** a window as CSS for a <Video> filling a panel: the video's own box (px, inside the panel, overflow hidden), cover
* fitted, and its object-position. The render's manifest then holds the window exactly (box, clip, position) */
export function css(win: Win, bw: number, bh: number): { left: number; top: number; width: number; height: number; objectPosition: string } {
const width = bw * win.zoom;
const height = bh * win.zoom;
// the window at zoom 1 (cover of the enlarged box), and where the panel sits inside it
const vw1 = win.vw * win.zoom;
const vh1 = win.vh * win.zoom;
// the enlarged box shows [l1, l1 + vw1] of the take; the panel the middle `vw` of it at offset (left - l1)
const l1 = clamp(win.left - (vw1 - win.vw) / 2, 0, 1 - vw1);
const t1 = clamp(win.top - (vh1 - win.vh) / 3, 0, 1 - vh1);
const px = vw1 >= 1 ? 50 : (l1 / (1 - vw1)) * 100;
const py = vh1 >= 1 ? 50 : (t1 / (1 - vh1)) * 100;
const left = -((win.left - l1) / vw1) * width;
const top = -((win.top - t1) / vh1) * height;
return { left, top, width, height, objectPosition: `${+px.toFixed(3)}% ${+py.toFixed(3)}%` };
}
/** a face's box on screen (px), when its take's window `win` fills the panel at `x`, `y`, `bw` x `bh` */
export function onScreen(p: Pick<Person, "cx" | "ey" | "fw" | "fh">, win: Win, x: number, y: number, bw: number, bh: number): [number, number, number, number] {
const sx = bw / win.vw;
const sy = bh / win.vh;
const top = p.ey - 0.4 * p.fh; // the eyes sit about 0.4 of the way down a face's box (YuNet's)
return [x + (p.cx - p.fw / 2 - win.left) * sx, y + (top - win.top) * sy, p.fw * sx, p.fh * sy];
}
-100
View File
@@ -1,100 +0,0 @@
#!/usr/bin/env python3
"""A take's faces, twice a second, for framing it (12-05, Shane: "the ai fucks up the composition of subjects in frame all
the time"). The agent placed each 9:16 crop by a number it guessed (objectPosition), and cut the speaker off at the edge
while the middle held a bench. This finds where the faces are, so components/Framed.tsx places the crop on them.
faces.py TAKE... -o OUT.json one JSON object, by each take's name without its extension:
{"w": W, "h": H, "t": [seconds, ...], "s": [[[cx, ey, fw, fh, score], ...], ...]}
cx: the face's centre across, ey: its eyes down, fw and fh: its size, all in shares of the picture; a sample's faces
largest first, at most 3, those YuNet scores 0.7 or more, at each of the take's keyframes (a phone's come about once a
second: only they are decoded, so a take is read many times faster than played; 12-05, every frame took 343 s for
a 36-take street shoot). A take it can't read is left out (the component then centres).
YuNet (opencv_zoo face_detection_yunet_2023mar, MIT) on the CPU: a 640-wide frame in a few ms.
"""
import json
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
import cv2
import numpy as np
MODEL = os.environ.get("RAEA_YUNET", "/opt/yunet.onnx")
WIDE = 640
LEAST = 0.7
MOST = 3
def size(take):
r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_side_data=rotation", "-of", "json", take], capture_output=True, text=True, stdin=subprocess.DEVNULL)
s = (json.loads(r.stdout or "{}").get("streams") or [{}])[0]
w, h = int(s.get("width") or 0), int(s.get("height") or 0)
rot = next((abs(int(d.get("rotation", 0))) for d in s.get("side_data_list") or [] if "rotation" in d), 0)
return (h, w) if rot in (90, 270) else (w, h)
def keytimes(take):
"""the keyframes' times, from the packets' flags (nothing decoded): the frames -skip_frame nokey gives, in order"""
r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0", take], capture_output=True, text=True, stdin=subprocess.DEVNULL)
ts = []
for line in r.stdout.splitlines():
f = line.split(",")
if len(f) >= 2 and "K" in f[1]:
try:
ts.append(round(float(f[0]), 2))
except ValueError:
pass
return sorted(ts)
def faces(take):
w, h = size(take)
if not w or not h:
return None
ts = keytimes(take)
sw, sh = WIDE, max(2, round(WIDE * h / w / 2) * 2)
det = cv2.FaceDetectorYN.create(MODEL, "", (sw, sh), LEAST, 0.3, 50)
p = subprocess.Popen(["ffmpeg", "-nostdin", "-v", "error", "-skip_frame", "nokey", "-i", take, "-fps_mode", "passthrough", "-vf", f"scale={sw}:{sh}", "-f", "rawvideo", "-pix_fmt", "bgr24", "-"], stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
n = sw * sh * 3
out = []
while True:
b = p.stdout.read(n)
if len(b) < n:
break
im = np.frombuffer(b, np.uint8).reshape(sh, sw, 3)
_, got = det.detect(im)
fs = []
for f in got if got is not None else []:
x, y, fw, fh = (float(v) for v in f[:4])
ey = (float(f[5]) + float(f[7])) / 2 # the right eye's y and the left's
fs.append([round((x + fw / 2) / sw, 3), round(ey / sh, 3), round(fw / sw, 3), round(fh / sh, 3), round(float(f[14]), 2)])
fs.sort(key=lambda f: -f[2] * f[3])
out.append(fs[:MOST])
p.wait()
k = min(len(ts), len(out))
return {"w": w, "h": h, "t": ts[:k], "s": out[:k]}
def main(a):
if "-o" not in a or a.index("-o") + 1 >= len(a):
print(__doc__, file=sys.stderr)
return 2
o = a[a.index("-o") + 1]
takes = [x for i, x in enumerate(a) if x != "-o" and (i == 0 or a[i - 1] != "-o")]
cv2.setNumThreads(1)
res = {}
with ThreadPoolExecutor(os.cpu_count() or 2) as ex:
for take, got in zip(takes, ex.map(lambda t: (lambda: faces(t))() if os.path.exists(t) else None, takes)):
if got and any(got["s"]):
res[os.path.splitext(os.path.basename(take))[0]] = got
with open(o + ".part", "w") as f:
json.dump(res, f, separators=(",", ":"))
os.replace(o + ".part", o)
print(f"faces: {len(res)} of {len(takes)} takes", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -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)))
+2 -4
View File
@@ -8,7 +8,7 @@
// POST /v1/claude-token/check {token} {ok, said}: one short turn on a token
import { type ChildProcess, spawn } from "node:child_process"
import { randomBytes } from "node:crypto"
import { existsSync, mkdtempSync, rmSync } from "node:fs"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
@@ -48,9 +48,7 @@ while True:
os.write(fd, b)
os.kill(pid, 9) if os.waitpid(pid, os.WNOHANG) == (0, 0) else None
`
// Claude Code where the image installs it (~/.local/bin, the agents' own), not only on the server's PATH, which holds the
// system's folders alone: 12-05, a sign-in link answered "No such file or directory" and no one could connect Claude
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? [path.join(process.env.HOME ?? "/home/raea", ".local/bin/claude"), "/home/raea/.local/bin/claude"].find((p) => existsSync(p)) ?? "claude"
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? "claude"
const TOKEN = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/
/** the text a terminal shows, with its escapes gone; OSC 8 links keep their address */
+14 -66
View File
@@ -144,9 +144,8 @@ const SMALL = 256 << 10
/** the farm's cache of media (farm.py POST /v1/blobs/have, PUT /v1/blobs/OID), over its own token */
export interface FarmBlobs {
/** which of these it holds, and whether it fetches an original of unknown size by its link; null when this farm has
* no cache (an older one): the media goes in the tar */
have(objects: { oid: string; size: number }[]): Promise<{ held: Set<string>; links: boolean } | null>
/** which of these it holds; null when this farm has no cache (an older one): the media goes in the tar */
have(objects: { oid: string; size: number }[]): Promise<Set<string> | null>
put(file: string, oid: string, size: number): Promise<void>
}
@@ -157,8 +156,7 @@ export function farmBlobs(url: string, token: string): FarmBlobs {
const r = await fetch(`${url}/v1/blobs/have`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ objects }) })
if (r.status === 404) return null
if (!r.ok) throw new Error(`the farm's media cache answered ${r.status}: ${(await r.text()).slice(0, 200)}`)
const j = (await r.json()) as { have: string[]; links?: number }
return { held: new Set(j.have), links: j.links === 1 }
return new Set(((await r.json()) as { have: string[] }).have)
},
async put(file, oid, size) {
// streamed from the disk: a file is never held in memory (a project's interviews are gigabytes)
@@ -201,7 +199,7 @@ function hashes(file: string) {
* farm's cache and named in the job's manifest with no href, so a render's tar holds the code and not the footage
* (StreetTalk's 1.9 GB of interviews went in every render's tar, even one frame's). null when the farm has no cache.
* `skip`: the tar's excludes. Links are left to the tar, as before. */
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json"), instead: Map<string, string> = new Map()): Promise<{ media: Media[]; sent: number; links: boolean } | null> {
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json")): Promise<{ media: Media[]; sent: number } | null> {
const found: { path: string; abs: string; id: string; size: number; mtime: number }[] = []
const walk = (dir: string) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
@@ -210,77 +208,28 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
if (skip(rel)) continue
if (e.isDirectory()) walk(abs)
else if (e.isFile()) {
// `instead`: a light copy whose original is here goes as that file, under the light copy's path (originals.ts)
const file = instead.get(rel) ?? abs
const st = statSync(file)
const st = statSync(abs)
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs: file, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
}
}
}
walk(root)
if (!found.length) {
const can = await farm.have([])
return can ? { media: [], sent: 0, links: can.links } : null
}
if (!found.length) return { media: [], sent: 0 }
const h = hashes(store)
const media: (Media & { abs: string })[] = []
for (const f of found) media.push({ path: f.path, oid: await h.of(f.abs, f.id, f.size, f.mtime), size: f.size, abs: f.abs })
h.save()
const can = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
if (!can) return null
const have = can.held
const have = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
if (!have) return null
let sent = 0
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
// four at a time: one by one, 50 takes took minutes on a box whose uplink sits mostly idle
let next = 0
const one = async () => {
for (let i = next++; i < todo.length; i = next++) {
await farm.put(todo[i].abs, todo[i].oid, todo[i].size)
sent += todo[i].size
}
for (const m of todo) {
await farm.put(m.abs, m.oid, m.size)
sent += m.size
}
await Promise.all(Array.from({ length: Math.min(4, todo.length) }, one))
return { media: media.map(({ abs: _, ...m }) => m), sent, links: can.links }
}
/** the project's video and audio that no source file names, which a render doesn't need: neither sent to the farm nor
* packed. 12-03: footage/originals/ (the full-size takes, several GB) went to the farm on the first render of every
* StreetTalk run, a still included, and the render ran past its 5 minutes. A file is named by its path, its file name,
* or its stem with its folder's name ("originals/" + `${id}.mov`). When no source names any, all of it is used, as
* before; RAEA_CLOUD_GPU_ALL_MEDIA=1 sends it all regardless */
export function unusedMedia(root: string, skip: (p: string) => boolean = () => false): string[] {
if (process.env.RAEA_CLOUD_GPU_ALL_MEDIA === "1") return []
const AV = new Set(["mp4", "mov", "m4v", "webm", "mkv", "mxf", "avi", "wav", "mp3", "m4a", "aac", "flac", "ogg"])
const SRC = new Set(["tsx", "ts", "jsx", "js", "mjs", "json", "css"])
// folders of what's made for the agent or by a render, not what a composition reads from (footage/index.json lists
// every take)
const NOT_SOURCE = new Set(["footage", "brief_docs", "review", "out", "node_modules", "previews"])
const av: string[] = []
let text = ""
const walk = (dir: string, source: boolean) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const abs = path.join(dir, e.name)
const rel = path.relative(root, abs).split(path.sep).join("/")
if (skip(rel) || e.name === ".git" || e.name.startsWith(".raea-cloud")) continue
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
if (e.isDirectory()) walk(abs, source && !(dir === root && NOT_SOURCE.has(e.name)))
else if (e.isFile() && AV.has(ext)) av.push(rel)
else if (e.isFile() && source && SRC.has(ext) && statSync(abs).size < 2 << 20) text += readFileSync(abs, "utf8") + "\n"
}
}
walk(root, true)
const named = (rel: string) => {
const name = rel.split("/").pop()!
const stem = name.replace(/\.[^.]+$/, "")
const folder = rel.includes("/") ? rel.split("/").slice(-2, -1)[0] + "/" : ""
return text.includes(rel) || text.includes(name) || (stem.length >= 3 && text.includes(stem) && (!folder || text.includes(folder)))
}
const used = av.filter(named)
// footage/originals/ (the full-size takes, gigabytes) goes only when a source names it, even when none names anything
// (12-05 review): an original by its file goes in its light copy's place (originals.ts), not as itself
return used.length ? av.filter((f) => !used.includes(f)) : av.filter((f) => f.startsWith("footage/originals/"))
return { media: media.map(({ abs: _, ...m }) => m), sent }
}
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
@@ -295,8 +244,7 @@ export function localSources(manifest: { sounds?: { clips?: { src: string }[] }
const byOid = new Map(media.map((m) => [m.oid, m.path]))
let n = 0
for (const c of manifest.sounds?.clips ?? []) {
// the farm's blob (blobs/OID) or the same under its own name (blobs/named/OID/NAME)
const oid = /(?:^|\/)(?:blobs\/)?(?:named\/)?([0-9a-f]{64})(?:\/[^/]+)?$/.exec(c.src)?.[1]
const oid = /(?:^|\/)(?:blobs\/)?([0-9a-f]{64})$/.exec(c.src)?.[1]
const p = oid ? byOid.get(oid) : undefined
if (p) {
c.src = path.join(root, p)
+16 -70
View File
@@ -21,8 +21,7 @@ import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { RaeaCloud } from "../src/index.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs, unusedMedia } from "./media.ts"
import { lightCopies, originalsRecord, recordOriginals, resolveOriginals, settle, withOriginals } from "./originals.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs } from "./media.ts"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
// flags whose value is a path raea writes; the rest of a render's path arguments are read
@@ -32,24 +31,12 @@ const COMPOSITION = /\.(tsx|ts|jsx|js|mjs|html)$/
const say = (s: string) => process.stderr.write(`raea cloud: ${s}\n`)
function local(args: string[], why?: string, root?: string): never {
function local(args: string[], why?: string): never {
if (why) say(`${why}, so this runs here, on the CPU`)
// here every take is its light copy: the record says so, as the farm's would (CL20)
const lit = lightCopies(root ?? process.cwd())
if (lit.length) say(`NO ORIGINAL: a render here reads footage's light copies, so it's a draft that's never shown or published`)
const r = spawnSync(REAL, args, { stdio: "inherit" })
const oi = args.indexOf("-o")
const mi = args.indexOf("--manifest")
const out = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
if (lit.length && !r.status && out && existsSync(out)) keep(out, mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : null, { read: [], light: [...lit].sort() })
process.exit(r.status ?? 1)
}
/** the render's record of what it read (originals.ts recordOriginals), said aloud when it couldn't be kept */
function keep(out: string, manifest: string | null, rec: { read: string[]; light: string[] }) {
for (const f of recordOriginals(out, manifest, rec).failed) say(`WARNING: couldn't add what this render read to ${f} (not a JSON object): raea cloud can't tell whether it read a light copy`)
}
const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep)
/** The project a render's composition is in: its folder, or the nearest above it that holds a project's files. */
@@ -105,7 +92,7 @@ async function main() {
{
const oi = args.indexOf("-o")
const o = oi >= 0 ? (args[oi + 1] ?? "") : ""
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest"))
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest") && process.env.RAEA_CLOUD_CHECK !== "0")
args.push("--manifest", `${o.slice(0, o.length - path.extname(o).length)}.render.json`)
}
const url = process.env.RAEA_CLOUD_GPU_URL
@@ -118,44 +105,22 @@ async function main() {
try {
// kits/ (raea-game-kit) is a link into the box's shared cache, hundreds of MB, that the farm can't follow: a
// composition uses copies of the kit files it needs in its own folder (11-21: the dangling link hung farm jobs)
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits ./.raea-cloud/proxies").split(/\s+/).filter(Boolean)
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits").split(/\s+/).filter(Boolean)
// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its own
const gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")
const sent = path.join(tmp, "in.tar")
// the media that goes by hash: out of the tar, named in its manifest
const lfs = lfsOf(p.root)
// video and audio no source file names stays here, out of the tar and the farm's cache (media.ts unusedMedia)
const unused = new Set(unusedMedia(p.root, excluded(excludes)))
if (unused.size) say(`${unused.size} video and audio files no source names stay here`)
const skip = (rel: string) => excluded(excludes)(rel) || unused.has(rel)
// each light copy the render reads goes as its full-size original (originals.ts): by its link, fetched by the farm
// itself, else by its file here. The light copy's own bytes never go
let orig = resolveOriginals(p.root, (rel) => !skip(rel))
const linked = new Set(orig.byLink.map((m) => m.path))
// what stays out of the farm's cache and LFS: what's skipped, and each light copy whose original goes by its link
const unsent = (rel: string) => skip(rel) || linked.has(rel)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, unsent)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
// leaves it in the tar, and the health check below says why the farm can't be reached
let viaFarm: { media: typeof byHash; sent: number; links: boolean } | null = null
let viaFarm: { media: typeof byHash; sent: number } | null = null
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
viaFarm = await farmInputs(p.root, farmBlobs(url, token), unsent, say, undefined, orig.byFile).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
if (viaFarm) byHash = viaFarm.media
}
// what reaches the farm decides what the render reads, decided once for every path: each original by its link in its
// light copy's place; what can't go is the light copy, recorded
// (LFS: the farm fetches by size from R2, so an original of unknown size or by its file can't go)
orig = settle(orig, viaFarm ? { links: viaFarm.links } : null)
byHash = withOriginals(byHash, orig)
if (orig.byLink.length || orig.byFile.size) say(`${orig.byLink.length + orig.byFile.size} takes go as their full-size originals${orig.byLink.length ? ` (${orig.byLink.length} fetched by the farm from the library)` : ""}`)
for (const w of orig.why) say(w)
if (orig.light.length) say(`NO ORIGINAL for ${orig.light.join(", ")}: rendered from the light copy, so this render is a draft that's never shown or published`)
const extra: string[] = []
if (unused.size) {
writeFileSync(path.join(tmp, "unused-excludes"), mediaExcludes([...unused].map((f) => ({ path: f, oid: "", size: 0 }))))
extra.push("-X", path.join(tmp, "unused-excludes"))
}
if (byHash.length) {
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
writeFileSync(path.join(tmp, ".raea-cloud-media.json"), JSON.stringify({ objects: byHash }))
@@ -171,20 +136,16 @@ async function main() {
try {
h = await cloud.health()
} catch (e) {
if (process.env.RAEA_CLOUD_GPU_FALLBACK === "cpu") local(args, `the GPU worker at ${url} didn't answer (${(e as Error).message})`, p.root)
if (process.env.RAEA_CLOUD_GPU_FALLBACK === "cpu") local(args, `the GPU worker at ${url} didn't answer (${(e as Error).message})`)
throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)
}
say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)
// what's fetched from the library by its link is counted apart: its size may be unknown
const cached = byHash.filter((m) => !("href" in m && orig.byLink.some((l) => l.path === m.path)))
const mb = (ms: { size: number }[]) => (ms.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)
if (viaFarm && cached.length) say(`${cached.length} media files (${mb(cached)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
else if (cached.length) say(`${cached.length} media files (${mb(cached)} MB) go by hash: the farm fetches them from R2`)
if (viaFarm && byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
else if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND (the card: it went as "gpu",
// which the client never read, so a named card never reached the farm), RAEA_CLOUD_MAX_USD, RAEA_CLOUD_NV (1 or 0)
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
const n = (v?: string) => (v ? Number(v) : undefined)
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), cpus: n(process.env.RAEA_CLOUD_CPUS), kept: process.env.RAEA_CLOUD_KEPT === "0" ? false : undefined, card: process.env.RAEA_CLOUD_GPU_KIND || undefined, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), nv: process.env.RAEA_CLOUD_NV === "1" ? true : process.env.RAEA_CLOUD_NV === "0" ? false : undefined, media: typeof lfs !== "string" }
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), cpus: n(process.env.RAEA_CLOUD_CPUS), kept: process.env.RAEA_CLOUD_KEPT === "0" ? false : undefined, gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }
let finish: (() => Promise<number>) | undefined
const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => {
const o = await outputs(p.root, lfs, made)
@@ -212,13 +173,6 @@ async function main() {
}
rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })
for (const m of p.moves) rmSync(path.join(p.root, m.from), { force: true })
// what it read, kept with it whether it's checked or not, video or still (CL20)
{
const oi = args.indexOf("-o")
const mi = args.indexOf("--manifest")
const out = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
if (out && existsSync(out)) keep(out, mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : null, originalsRecord(orig))
}
if (finish) {
const bytes = await finish()
say(`its media (${(bytes / 1e6).toFixed(1)} MB) went from the farm to R2; here it's pointers (git lfs pull PATH brings one here)`)
@@ -239,25 +193,20 @@ async function main() {
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
const beside = `${made.slice(0, made.length - path.extname(made).length)}.render.json`
if (man && man !== beside && existsSync(man)) writeFileSync(beside, readFileSync(man))
// its takes named as they are here, not as the farm's cache holds them, so every edit point is checked; and which
// light copies it read as their originals and which as themselves (raea cloud shows none of the latter)
if (existsSync(beside)) {
// its takes named as they are here, not as the farm's cache holds them, so every edit point is checked
if (byHash.length && existsSync(beside)) {
try {
const m = JSON.parse(readFileSync(beside, "utf8"))
if (byHash.length && localSources(m, byHash, p.root)) writeFileSync(beside, JSON.stringify(m))
if (localSources(m, byHash, p.root)) writeFileSync(beside, JSON.stringify(m))
} catch (e) {
say(`${path.basename(beside)}: ${(e as Error).message}`)
}
}
say(`raea goal check ${path.basename(made)} --at render`)
const r = spawnSync(REAL, CHECK_ARGS(made), { stdio: "inherit", env: { ...process.env, RAEA_REAL: REAL } })
const r = spawnSync(REAL, ["make", "check", made, "--at", "render"], { stdio: "inherit", env: { ...process.env, RAEA_REAL: REAL } })
if (r.status === 1) {
say(`${path.basename(made)} fails its checks: fix every ERROR above (each says what to change), then render again before any review`)
process.exitCode = 1
} else if (r.status !== 0) {
// a refused or crashed check is loud: called by an old name, it was refused with exit 2 and every cloud render went unchecked
say(`raea goal check couldn't check ${path.basename(made)} (exit ${r.status ?? r.signal}): the render isn't done until it can`)
process.exitCode = r.status || 1
}
}
} finally {
@@ -265,9 +214,6 @@ async function main() {
}
}
/** raea's one check on a finished render, as the box runs it */
export const CHECK_ARGS = (made: string) => ["goal", "check", made, "--at", "render"]
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
main().catch((e) => {
say((e as Error).message)
-201
View File
@@ -1,201 +0,0 @@
// Light copies on the box, originals on the farm (docs/cloud.feature CL17-CL20). raea cloud brings a run's footage onto
// its box as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt): every look the agent takes reads
// them, and nothing on the box ever puts anything else in their place. A render on the farm reads each one's full-size
// original instead, resolved here as the render is sent:
//
// by its link .raea-cloud/originals.json, written by raea cloud at the run's start and again before each render:
// {"footage/NAME.mp4": {"sha256", "bytes", "url", "expires"}}. The farm fetches the original from the
// library itself and keeps it by its hash, so the box never downloads it or sends it on (12-05, Dutch
// run 24: each run's box fetched 2.4 GB of originals and hashed and sent them to the farm again)
// by its file footage/originals/NAME.EXT, fetched onto the box for a take the library has no hash for: sent in the
// light copy's place, by its own hash
//
// A light copy with neither is rendered as itself and named in the render's manifest ("originals": {"light": [...]}),
// so raea cloud never shows or publishes what was made from it.
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import type { Media } from "../src/index.ts"
export const LIGHT_LIST = ".raea-cloud/light.txt"
export const ORIGINALS_MAP = ".raea-cloud/originals.json"
export const ORIGINALS_DIR = "footage/originals"
/** a link that ends sooner than this isn't handed to the farm: it would be gone before the farm asks for it */
export const LINK_MARGIN_MS = 5 * 60_000
export interface Original {
sha256?: string
bytes?: number
url?: string
/** when the link stops working (ms since 1970); none, it's taken as working */
expires?: number
}
/** where each light copy a render reads comes from */
export interface Resolved {
/** fetched by the farm from its link: the light copy's path, the original's hash, size and link */
byLink: (Media & { href: string })[]
/** sent from the box: the light copy's path, the original's file here */
byFile: Map<string, string>
/** rendered as themselves: no usable link and no file */
light: string[]
/** why a light copy's link wasn't used, a line each */
why: string[]
}
const read = (f: string) => {
try {
return readFileSync(f, "utf8")
} catch {
return ""
}
}
const stem = (n: string) => n.replace(/\.[^./]*$/, "")
const HASH = /^[0-9a-f]{64}$/
/** the light copies here, as paths from the project's top (footage/NAME.mp4) */
export function lightCopies(root: string): string[] {
const names = read(path.join(root, LIGHT_LIST)).split("\n").map((s) => s.trim()).filter(Boolean)
return [...new Set(names.map((n) => (n.startsWith("footage/") ? n : `footage/${n}`)))].filter((p) => !p.includes("..") && existsSync(path.join(root, p)))
}
/** .raea-cloud/originals.json, each entry kept only when it's a light copy's path and an object */
export function originalsMap(root: string): Record<string, Original> {
let j: unknown
try {
j = JSON.parse(read(path.join(root, ORIGINALS_MAP)) || "{}")
} catch {
return {}
}
const out: Record<string, Original> = {}
if (!j || typeof j !== "object" || Array.isArray(j)) return out
for (const [k, v] of Object.entries(j as Record<string, unknown>)) if (v && typeof v === "object" && !Array.isArray(v)) out[k.startsWith("footage/") ? k : `footage/${k}`] = v as Original
return out
}
/** a light copy's original fetched onto the box: footage/originals/ holds it under the light copy's name, any extension */
export function originalFile(root: string, light: string): string | null {
// prep puts every light copy straight in footage/: one in a folder of its own has no original here by its name
if (path.posix.dirname(light) !== "footage") return null
const dir = path.join(root, ORIGINALS_DIR)
const want = stem(path.basename(light)).toLowerCase()
let names: string[] = []
try {
names = readdirSync(dir)
} catch {
return null
}
for (const n of names.sort()) {
if (n === "STATUS" || n.startsWith(".") || /\.(json|txt|part|lock|tsv)$/i.test(n) || stem(n).toLowerCase() !== want) continue
const abs = path.join(dir, n)
try {
const st = statSync(abs)
if (st.isFile() && st.size > 0) return abs
} catch {}
}
return null
}
/** Each light copy a render reads (`uses`: the render's media walk would send it), resolved to its original. */
export function resolveOriginals(root: string, uses: (p: string) => boolean, now = Date.now()): Resolved {
const map = originalsMap(root)
const r: Resolved = { byLink: [], byFile: new Map(), light: [], why: [] }
for (const l of lightCopies(root)) {
if (!uses(l)) continue
const o = map[l]
if (o) {
const bad =
typeof o.sha256 !== "string" || !HASH.test(o.sha256) ? "no hash"
: typeof o.url !== "string" || !/^https:\/\//.test(o.url) ? "no link"
: typeof o.expires === "number" && o.expires < now + LINK_MARGIN_MS ? "its link has ended"
: null
if (!bad) {
r.byLink.push({ path: l, oid: o.sha256!, size: typeof o.bytes === "number" && o.bytes > 0 ? Math.round(o.bytes) : 0, href: o.url! })
continue
}
r.why.push(`${l}: ${bad}`)
}
const f = originalFile(root, l)
if (f) r.byFile.set(l, f)
else r.light.push(l)
}
return r
}
/** what can reach the farm: an original by its file goes only into the farm's cache (by LFS or in the tar it would go as
* the light copy), and one of unknown size only to a farm that says it fetches those (`links` from /v1/blobs/have: an
* older farm checks every size). What can't is rendered as its light copy, and said */
export function settle(r: Resolved, farm: { links: boolean } | null): Resolved {
if (farm?.links) return r
const out: Resolved = { byLink: [], byFile: farm ? new Map(r.byFile) : new Map(), light: [...r.light], why: [...r.why] }
for (const m of r.byLink) {
if (m.size > 0) out.byLink.push(m)
else (out.light.push(m.path), out.why.push(`${m.path}: this farm doesn't fetch an original of unknown size`))
}
if (!farm) for (const l of r.byFile.keys()) (out.light.push(l), out.why.push(`${l}: this farm has no media cache, so its original's file can't go to it`))
return out
}
/** the paths a render's manifest names as its sources (any "src" in it, as footage/NAME), or null when it names none */
export function manifestSources(m: unknown): Set<string> | null {
const out = new Set<string>()
const walk = (v: unknown) => {
if (Array.isArray(v)) for (const x of v) walk(x)
else if (v && typeof v === "object")
for (const [k, x] of Object.entries(v)) {
if (k === "src" && typeof x === "string") {
const f = /(?:^|\/)footage\/([^/?#]+)$/.exec(x.replace(/\\/g, "/"))
if (f) out.add(`footage/${f[1]}`)
} else walk(x)
}
}
walk(m)
return out.size ? out : null
}
/** the render's media by hash: what went (by LFS or into the farm's cache) with each original by its link in its light
* copy's place */
export function withOriginals<M extends { path: string }>(media: M[], r: Resolved): (M | (Media & { href: string }))[] {
const linked = new Set(r.byLink.map((m) => m.path))
return [...media.filter((m) => !linked.has(m.path)), ...r.byLink]
}
/** a render's record of what it read, in its manifest (its --manifest, else OUT.render.json beside it, made when there's
* none: a still), so raea cloud never shows or publishes what was made from a light copy */
export function recordOriginals(out: string, manifest: string | null, rec: { read: string[]; light: string[] }): { files: string[]; failed: string[] } {
const beside = `${out.slice(0, out.length - path.extname(out).length)}.render.json`
const files: string[] = []
const failed: string[] = []
// into the --manifest and beside the output both: whichever raea cloud reads, it holds the record
const targets = [...new Set([...(manifest && existsSync(manifest) ? [manifest] : []), beside])]
let named: Set<string> | null = null
for (const file of targets) {
let m: Record<string, unknown> = {}
try {
if (existsSync(file)) m = JSON.parse(readFileSync(file, "utf8"))
} catch {
failed.push(file)
continue
}
if (!m || typeof m !== "object" || Array.isArray(m)) {
failed.push(file)
continue
}
named ??= manifestSources(m)
// only what this render read, when its manifest says what it read
const r = named ? { read: rec.read.filter((f) => named!.has(f)), light: rec.light.filter((f) => named!.has(f)) } : rec
if (!r.read.length && !r.light.length) {
// a clean render: an earlier render's record goes, and no file is made for nothing
if (!("originals" in m)) continue
delete m.originals
} else m.originals = r
writeFileSync(file, JSON.stringify(m))
files.push(file)
}
return { files, failed }
}
/** what a render read, for its manifest: the light copies sent as their originals, and those sent as themselves */
export function originalsRecord(r: Resolved): { read: string[]; light: string[] } {
return { read: [...r.byLink.map((m) => m.path), ...r.byFile.keys()].sort(), light: [...r.light].sort() }
}
-4
View File
@@ -39,9 +39,6 @@ export interface Farm {
kept?: boolean
card?: string
maxUsd?: number
/** NVIDIA's encoder and decoder (RAEA_NV) for every run: true on, false off; unset, only a piece with 3D in it (CR34).
* On forces the job onto GPUs */
nv?: boolean
/** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */
media?: boolean
}
@@ -172,7 +169,6 @@ export class RaeaCloud {
if (farm.card) q.set("gpu", farm.card)
if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd))
if (farm.media) q.set("media", "1")
if (farm.nv !== undefined) q.set("nv", farm.nv ? "1" : "0")
const r = await this.fetch(`/v1/jobs?${q}`, { method: "POST", body: new Blob([folder as Uint8Array<ArrayBuffer>]), headers: { "content-type": "application/octet-stream" }, signal })
return ((await r.json()) as { id: string }).id
}
-104
View File
@@ -1,104 +0,0 @@
# The farm API's volume gate (deploy/modal/farm.py's Gate, cut from the file as it is) against a stand-in volume:
# python3 test/farm_gate.py from sdk/cloud. 12-04: a reload starved behind uploads lost a finished cut (GET out: 408).
import asyncio
import contextlib
import os
import sys
import textwrap
src = open(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "deploy", "modal", "farm.py")).read()
a = src.index(" class Gate:\n")
b = src.index(" gate = Gate()\n")
code = textwrap.dedent(src[a:b])
class Vol:
def __init__(self):
self.reloads = 0
async def _reload(self):
await asyncio.sleep(0.05)
self.reloads += 1
class _R:
def __init__(self, v):
self.v = v
async def aio(self):
await self.v._reload()
@property
def reload(self):
return Vol._R(self)
async def main():
vol = Vol()
ns = {"asyncio": asyncio, "contextlib": contextlib, "vol": vol}
exec(code, ns)
Gate = ns["Gate"]
# 1. users that overlap without a break (each 0.2 s, a new one every 0.1 s) for 3 s: a reload still happens quickly
g = Gate()
stop = False
async def user():
async with g.use():
await asyncio.sleep(0.2)
async def stream():
tasks = []
while not stop:
tasks.append(asyncio.create_task(user()))
await asyncio.sleep(0.1)
await asyncio.gather(*tasks)
s = asyncio.create_task(stream())
await asyncio.sleep(0.3)
t0 = asyncio.get_running_loop().time()
ok = await g.reload(within=2)
took = asyncio.get_running_loop().time() - t0
stop = True
await s
assert ok, "a reload behind a stream of users gave up"
assert took < 0.6, f"a reload behind a stream of users took {took:.2f} s"
print(f"ok: a reload behind a stream of users in {took:.2f} s")
# 2. ten reloads asked at once share: fewer volume reloads than asks, and all True
g = Gate()
before = vol.reloads
rs = await asyncio.gather(*[g.reload() for _ in range(10)])
assert all(rs)
n = vol.reloads - before
assert n <= 2, f"10 asks made {n} reloads"
print(f"ok: 10 reloads asked together made {n} volume reload(s)")
# 3. a user that holds the volume past the limit: the reload gives up (False), and the gate still works after
g = Gate()
async def long_user():
async with g.use():
await asyncio.sleep(0.5)
lu = asyncio.create_task(long_user())
await asyncio.sleep(0.05)
assert await g.reload(within=0.2) is False
await lu
async with g.use():
pass
assert await g.reload(within=1) is True
print("ok: a wait past its limit gives up, and the gate is usable after")
# 4. wait=False while a reload is waiting: skipped
g = Gate()
lu = asyncio.create_task(long_user())
await asyncio.sleep(0.05)
w = asyncio.create_task(g.reload())
await asyncio.sleep(0.05)
assert await g.reload(wait=False) is False
await lu
assert await w is True
print("ok: wait=False skips while a reload waits")
asyncio.run(main())
+1 -26
View File
@@ -79,17 +79,13 @@ ws = job([{"path": "media/int1.MOV", "oid": soid, "size": len(sent)}])
gets = hits["GET"]
ss = fm.fetch(ws, cache, log=lambda _: None)
assert open(os.path.join(ws, "media/int1.MOV"), "rb").read() == sent and os.path.islink(os.path.join(ws, "media/int1.MOV"))
# followed to the end, the link is a file with the take's own name: a bundler resolves it, and a composition that knows
# its takes by name (Framed's faces) still finds this one
real = os.path.realpath(os.path.join(ws, "media/int1.MOV"))
assert os.path.basename(real) == "int1.MOV" and os.path.samefile(real, os.path.join(cache, soid)), real
assert ss == {"objects": 1, "fetched": 0, "cached": len(sent)} and hits["GET"] == gets, ss
try:
fm.fetch(job([{"path": "media/gone.MOV", "oid": "ab" * 32, "size": 10}]), cache, log=lambda _: None)
raise AssertionError("footage never sent was used")
except ValueError as e:
assert "never sent" in str(e)
ok("footage the box sent the farm itself comes from the cache as a link that ends at its own name, and footage it never sent is refused")
ok("footage the box sent the farm itself comes from the cache as a link, and footage it never sent is refused")
w1 = job([obj])
s1 = fm.fetch(w1, cache, log=lambda _: None)
@@ -124,27 +120,6 @@ except ValueError:
pass
ok("a file that isn't its hash, and a path out of the job, are refused")
# a library original whose size raea cloud doesn't know (size 0, its link given): fetched and kept by its hash alone,
# then held for the next job; a size-0 entry with no link is never held
c0 = tempfile.mkdtemp()
z = dict(obj, size=0)
w3 = job([z])
s3 = fm.fetch(w3, c0, log=lambda _: None)
assert open(os.path.join(w3, "footage/take.mov"), "rb").read() == take and s3["fetched"] == len(take), s3
s4 = fm.fetch(job([z]), c0, log=lambda _: None)
assert s4["fetched"] == 0 and s4["cached"] == len(take), s4
try:
fm.fetch(job([dict(z, oid="0" * 64)]), tempfile.mkdtemp(), log=lambda _: None)
raise SystemExit("FAIL a size-0 original with the wrong hash was taken")
except ValueError:
pass
try:
fm.fetch(job([{"path": "footage/take.mov", "oid": oid, "size": 0}]), c0, log=lambda _: None)
raise SystemExit("FAIL a size-0 entry with no link was held")
except ValueError as e:
assert "never sent" in str(e)
ok("an original of unknown size is fetched and held by its hash, a wrong one refused, and none held without its link")
out = tempfile.mkdtemp()
os.makedirs(os.path.join(out, "out"))
render = os.urandom(200_000)
-16
View File
@@ -128,14 +128,6 @@ clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
# 12-04 (StreetTalk round 22): each run numbers its React nodes its own way, so one clip came back as n3 then n11 by
# turns; joined only by key, it stayed in pieces and the sound check called every seam a cut inside a word
m2 = fp.joined({"frames": []}, [
{"frames": [{"frame": 0}], "sounds": {"fps": 30, "clips": [{"key": "n3", "src": "t.mp4", "from": 0, "to": 60, "at": 194.667}]}},
{"frames": [{"frame": 60}], "sounds": {"fps": 30, "clips": [{"key": "n11", "src": "t.mp4", "from": 60, "to": 90, "at": 196.667}]}},
])
assert [(c["src"], c["from"], c["to"]) for c in m2["sounds"]["clips"]] == [("t.mp4", 0, 90)], m2["sounds"]["clips"]
ok("a clip carried across a run's seam under another key is joined whole")
lines.clear()
long = FakeGpu(root, length=1000)
@@ -263,14 +255,6 @@ g = Flat(root, name="T4")
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 0}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run) == 0, lines
assert g.nv and not any(g.nv), g.nv
ok("a piece with 3D draws on GPUs with NVENC and NVDEC asked for; a 2D piece kept on GPUs doesn't ask")
# the job says so (opts nv): "1" puts a 2D piece on GPUs with them, "0" keeps a 3D piece's GPU without them
g, c = Flat(root, name="T4"), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 8, "nv": "1"}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run, cpu_render=c) == 0, lines
assert not c.calls and g.nv and all(g.nv), (c.calls, g.nv)
g, c = Flat(root, name="T4", has3d=True), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 8, "nv": "0"}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run, cpu_render=c) == 0, lines
assert not c.calls and g.nv and not any(g.nv), (c.calls, g.nv)
ok("a job's nv=1 draws a 2D piece on GPUs with NVENC and NVDEC; nv=0 keeps a 3D piece's GPU without them")
# the join keeps every frame of runs that have B-frames, with the piece's sound (11-30: -shortest ended the joined
# video 2 frames early, 892 of an 894-frame ad)
-169
View File
@@ -1,169 +0,0 @@
// Light copies on the box, originals on the farm (server/originals.ts, docs/cloud.feature CL17-CL20): node
// test/originals.ts from sdk/cloud.
// Checked: a light copy the render reads goes as its original by its link (the light copy's own bytes never go); one
// the render doesn't read goes nowhere; a link that has ended, or an entry with no hash, falls back to the original's
// file under footage/originals/; with neither, the light copy is rendered as itself and named for the manifest; the
// original's file is sent by its own hash under the light copy's path; footage/originals/ and the kept light copies
// never go in the tar.
import { createHash } from "node:crypto"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"
import { createServer } from "node:http"
import type { AddressInfo } from "node:net"
import { tmpdir } from "node:os"
import path from "node:path"
import { excluded, farmBlobs, farmInputs } from "../server/media.ts"
import { lightCopies, originalFile, originalsRecord, recordOriginals, resolveOriginals, settle, withOriginals } from "../server/originals.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const assert = (c: unknown, m: string) => {
if (!c) throw new Error(`not ok: ${m}`)
}
const sha = (b: Buffer | string) => createHash("sha256").update(b).digest("hex")
const root = mkdtempSync(path.join(tmpdir(), "originals-"))
const put = (rel: string, body: Buffer | string) => {
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
writeFileSync(path.join(root, rel), body)
}
// four light copies; a's and b's originals have links, c's link has ended and its original is here, d has nothing
const light = (n: string) => Buffer.alloc(300_000, n)
for (const n of ["a", "b", "c", "d"]) put(`footage/${n}.mp4`, light(n))
put("footage/e.mp4", light("e")) // not a light copy: the agent's own file
put(".raea-cloud/light.txt", "a.mp4\nb.mp4\nfootage/c.mp4\nd.mp4\nmissing.mp4\n")
const A = "a".repeat(64)
const now = 1_000_000_000
put(
".raea-cloud/originals.json",
JSON.stringify({
"footage/a.mp4": { sha256: A, bytes: 693_000_000, url: "https://r2.example/a?sig=1", expires: now + 86_400_000 },
"b.mp4": { sha256: "b".repeat(64), url: "https://drive.example/b" },
"footage/c.mp4": { sha256: "c".repeat(64), bytes: 9, url: "https://r2.example/c", expires: now + 60_000 },
"footage/d.mp4": { url: "https://r2.example/d" },
}),
)
const cOrig = Buffer.alloc(5_000_000, "C")
put("footage/originals/c.MOV", cOrig)
put("footage/originals/STATUS", "done")
put("footage/originals/d.mp4.part", "half")
assert(lightCopies(root).join() === "footage/a.mp4,footage/b.mp4,footage/c.mp4,footage/d.mp4", "light.txt read as paths, a name with no file left out")
assert(originalFile(root, "footage/c.mp4")?.endsWith("footage/originals/c.MOV"), "an original's file found by its name, any extension")
assert(originalFile(root, "footage/d.mp4") === null, "a part-fetched original isn't one")
ok("light copies and originals' files found")
const reads = new Set(["footage/a.mp4", "footage/b.mp4", "footage/c.mp4", "footage/d.mp4"])
const r = resolveOriginals(root, (p) => reads.has(p), now)
assert(r.byLink.length === 2, `two by their links (${r.byLink.map((m) => m.path)})`)
const a = r.byLink.find((m) => m.path === "footage/a.mp4")!
assert(a.oid === A && a.size === 693_000_000 && a.href === "https://r2.example/a?sig=1", "a's original: its hash, size and link, under the light copy's path")
const b = r.byLink.find((m) => m.path === "footage/b.mp4")!
assert(b.size === 0 && !("expires" in b), "a size raea cloud doesn't know goes as 0; a link with no end is used")
assert(r.byFile.get("footage/c.mp4")?.endsWith("footage/originals/c.MOV"), "an ended link falls back to the original's file")
assert(r.light.join() === "footage/d.mp4", "no hash and no file: the light copy as itself")
assert(r.why.some((w) => w.startsWith("footage/c.mp4: its link has ended")) && r.why.some((w) => w.startsWith("footage/d.mp4: no hash")), `why each link wasn't used (${r.why})`)
ok("each light copy resolved to its original's link, its file, or itself")
const some = resolveOriginals(root, (p) => p === "footage/a.mp4", now)
assert(some.byLink.length === 1 && !some.byFile.size && !some.light.length, "a light copy the render doesn't read goes nowhere, its original included")
ok("only what the render reads")
const rec = originalsRecord(r)
assert(rec.read.join() === "footage/a.mp4,footage/b.mp4,footage/c.mp4" && rec.light.join() === "footage/d.mp4", "the manifest's record")
ok("the record: read as originals, and as themselves")
writeFileSync(path.join(root, ".raea-cloud/originals.json"), "{not json")
assert(resolveOriginals(root, () => true, now).byLink.length === 0, "a broken map is no map")
writeFileSync(path.join(root, ".raea-cloud/originals.json"), JSON.stringify([1, 2]))
assert(resolveOriginals(root, () => true, now).byLink.length === 0, "an array is no map")
ok("a broken map renders from files or light copies, never crashes")
// the original's file goes to the farm by its own hash, under the light copy's path; the tar's excludes keep
// footage/originals/ and the kept light copies out
put(".raea-cloud/proxies/x.mp4", light("x"))
const held = new Map<string, number>()
const farm = createServer((req, res) => {
const u = new URL(req.url!, "http://x")
if (req.method === "POST" && u.pathname === "/v1/blobs/have") {
let s = ""
req.on("data", (c) => (s += c)).on("end", () => {
const objects = (JSON.parse(s).objects ?? []) as { oid: string }[]
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ have: objects.filter((o) => held.has(o.oid)).map((o) => o.oid), links: 1 }))
})
return
}
const m = /^\/v1\/blobs\/([0-9a-f]{64})$/.exec(u.pathname)
if (req.method === "PUT" && m) {
const h = createHash("sha256")
let n = 0
req.on("data", (c: Buffer) => (h.update(c), (n += c.length))).on("end", () => {
if (h.digest("hex") !== m[1]) return void res.writeHead(400).end("wrong hash")
held.set(m[1], n)
res.writeHead(200).end()
})
return
}
res.writeHead(404).end()
})
await new Promise<void>((ok) => farm.listen(0, "127.0.0.1", ok))
const url = `http://127.0.0.1:${(farm.address() as AddressInfo).port}`
const tar = excluded(["./.git", "./out/*", "./.raea-cloud/proxies", "./footage/originals"])
const linked = new Set(r.byLink.map((m) => m.path))
const store = path.join(root, ".hashes.json")
const got = await farmInputs(root, farmBlobs(url, "t"), (p) => tar(p) || linked.has(p), () => {}, store, r.byFile)
farm.close()
assert(got, "the farm has a cache")
const paths = got!.media.map((m) => m.path).sort()
assert(!paths.includes("footage/a.mp4") && !paths.includes("footage/b.mp4"), `light copies with links aren't sent (${paths})`)
assert(!paths.some((p) => p.startsWith("footage/originals/") || p.startsWith(".raea-cloud/proxies/")), `footage/originals/ and the kept light copies stay out (${paths})`)
const c = got!.media.find((m) => m.path === "footage/c.mp4")!
assert(c.oid === sha(cOrig) && c.size === cOrig.length && held.get(c.oid) === cOrig.length, "c goes as its original's bytes, by their hash, under its own path")
const d = got!.media.find((m) => m.path === "footage/d.mp4")!
assert(d.oid === sha(readFileSync(path.join(root, "footage/d.mp4"))), "d, with no original, goes as itself")
ok("an original's file sent in its light copy's place; footage/originals/ and kept light copies never sent")
// the one list the farm gets: what went, with each original by its link in its light copy's place (12-05 review: the
// farm-cache path kept only what went, and the links were dropped while the manifest said they were read)
const went = [{ path: "footage/c.mp4", oid: "c".repeat(64), size: 5 }, { path: "media/logo.png", oid: "d".repeat(64), size: 9 }, { path: "footage/a.mp4", oid: "e".repeat(64), size: 7 }]
const all = withOriginals(went, r)
assert(all.length === 4 && all.filter((m) => m.path === "footage/a.mp4").length === 1, `each path once (${all.map((m) => m.path)})`)
assert((all.find((m) => m.path === "footage/a.mp4") as { href?: string }).href === "https://r2.example/a?sig=1", "the light copy's path carries its original's link")
assert(all.some((m) => m.path === "footage/b.mp4") && all.some((m) => m.path === "media/logo.png"), "the links and the rest, together")
ok("the farm's list holds every original by its link, and what went")
// what a farm can take: one that fetches by link takes them all; an older cache farm, no unknown size; no cache, no file
assert(settle(r, { links: true }) === r, "a farm that fetches by link takes them all")
const older = settle(r, { links: false })
assert(older.byLink.map((m) => m.path).join() === "footage/a.mp4" && older.byFile.size === 1, `an older cache farm: known sizes and files (${older.byLink.map((m) => m.path)})`)
assert(older.light.join() === "footage/d.mp4,footage/b.mp4", `the unknown size light (${older.light})`)
const old = settle(r, null)
assert(old.byLink.map((m) => m.path).join() === "footage/a.mp4", `only a known size by link (${old.byLink.map((m) => m.path)})`)
assert(old.byFile.size === 0 && old.light.join() === "footage/d.mp4,footage/b.mp4,footage/c.mp4", `the rest light (${old.light})`)
assert(old.why.filter((w) => w.includes("no media cache")).length === 1 && old.why.some((w) => w.includes("unknown size")), "and said")
ok("a farm gets only what it says it can take; the rest is recorded light")
// the record: into the manifest and beside the output, only what the render read, cleared when clean
const rec2 = originalsRecord(old)
const man = path.join(root, "out/m.json")
put("out/cut.mp4", "v")
put("out/m.json", JSON.stringify({ frames: [1], sounds: { clips: [{ src: "/farm/cache/named/x/footage/b.mp4" }, { src: "footage/a.mp4" }] } }))
const rc = recordOriginals(path.join(root, "out/cut.mp4"), man, rec2)
assert(rc.failed.length === 0 && rc.files.length === 2, `into both (${rc.files})`)
const mj = JSON.parse(readFileSync(man, "utf8"))
assert(mj.frames[0] === 1 && mj.originals.light.join() === "footage/b.mp4" && mj.originals.read.join() === "footage/a.mp4", `only what it read (${JSON.stringify(mj.originals)})`)
assert(JSON.parse(readFileSync(path.join(root, "out/cut.render.json"), "utf8")).originals.light.join() === "footage/b.mp4", "beside it too")
put("out/still.png", "p")
recordOriginals(path.join(root, "out/still.png"), null, rec2)
const side = path.join(root, "out/still.render.json")
assert(JSON.parse(readFileSync(side, "utf8")).originals.read.join() === "footage/a.mp4", "beside a still, which names no sources: all of it")
recordOriginals(path.join(root, "out/still.png"), null, { read: [], light: [] })
assert(!("originals" in JSON.parse(readFileSync(side, "utf8"))), "a clean render again clears the old record")
assert(recordOriginals(path.join(root, "out/x.png"), null, { read: [], light: [] }).files.length === 0 && !existsSync(path.join(root, "out/x.render.json")), "nothing to record, nothing made")
put("out/bad.json", "[1]")
assert(recordOriginals(path.join(root, "out/cut.mp4"), path.join(root, "out/bad.json"), rec2).failed.join().endsWith("out/bad.json"), "a manifest that isn't an object is said")
ok("every render keeps its record of what it read, a still beside it, and a clean one clears it")
put("footage/day1/take.mp4", light("t"))
put("footage/originals/take.mov", "T")
assert(originalFile(root, "footage/day1/take.mp4") === null, "a light copy in a folder of its own isn't matched by name")
ok("an original's file is matched only for a light copy straight in footage/")
console.log("originals: all ok")
-4
View File
@@ -213,10 +213,6 @@ console.log("units: ok")
assert.equal(localSources(m, [{ path: "media/raw/a1_hl1.mov", oid }], "/work/project"), 1)
assert.deepEqual(m.sounds.clips.map((c) => c.src), ["/work/project/media/raw/a1_hl1.mov", "/work/abc/media/music.mp3", "f".repeat(64)])
assert.equal(localSources({}, [], "/x"), 0)
// the farm's blob under the take's own name (blobs/named/OID/NAME) maps back the same
const named = { sounds: { clips: [{ src: `/__modal/volumes/vo-F8fh/blobs/named/${oid}/a1_hl1.mov` }] } }
assert.equal(localSources(named, [{ path: "media/raw/a1_hl1.mov", oid }], "/work/project"), 1)
assert.equal(named.sounds.clips[0].src, "/work/project/media/raw/a1_hl1.mov")
console.log("ok localSources")
}
-41
View File
@@ -1,41 +0,0 @@
// What a render leaves on the box (server/media.ts unusedMedia): video and audio no source file names. 12-03: every
// StreetTalk run's first render sent footage/originals/ (several GB) to the farm, a still included, and ran past its
// 5 minutes. Run: node test/unused-media.ts (prints ok, or FAIL and exits 1)
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { unusedMedia } from "../server/media.ts"
const fail = (m: string): never => {
console.error(`FAIL ${m}`)
process.exit(1)
}
const project = (files: Record<string, string>) => {
const root = mkdtempSync(path.join(tmpdir(), "raea-unused-"))
for (const [f, c] of Object.entries(files)) {
mkdirSync(path.dirname(path.join(root, f)), { recursive: true })
writeFileSync(path.join(root, f), c)
}
return root
}
const same = (a: string[], b: string[], what: string) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort()) || fail(`${what}: ${JSON.stringify([...a].sort())}`)
// a cut on the light copies: the originals and the untouched takes stay; index.json (which lists every take) isn't source
const takes = {
"footage/Angle1-Take1.mp4": "x", "footage/Angle1-Take2.mp4": "x", "footage/Angle2-Take1.mp4": "x",
"footage/originals/Angle1-Take1.mov": "x", "footage/originals/Angle1-Take2.mov": "x", "footage/originals/Angle2-Take1.mov": "x",
"footage/index.json": JSON.stringify(["Angle1-Take1.mp4", "Angle1-Take2.mp4", "Angle2-Take1.mp4"]),
"media/music/bed.mp3": "x",
}
same(unusedMedia(project({ ...takes, "cut_a.tsx": `<Video src="footage/Angle1-Take1.mp4" /><Video src={"footage/" + "Angle1-Take2.mp4"} /><Audio src="media/music/bed.mp3" />` })),
["footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "a cut on the light copies")
// the final render on the originals by id: originals/ named, the stem from data. The take's light copy goes too
// ("footage/" is in "footage/originals/"): a few MB, against the GB of originals that stay
same(unusedMedia(project({ ...takes, "cut_a.tsx": "const src = (id: string) => `footage/originals/${id}.mov`", "cuts.json": JSON.stringify({ shots: ["Angle1-Take1"] }) })),
["footage/Angle1-Take2.mp4", "footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov", "media/music/bed.mp3"], "the final render on the originals")
// nothing names any media: all of it is used, as before, but footage/originals/ (gigabytes; each original goes in its
// light copy's place when it goes at all: originals.ts)
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), ["footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "no source names any")
console.log("ok")
+40 -21
View File
@@ -36,6 +36,8 @@ export const PACKS = {
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
place: "no text over a face, hands or what the shot is about where a clear place of its size exists",
seen: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said",
surprise: "one earned surprise, named with its moment in seconds",
naming: "files named client_concept_variant_v#_size",
sizes: "one size first: no other size before the first is approved",
quotes: "every rule quotes the brief's own words",
@@ -46,37 +48,55 @@ export const PACKS = {
cta: "each cut ends on the CTA",
shape: "each cut in its format and length",
run: "each command rule exits 0",
says: "each `says` rule found true by a fresh critic after the work's last change",
deliverables: "every deliverable exists",
floor: "no clipped text, text in the app's buttons, low contrast, freeze, flash or loudness out of range",
render: "nothing the render's own end checks found: a missing font, clipping, a part out of place or under its detail, light that jumps",
critic: "the critic's rounds: a pass newer than the work, its blocking defects fixed or answered",
record: "every composition the plan names rendered or checked clean since it last changed",
notes: "NOTES.md, with what the skill got wrong",
floor: "no clipped text, low contrast, freeze, flash or loudness out of range",
stills: "a composition's stills as it's saved: no clipped or cramped text, nothing out of the safe areas",
playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed",
} as const
export type PackName = keyof typeof PACKS
/** each kind's packs, on unless the brief switches them off. Only rules that catch a real fault in that kind of work,
* each run once on a deliverable after its render (12-04, Shane: "fix how every agent checks its work"; round 26's
* checks gave 183 findings on 10 cuts, about 10 of them real faults, and the agents spent their 20 minutes on the
* rest). The others stay a brief's to switch on (`packs: { montage: true }`),
* never an agent's loop: voice, reading, hook, airgaps, montage, quotes. Nothing asks a model to judge the work. */
/** each kind's packs, on unless the brief switches them off (surprise is on only where a brief turns it on) */
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
// a word clipped or missing, a face cut by the frame, text over a face, a sign or the app's buttons, captions over
// talking, the brief's must-say, never-say and CTA, the size, length and name, and what the render itself found
cut: ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"],
rules: ["deliverables", "render"],
// a 3D scene, kit or shot: what its render found (clipping, a part out of place or under its detail, light that
// jumps or boils: the render's own end checks, in its manifest)
scene: ["deliverables", "render"],
kit: ["deliverables", "render"],
shot: ["deliverables", "render"],
playable: ["deliverables", "playable", "render"],
// a project with no `goal`: what any made video is held to
floor: ["frames", "place", "captions", "floor", "render"],
cut: ["words", "captions", "voice", "reading", "hook", "airgaps", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
rules: ["deliverables", "stills"],
scene: ["deliverables", "record", "critic", "notes", "stills"],
kit: ["deliverables", "record", "critic", "notes", "stills"],
shot: ["deliverables", "record", "critic", "notes", "stills"],
playable: ["deliverables", "playable", "stills"],
// a project with no `goal`: what any made video is held to, and any composition as it's saved
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
}
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */
export type Said = { id: string; says: string }
/** every `says` rule a goal is held to: its own, then a cut goal's beats (MK48), each judged on its cut as a viewer sees
* it, shots in sequence: what a shot means comes from its neighbours (Kuleshov), so a beat is read in the cut, never
* shot by shot. Murch puts emotion (51%) and story (23%) above all a cut's other reasons; no measure finds them */
export function saysOf(g: Contract | null): Said[] {
const own = (g?.rules ?? []).flatMap((r) => (r.says ? [{ id: r.id, says: r.says }] : []))
const c = g?.kind === "cut" ? g.cut : undefined
const beats = (c?.cuts ?? []).flatMap((p) => {
const formats = p.formats?.length ? p.formats : (c?.formats ?? [])
const file = formats.length ? `out/cuts/${p.id}_${formats[0].replace(":", "x")}.mp4` : `cut ${p.id}`
const bs = p.beats ?? []
return bs.map((b, i) => {
const until = bs[i + 1] ? `${bs[i + 1].at} s` : "its end"
return { id: `beat_${p.id}_${i + 1}`, says: `In ${file}, from ${b.at} s to ${until}, watched in sequence as cut (a shot reads by its neighbours), the viewer feels ${b.feel}${b.story ? `, and by its end understands ${b.story}` : ""}` }
})
})
return [...own, ...beats]
}
/** the packs that hold a goal: its kind's, its rules' (any goal with rules is held to them), then its switches */
export function packsOf(c: Contract | null): PackName[] {
const on = new Set<PackName>(DEFAULTS[c?.kind ?? "floor"])
if (c?.rules?.some((r) => r.run)) on.add("run")
if (saysOf(c).length) on.add("says")
for (const [k, v] of Object.entries(c?.packs ?? {})) {
if (!(k in PACKS)) continue
if (v) on.add(k as PackName)
@@ -110,8 +130,7 @@ export const rules = (m: Kindless): Contract => ({ kind: "rules", ...m })
export const workflow = (w: Workflow): Workflow => w
/** brief.ts's `goal` (or a workflow's steps) as a list, in order */
export const goalsOf = (g: Goals | Workflow | (Contract | Workflow)[] | null | undefined): Contract[] =>
!g ? [] : Array.isArray(g) ? g.flatMap((x) => goalsOf(x as Contract | Workflow)) : typeof g === "object" && "steps" in g && Array.isArray(g.steps) ? g.steps : typeof g === "object" ? [g as Contract] : []
export const goalsOf = (g: Goals | Workflow | null | undefined): Contract[] => (!g ? [] : Array.isArray(g) ? g : "steps" in g ? g.steps : [g])
/** a goal's name: its own, else its kind's */
export const nameOf = (c: Contract) => c.name ?? c.kind
+14
View File
@@ -17,6 +17,8 @@ export type Clip = { key?: string; from: number; to: number; src: string; at: nu
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[] } }
/** 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 }
export interface FileFacts {
/** as the project names it (relative to its folder) */
@@ -48,6 +50,8 @@ export interface FileFacts {
scene(at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }>
/** its contact sheet's path */
sheet(): string
/** what was seen of it since its last change, or null */
seen(): Seen | null
}
export interface Job {
@@ -138,6 +142,16 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
return scenes.get(k)!
},
sheet: () => media.sheet(abs),
seen: () => {
const f = `${media.stem(abs)}.seen.json`
if (!existsSync(f)) return null
try {
const s = JSON.parse(readFileSync(f, "utf8")) as Seen
return s.render === stamp ? s : null
} catch {
return null
}
},
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
// raea/goal (@raea/goal): the loop's goals (docs/goal.feature): plan, run, check, done, for one goal or a workflow of
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea check`) read
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea goal check`) read
// files and run programs, and are loaded only by the runner.
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, playable, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
export type { Contract, Goals, Moment, PackName, Workflow } from "./contract.ts"
+15 -79
View File
@@ -18,8 +18,6 @@ import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import type { TextLine } from "./place.ts"
import { asDigits, digitsIn } from "./numbers.ts"
import { busOf } from "./sound.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
export type Read = TextLine
@@ -31,6 +29,9 @@ export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(
const FILLER = new Set(["um", "uh", "uhh", "umm", "mm", "mhm", "hmm", "er", "erm", "ah"])
/** a line is a caption when this share of its letters is matched by what's said around it */
export const CAPTION = 0.6
/** the time around a caption that what it says may be heard: before it shows, after */
const BEFORE = 2.5
const AFTER = 1.0
/** least score a read line counts at */
export const LEAST = 0.6
@@ -65,6 +66,7 @@ export function fit(cap: string, said: string): { dist: number; bad: boolean[];
/** the heard words whose time falls in [a, b] */
const heardIn = (heard: Word[], a: number, b: number) => heard.filter((w) => w.end >= a && w.start <= b)
const saidAround = (heard: Word[], a: number, b: number) => heardIn(heard, a - BEFORE, b + AFTER).map((w) => letters(w.text)).join("")
/** a caption's showings: one line of text, from its first frame to its last (the same line in frames side by side), and
* how far down the frame its middle is (a share of the frame's height) */
@@ -94,14 +96,13 @@ const LINE = 0.7
* fitting what's said while they're up with few edits. A badge, an app's screen, a sign or an end card stays up or
* says something else. With captions up for under TRACK of the speech, the cut has none to hold */
export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
heard = asDigits(heard)
const all: (Shown & { caps: boolean })[] = []
frames.forEach((fr, i) => {
const t = i / rate
// a frame full of text is a screen or a card (an app, an end card, a product's label), not a caption over the picture
if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
for (const [, y, , h, text, score] of fr.lines) {
const key = letters(digitsIn(text))
const key = letters(text)
if (score < LEAST || key.length < 4) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = all.findLast((s) => s.to >= t - 1.01 / rate && Math.abs(s.y - mid) <= ROW && similar(s.key, key))
@@ -148,20 +149,12 @@ function wholeWord(text: string, key: string, i: number, j: number): boolean {
}
/** the captions held to what's heard: letters shown that weren't said, and words said that no caption up then shows */
export function compare(shown: Shown[], heard: Word[], placed: Word[] = []): Finding[] {
heard = asDigits(heard)
placed = asDigits(placed)
export function compare(shown: Shown[], heard: Word[]): Finding[] {
if (!shown.length) return []
const out: Finding[] = []
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have, in
// the export as heard again or in its takes' own words where the edit placed them (what captions are built from):
// 12-05, run 11, a second hearing of the same speech wrote "That's" and "take" otherwise, and right captions read as
// retyped
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have
for (const s of shown) {
const f0 = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
const near = heardIn(placed, s.from - 0.8, s.to + 0.4)
const f1 = near.length ? fit(s.key, near.map((w) => letters(w.text)).join("")) : null
const f = f1 ? { ...f0, bad: f0.bad.map((b, i) => b && !!f1.bad[i]) } : f0
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue }
let j = i
@@ -197,17 +190,6 @@ export function compare(shown: Shown[], heard: Word[], placed: Word[] = []): Fin
const a = dropped[i].k - 1
const b = dropped[j - 1].k + 1
const inside = phrases && run.length >= 3 && shownAt(a) && shownAt(b) && run[0].start - heard[a].end < LINE && heard[b].start - run[run.length - 1].end < LINE
// the take's own words over the same stretch, captioned: the export heard again wrote them otherwise (12-05, run 11:
// the take's "he heard his label paw", captioned, was heard again as "he sleep with Paul")
const theirs = heardIn(placed, run[0].start - 0.2, run[run.length - 1].end + 0.2).filter((w) => letters(w.text) && !FILLER.has(letters(w.text)))
const covered = theirs.length > 0 && theirs.every((w) => {
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
return fit(letters(w.text), near).dist <= (letters(w.text).length >= 5 ? 1 : 0)
})
if (covered) {
i = j
continue
}
const words = run.map((w) => w.text).join(" ")
out.push(inside
? { level: "error", kind: "dropped", at: run[0].start, says: `"${words}" is said at ${run[0].start.toFixed(1)} s, between words the captions show, but no caption shows ${run.length > 1 ? "them" : "it"}: build the captions from the words file so they say every word` }
@@ -227,7 +209,6 @@ const HOOK_S = 5
* and so is a stretch of talking with none up. A text hook may be on screen beside them; it doesn't stand in for them.
* A brief that wants no captions says so, and the render says it with --despite captions WHY */
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false): Finding[] {
heard = asDigits(heard)
// a brief's "captions OR a text hook, never both" means not both in one frame (12-03, Shane): the hook may hold the
// opening alone, so words in the first HOOK_S with other text up are covered by it; anywhere later it's no caption
const said = heard.filter((w) => {
@@ -253,63 +234,18 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
return out
}
/** a render manifest's texts as frames read at `RATE` a second: each text its ink box, read with full confidence */
const RATE = 5
export function framesOfManifest(manifest: unknown): { frames: Frame[]; rate: number } | null {
const m = manifest as { height?: number; fps?: number; frames?: { frame: number; text?: { text?: string; ink?: number[]; box?: number[]; opacity?: number }[] }[] } | null
if (!m?.frames?.length) return null
const fps = Number(m.fps) || 30
const h = Number(m.height) || 1920
const step = Math.max(1, Math.round(fps / RATE))
const frames: Frame[] = []
for (let i = 0; i < m.frames.length; i += step) {
const fr = m.frames[i]
const lines = (fr?.text ?? []).flatMap((t) => {
const b = t.ink ?? t.box
const text = String(t.text ?? "").trim()
return b && b.length >= 4 && text && (t.opacity ?? 1) > 0.2 ? [[b[0], b[1], b[2], b[3], text, 1] as Read] : []
})
frames.push({ h, lines })
}
return { frames, rate: fps / step }
}
/** the takes' own words where the edit placed them, on the cut's clock: each voice clip of the manifest's sound, its
* take's words over the stretch it plays. A take that isn't here adds none */
export async function placedWords(f: FileFacts): Promise<Word[]> {
const m = f.manifest
const fps = m?.sounds?.fps ?? m?.fps ?? 30
const out: Word[] = []
for (const c of m?.sounds?.clips ?? []) {
if (busOf(c) !== "voice") continue
const file = f.take(c.src)
if (!file) continue
const words = await f.takeWords(file).catch(() => [] as Word[])
const a = c.at
const b = c.at + (c.to - c.from) / fps
const shift = c.from / fps - c.at
for (const w of words) if (w.end > a && w.start < b) out.push({ ...w, start: Math.max(a, w.start) + shift, end: Math.min(b, w.end) + shift })
}
return out.sort((x, y) => x.start - y.start)
}
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"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// numbers in words and in digits read alike on both sides (numbers.ts)
const heard = asDigits(await f.words())
const heard = await f.words()
if (!heard.length) return
// the render's own texts when its manifest is here: exactly what it drew, where, every frame, and never the footage's
// own text (12-04, round 26: Elfster's phone recordings read as "HO Nam Grou Too Ur", and its captions, drawn at the
// top, weren't recognised as captions at all); else the export read frame by frame
const own = f.manifest ? framesOfManifest(f.manifest) : null
const sc = own ? null : await f.scene()
const frames: Frame[] = own ? own.frames : sc!.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!own && !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 rate = own ? own.rate : sc!.rate || 2
const shown = captionsOf(frames, rate, heard)
const sc = await f.scene()
const frames: Frame[] = 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
const textUp = (t: number) => (frames[Math.round(t * rate)]?.lines ?? []).some(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4)
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard)].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+10 -76
View File
@@ -7,14 +7,12 @@
// say every phrase each cut must say, heard or shown; `every: false` phrases once across the cuts
// never no banned phrase heard or shown
// cta each cut ends on the CTA (in its last `within` seconds, 8 by default), heard or shown
import { existsSync, readdirSync, readFileSync } from "node:fs"
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { CutGoal, CutPlan } from "raea/brief.gen"
import type { FileFacts, Job, Manifest } from "../facts.ts"
import { has, inOrder, joined, norm, SAY_GAP, saidAt } from "../text.ts"
import { quote } from "../text.ts"
import { asDigits } from "./numbers.ts"
export const CTA_WITHIN = 8
/** how much of the CTA a run of words must have, in order */
@@ -62,21 +60,6 @@ export function shown(m: Manifest | null): [string, number][] {
return out
}
/** what each frame from `from` (s) on shows, its texts read together in the order drawn: an end card draws its CTA as
* lines (12-04, Elfster run 4: "Make your Wishlist and organize your Gift Exchange on Elfster." over "It's free.", each
* alone under the CTA's share, and a cut ending on its CTA was failed for none) */
export function shownTogether(m: Manifest | null, from: number): string[] {
if (!m) return []
const fps = m.fps && m.fps > 0 ? m.fps : 30
const out = new Set<string>()
for (const fr of m.frames ?? []) {
if (fr.frame / fps < from) continue
const s = (fr.text ?? []).filter((t) => (t.opacity ?? 1) > 0.05).map((t) => norm(t.text ?? "")).filter(Boolean).join(" ")
if (s) out.add(s)
}
return [...out]
}
const cutJob = (j: Job) => (j.contract?.kind === "cut" ? (j.contract.cut ?? null) : null)
const cutFile = (f: FileFacts) => {
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
@@ -86,8 +69,7 @@ const cutFile = (f: FileFacts) => {
/** what a cut says and shows */
async function heardOf(f: FileFacts) {
// numbers said in words as the brief writes them ("pets sixty" is PETS60, "sixty dollars" $60): 12-05, Dutch run 10
const words = asDigits(await f.words())
const words = await f.words()
const spoken = words.map((w) => norm(w.text)).filter(Boolean)
const times = words.filter((w) => norm(w.text)).map((w) => w)
return { spoken, times, screen: shown(f.manifest) }
@@ -101,7 +83,7 @@ export const quotesPack = check<Job>({ id: "quotes", text: "every rule quotes th
if (!existsSync(file)) return found({ says: `no brief text at ${c.brief}: pdftotext -layout BRIEF.pdf ${c.brief}`, fix: `pdftotext -layout BRIEF.pdf ${c.brief}` })
const text = norm(readFileSync(file, "utf8"))
const unfound = quotes(c).filter(([, from]) => !has(text, norm(from)))
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${quote(from, 60)}")`).join("; ")}` })
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${from.slice(0, 60)}")`).join("; ")}` })
})
export const countPack = check<Job>({ id: "count", text: "as many cuts as the brief asks for, or a person's answer saying why not", over: "job", at: ["edit", "done"] }, async (j) => {
@@ -135,9 +117,8 @@ export const shapePack = check<FileFacts>({ id: "shape", text: "each cut in its
export const sayPack = check<FileFacts>({ id: "say", text: "every phrase the brief says each cut says, heard or shown", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
const at = cutFile(f)
if (!at?.c.say?.length) return
const { spoken } = await heardOf(f)
const together = shownTogether(f.manifest, 0)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || together.some((s) => onScreen(s, p, SAY_GAP))
const { spoken, screen } = await heardOf(f)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, p, SAY_GAP))
const missing = at.c.say.filter((p) => p.every !== false && !on(norm(p.text)))
if (missing.length) found({ says: `never says or shows: ${missing.map((m) => `"${m.text}"`).join(", ")}` })
})
@@ -162,7 +143,7 @@ export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the
const at = cutFile(f)
const cta = at?.c.cta
if (!cta) return
const { times } = await heardOf(f)
const { times, screen } = await heardOf(f)
const within = cta.within ?? CTA_WITHIN
const end = f.seconds ?? times[times.length - 1]?.end ?? 0
const last = times.filter((w) => w.end >= end - within).map((w) => norm(w.text))
@@ -174,67 +155,20 @@ export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the
const heard = lines.map((l) => share(l, last))
const best = Math.max(0, ...heard)
const line = best > 0 ? lines[heard.indexOf(best)] : cta.text
// said and shown together: 12-05, Dutch run 10, the host said "use code PETS60 for sixty dollars off your first" as the
// end card showed "Code PETS60: $60 off your first year", and neither alone was 85% of the line
const late = shownTogether(f.manifest, end - within)
const shownLate = late.some((s) => lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE || share(l, [...last, ...s.split(" ")]) >= CTA_SHARE || share(l, [...s.split(" "), ...last]) >= CTA_SHARE))
if (best < CTA_SHARE && !shownLate) {
// the takes that say it, so the fix is one `raea cut` away (12-05, a street interview run: every cut ended on a host take
// that says "download the app", while two other takes say the brief's "Go to the site" line word for word)
const takes = takesSaying(f.root, lines)
const where = takes.length ? `; said in ${takes.map((t) => `${t.take} at ${t.at.toFixed(1)} s`).join(", ")}: cut it from there` : "; no take says it: show it on the end card"
found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"${where}`, seconds: [Math.max(0, end - within), end] })
}
const shownLate = screen.some(([s, t]) => t >= end - within && lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE))
if (best < CTA_SHARE && !shownLate) found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"`, seconds: [Math.max(0, end - within), end] })
})
/** the takes in footage/ whose words say one of `lines` (CTA_SHARE of its words in order, inside a window a little longer
* than it), the closest first, three at most */
export function takesSaying(root: string, lines: string[]): { take: string; at: number; share: number }[] {
const dir = path.join(root, "footage")
if (!existsSync(dir)) return []
const out: { take: string; at: number; share: number }[] = []
let names: string[] = []
try {
names = readdirSync(dir).filter((n) => n.endsWith(".words.json"))
} catch {
return []
}
const wants = lines.map((l) => norm(l).split(" ").filter(Boolean)).filter((w) => w.length)
for (const n of names) {
let ws: { text: string; start_ms: number; end_ms?: number }[] = []
try {
ws = JSON.parse(readFileSync(path.join(dir, n), "utf8"))
} catch {
continue
}
if (!Array.isArray(ws)) continue
const heard = asDigits(ws.map((w) => ({ text: String(w.text ?? ""), start: w.start_ms / 1000, end: (w.end_ms ?? w.start_ms) / 1000 })))
// one token per word of norm's (it makes "acme.com" two), each at its word's time
const flat = heard.flatMap((w) => norm(w.text).split(" ").filter(Boolean).map((t) => ({ t, start: w.start })))
const toks = flat.map((x) => x.t)
let best: { at: number; share: number } | null = null
for (const want of wants)
for (let i = 0; i < toks.length; i++) {
if (!want.includes(toks[i])) continue
const win = toks.slice(i, i + want.length + 3)
const sh = inOrder(want, joined(win, want).map(([w]) => w))
if (sh >= CTA_SHARE && (!best || sh > best.share)) best = { at: flat[i].start, share: sh }
}
if (best) out.push({ take: n.replace(/\.words\.json$/, ""), ...best })
}
return out.sort((a, b) => b.share - a.share).slice(0, 3)
}
/** a phrase one cut is enough for (`every: false`): some delivered cut says or shows it */
export const sayOncePack = check<Job>({ id: "say-once", text: "each phrase one cut is enough for, said or shown by one", over: "job", at: ["publish", "done"], needs: "words" }, async (j) => {
const c = cutJob(j)
const once = (c?.say ?? []).filter((p) => p.every === false)
if (!c || !once.length) return
const cuts = j.files.filter((f) => cutOf(c, f.path))
const heard = await Promise.all(cuts.map(async (f) => ({ ...(await heardOf(f)), together: shownTogether(f.manifest, 0) })))
const heard = await Promise.all(cuts.map(heardOf))
for (const p of once) {
const n = norm(p.text)
const by = heard.some(({ spoken, together }) => saidAt(spoken, n, SAY_GAP) !== null || together.some((s) => onScreen(s, n, SAY_GAP)))
const by = heard.some(({ spoken, screen }) => saidAt(spoken, n, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, n, SAY_GAP)))
if (!by) found({ says: `no cut says or shows "${p.text}" (brief: "${p.from}")` })
}
})
+3 -32
View File
@@ -19,11 +19,8 @@ function measure(args: string[], cwd: string): Measured[] {
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-floor-"))
try {
const out = path.join(dir, "check.json")
const run = (verb: string) => spawnSync(RAEA, [verb, ...args, "-o", out], { cwd, encoding: "utf8", env: { ...process.env, RAEA_RECORD: "off" }, maxBuffer: 1 << 24 })
// `raea floor` since 12-04; a raea from before it measures as `raea check VIDEO`
let r = run("floor")
if (!existsSync(out)) r = run("check")
if (!existsSync(out)) throw new Error(`raea floor ${args[0]} wrote no report: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
const r = spawnSync(RAEA, ["check", ...args, "-o", out], { cwd, encoding: "utf8", env: { ...process.env, RAEA_RECORD: "off" }, maxBuffer: 1 << 24 })
if (!existsSync(out)) throw new Error(`raea check ${args[0]} wrote no report: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
return (JSON.parse(readFileSync(out, "utf8")).findings ?? []) as Measured[]
} finally {
rmSync(dir, { recursive: true, force: true })
@@ -56,36 +53,10 @@ 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 })
/** what the floor reports that isn't a fault in the delivery (12-04, round 26: 48 of Elfster's 85 floor lines were
* "3 words need 1.0 s to read" on captions, which follow speech at its own pace, and 4 a brand kit's provenance): a
* text's reading time is a brief's to ask for (the reading pack), where its kit came from is the brand step's */
export const NOT_A_FAULT = [/ words? need [0-9.]+ s to read/, /wasn't read from the brand/, /blocky patches in dark areas.*: the picture's own/]
/** blocky darks the floor couldn't trace to the encode (12-04, Body Shop: an ERROR on a 17 Mbps cut whose frame shows no
* blocks at full size; the footage's own compression, a phone's): an error only when it measured that the encode added
* them, a warning otherwise */
const UNTOLD = /blocky patches in dark areas.*(or the footage holds them|couldn't be told)/
/** the app's right-hand buttons start this far down (sdk/video/src/zones.ts RAIL, apps/check/text RAIL) */
const RAIL = 0.45
const RIGHT = /in the app's UI zone at the right \(keep [0-9]+ px clear\): its (?:box|letters) -?[0-9]+,(-?[0-9]+) [0-9]+x([0-9]+) in [0-9]+x([0-9]+)/
/** a raea from before the rail (12-05) held the right zone the whole height: text in it above the buttons isn't a fault
* (Body Shop's centred end card at 35% down was an error). Where more texts like it were found it's a warning, since
* one of those may reach the buttons */
function aboveRail(x: Measured): Measured | null {
const m = RIGHT.exec(x.says)
if (!m || +m[1] + +m[2] > RAIL * +m[3]) return x
return / more like it/.test(x.says) ? { ...x, level: x.level === "error" ? "warn" : x.level } : null
}
export const faultsOf = (xs: Measured[]) =>
xs
.filter((x) => !NOT_A_FAULT.some((r) => r.test(x.says)))
.map((x) => (x.level === "error" && UNTOLD.test(x.says) ? { ...x, level: "warn" as const } : x))
.map(aboveRail)
.filter((x): x is Measured => !!x)
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 faultsOf(floorOf(f.abs, 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) => {
+1 -2
View File
@@ -13,7 +13,6 @@ 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 { quote } from "../text.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
@@ -128,7 +127,7 @@ export function smallText(manifest: any): Finding[] {
}
const out: Finding[] = []
for (const [text, { at, px }] of seen) {
const q = `"${quote(text, 40)}"`
const q = text.length > 40 ? `"${text.slice(0, 40)}..."` : `"${text}"`
if (px < TEXT_ERROR) out.push({ level: "error", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px (in a 1080-wide frame): under ${TEXT_ERROR} px no one reads it on a phone. Make it bigger, or cut words so it fits bigger` })
else if (px < TEXT_WARN) out.push({ level: "warn", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px: small for anything but a badge or small print (captions 52 px, hooks 64 px)` })
}
+261 -4
View File
@@ -1,15 +1,272 @@
// The rules pack: a goal's command rules, each run in the brief's folder within its timeout (300 s by default), run
// again each time. A goal's `file` rules are deliverables (the deliverables pack holds them). Nothing here asks a model
// to judge the work (12-04, Shane: "removing ask and judge completely and all that exists is check").
// 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}}}.
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"
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 j.contract?.rules ?? []) {
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 = 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[]>
/** `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[]> {
return new Promise((ok, no) => {
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 = 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)
})
})
}
/** 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)))
+11 -5
View File
@@ -3,18 +3,18 @@ import type { Check } from "raea/check"
import type { PackName } from "../contract.ts"
import captions from "./captions.ts"
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
import { floorPack } from "./floor.ts"
import { floorPack, stillsPack } from "./floor.ts"
import frames from "./frames.ts"
import montage from "./montage.ts"
import { runPack } from "./goal.ts"
import { deliverablesPack } from "./job.ts"
import { runPack, saysPack } from "./goal.ts"
import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import naming from "./naming.ts"
import place from "./place.ts"
import { playablePack } from "./playable.ts"
import sizes, { allSizes } from "./sizes.ts"
import sound from "./sound.ts"
import reading from "./reading.ts"
import render from "./render.ts"
import { airgapsPack, hookPack } from "./hook.ts"
import voice from "./voice.ts"
import words from "./words.ts"
@@ -31,6 +31,8 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
frames: [frames],
montage: [montage],
place: [place],
seen: [seenPack],
surprise: [surprisePack],
naming: [naming],
sizes: [sizes, allSizes],
quotes: [quotesPack],
@@ -41,8 +43,12 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
cta: [ctaPack],
shape: [shapePack],
run: [runPack],
says: [saysPack],
deliverables: [deliverablesPack],
critic: [criticPack],
record: [recordPack],
notes: [notesPack],
floor: [floorPack],
stills: [stillsPack],
playable: [playablePack],
render: [render],
}
+61 -3
View File
@@ -1,12 +1,23 @@
// The deliverables pack: every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file`
// rules, a kit's GLBs, LODs, thumbnails, lineup and kit.json, a shot's still or move, a scene's three stills).
import { existsSync, readdirSync, statSync } from "node:fs"
// The job packs: what must exist, and for a scene, kit or shot job the record of its renders and its critic's rounds.
// deliverables every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file` rules, a
// kit's GLBs, LODs, thumbnails, lineup and kit.json, a shot's still or move, a scene's three stills)
// notes NOTES.md with a "What the skill got wrong" section (scene, kit and shot jobs)
// record every composition the plan names rendered or checked clean since it last changed, and its LODs held
// critic a fresh critic's round newer than the newest deliverable, on the kind's rubric, its blocking
// defects fixed or answered in NOTES.md, and the make questions asked of its sheets
// record and critic read raea's record and the judge's rounds through `raea goal gates --json`.
import { spawnSync } from "node:child_process"
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { Contract } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
import { deliverables as cutFiles } from "./cut.ts"
import { deliverables as playableFiles } from "./playable.ts"
import { unregistered } from "../project.ts"
export const SKILL_HEADING = "What the skill got wrong"
/** what must exist when the goal is done, relative to the brief's folder: its own list, else its kind's; and each of
* its `file` rules */
@@ -51,3 +62,50 @@ export const deliverablesPack = check<Job>({ id: "deliverables", text: "every de
if (typeof a === "string") found({ says: `missing: ${a}`, about: [want] })
}
})
/** MK43: every file in the folder that uses raea's SDK is reached from brief.ts (or taste.ts), so it's compiled and
* run; one nothing reaches is said at every moment, an error once the work is handed over or called done */
export const registeredPack = check<Job>({ id: "registered", text: "every raea file is reached from brief.ts", over: "job", at: ["edit", "render", "publish", "done"] }, async (j) => {
if (j.project.problem) {
found({ says: `brief.ts doesn't run: ${j.project.problem}`, level: "error" })
return
}
if (!j.project.brief) return
const loose = unregistered(j.project)
const level = j.moment === "publish" || j.moment === "done" ? "error" : "warn"
for (const f of loose)
found({ says: `${f} uses raea but nothing in brief.ts reaches it, so it never runs`, about: [f], level, fix: "import it from a file the brief reaches, name its path in the brief (a deliverable, a shot's composition, a rule), or delete it" })
})
export const notesPack = check<Job>({ id: "notes", text: "NOTES.md, with what the skill got wrong", over: "job", at: ["done"] }, async (j) => {
const p = path.join(j.root, "NOTES.md")
const t = existsSync(p) ? readFileSync(p, "utf8") : ""
if (!t.toLowerCase().includes(SKILL_HEADING.toLowerCase())) found({ says: `NOTES.md has no "${SKILL_HEADING}" section: one line per thing that cost time, and what the guide got wrong for this job` })
})
type Gate = { gate: string; of?: string; clear: boolean; says: string }
type Gates = { gates: Gate[]; short?: string[]; error?: string }
/** raea's record and critic gates for a scene, kit or shot job (`raea goal gates --json` in the brief's folder) */
function gatesOf(j: Job): Gates {
const r = spawnSync(RAEA, ["goal", "gates", "--json"], { cwd: j.root, encoding: "utf8", maxBuffer: 1 << 24 })
try {
return JSON.parse(String(r.stdout)) as Gates
} catch {
throw new Error(`raea goal gates said no JSON: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
}
}
const RECORD = new Set(["checks", "lod"])
function gatePack(id: "record" | "critic", text: string, mine: (g: Gate) => boolean) {
return check<Job>({ id, text, over: "job", at: ["done"] }, async (j) => {
if (!["scene", "kit", "shot"].includes(j.contract?.kind ?? "")) return
const g = gatesOf(j)
if (g.error) throw new Error(g.error)
// out of rounds or stalled: delivered with what's still open, said as warnings
const short = (g.short ?? []).length > 0
for (const x of g.gates.filter((x) => mine(x) && !x.clear)) found({ says: `${x.gate}${x.of ? ` ${x.of}` : ""}: ${x.says}`, level: short ? "warn" : "error", about: x.of ? [x.of] : [] })
if (short && id === "critic") found({ level: "warn", says: (g.short ?? []).join("; ") })
})
}
export const recordPack = gatePack("record", "every composition the plan names rendered or checked clean since it last changed", (g) => RECORD.has(g.gate))
export const criticPack = gatePack("critic", "the critic's rounds: a pass newer than the work, its blocking defects fixed or answered", (g) => !RECORD.has(g.gate))
+86
View File
@@ -0,0 +1,86 @@
// The looking packs (11-29, Shane on Dutch: "the agent clearly didnt see it. we should be encouraging the agent to look
// at video clips"; "a way of prompting the agent to go above and beyond by adding little surprises").
// seen a video made here has been looked at since its last render: `raea goal seen FILE` makes its contact
// sheet and shows it, and `raea goal seen FILE "what I see and would change"` says what was seen. Both
// are tied to the file as it is now (its time and size): a render after it needs a new look. A video's
// design is judged apart, on its frames at full size (`--look "..."`): a sheet's tiles show what
// happens, never whether the type, captions and cards look good (12-01, Shane on Dutch).
// surprise (off unless the brief turns it on) the look names the cut's one earned surprise with its moment in
// seconds: `raea goal seen FILE "..." --surprise "12.5 s: the dog barks on the punchline"`.
import { spawnSync } from "node:child_process"
import { readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts"
/** the least a look says: what's in it and what would change, not "looks good" */
export const SEEN_LEAST = 80
const MOMENT = /\b\d+(\.\d+)?\s*s\b/
/** a look that says nothing of the design at full size (a sheet's tiles can't show it) */
export const unjudged = (s: { look?: string }) => (s.look?.trim().length ?? 0) < SEEN_LEAST
const looked = (f: FileFacts) => f.made && f.kind === "video" && !bookkeeping(f.path)
export const seenPack = check<FileFacts>({ id: "seen", text: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said", over: "file", at: ["publish", "done"], needs: "sheet" }, async (f) => {
if (!looked(f)) return
const s = f.seen()
const name = path.basename(f.path)
if (!s) return found({ says: `${name} hasn't been looked at since its last render`, fix: `raea goal seen ${f.path}, look at every frame of the sheet, then raea goal seen ${f.path} "what you see and would change"` })
if (s.seen.trim().length < SEEN_LEAST) found({ says: `what was seen of ${name} is ${s.seen.trim().length} characters: say what's in it, frame by frame, and what you'd change (${SEEN_LEAST} at least)`, fix: `raea goal seen ${f.path} "..."` })
if (unjudged(s)) found({ says: `${name}'s design isn't judged at full size: its type, captions, cards and end, beside a reference ad's frame (${SEEN_LEAST} characters at least)`, fix: `raea goal seen ${f.path}, open each full-size frame beside a reference's, then raea goal seen ${f.path} "..." --look "how it looks beside the reference and what you changed"` })
})
export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned surprise, named with its moment in seconds", over: "file", at: ["publish", "done"] }, async (f) => {
if (!looked(f)) return
const s = f.seen()
if (!s) return
if (!s.surprise?.trim() || !MOMENT.test(s.surprise)) found({ says: `${path.basename(f.path)}'s surprise isn't named with its moment ("12.5 s: the dog barks on the punchline")`, fix: `raea goal seen ${f.path} "..." --surprise "SECONDS s: what it is"` })
})
/** what the second opinion is asked of a whole cut, picture and sound (`raea ask`, clef-omni): pointed checks, each
* a yes when the fault is there. Never "does it look good": asked whether Dutch's plain boxes looked designed, clef
* said "strong". 12-01, Shane: "you just have to have them be more specific or pointed like giving it some list of
* design checks to answer ... a few catch all checks on visual and audio design"; "the agent itself is really
* responsible for design" */
export const SECOND = [
// picture
"Are three or more separate text boxes or cards on screen at the same moment at any point?",
"Do the captions, cards and badges all look like the same plain rounded box, with nothing but colour telling them apart?",
"Is any text too small or too cluttered to read at a glance on a phone?",
"Does any text or graphic cover a person's face, or sit cut off at the edge of the frame?",
"Is a product or an app shown only as a box of text, and never as the real product or its screen?",
"Does the end card hold more than a logo, one line and one thing to do?",
"Is there a rendering glitch: a black or frozen frame, torn or blocky video, or a flash?",
// sound
"Is a voice muffled, distant or hard to understand, or is music louder than the person speaking?",
"Is there harsh, shrill or clipping sound, or music that starts or stops abruptly?",
"Is there a stretch of dead air, where nothing is said and nothing is heard?",
"Is the same sound effect used in the same way more than three times?",
]
type Opinion = { choice?: string; says?: string }
/** a second opinion on a cut, from clef watching and hearing all of it (12-01, Shane: "the agent itself should be
* watching and revising itself always and use clef omni as a secondary opinion or catch all"): each check, the
* faults it found first, kept beside the file (FILE.second.json) for the file as it is now. Null where it couldn't
* be asked. */
export function second(file: string, ask = askSecond): string | null {
const [st, kept] = [statSync(file), `${stem(file)}.second.json`]
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { render: string; says: string }
if (k.render === stamp) return k.says
} catch {}
const got = ask(file)
if (got.length !== SECOND.length) return null
const rows = got.map((o, i) => ({ q: SECOND[i], found: o.choice === "yes", says: o.says ?? o.choice ?? "no answer" }))
const says = [...rows.filter((r) => r.found), ...rows.filter((r) => !r.found)].map((r) => ` ${r.found ? "FOUND" : "clear"} (${r.says}): ${r.q}`).join("\n")
writeFileSync(kept, `${JSON.stringify({ render: stamp, says }, null, 1)}\n`)
return says
}
function askSecond(file: string): Opinion[] {
const r = spawnSync(RAEA, ["ask", file, ...SECOND, "--choose", "yes,no", "--json", "--brief", "none"], { cwd: path.dirname(file), encoding: "utf8", maxBuffer: 1 << 26 })
return String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Opinion] : [] } catch { return [] } })
}
-93
View File
@@ -1,93 +0,0 @@
// Numbers said in words, as a caption writes them: 12-05, Dutch run 9, "it's twenty four seven" was captioned "24-7"
// and the captions check called "247" a word that isn't said. Runs of number words become one word in digits, each
// number its own ("twenty four seven" is 24 and 7), so a caption in digits and one in words both match what's heard.
import type { Word } from "../media.ts"
const UNITS: Record<string, number> = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19 }
const TENS: Record<string, number> = { twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }
const SCALES: Record<string, number> = { hundred: 100, thousand: 1000, million: 1_000_000 }
const bare = (s: string) => s.toLowerCase().replace(/[^a-z]/g, "")
/** a word that is a number or part of one ("twenty-four" counts as two) */
const parts = (s: string) => s.toLowerCase().split(/[-\s]+/).map((p) => p.replace(/[^a-z]/g, "")).filter(Boolean)
const isNum = (p: string) => p in UNITS || p in TENS || p in SCALES
/** the numbers a run of number words says, each in digits: ["twenty","four","seven"] -> ["24","7"] */
export function numbersOf(ps: string[]): string[] {
const out: string[] = []
let total = 0
let cur = 0
let last: "unit" | "teen" | "tens" | "scale" | null = null
const close = () => {
if (last !== null) out.push(String(total + cur))
total = 0
cur = 0
last = null
}
for (const p of ps) {
if (p in SCALES) {
const s = SCALES[p]
if (s === 100) cur = (cur || 1) * 100
else {
total += (cur || 1) * s
cur = 0
}
last = "scale"
} else if (p in TENS) {
// "twenty" after a unit or tens starts a new number; after a scale it adds ("one hundred twenty")
if (last === "unit" || last === "teen" || last === "tens" || (cur % 100 !== 0 && last !== "scale")) close()
cur += TENS[p]
last = "tens"
} else {
const v = UNITS[p]
// a unit joins a bare tens ("twenty four") or a scale ("hundred one"); otherwise it's its own number
const joins = (last === "tens" && cur % 10 === 0) || last === "scale"
if (!joins && last !== null) close()
cur += v
last = v >= 10 ? "teen" : "unit"
}
}
close()
return out
}
/** `heard` with each run of number words ("a hundred and forty nine", "twenty four seven") one word in digits */
/** "$60" as it's said, "60 dollars" (12-05, Dutch run 10: the transcript wrote "sixty dollars" as "$60", a caption wrote
* it out, and "dollars" read as a word the host never said) */
const money = (w: Word): Word => {
const m = w.text.match(/^\$(\d[\d,]*(?:\.\d+)?)([^\d]*)$/)
return m ? { ...w, text: `${m[1]} dollars${m[2]}` } : w
}
export function asDigits(heard: Word[]): Word[] {
heard = heard.map(money)
const out: Word[] = []
for (let i = 0; i < heard.length; ) {
const run: Word[] = []
let j = i
for (; j < heard.length; j++) {
const ps = parts(heard[j].text)
const joiner = run.length > 0 && (bare(heard[j].text) === "and" || bare(heard[j].text) === "a") && j + 1 < heard.length && parts(heard[j + 1].text).every(isNum)
const lead = run.length === 0 && bare(heard[j].text) === "a" && j + 1 < heard.length && parts(heard[j + 1].text).some((p) => p in SCALES)
if (ps.length && ps.every(isNum)) run.push(heard[j])
else if (joiner || lead) run.push({ ...heard[j], text: "" })
else break
}
if (!run.some((w) => parts(w.text).length)) {
out.push(heard[i])
i++
continue
}
const ps = run.flatMap((w) => parts(w.text))
// "a" before a scale is one ("a hundred")
const text = numbersOf(ps).join(" ")
const tail = heard[j - 1]?.text.match(/[^A-Za-z0-9]+$/)?.[0] ?? ""
out.push({ ...run[0], text: `${text}${tail}`, end: run[run.length - 1].end })
i = j
}
return out
}
/** a caption's text with its numbers in words written in digits, as asDigits writes what's heard ("One more" -> "1 more") */
export const digitsIn = (text: string): string =>
asDigits(text.split(/\s+/).filter(Boolean).map((t, i) => ({ text: t, start: i, end: i + 1 }))).map((w) => w.text).join(" ")
+2 -6
View File
@@ -17,7 +17,6 @@ import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE } from "../media.ts"
import { quote } from "../text.ts"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
/** the scene reader's reading of a frame's text: [x, y, w, h, text, score] a line (the captions pack) */
@@ -256,17 +255,14 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
const best = places(ks, W, H, [on.box[2], on.box[3]], 1)[0]
const under = [...new Set(on.frames.flatMap((i) => (scenes[i] ? thingsUnder(scenes[i]!, on.box, onFrame.get(i) ?? []) : [])))]
const what = under.length ? under.join(", ") : "what the shot shows"
const q = `“${quote(on.text, 40)}”${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
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) {
// 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)
// 12-05, Shane's rule list for a cut: text over a face, a sign or the app's buttons. Over anything else the
// detector names (a dog, a suitcase, a coat) it's a warning with the place said: run 12 held "covers a suitcase"
// as an error
const hard = under.some((u) => u === "a face" || u.startsWith("words in the shot"))
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` })
+10 -28
View File
@@ -1,7 +1,7 @@
// The reading pack (11-30, Shane: "the words on screen relative to duration ... if a wordy CTA or component or scene is
// meant to be fully read or if it just adds glossable content or context, and if it's on screen long enough to be
// read"). From the render's own texts when its manifest is here (exactly what it drew, five times a second, no farm
// call), else the scene reader's (the farm's texts, two frames a second), every block of text that isn't a caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
// read"). From the scene reader's text (the farm's texts, two frames a second), every block of text that isn't a
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
//
// time to read: READ_BASE s to find it, then WPS words a second (a feed viewer's skim of short ad text; subtitle
// standards sit near 3 words a second). A block up for under its time is a warning; under SHORT of it an error,
@@ -12,8 +12,7 @@
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { captionsOf, fit, type Frame, framesOfManifest, LEAST, letters, type Read, similar } from "./captions.ts"
import { quote } from "../text.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 }
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block }
@@ -97,41 +96,24 @@ export function reading(blocks: Block[]): Finding[] {
const up = b.to - b.from
const n = need(b.words)
if (up >= n) continue
const said = quote(b.text, 67)
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
const load = `${b.words} words up ${up.toFixed(1)} s (${(b.words / up).toFixed(1)} words a second; reading takes about ${n.toFixed(1)} s at ${WPS} a second)`
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${said}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${said}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
}
return out
}
/** a render manifest's texts as `framesOfManifest` steps them, each a line as tall as one of its lines: a text set on
* three lines has one ink box over all three, and its size (fine print or a headline) is a line's, not the box's */
export function readingFrames(manifest: unknown): { frames: Frame[]; rate: number } | null {
const own = framesOfManifest(manifest)
const m = manifest as { fps?: number; frames?: { text?: { text?: string; ink?: number[]; box?: number[]; opacity?: number; lines?: number }[] }[] } | null
if (!own || !m?.frames) return null
const step = Math.max(1, Math.round((Number(m.fps) || 30) / own.rate))
const frames = own.frames.map((fr, k) => {
const texts = (m.frames![k * step]?.text ?? []).filter((t) => { const b = t.ink ?? t.box; return !!b && b.length >= 4 && !!String(t.text ?? "").trim() && (t.opacity ?? 1) > 0.2 }) // framesOfManifest's own test, so each line is its text
return { h: fr.h, lines: fr.lines.map((l, i) => [l[0], l[1], l[2], l[3] / Math.max(1, Number(texts[i]?.lines) || 1), l[4], l[5]] as Read) }
})
return { frames, rate: own.rate }
}
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"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// the render's own texts when its manifest is here (no farm call, and never the footage's own text), else the export
// read frame by frame; captions are found in the same frames the captions pack reads
const own = f.manifest ? readingFrames(f.manifest) : null
const sc = own ? null : await f.scene()
const frames: Frame[] = own ? own.frames : sc!.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = own ? own.rate : sc!.rate || 2
const rate = sc.rate || 2
const heard = await f.words()
const caps = captionsOf(own ? framesOfManifest(f.manifest)!.frames : frames, rate, heard)
const caps = captionsOf(frames, rate, heard)
const isCaption = (t: number, key: string) => caps.some((c) => t >= c.from - 0.01 && t < c.to && (similar(c.key, key) || c.key.includes(key)))
for (const x of reading(blocksOf(frames, rate, isCaption, heard))) found({ level: x.level, says: x.says, seconds: x.at })
},
-34
View File
@@ -1,34 +0,0 @@
// The render pack: what the render itself found as it drew (its manifest's `findings`: a missing font, clipping, a part
// out of place or under its planned detail, light that jumps, a frame drawn empty), held to the deliverable it made.
// Read, never measured again: the render's end checks saw every frame as it was drawn, which nothing after it can do
// as cheaply (12-04, Shane: "fix how every agent checks its work": one check, after the render, everything else
// reusing it). One line a kind of finding: its first, and how many more like it.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { bookkeeping } from "./naming.ts"
type Said = { check?: string; level?: string; says?: string; fix?: string | null; frames?: [number, number] | null }
/** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice */
const MEASURED_AGAIN = new Set(["safe-area"])
/** the manifest's findings, one a kind: the first of each (by check and level), with how many more there were */
export function renderFindings(manifest: unknown): Said[] {
const all = ((manifest as { findings?: Said[] } | null)?.findings ?? []).filter((x) => x && (x.level === "error" || x.level === "warn"))
const firsts = new Map<string, Said & { more: number }>()
for (const x of all) {
const k = x.check ?? "render"
if (MEASURED_AGAIN.has(k)) continue
const key = `${k} ${x.level}`
const had = firsts.get(key)
if (had) had.more++
else firsts.set(key, { ...x, more: 0 })
}
return [...firsts.values()].map((x) => ({ ...x, says: `${x.check ?? "render"}: ${x.says ?? ""}${x.more ? ` (and ${x.more} more like it)` : ""}` }))
}
export default check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || bookkeeping(f.path) || !f.manifest) return
for (const x of renderFindings(f.manifest))
found({ level: x.level as "error" | "warn", says: x.says ?? "", fix: x.fix ?? undefined, frames: x.frames ?? undefined })
})
+1 -1
View File
@@ -15,7 +15,7 @@ import { adOf, bookkeeping, sizeOf } from "./naming.ts"
* 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 | null; height?: number | null }): string | null {
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
+4 -38
View File
@@ -29,8 +29,6 @@ const GAP_LEAST = 8
const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4
/** sound this close to a word (s) at a cut is the word's, cut; further off it's another sound */
const WORD_NEAR = 0.6
/** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6
const LEVEL_WARN = 4
@@ -104,9 +102,6 @@ export function nearestGap(l: Levels, t: number, ref: number, words: Word[], ins
return null
}
/** the longest a spoken word runs (s): a drawn-out "sooo" is under it */
export const WORD_MAX = 2.5
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
* to about 30 ms) */
const SEAM = 0.03
@@ -121,27 +116,6 @@ export function seams(words: Word[]): { at: number; before: string; after: strin
return out
}
/** a manifest's clips with every seam that isn't an edit joined: a take that plays straight on across two clips (the
* same source and level, touching in the cut and in the take, no fade between) is one clip, so its seam is never read
* as an edit point. A composition splits a clip that way when it reframes or restyles a shot mid-clip */
export function joined(clips: Clip[], fps: number): Clip[] {
const out: Clip[] = []
const frame = 1.5 / fps
for (const c of [...clips].sort((p, q) => p.from - q.from)) {
const prev = out.findLast((p) => p.src === c.src && Math.abs(p.to - c.from) <= 1)
const on =
prev &&
(prev.gainDb ?? 0) === (c.gainDb ?? 0) &&
prev.bus === c.bus &&
!prev.fadeOut &&
!c.fadeIn &&
Math.abs(prev.at + (prev.to - prev.from) / fps - c.at) <= frame
if (prev && on) Object.assign(prev, { to: c.to, fadeOut: c.fadeOut })
else out.push({ ...c })
}
return out
}
/** a voice clip's in and out: inside a word, or on sound */
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
const out: Finding[] = []
@@ -160,9 +134,7 @@ export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Find
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
continue
}
// a "word" longer than WORD_MAX is a transcriber's timing gone wrong, not a word (12-04, Elfster run 5: "secret"
// timed 143.28-166.96 s, and a cut 15 s into it was called a word cut in two): the sound there is read instead
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t && w.end - w.start <= WORD_MAX)
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
@@ -180,10 +152,7 @@ export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Find
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
// sound with no word near it isn't a word cut (12-05, run 12: a cut "5397 ms from" the nearest word was an
// error): a laugh, a noise, or speech the transcript missed, for the ear: a warning
const off = near ? Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) : Infinity
out.push({ level: off <= WORD_NEAR ? "error" : "warn", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
}
}
return out
@@ -231,7 +200,7 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
out.push({ level: "error", kind: "manifest", at: null, says: `its render manifest holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again` })
const heard: Heard[] = []
let voice = 0
for (const c of joined(m.sounds?.clips ?? [], fps)) {
for (const c of m.sounds?.clips ?? []) {
const kind = busOf(c)
const file = f.take(c.src)
if (!file) {
@@ -248,10 +217,7 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
const words = await f.takeWords(file)
const l = f.levels(c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1, file)
out.push(...editPoints(c, fps, words, l))
// a line is a clip a word is said in: one with none, or only a transcriber's broken timing (a "word" 90 s long,
// 12-05 run 12), is a pause or a reaction, never "a line 51 dB under the others"
const said = words.filter((w) => w.end - w.start <= WORD_MAX && w.end > c.at && w.start < c.at + dur)
if (said.length) heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, said) + (c.gainDb ?? 0) })
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
} else {
const l = f.levels(c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20), file)
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
+35
View File
@@ -0,0 +1,35 @@
// The taste pack (docs/goal.feature MK47): every rule a project registers runs inside the loop. The person's, the
// workspace's and the project's taste lines (with their checks: raea's forms, raea's checks by name, a project's own
// .ts check such as a story check) and a person's signed asks are run by `raea check`, the instrument, over each
// composition's newest render; their findings become the goal check's, so none runs only when an agent remembers to.
// What needs a render that isn't there waits, and says so; it never fails the goal.
import { spawnSync } from "node:child_process"
import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { RAEA, Unmet } from "../media.ts"
type Said = { check: string; level: "error" | "warn" | "note"; says: string; fix?: string | null; by?: string; about?: { name?: string }[] }
type Report = { unread?: Said[]; compositions?: { file: string; composition?: string; findings: Said[]; waits: { rule: string; for: string }[] }[]; asks?: unknown }
/** `raea check ROOT --no-render --json`, read; null when the instrument couldn't run */
export function tasteReport(root: string): Report | null {
const r = spawnSync(RAEA, ["check", root, "--no-render", "--json"], { cwd: root, encoding: "utf8", maxBuffer: 1 << 26, env: { ...process.env, RAEA_RECORD: "off" } })
const text = String(r.stdout ?? "")
const at = text.indexOf("{")
if (at < 0) return null
try {
return JSON.parse(text.slice(at)) as Report
} catch {
return null
}
}
export const tastePack = check<Job>({ id: "taste", text: "every taste line and signed ask the project is held to", over: "job", at: ["publish", "done"] }, async (j) => {
const r = tasteReport(j.root)
if (!r) throw new Unmet("raea check didn't answer here, so the taste lines wait")
for (const u of r.unread ?? []) found({ says: u.says, level: u.level })
for (const c of r.compositions ?? []) {
// raea's own floor is the floor and stills packs' already; here, only what the taste lines and asks found
for (const f of c.findings.filter((x) => x.by !== "raea")) found({ says: `${f.check}: ${f.says}`, level: f.level, about: [c.file], ...(f.fix ? { fix: f.fix } : {}) })
}
})
+1 -2
View File
@@ -11,7 +11,6 @@
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { quote } from "../text.ts"
export type Finding = { level: "error" | "warn"; kind: "buried" | "quiet"; at: number; says: string }
@@ -81,7 +80,7 @@ export function voice(db: number[], heard: Word[]): Finding[] {
const under = typical - d
if (under < QUIET_WARN || l.length < 2) continue
const text = l.map((w) => w.text).join(" ")
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${quote(text, 57)}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${text.length > 60 ? `${text.slice(0, 57)}...` : text}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
}
return out.sort((a, b) => a.at - b.at)
}
+2
View File
@@ -5,6 +5,7 @@
// crossfades on audio that make it so you can't hear it, and cuts where it will cut early over someone speaking").
// With no lines beside it, only the fades and the edges are held.
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { stem, type Word } from "../media.ts"
@@ -129,5 +130,6 @@ export default check<FileFacts>(
const l = f.levels()
const out = [...(lines ? compare(readFileSync(lines, "utf8"), heard) : []), ...fades(l.db, heard, f.seconds ?? heard[heard.length - 1].end)]
for (const x of out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))) found({ level: x.level, says: x.says, seconds: x.at ?? undefined })
if (!lines && f.moment !== "edit") found({ level: "note", says: `no ${path.basename(stem(f.abs))}.lines.txt beside it: write the words this cut should say there, in order, and every one is held to what's heard` })
},
)
+71 -79
View File
@@ -1,81 +1,41 @@
// `raea check` (docs/check.feature): the one check. Every rule each goal of brief.ts holds at one of four moments, on
// raea's own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal
// or several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
// `raea goal` (docs/goal.feature): every rule each goal of brief.ts is held to, run at one of four moments, on raea's
// own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal or
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// 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. The files are the ones named, else (publish, done) every deliverable and
// every video or still made under out/. Each check whose moments include --at (done by default) runs: a file
// check on each file, a job check once. A file's check after its render is kept beside it (FILE.check.json) and
// publish and done read it while it's fresh, never running it again. One line a rule a file. Writes
// review/goal.json and prints each finding. Exit 1 on an error, 2 when it can't run (brief.ts doesn't load). A
// check that needs what this machine hasn't (a transcriber) waits, and says what for; it holds nothing.
// `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/.
// Each check whose moments include --at (done by default) runs: a file check on each file, a job check once.
// Every project is also held to `registered` (every raea file reached from brief.ts). Writes review/goal.json
// (and FILE.check.json beside each file named) and prints each finding. Exit 1 on an error, 2 when it can't run
// (brief.ts doesn't load). A check that needs what this machine hasn't (a scene reader, a transcriber) waits, and
// says what for; it holds nothing.
// 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 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, unknownPacks } from "./contract.ts"
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 * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts"
import { loadProject, type Project } from "./project.ts"
import { judge } from "./packs/goal.ts"
import { PACK_CHECKS } from "./packs/index.ts"
import { second } from "./packs/look.ts"
import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts"
import { tasksMain } from "./tasks.ts"
import { wellFormed } from "./text.ts"
/** the checks every project is held to once, whatever its goals: none in the loop (12-04: `registered`, how brief.ts
* imports files, failed every Dutch cut, and the taste check waits on every box; neither is a fault in the work) */
const ALWAYS: Check[] = []
/** the checks every project is held to once, whatever its goals */
const ALWAYS: Check[] = [registeredPack, tastePack]
/** the moments a deliverable's own check, run once after its render, stands for: publish and done read it, never run it again */
const REUSED: Moment[] = ["publish", "done"]
/** a deliverable's check kept beside it (FILE.check.json), while it's no older than the file or its manifest: the
* checks it ran and what they found */
export function keptCheck(abs: string): { checks: string[]; findings: Said[] } | null {
const k = `${media.stem(abs)}.check.json`
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
if (!existsSync(k) || when(k) < when(abs) || when(k) < when(`${media.stem(abs)}.render.json`)) return null
try {
const j = JSON.parse(readFileSync(k, "utf8")) as { checks?: string[]; findings?: Said[] }
return Array.isArray(j.checks) ? { checks: j.checks, findings: j.findings ?? [] } : null
} catch {
return null
}
}
/** one line a rule a file (12-04, round 26: 34 of one cut's errors were each caption phrase in the same UI zone; 12-05,
* run 5: an ERROR and a WARN of the same check each had a line, and a cut listed 12): of a check's findings at moments
* in the file, the most severe first one, and how many more there were; findings with no moment are distinct faults,
* said once each */
const RANK: Record<Said["level"], number> = { error: 0, warn: 1, note: 2 }
export function collapse(xs: Said[]): Said[] {
const firsts = new Map<string, { x: Said; same: number; lesser: number; to: number | null }>()
for (const x of xs) {
// a fault found at many moments (located in time) is one line; distinct faults with no moment each keep theirs
const key = `${x.goal ?? ""}\u0000${x.file ?? ""}\u0000${x.check}\u0000${x.seconds ? "" : `${x.level}\u0000${x.says}`}`
const had = firsts.get(key)
if (!had) firsts.set(key, { x, same: 0, lesser: 0, to: x.seconds?.[1] ?? null })
else {
if (RANK[x.level] < RANK[had.x.level]) {
// a worse one leads the line; what led it is counted under it
had.lesser += had.same + 1
had.same = 0
had.x = x
} else if (x.level === had.x.level) had.same++
else had.lesser++
if (x.seconds && (had.to === null || x.seconds[1] > had.to)) had.to = x.seconds[1]
}
}
return [...firsts.values()].map(({ x, same, lesser }) => {
const more = [same ? `${same} more like it${x.seconds ? ", to the same fix" : ""}` : "", lesser ? `${lesser} lesser` : ""].filter(Boolean).join("; ")
return more ? { ...x, says: `${x.says} (and ${more})` } : x
})
}
/** a finding as `raea check` reports it: its goal, its check, the file it's in, and where in it */
/** a finding as `raea goal check` reports it: its goal, its check, the file it's in, and where in it */
export type Said = { goal: string | null; check: string; level: Finding["level"]; file: string | null; seconds: [number, number] | null; says: string; fix: string | null; by: string }
/** one goal's verdict at a moment */
export type GoalVerdict = { name: string; kind: Contract["kind"] | "floor"; step: string | null; after: string[]; passed: boolean; errors: number; warnings: number; checks: string[]; files: string[] }
@@ -158,10 +118,8 @@ function planOf(goals: Contract[]): string[] {
const out = [...doctor]
for (const c of goals) {
const at = goals.length > 1 ? `${nameOf(c)}: ` : ""
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea check --json lists them)`))
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea goal check --json lists them)`))
for (const k of (c.checks ?? []) as unknown[]) if (!k || typeof (k as Check).id !== "string") out.push(`${at}checks: each is a check() imported from the project's checks/ folder`)
// nothing judges a `says` rule any more (12-04): said, so it isn't taken for checked
for (const r of c.rules ?? []) if (r.says && !r.run && !r.file) out.push(`${at}rules.${r.id}: a \`says\` rule isn't checked by anything: make it a command (\`run\`) or a file (\`file\`), or leave it to the person's review`)
}
return out
}
@@ -204,16 +162,9 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null]))
for (const c of checks) {
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }]))
else
for (const f of files) {
const k = kept.get(f.path)
// run once, after its render: what it found then stands (its own findings, at this goal)
if (k?.checks.includes(c.id)) findings.push(...k.findings.filter((x) => x.check === c.id).map((x) => ({ ...x, goal: contract ? name : null })))
else keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
}
else for (const f of files) keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
}
const mine = findings.slice(before)
const errors = mine.filter((x) => x.level === "error").length
@@ -221,8 +172,6 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
verdicts.push({ name, kind: contract?.kind ?? "floor", step: contract?.step ?? null, after: contract?.after ?? [], passed: errors === 0 && broke.length === brokeBefore, errors, warnings: mine.filter((x) => x.level === "warn").length, checks: checks.map((c) => c.id), files: files.map((f) => f.path) })
}
findings.sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.seconds?.[0] ?? -1) - (b.seconds?.[0] ?? -1))
// printed and saved whole: no finding holds half a character (12-05, Dutch run 9: one broke the check as it printed)
findings.splice(0, findings.length, ...collapse(findings).map((x) => ({ ...x, says: wellFormed(x.says), fix: x.fix && wellFormed(x.fix) })))
const errors = findings.filter((x) => x.level === "error").length
return {
object: "goal.check",
@@ -250,7 +199,7 @@ export function writeReport(r: Report, named: string[]) {
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
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"), checks: r.checks, findings: mine }, null, 1)}\n`)
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`)
}
}
@@ -267,7 +216,7 @@ export function text(r: Report): string {
for (const b of r.broke) t.push(`BROKE ${b.check}${b.file ? ` ${b.file}` : ""} ${b.says}`)
if (r.goals.length > 1) for (const g of r.goals) t.push(`${g.passed ? "ok " : "open"} goal ${g.name} (${g.kind}${g.step ? `, step ${g.step}` : ""}${g.after.length ? `, after ${g.after.join(", ")}` : ""}): ${g.errors} errors, ${g.warnings} warnings`)
const kinds = r.goals.map((g) => (r.goals.length > 1 ? g.name : g.kind)).join(", ")
t.push(`${r.passed ? "PASSED" : "FAILED"} raea check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
t.push(`${r.passed ? "PASSED" : "FAILED"} goal check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
return t.join("\n")
}
@@ -277,8 +226,11 @@ 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 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,...] [--json]
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"]
raea goal judge [--goal NAME]
raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> {
@@ -286,7 +238,7 @@ export async function main(argv: string[]): Promise<number> {
if (verb === "check") {
const at = (flag(a, "--at") ?? "done") as Moment
if (!MOMENTS.includes(at)) {
console.error(`raea check: --at is one of ${MOMENTS.join(", ")}`)
console.error(`raea goal check: --at is one of ${MOMENTS.join(", ")}`)
return 2
}
const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
@@ -294,7 +246,7 @@ export async function main(argv: string[]): Promise<number> {
try {
r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") })
} catch (e) {
console.error(`raea check: ${(e as Error).message}`)
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))))
@@ -302,6 +254,33 @@ export async function main(argv: string[]): Promise<number> {
return r.passed ? 0 : 1
}
if (verb === "tasks") return tasksMain(a)
if (verb === "seen") {
const [file, said] = positional(a, ["--surprise", "--look"])
if (!file || !existsSync(file)) return usage()
if (!said?.trim()) {
const sheet = media.sheet(path.resolve(file))
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
// on raea cloud (where Clef-Omni is paid for), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? second(path.resolve(file)) : null
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
return 0
}
const abs = path.resolve(file)
const sheet = `${media.stem(abs)}.sheet.jpg`
if (kindOf(abs) === "video" && !media.freshBeside(abs, "sheet.jpg")) {
console.error(`raea goal seen: ${path.basename(file)} has no sheet since its last render: raea goal seen ${file}, and look at it first`)
return 1
}
const [st, surprise, look] = [statSync(abs), flag(a, "--surprise"), flag(a, "--look")?.trim()]
if (kindOf(abs) === "video" && (!look || !media.looksFresh(abs))) {
console.error(`raea goal seen: ${path.basename(file)}'s design isn't judged yet: raea goal seen ${file} makes its frames at full size; open them, then say --look "its type, captions and cards beside a reference, and what you changed"`)
return 1
}
writeFileSync(`${media.stem(abs)}.seen.json`, `${JSON.stringify({ video: path.basename(abs), render: `${Math.round(st.mtimeMs)} ${st.size}`, sheet: path.basename(sheet), seen: said.trim(), ...(look ? { look } : {}), ...(surprise ? { surprise } : {}), at: new Date().toISOString() }, null, 1)}\n`)
console.log(`${media.stem(path.basename(abs))}.seen.json: seen as it is now`)
return 0
}
if (verb === "place") {
const file = positional(a, ["--at", "--box", "-o"])[0]
if (!file || !existsSync(file)) return usage()
@@ -324,6 +303,19 @@ export async function main(argv: string[]): Promise<number> {
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
if (verb === "judge") {
const root = rootOf(process.cwd())
const { goals } = root ? await goalsIn(root) : { goals: [] as Contract[] }
const name = flag(a, "--goal")
const said = goals.filter((g) => (name ? nameOf(g) === name : true) && saysOf(g).length)
if (!root || said.length !== 1) {
console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`)
return 2
}
const v = await judge(said[0], root)
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
return 0
}
return usage()
}
-15
View File
@@ -64,18 +64,3 @@ export function inOrder(want: string[], got: string[]): number {
}
return row[got.length] / want.length
}
// A finding's quoted text, safe to print. 12-05, Dutch run 9: a caption's text cut at 40 UTF-16 units split an emoji, the
// report held half of it, and printing it broke the check ("Conversion from string failed: invalid utf-8 sequence").
/** a lone half of a surrogate pair: no character, and nothing UTF-8 can hold */
const LONE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
/** `s` with any half character replaced by U+FFFD */
export const wellFormed = (s: string): string => s.replace(LONE, "�")
/** `s` cut to at most `n` characters (whole code points, never half an emoji), with "..." when it was longer */
export function quote(s: string, n: number): string {
const cs = Array.from(s)
return cs.length > n ? `${cs.slice(0, n).join("")}...` : s
}
-19
View File
@@ -93,22 +93,3 @@ test("captions are a must: a cut that talks with only a text hook up fails, a ba
// a cut with hardly any talking needs none
expect(uncaptioned([], said.slice(0, 4))).toEqual([])
})
test("a caption the takes' own words say passes, though a second hearing of the export wrote it otherwise (12-05, run 11)", () => {
const shown = captionsOf(frames, 2, said)
// the export heard again has no "god" after "my,"; the take's own words, placed where the edit plays them, do
const placed = said.map((x) => (x.text === "my," ? { ...x, text: "my, god" } : x))
expect(compare(shown, said).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
expect(compare(shown, said, placed).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(false)
// a word in neither is still found
expect(compare(shown, said, said).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
})
test("words said but uncaptioned that the take's own words have captioned are a second hearing's, not a fault (12-05, run 11)", () => {
const shown = captionsOf(frames, 2, said)
// the export heard again inserts words where the take's own words, which the captions follow, have none
const again = said.flatMap((x) => (x.text === "know?" ? [x, { ...x, text: "sleep with Paul", start: x.end + 0.01, end: x.end + 0.2 }] : [x]))
expect(compare(shown, said, said).filter((x) => x.kind === "dropped" && x.says.includes("okay, this is")).length).toBe(1)
// "okay, this is" is in the take's words too: still a fault
expect(compare(shown, again, said).some((x) => x.kind === "dropped" && x.says.includes("okay, this is"))).toBe(true)
})
-46
View File
@@ -1,46 +0,0 @@
// docs/check.feature: one check, run once after the render, one line a rule a file, our own text from the manifest.
import { expect, test } from "bun:test"
import { mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { renderFindings } from "../src/packs/render.ts"
import { collapse, keptCheck } from "../src/run.ts"
const at = (s: number, says = "a caption under the app's buttons") => ({ goal: null, check: "floor", file: "a.mp4", level: "error" as const, says, seconds: [s, s + 1] as [number, number] })
test("CK2: one fault found at many moments is one line, distinct faults keep theirs", () => {
const xs = collapse([at(1), at(4, "another phrase in the same zone"), at(9), { goal: null, check: "playable", file: null, level: "error", says: "no landscape composition", seconds: null }, { goal: null, check: "playable", file: null, level: "error", says: "over the 5120 KB cap", seconds: null }] as never)
expect(xs).toHaveLength(3)
expect(xs[0].says).toContain("(and 2 more like it")
expect(xs.filter((x) => x.check === "playable")).toHaveLength(2)
})
test("CK1: a kept check stands while it's no older than the file and its manifest", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
writeFileSync(path.join(d, "a.check.json"), JSON.stringify({ checks: ["words", "floor"], findings: [at(1)] }))
utimesSync(v, new Date(1_000_000), new Date(1_000_000))
expect(keptCheck(v)?.checks).toEqual(["words", "floor"])
// re-rendered after it was checked: stale
utimesSync(v, new Date(), new Date(Date.now() + 60_000))
expect(keptCheck(v)).toBeNull()
})
test("CK2: the render's own findings, one line a kind; safe-area is measured on the video", () => {
const said = renderFindings({ findings: [
{ check: "font-missing", level: "error", says: "Inter isn't installed" },
{ check: "font-missing", level: "error", says: "Inter Bold isn't installed" },
{ check: "safe-area", level: "warn", says: "text in the bottom zone" },
{ check: "clipping", level: "info", says: "fine" },
] })
expect(said).toHaveLength(1)
expect(said[0].says).toBe("font-missing: Inter isn't installed (and 1 more like it)")
})
test("CK3: one line a rule a file across levels: the worst leads, the rest counted under it (12-05, run 5)", () => {
const f = (level: string, check: string, s: number, says: string) => ({ goal: "g", check, file: "out/cuts/a.mp4", level, says, seconds: [s, s + 1], fix: null, by: "raea" })
const xs = collapse([f("warn", "place", 3.5, "text covers a person"), f("error", "place", 0, "text covers a dog"), f("warn", "frames", 4, "face cut by the bottom edge"), f("error", "frames", 3, "face cut by the right edge"), f("warn", "sound", 8.8, "a tight cut"), f("error", "sound", 14.1, "cuts a word")] as never)
expect(xs.map((x: any) => [x.check, x.level])).toEqual([["place", "error"], ["frames", "error"], ["sound", "error"]])
expect(xs[0].says).toBe("text covers a dog (and 1 lesser)")
})
+7 -7
View File
@@ -7,17 +7,17 @@ import { cut, packsOf, rules } from "../src/contract.ts"
import { goalCheck } from "../src/run.ts"
import { project } from "./project.ts"
test("a cut holds only the rules that catch real faults (docs/check.feature CK2)", () => {
test("a cut holds the craft by default, surprise only when asked", () => {
const on = packsOf(cut({ cut: { brief: "b.txt" } }))
for (const p of ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"] as const) expect(on).toContain(p)
for (const p of ["voice", "reading", "hook", "airgaps", "montage", "quotes"] as const) expect(on).not.toContain(p)
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { montage: true, place: false } }))).toContain("montage")
for (const p of ["words", "sound", "frames", "place", "seen", "naming", "sizes", "say", "cta"] as const) expect(on).toContain(p)
expect(on).not.toContain("surprise")
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { surprise: true, place: false } }))).toContain("surprise")
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { place: false } }))).not.toContain("place")
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "render"])
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "render", "run"])
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "stills"])
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "stills", "run", "says"])
expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
// no contract: the floor every made video is held to
expect(packsOf(null)).toEqual(["frames", "place", "captions", "floor", "render"])
expect(packsOf(null)).toEqual(["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
})
test("a project's own check runs at its moments", async () => {
+1 -44
View File
@@ -14,7 +14,7 @@ beforeAll(() => {
const BRIEF = 'Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase "free, fun, and easy."\nDon\'t let it read as White Elephant.\nEnd on the CTA: "Make your Wishlist and organize your Gift Exchange on Elfster. It\'s free."\nCTV specs from the client [TO CONFIRM]\n'
const contract = (cut: Record<string, unknown> = {}) => ({
kind: "cut",
packs: { words: false, sound: false, frames: false, place: false, captions: false, floor: false, render: false, naming: false, sizes: false, quotes: true },
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
cut: {
brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" },
@@ -128,46 +128,3 @@ test("a rotated CTA lands on any of its lines", async () => {
put(d2, "media/brief.txt", `${BRIEF}"See a vet today at Dutch.com."\n`)
expect(of(await run(d2), "quotes")).toHaveLength(1)
})
test("an end card's lines are read together: a CTA drawn as two lines is shown (12-04, Elfster run 4)", async () => {
const d = project(contract({ cuts: [{ id: "a1_s1" }] }))
put(d, "media/brief.txt", BRIEF)
// nothing of the CTA is said; the end card draws it as two lines at the clip's end
deliver(d, S1, "so it draws the names for you and everyone gets a gift they want")
const card = (lines: string[]) => JSON.stringify({ fps: 30, frames: [{ frame: 0, text: lines.map((text) => ({ text, opacity: 1 })) }] })
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Elfster", "Make your Wishlist and organize your Gift Exchange on Elfster.", "It's free."]))
expect(of(await run(d), "cta")).toEqual([])
// its first line alone isn't the CTA
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Make your Wishlist and organize your Gift Exchange on Elfster."]))
expect(of(await run(d), "cta")).toHaveLength(1)
})
test("a CTA said in part and shown in part lands, numbers said in words included (12-05, Dutch run 10)", async () => {
const cta = { text: "Go to Dutch.com and use code PETS60 for $60 off your first year.", from: "Go to Dutch.com and use code PETS60 for $60 off your first year." }
const d = project(contract({ cta, cuts: [{ id: "a1_s1" }] }))
put(d, "media/brief.txt", `${BRIEF}"Go to Dutch.com and use code PETS60 for $60 off your first year."\n`)
// the host's words (Dutch.com misheard), cut before "year"; the end card shows the offer
deliver(d, S1, "go visit Dodge com and use code pets sixty for sixty dollars off your first")
const card = (lines: string[]) => JSON.stringify({ fps: 30, frames: [{ frame: 0, text: lines.map((text) => ({ text, opacity: 1 })) }] })
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Code PETS60: $60 off your first year"]))
expect(of(await run(d), "cta")).toEqual([])
// with no end card it's 79%, and still held
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Dutch"]))
expect(of(await run(d), "cta")).toHaveLength(1)
})
test("a CTA no cut ends on is found in the takes that say it, so the fix is one raea cut away (12-05)", async () => {
const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs")
const { tmpdir } = await import("node:os")
const { join } = await import("node:path")
const { takesSaying } = await import("../src/packs/cut.ts")
const root = mkdtempSync(join(tmpdir(), "cta-"))
mkdirSync(join(root, "footage"))
const words = (s: string, from: number) => s.split(" ").map((text, i) => ({ text, start_ms: (from + i * 0.3) * 1000, end_ms: (from + i * 0.3 + 0.25) * 1000 }))
writeFileSync(join(root, "footage", "host.words.json"), JSON.stringify(words("Alright, so download the Acme app and book a call today. Use code SAVE60 for $60 off your first year.", 0)))
writeFileSync(join(root, "footage", "ugc4.words.json"), JSON.stringify(words("Saves a lot of time. Go to acme.com today and use code SAVE60 for sixty dollars off for your first year.", 20)))
const got = takesSaying(root, ["Go to acme.com and use code SAVE60 for $60 off your first year."])
expect(got.map((t) => t.take)).toEqual(["ugc4"])
expect(got[0].at).toBeCloseTo(21.5, 1)
expect(takesSaying(root, ["Visit the moon today."])).toEqual([])
})
+1 -20
View File
@@ -3,7 +3,7 @@ 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 { faultsOf, floorOf, type Measured } from "../src/packs/floor.ts"
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", () => {
@@ -50,22 +50,3 @@ test("montage findings are kept: measured again when the video is newer or its b
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
test("blocky darks are an error only when the encode added them; untraced, a warning; the picture's own, nothing (12-04)", () => {
const xs: Measured[] = [
{ level: "error", says: "blocky patches in dark areas in 1 of 1 sampled frames (worst 6% of dark blocks stepping): the encode starved the near-blacks, or the footage holds them; render with --quality master" },
{ level: "error", says: "blocky patches in dark areas in 2 of 9 sampled frames (worst 5% of dark blocks stepping); whether the encode made them or the picture holds them couldn't be told (no composition)" },
{ level: "note", says: "blocky patches in dark areas in 3 of 9 sampled frames (worst 4%): the picture's own, there as the composition draws them" },
{ level: "error", says: "the encode added blocky patches in dark areas: 4 of 9 samples are blotchier than the composition draws them unencoded" },
]
expect(faultsOf(xs).map((x) => x.level)).toEqual(["warn", "warn", "error"])
})
test("text at the right edge above the app's buttons isn't in its UI zone; below them it is (12-05)", () => {
const at = (y: number, more = "") => ({ level: "error" as const, says: `“THE BODY SHOP” sits in the app's UI zone at the right (keep 140 px clear): its box 134,${y} 812x112 in 1080x1920${more}` })
expect(faultsOf([at(682)])).toEqual([])
expect(faultsOf([at(1290)])).toEqual([at(1290)])
expect(faultsOf([at(682, " (and 1 more like it)")])[0].level).toBe("warn")
const top = { level: "error" as const, says: "“Hook” sits in the app's UI zone at the top (keep 220 px clear): its letters 86,150 908x196 in 1080x1920" }
expect(faultsOf([top])).toEqual([top])
})
+131 -5
View File
@@ -1,10 +1,15 @@
// 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, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
const goal = (rules: unknown[]) => ({ kind: "rules", aim: "tests pass", rules })
const VERDICT = "review/judge/rules.json"
test("a command passes or says why", async () => {
const d = project(goal([{ id: "ok", run: "true" }, { id: "bad", run: "echo broke; exit 3" }]))
@@ -21,6 +26,81 @@ test("a command past its timeout fails", async () => {
expect(r.findings.find((x) => x.check === "run")?.says).toContain("still running after 1 s")
})
test("words need a fresh critic", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const says = async () => (await goalCheck({ cwd: d })).findings.filter((x) => x.check === "says")
// no critic in this session: it says so, and names no tool or agent to run
expect((await says())[0].fix).toBe(NO_CRITIC)
const later = Math.floor(Date.now() / 1000) + 5
mkdirSync(path.join(d, "review/judge"), { recursive: true })
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, by: "claude", rules: { friendly: { pass: true, why: "it says hello warmly" } } }))
expect(await says()).toEqual([])
// the critic's own file (and raea's report) don't count as the work changing
expect(newest(d)!).toBeLessThan(later * 1000)
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: 1, rules: { friendly: { pass: true, why: "" } } }))
expect((await says())[0].says).toContain("changed after")
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, rules: { friendly: { pass: false, why: "it is curt" } } }))
expect((await says())[0].says).toContain("it is curt")
})
test("the check asks this session's critic itself", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const heard: { auth: string | null; cwd: string; prompt: string }[] = []
const server = Bun.serve({
port: 0,
async fetch(req) {
const b = (await req.json()) as { cwd: string; prompt: string }
heard.push({ auth: req.headers.get("authorization"), ...b })
return Response.json({ text: 'thinking... {"rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}}' })
},
})
process.env.RAEA_JUDGE_URL = `http://127.0.0.1:${server.port}/host/judge`
process.env.RAEA_JUDGE_TOKEN = "t0k"
try {
const r = await goalCheck({ cwd: d })
expect(r.findings.filter((x) => x.check === "says")).toEqual([])
expect(heard).toHaveLength(1)
expect(heard[0].auth).toBe("Bearer t0k")
expect(heard[0].prompt).toContain("friendly: the reply is friendly")
// judged once: a second check reads the kept verdict
await goalCheck({ cwd: d })
expect(heard).toHaveLength(1)
} finally {
delete process.env.RAEA_JUDGE_URL
delete process.env.RAEA_JUDGE_TOKEN
server.stop(true)
}
})
test("a rule with a piece to watch goes to clef, any other to the agent", async () => {
const g = goal([
{ id: "plan", says: "plan.md names every cut" },
{ id: "cut", says: "out/a.mp4 opens on the hook" },
])
const d = project(g)
put(d, "out/a.mp4", "video")
const clefAsked: string[] = []
const agentAsked: string[] = []
const v = await judge(g as never, d, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}}}'),
})
// out/ holds a video, so both are about a piece: clef judges both, and nothing asks the agent
expect(agentAsked).toEqual([])
expect(Object.keys(v.rules).sort()).toEqual(["cut", "plan"])
const bare = project(g)
const v2 = await judge(g as never, bare, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}, "cut": {"pass": false, "why": "no cut yet"}}}'),
})
expect(agentAsked).toHaveLength(1)
expect(agentAsked[0]).toContain("plan: plan.md names every cut")
expect(v2.rules.plan?.why).toBe("cut 3 is missing")
expect(v2.by).toBe("agent")
})
test("file rules are deliverables", async () => {
const d = project(goal([{ id: "export", file: "out/final.txt" }]))
expect((await goalCheck({ cwd: d })).findings.map((x) => [x.check, x.says])).toEqual([["deliverables", "missing: out/final.txt"]])
@@ -28,6 +108,12 @@ test("file rules are deliverables", async () => {
expect((await goalCheck({ cwd: d })).passed).toBe(true)
})
test("the verdict is the last JSON with rules", () => {
const t = 'the shape is {"rules": {"ID": ...}} so: {"x": 1} then {"rules": {"a": {"pass": true, "why": "seen"}}}'
expect(lastVerdict(t)?.rules.a?.pass).toBe(true)
expect(lastVerdict("no json here")).toBeNull()
})
test("a check runs only at its moments", async () => {
const d = project(goal([{ id: "bad", run: "exit 1" }]))
// run rules hold at done, not at an edit
@@ -35,9 +121,49 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
})
test("a `says` rule is said to be unchecked: nothing judges the work (docs/check.feature CK4)", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
const r = await goalCheck({ cwd: d })
expect(r.plan.some((p) => p.includes("rules.friendly") && p.includes("isn't checked"))).toBe(true)
expect(r.checks).not.toContain("says")
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
const asked: string[] = []
const rules = await clefVerdict(g, d, (_dir, file, says, from, to) => {
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
})
expect(asked.sort()).toEqual(["out/cuts/a_9x16.mp4 - 1", "out/cuts/a_9x16.mp4 0-3 1", "out/cuts/b_9x16.mp4 - 1"])
expect(rules.named?.pass).toBe(true)
expect(rules.all?.pass).toBe(false)
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect((await 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)
})
test("clef hears several cuts at once, and the critic reads while it does", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-at-once-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const names = ["a", "b", "c", "d", "e", "f", "g", "h"]
for (const n of names) writeFileSync(path.join(d, `out/cuts/${n}_9x16.mp4`), "x")
const g = { name: "rules", rules: [{ id: "seen", says: "No caption covers a face" }] } as never
let now = 0, most = 0
const rules = await clefVerdict(g, d, async (_dir, _file, says) => {
most = Math.max(most, ++now)
await new Promise((ok) => setTimeout(ok, 20))
now--
return says.map(() => ({ choice: "true", says: "fine" }))
})
expect(most).toBe(6)
expect(rules.seen?.pass).toBe(true)
})
+40
View File
@@ -0,0 +1,40 @@
// The seen pack's two looks (12-01): what happens, on the contact sheet, and how it looks, on frames at full size.
import { expect, test } from "bun:test"
import { existsSync, readFileSync, writeFileSync } from "node:fs"
import { LOOKS, looks, looksFresh, stem } from "../src/media.ts"
import { SECOND, second, unjudged } from "../src/packs/look.ts"
import { CLIP, project, put, touch } from "./project.ts"
test("a video's frames at full size are made beside it, and again only after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
touch(f, -60)
expect(looksFresh(f)).toBe(false)
const made = looks(f)
expect(made.length).toBe(LOOKS)
expect(made.every((p) => existsSync(p) && p.startsWith(`${stem(f)}.looks`))).toBe(true)
expect(looksFresh(f)).toBe(true)
writeFileSync(f, readFileSync(CLIP))
touch(f, 60)
expect(looksFresh(f)).toBe(false)
})
test("a look at the sheet alone doesn't pass: the design is judged at full size, in its own words", () => {
expect(unjudged({})).toBe(true)
expect(unjudged({ look: "looks good" })).toBe(true)
expect(unjudged({ look: "Captions are 72 px bold with the spoken word in yellow, as the reference's; the offer is one pill, not three boxes." })).toBe(false)
})
test("the second opinion is asked once for a file as it is, the faults it found first, and again after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
let asked = 0
const ask = () => (asked++, SECOND.map((_, i) => ({ choice: i === 3 ? "yes" : "no", says: i === 3 ? "yes (0.81)" : "no (0.9)" })))
const says = second(f, ask)!
expect(says.split("\n")[0]).toBe(` FOUND (yes (0.81)): ${SECOND[3]}`)
expect(says.split("\n")[1]).toStartWith(" clear")
expect(second(f, ask)).toBe(says)
expect(asked).toBe(1)
touch(f, 60)
second(f, ask)
expect(asked).toBe(2)
expect(second(put(project({}), "out/a_b_c_v1_9x16.mp4", readFileSync(CLIP)), () => [])).toBeNull()
})
+10 -1
View File
@@ -5,7 +5,8 @@ import { spawnSync } from "node:child_process"
import { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import type { CutBeat as Beat } from "raea/brief.gen"
import type { Beat } from "raea/brief.gen"
import { saysOf } from "../src/contract.ts"
import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts"
const W = 96
@@ -73,3 +74,11 @@ test("a beat's shots average within a third of its asl; build shortens and relea
expect(flat[0]).toMatchObject({ kind: "tempo" })
expect(tau([3, 2, 1])).toBe(-1)
})
test("a cut goal's beats are rules a fresh critic judges on the cut in sequence", () => {
const said = saysOf({ kind: "cut", cut: { brief: "b.txt", formats: ["9:16"], cuts: [{ id: "a1", beats: [{ at: 0, feel: "the itch of a chore", story: "the app reminds you" }, { at: 4, feel: "relief" }] }] } } as never)
expect(said.map((r) => r.id)).toEqual(["beat_a1_1", "beat_a1_2"])
expect(said[0].says).toContain("out/cuts/a1_9x16.mp4, from 0 s to 4 s")
expect(said[0].says).toContain("in sequence")
expect(said[1].says).toContain("to its end")
})
-31
View File
@@ -1,31 +0,0 @@
import { test, expect } from "bun:test"
import { asDigits, digitsIn, numbersOf } from "../src/packs/numbers.ts"
test("numbers said in words read as digits (12-05, Dutch run 9: \"twenty four seven\" captioned \"24-7\")", () => {
expect(numbersOf(["twenty", "four", "seven"])).toEqual(["24", "7"])
expect(numbersOf(["one", "hundred", "forty", "nine"])).toEqual(["149"])
expect(numbersOf(["one", "thousand"])).toEqual(["1000"])
expect(numbersOf(["nineteen"])).toEqual(["19"])
const w = (text: string, start: number) => ({ text, start, end: start + 0.2 })
const got = asDigits([w("it's", 0), w("twenty", 1), w("four", 1.2), w("seven", 1.4), w("virtual", 2)])
expect(got.map((x) => x.text)).toEqual(["it's", "24 7", "virtual"])
expect(got[1].end).toBeCloseTo(1.6)
expect(asDigits([w("a", 0), w("hundred", 0.2), w("and", 0.4), w("forty-nine", 0.6), w("bucks.", 1)]).map((x) => x.text)).toEqual(["149", "bucks."])
expect(asDigits([w("I", 0), w("want", 0.2), w("a", 0.4), w("dog", 0.6)]).map((x) => x.text)).toEqual(["I", "want", "a", "dog"])
expect(asDigits([w("One", 0), w("more", 0.2)]).map((x) => x.text)).toEqual(["1", "more"])
})
test("a caption in words and one in digits both match what's heard", async () => {
const { digitsIn } = await import("../src/packs/numbers.ts")
const { letters } = await import("../src/packs/captions.ts")
const heard = (await import("../src/packs/numbers.ts")).asDigits([{ text: "One", start: 0, end: 0.2 }, { text: "more", start: 0.2, end: 0.4 }]).map((w) => letters(w.text)).join("")
expect(letters(digitsIn("One more"))).toBe(heard)
expect(letters(digitsIn("it's 24-7"))).toBe(letters(digitsIn("it's twenty-four seven")))
})
test("dollars written as $ match dollars said (12-05, Dutch run 10)", () => {
expect(digitsIn("for sixty dollars off")).toBe("for 60 dollars off")
expect(digitsIn("for $60 off")).toBe("for 60 dollars off")
const w = (t: string, i: number) => ({ text: t, start: i, end: i + 1 })
expect(asDigits(["for", "$60", "off"].map(w)).map((x) => x.text)).toEqual(["for", "60 dollars", "off"])
})
+2 -3
View File
@@ -20,12 +20,11 @@ test("the place pack's model", async () => {
// c: a woman sitting with her dog; the caption on the dog, the hook over the crowd behind her
const c = textOver(man([t("$1,000 for one vet visit?", 116, 236, 848, 112), t("He hurt his little", 290, 1335, 630, 90)]), [sc.c], 1)
assert.equal(c.length, 1, JSON.stringify(c))
// a face or a sign is an error (Shane's rule list, 12-05); the dog, a warning that names the clear place
assert.equal(c[0].level, "warn")
assert.equal(c[0].level, "error")
assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`)
ok("a caption over the dog is a warning, moved to the clear ground under it; the hook over passers-by is fine")
ok("a caption over the dog is an error, moved to the clear ground under it; the hook over passers-by is fine")
// a: a checklist on a woman's lap, a sign under her, a man standing behind: no clear place for a block that size
const a = textOver(man([t("✓ 24/7 virtual vet care", 256, 1044, 568, 80), t("✓ Price-matched Rx", 280, 1130, 520, 76), t("✓ Free delivery", 336, 1214, 410, 76)]), [sc.a], 1)
-21
View File
@@ -33,24 +33,3 @@ test("a frame full of lines (a shelf of labels) is left out, and words said as t
const heard = "so good I want to eat it".split(" ").map((t, i) => ({ text: t, start: 0.2 + i * 0.3, end: 0.45 + i * 0.3 }))
expect(blocksOf(frames(4, (t) => (t < 0.5 ? [line(300, "SO GOOD I WANT TO EAT IT")] : [])), 2, none, heard)).toEqual([])
})
test("a render's manifest is read as the texts it drew: a three-line card's size is a line's, and its time is exact", async () => {
const { readingFrames } = await import("../src/packs/reading.ts")
const card = { text: "How does your group do Secret Santa this year? Names in a hat or chaos", ink: [60, 300, 900, 288], opacity: 1, lines: 3 }
const frames = Array.from({ length: 60 }, (_, i) => ({ frame: i, text: [{ ...card, opacity: i < 30 ? 1 : 0.1 }] }))
const own = readingFrames({ fps: 30, height: 1920, frames })!
expect(own.rate).toBe(5)
expect(own.frames[0].lines[0][3]).toBe(96)
// up exactly a second (frames 0-29), gone once it fades below 0.2: 15 words in a second is an error
const blocks = blocksOf(own.frames, own.rate, none)
expect(blocks.length).toBe(1)
expect(blocks[0].to - blocks[0].from).toBeCloseTo(1, 5)
expect(reading(blocks)[0].level).toBe("error")
// fine print a line 24 px tall is texture: a warning that asks
const fine = { text: "Terms apply. See site for details on the offer and its dates", ink: [60, 1800, 600, 24], opacity: 1, lines: 1 }
const small = readingFrames({ fps: 30, height: 1920, frames: Array.from({ length: 60 }, (_, i) => ({ frame: i, text: i < 15 ? [fine] : [] })) })!
const f = reading(blocksOf(small.frames, small.rate, none))
expect(f.length).toBe(1)
expect(f[0].level).toBe("warn")
expect(f[0].says).toContain("texture")
})
+1 -30
View File
@@ -2,7 +2,7 @@ import { test } from "bun:test"
import assert from "node:assert/strict"
import type { Clip } from "../src/facts.ts"
import type { Levels } from "../src/media.ts"
import { balance, busOf, editPoints, joined, nearestGap, soundOf, type Heard } from "../src/packs/sound.ts"
import { balance, busOf, editPoints, nearestGap, soundOf, type Heard } from "../src/packs/sound.ts"
test("the sound pack's measures", async () => {
// the sound pack's measures, on made-up takes
@@ -38,15 +38,8 @@ test("the sound pack's measures", async () => {
const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/)
assert.equal(onSound[0].level, "error")
ok("an in point on a word's first sound is an error")
// a loud sound 3 s from any word (a laugh, a door): a cut on it is no word cut, a warning for the ear (12-05, run 12)
const noisy: number[] = db.map((x, i) => (i >= 340 && i < 360 ? -22 : x))
const away = editPoints(clip(3.45, 0.4), fps, [{ text: "very", start: 0.1, end: 0.3 }], { start: 0, db: noisy })
assert.ok(away.length >= 1 && away.every((x) => x.level === "warn"), JSON.stringify(away))
ok("a cut on a sound far from any word is a warning, not a word cut")
// "loud" and "next" run together with no pause: a cut on their boundary is tight (a warning), not a cut word
const run = [{ text: "say", start: 1.0, end: 1.4 }, { text: "so", start: 1.42, end: 1.7 }, { text: "then", start: 1.72, end: 2.0 }]
const runDb: number[] = []
@@ -104,25 +97,3 @@ test("a voice clip, or a take named only by a farm cache's hash, that isn't here
assert.deepEqual(findings.map((x) => [x.level, x.at]), [["error", 0], ["warn", 0], ["error", 1]])
assert.match(findings[0].says, /^a take named only by its hash isn't on this machine/)
})
test("a word timed longer than a word runs is no word to cut in two (12-04, Elfster run 5: \"secret\" over 23.7 s)", () => {
const words = [{ text: "secret", start: 1.0, end: 24.7 }]
const db: number[] = []
for (let t = 0; t < 30; t += 0.01) db.push(-50)
const take: Levels = { start: 0, db }
const clip: Clip = { key: "n1", from: 150, to: 300, src: "/w/work/media/raw/take.mov", at: 5, gainDb: 0, bus: "voice" }
// a cut 4 s into the stretch, on quiet: nothing to say about a word
assert.equal(editPoints(clip, 30, words, take).filter((f) => f.kind === "edit-in-word").length, 0)
})
test("a take that plays straight on across two clips is one clip: its seam is no edit point", () => {
const take = "/w/footage/Acme_Interview.mp4"
const a: Clip = { from: 76, to: 96, src: take, at: 53.7, gainDb: 5.5 }
const b: Clip = { from: 96, to: 183, src: take, at: 54.3667, gainDb: 5.5 }
assert.deepEqual(joined([b, a], 30), [{ ...a, to: 183, fadeOut: undefined }])
// a real cut: the take jumps, or the level changes, or the two meet in a fade
assert.equal(joined([a, { ...b, at: 92.9 }], 30).length, 2)
assert.equal(joined([a, { ...b, gainDb: -1 }], 30).length, 2)
assert.equal(joined([{ ...a, fadeOut: 0.2 }, b], 30).length, 2)
assert.equal(joined([a, { ...b, src: "/w/footage/Other.mp4" }], 30).length, 2)
})
+13 -1
View File
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
import { readFileSync, writeFileSync } from "node:fs"
import path from "node:path"
import { applyTasks, putTasks, tasksOf } from "../src/tasks.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
test("tasks come from the brief's run, and an edit lands in the module that writes the task", async () => {
@@ -41,3 +41,15 @@ test("--put writes the whole plan back only while the brief's is still the base
expect(r).toMatchObject({ put: true, written: ["brief.ts"] })
expect(readFileSync(path.join(d, "brief.ts"), "utf8")).toContain('keyword: "DONE"')
})
test("a raea file the brief never reaches is said at every moment, an error once it's handed over", async () => {
const d = project({ kind: "rules", aim: "x", rules: [], compositions: ["compositions/hero.tsx"] })
put(d, "compositions/hero.tsx", `import { Box } from "raea"\nimport { Logo } from "../components/logo.tsx"\nexport default () => null\n`)
put(d, "components/logo.tsx", `import { Text } from "raea"\nexport const Logo = () => null\n`)
put(d, "compositions/old-test.tsx", `import { Box } from "raea"\nexport default () => null\n`)
put(d, "tools/notes.ts", `// import { x } from "raea/brief" is only a comment\nexport const n = 1\n`)
const edit = await goalCheck({ cwd: d, at: "edit" })
expect(edit.findings.filter((x) => x.check === "registered").map((x) => [x.level, x.file])).toEqual([["warn", "compositions/old-test.tsx"]])
const done = await goalCheck({ cwd: d, at: "done" })
expect(done.findings.filter((x) => x.check === "registered").map((x) => [x.level, x.file])).toEqual([["error", "compositions/old-test.tsx"]])
})
-15
View File
@@ -1,15 +0,0 @@
import { test, expect } from "bun:test"
import { quote, wellFormed } from "../src/text.ts"
import { collapse } from "../src/run.ts"
test("a quote never splits an emoji, and a half character is replaced (12-05, Dutch run 9)", () => {
const s = "Asking NYC dogs what they really think 🐶🐶 about it"
const q = quote(s, 40)
expect(q).toBe("Asking NYC dogs what they really think 🐶...")
expect(wellFormed(q)).toBe(q)
const half = s.slice(0, 40) // the first half of 🐶
expect(wellFormed(half).endsWith("�")).toBe(true)
expect(new TextDecoder().decode(new TextEncoder().encode(wellFormed(half)))).toBe(wellFormed(half))
expect(quote("short", 40)).toBe("short")
expect(collapse([{ goal: null, check: "place", file: "a.mp4", level: "error", says: half, seconds: [1, 2], fix: null, by: "raea" }] as never)).toHaveLength(1)
})
+1 -1
View File
@@ -112,7 +112,7 @@ names. A note with three asks is three moves, not one:
- **extract:** a brand kit read from finished work;
- **generate:** variants of one element to pick from;
- **polish:** close out the latest critique;
- **critique:** when the person asks "is it good?": an honest look at the piece as it rendered.
- **critique:** judge the piece honestly before you call it done.
Each move has a short guide: `raea guide quieter` (and the rest). Read the one an ask calls for before you act on
it. Never show these words to the person. Answer the note in their terms.
+5 -4
View File
@@ -3,7 +3,7 @@
A kit is a set of objects that belong together (a 1970s flight desk's phone, clock, ashtray and lamp) and land as
components any project can import. It holds together because every reference comes from the same style images and
paragraph, every model is picked on clay from two generators, and the whole set is checked on one sheet before
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea check` holds you to it
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea goal check` holds you to it
and the Stop hook won't let you end before it says done.
## What to do
@@ -31,9 +31,10 @@ and the Stop hook won't let you end before it says done.
project's `components/KIT/`): one component per object (`RotaryPhone.tsx`, importing its model and LOD from
beside it, `lod` for when it's small on screen), `lineup.tsx` (every piece at its real size beside a 1 m bar),
`cover.png`, `thumbs/` and `kit.json`. Import it as `@shared/components/KIT/RotaryPhone`.
7. **Review.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, and look at every tile yourself:
the pieces belong together, match their references and the brief, hold their form in clay, and stand at their real
size. Fix every ERROR the render's check names; keep a list of what you'd still change.
7. **Review and judge.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, then
`raea judge review/rN --kind kit --brief brief.ts --json`. The kit rubric: cohesion, reference
fidelity, the brief, mesh (clay), texture, assembly (clay), scale (clay), labels. Fix its blocking defects or
answer them in NOTES.md, and keep going until `raea goal check` passes.
Cost: a six-piece kit is about $8-10 (references about $0.25 each, Tripo H3.1 and Meshy about $0.60-0.80 each).
`--dry` on refs and gen says the price first; ask before going over $10.
+86 -27
View File
@@ -1,25 +1,28 @@
# Scene prompts: the brief and the builder
# Scene prompts: the brief, the builder and the judge
There are two texts to copy and fill: a brief template and a builder prompt. `bevy/scenes` says why each step
exists. This page gives the words.
There are three texts to copy and fill: a brief template, a builder prompt and a judge prompt for a fresh context.
`bevy/scenes` says why each step exists. This page gives the words.
You are the builder. What the scene must hold is checked by raea as each render ends: a part floating, sinking or
passing through another, a part out of place or under its planned detail, light that jumps or boils. Those are
faults, each with its fix (`raea check`). How it should look is the brief's, the target's and this page's, read while
you build; nothing grades it after (raea docs/check.feature).
Who plays which role: you are the builder; `raea judge` is the judge, a fresh session every round that raea starts
for you (the agent this project runs on where the raea app or raea cloud started it, else clef-omni for the numbers).
You never pick it.
The judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
the pass, and the builder never sees the pass line. A figure the builder can read becomes a target to game.
Where these texts come from: the published Blender + Claude workflows.
- dream-loop: the target is a real in-engine screenshot; a per-category rubric; defects named precisely.
- Muska and KOBATAKA: plan before code; route each object.
- ProfRino and AnyScene: placement is measured; pass is decided in code.
- hayashimon: coarse to fine; one shared wear recipe.
- kiln and prasenx: fixed clay and colour cameras, the same every round.
- kiln and prasenx: fixed clay and colour cameras; a fresh judge each round; stop after two clean reads.
## What to do
1. Write the brief from the template (section 1). Write a `NAME.parts.ts` for every hero object.
2. Start the builder with the builder prompt (section 2), filled from the brief.
3. After every stage and every fix, run step R: the review sheets, looked at by you, and the render's own check.
3. After every stage and every fix, run step R: the review sheets, then the judge prompt (section 3) in a new context
and `raea judge` on the same sheets.
## 1. The brief template
@@ -40,8 +43,8 @@ export default brief({
references: [
// the TARGET: a real in-engine screenshot of this scene from the hero camera
{ /* media/ref/target.png, role: target */ },
// real photos, to compare against; they never ship
{ /* media/ref/real-*.jpg, role: compare-only */ },
// real photos, for the judge only; they never ship
{ /* media/ref/real-*.jpg, role: judge-only */ },
],
notDoing: [
// the do-not-add list: without it the builder adds rain, neon and UI
@@ -57,7 +60,7 @@ export default brief({
{ heading: "Wear", text: "[one recipe for every surface: dust on tops, dirt in gaps and at the floor line, worn edges]" },
{ heading: "Printed matter", text: "[every sign, label and screen: exact text, fictional names, size, age]" },
{ heading: "Motion", text: "[added last, small: one dryer turning, irregular flicker, a slow push-in]" },
{ heading: "Budget", text: "[gen cents cap; review rounds cap (4)]" },
{ heading: "Budget", text: "[gen cents cap; judge rounds cap (8)]" },
],
});
```
@@ -68,8 +71,8 @@ Each generated object needs a reference picture made from this template:
> light, plain pale grey seamless background, the whole object in frame with margin, three-quarter view from slightly
> above, sharp focus, no people, no text, no brand names, no logos.
Each hero object gets its parts (NAME.parts.ts). Its fields are the frozen contract that `raea make solid info --expect` and the render's check hold it
to:
Each hero object gets its parts (NAME.parts.ts). Its fields are the frozen contract that `raea make solid info --expect` and the judge check
against:
```ts
import { parts } from "raea/brief";
@@ -140,34 +143,90 @@ STEP R: REVIEW (after every stage, and after every fix)
the same cameras every round.
- Open both sheets and look at every tile yourself. Write your own list. "Looks good" is not a review. Name each
problem precisely ("the dryer doors are flat grey discs", not "the dryers look off"), with its tile and its fix.
- Read the render's check (`raea render` prints it as it ends; `raea check out/scene.mp4` reads it back): fix every
ERROR. A warning is a note for the person. Change one material per round; every fix is code in the scene.
- Run `raea judge review/r<n>`. It's a new session that sees only the sheets, the brief's words, the target, the real
photos, this round's sheets, and last round's sheets and verdict: never your code, your log or your list. Who reads
them is raea's to settle, not yours.
- Fix every blocking defect named, or write in review/log.md why it is wrong and what you checked. A judge can be
wrong: a shadow read as a hole. Change one material per round. Every fix is code in the scene.
- Re-run the stage's checks after every fix. A fix that breaks a check is not done.
STOPPING
- Done: the render's check has no ERROR, and your own list for the round names nothing blocking.
- Stall: the same problem on your list twice. Stop tweaking and change the approach for that part: another route
(solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved camera. A defect that comes back after two
fixes is the method's fault, not the dose's.
- Cap: 4 review rounds per scene. At the cap, deliver and list what is still wrong.
STOPPING (the loop decides, not you)
- Done: `raea judge` prints "done" (two passes in a row), and the last fresh judge named no blocking defect.
- Stall: the score hasn't risen a full point in 2 rounds, or the same defect is named twice. Stop tweaking and change
the approach for that part: another route (solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved
camera. A defect that comes back after two fixes is the method's fault, not the dose's.
- Stalled: the big change didn't move it. Stop and show Shane the latest sheets and the open defects.
- Cap: 8 judge rounds per scene. At the cap, deliver and list what is still wrong.
RULES
- One builder at a time on coupled systems (light, exposure, materials). Generation may run in parallel.
- Never trust a command just because it ran: back every claim with an image or a check's output.
- A Blender fix counts only once it is a saved script that re-runs from the source; the live MCP is for looking.
- Never edit the plans or the review cameras to pass.
- Never edit the judge prompt, the plans or the review cameras to pass.
- Quote every paid step first, and never spend past the brief's cap.
- Keep review/NOTES.md: one line per thing that cost time.
```
## 3. The judge prompt (a new context every round)
It takes only images and the brief's words, and answers JSON. The pass threshold is not in it.
```text
You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built
and you never will. Judge what is in the pixels; do not guess at intentions.
PART 1, BLIND (answer before reading the brief below):
hero-colour.png is one frame. In one sentence: what place is this, what time, what era? List five objects you can
name. Is it a photograph or a render, and which three tells decided it?
PART 2, SCORED. The brief: "<brief.ts look + logline + notDoing>". The target picture is TARGET.png. Real photos of
this kind of place: REAL_*.jpg. This round's sheets: colour.png and clay.png, tiles hero, front, right, top, iso, low.
The previous round's sheets and verdict, if any: PREV_*.png, PREV.json.
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from
the reference). Halves are allowed.
- composition: camera, framing, layout, and the position and scale of every major object, against the target and the
brief's space.
- form, judged on CLAY: silhouettes read at a glance; parts have real thickness; nothing blobby, melted or a
primitive standing in for a thing; repeated things vary.
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the
low tile shows the feet.
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.
- light: motivated by the place's own sources; exposure and contrast match the target.
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads; nothing from the
do-not-add list.
- world: the same place as the target and the real photos; nothing off-era, no real brands, nothing invented
beyond the brief.
Then list EVERY defect, most damaging first, each as:
{tile, where in the tile, what is wrong, what the real thing would look like, the fix, blocking|detail}
"Blocking" means someone using this scene would notice it in the views it will be seen in. Name exactly what gives
the scene away: not "the dryer looks fake" but "the dryer door is a flat disc with no rim or glass depth; a real
door has a 3 cm chrome ring and domed glass". If a part must be rebuilt another way, say so. If a previous verdict is
given, stay consistent with it, but don't feel bound to match it or to raise the score; a regression scores lower.
Where the target and the real photos disagree on physics (scale, light falloff, contact), the real photos win.
Answer only this JSON:
{"blind": {"place": "", "objects": [], "photo": "yes|no", "tells": []},
"scores": {"composition": 0, "form": 0, "assembly": 0, "materials": 0, "light": 0, "detail": 0, "world": 0},
"defects": [{"tile": "", "where": "", "wrong": "", "real": "", "fix": "", "level": "blocking|detail"}],
"show_as_is": "one line: would you show this to the person as is, and why"}
```
The loop's rules live in code (`raea judge`), out of the builder's sight:
- A round passes when there is no blocking defect, the lowest score is at least 6 and the mean is at least 7.
- The scene is done after two passes in a row.
- The blind read is reported, not gated, until it is calibrated. Track how often the judge calls our render a photo.
## Why
- A picture first and a do-not-add list keep the builder from inventing a scene nobody asked for.
- Faults are measured by raea as each render ends, the same way every time, so a fix is known to have worked.
- The same cameras every round, in colour and clay, show what changed and hide nothing.
- A judge that has seen the code forgives what it knows was meant. One that sees only pixels judges what a viewer will.
- Numbers and named defects, with the pass decided in code, stop "looks great" from ending a loop early.
## Common mistakes
- Giving the judge the builder's notes, or the pass line. Its scores then drift toward what the builder hoped.
- Skipping the clay sheet. Materials hide broken form and floating parts; clay shows them.
- Fixing three things in one round. When it changes, you can't tell which fix did it.
- Calling the scene done with an ERROR in its render's check.
- Fixing three things in one round. When the score moves, you can't tell which fix did it.
- Calling the scene done on the builder's own reading. Done is two judge passes in a row.
+42 -23
View File
@@ -1,24 +1,25 @@
# Whole scenes: brief, build, review
# Whole scenes: brief, build, review, judge
A believable scene is planned before it is modelled, built big to small with a measured check after every step, and
reviewed from the same fixed cameras every round, and checked once by `raea check` as each render ends. This is the loop the people
reviewed from the same fixed cameras every round by a judge that has never seen the code. This is the loop the people
who make striking Blender scenes with an agent use (the 11-06 research: dream-loop, AnyScene, kiln, prasenx,
hayashimon, KOBATAKA), each step on a raea verb.
## What to do
The brief template and the builder prompt to paste are in `bevy/prompts`. A kit of props is
The brief template, the builder prompt and the judge prompt to paste are in `bevy/prompts`. A kit of props is
`bevy/kits`; shooting a finished set is `bevy/shots`.
### 0. The job: `make` on brief.ts, held by `raea check`
### 0. The job: `make` on brief.ts, held by `raea goal check`
- Put the job on the brief: `goal: scene({ references, style, dials, objects })` from `raea/brief`. Each object has
one size (`h`, `dims` or `max`), a `route`, `source: "reference" | "invented"` and, in a scene, `at` and `rot`
(metres from the floor's front-left corner; rot 0 faces the entrance). Dials you don't set are read from the
reference, so set only the ones the person asked for (`source: "customer"`).
- `raea check` decides in code whether you're done: the deliverables on disk, and no ERROR in their renders' checks.
The Stop hook reads it at the end of a turn (`--at done`) and holds you once for what's still failing. Each
finding says what to change; review/goal.json holds them all.
- `raea goal check` decides in code whether you're done: the deliverables on disk, the record of renders, the judge's
rounds, the make questions, NOTES.md. The Stop hook runs it at the end of every turn (`--at done`), and you can't
stop while it fails (the loop gives way at the 8-round cap, on a stall, or when the same thing is failing three
turns running). Each finding says what to change; review/goal.json holds them all.
- `raea make blockout` is the stop before anything costs money: `review/plan/floor-plan.png` (every footprint, invented
ones dashed), a grey-box blockout seen from the entrance with its review sheets, and `comparison.png` beside the
reference. Show it, fix positions and sizes, and only then generate.
@@ -29,7 +30,7 @@ The brief template and the builder prompt to paste are in `bevy/prompts`. A kit
`<Entity transform lod={4}>` plans everything inside it. Every render then says `lod-closer` when a shot shows a
part finer than planned (a camera move added later, a box you meant to replace and forgot), and
`raea scene lod EDIT.tsx` lists every part's plan beside the largest the frames show it, the unplanned ones too.
Two levels finer is an error; one holds `raea check` until you build it up and replan it, keep the camera
Two levels finer is an error; one holds `raea goal check` until you build it up and replan it, keep the camera
off it, or answer it in NOTES.md on a line with `lod` and its name.
- NOTES.md beside the brief ends with `## What the skill got wrong`: what the guides or tools led you into. The notes
pack checks it's there once the work is.
@@ -52,7 +53,7 @@ The brief template and the builder prompt to paste are in `bevy/prompts`. A kit
- Wear.
- Printed matter.
- Motion.
- Budget: generation cents and review rounds.
- Budget: generation cents and judge rounds.
- Each hero object gets a `NAME.parts.ts` (`parts()`) with its concept (what, style, size, seenFrom, material) and parts, each
with a role, a level (primary, secondary, tertiary), a parent, a count and `near` detail. Below it, add a connection
map with one line per joint: `door <-> cabinet hinge side touches`.
@@ -124,10 +125,10 @@ and its materials as jobs (`<Mat job="steel" />`), so a note can name it and the
6. **Motion, last and small.** First `raea scene stage EDIT.tsx`: it steps every frame without drawing and holds it
to the checks the render fails on (3D words too small or turned too far to read, a part that snaps, a camera that
lurches or goes in and back out, frames with almost nothing on screen). A sign nobody is meant to read takes
`read={false}`. Then `raea render EDIT.tsx -o out/scene.mp4`: it checks its export as it ends (`raea check`).
`read={false}`. Then `raea render EDIT.tsx -o out/scene.mp4` and `raea check out/scene.mp4`.
- Once things move, check how they move. Render with `--layers`, and render `--aov -o out/scene.aov` beside it for
depth. Then run `raea fingerprint things out/scene.mp4 --json > things.json` and
`raea floor out/scene.mp4 --things things.json`. It finds a thing floating or passing through another, the
`raea check out/scene.mp4 --things things.json`. It finds a thing floating or passing through another, the
camera lurching mid-move, and an empty frame.
### R. Review after every stage and every fix
@@ -141,29 +142,47 @@ and its materials as jobs (`<Mat job="steel" />`), so a note can name it and the
`--clay` alone renders any frame in clay.
- Open the sheets and look at every tile yourself. "Looks good" is not a review. Name each problem with its tile and
its fix, for example "the dryer doors are flat grey discs".
- Read the render's check and fix every ERROR in it. A warning is a note for the person.
- Hand the sheets to the judge (below). Fix every blocking defect it names, or write down why it is wrong and what
you checked.
- Change one thing per material per round. Re-run the stage's checks after every fix.
### The checks
### The judge, and the gates
Only measured faults hold the work (raea docs/check.feature), and each says its fix: `raea scene lint` (floats and
sinks at the feet, clips with the move that clears them, faces z-fighting in one plane), `raea gen check` on every
generated model, `raea scene stage --clearance 0.45` on a moving camera, the render's own end checks (a part out of
place or under its planned detail, light that jumps or boils), and the deliverables' counts. How it should look is
this guide's, the brief's and the target's, read while you build: nothing grades it after.
Three tiers, each gating once it has earned it (`raea goal check` lists them):
1. **Measured checks always gate:** `raea scene lint` (floats and sinks at the feet, clips with the move that clears
them, faces z-fighting in one plane), `raea gen check` on every generated model, `raea scene stage --clearance 0.45` on
a moving camera, and the deliverables' counts.
2. **`raea ask` questions gate one at a time, once calibrated.** The make set (`raea ask SHEET --set make`, or the
command the critic pack prints) asks yes/no about one sheet: floating, intersecting, blobby, a stand-in, flat colour,
plastic, opaque glass, garbled hero text, a real brand, too dark or bright; on a reference sheet, an outlier, two
objects, a brand; on a framing sheet, a camera through a wall or a subject lost. Every answer lands in the ask
ledger, matched to the sheet's bytes, so a re-rendered sheet needs asking again. A question gates once
`raea ask calibrate` passes it (16 problem and 16 clean labels, held-out AUC 0.8); until then it's advice.
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --brief brief.ts --target
media/ref/target.png --json` scores the kind's rubric (scene: layout, props, signage, materials,
light, atmosphere, plausibility, composition; layout and props judged on clay), on a production bar: don't
nitpick, at most five fixes. It sees the sheets and the brief's words only, never the code or your log. Code
decides the pass; the thresholds aren't in the prompt. A round judged on another kind's rubric doesn't count.
Fix every blocking defect it names, or answer it in NOTES.md (its words, then what you checked). Its score gates
once `raea judge calibrate --kind scene` agrees with Shane's eye (`raea judge eye`).
### Stopping
- **Done:** every deliverable on disk, and no ERROR in its render's check (`raea check` reads them all back).
- **Stall:** the same problem on your list twice. Stop tweaking and change the approach for that part: another route
(solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera. A defect that comes back after two fixes
belongs to the method, not the dose.
- **Cap:** 4 review rounds a job. At the cap or a stall, deliver and say what's still wrong.
`raea goal check` says it; you don't decide it.
- **Done:** every deliverable on disk, every gate clear, and two fresh critic passes in a row on the latest renders.
- **Stall:** three rounds without beating the best score, or the same defect named twice. Stop tweaking and change
the approach for that part: another route (solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera.
A defect that comes back after two fixes belongs to the method, not the dose.
- **Cap:** 8 critic rounds a job. At the cap or a stall the job is delivered short: status lists what's still
missing, and the Stop hook lets you end with it said.
## Why
- Fixed cameras and a clay pass are what every strong source judges on. Colour hides bad form, and a moving camera
hides regressions.
- A judge that has seen the code grades the intent, not the pixels. A judge that knows the pass line gets gamed.
- Measured checks (lint, light, exposure, gen check) catch what eyes miss: a 3 cm float, a fridge at 4 m tall, a
frame two stops under.
+3 -2
View File
@@ -3,7 +3,7 @@
A shot list in a crew's words ("slow push on the counter, handheld, 35 mm") becomes camera paths that can't lurch,
checked on a framing sheet and for clearance before anything is rendered long. This is AnyShot's loop (MIT) on raea's
camera: `raea/camera` for the moves, `raea make framing` and `lenschart` for the sheets, `raea scene stage
--clearance` for the camera's path through the set. `raea check` holds the job; the Stop hook won't let you end
--clearance` for the camera's path through the set. `raea goal check` holds the job; the Stop hook won't let you end
before it says done.
## What to do
@@ -43,7 +43,8 @@ before it says done.
(`review/lens-SHOT.png`). Pick from it and set the shot's `lens`.
4. **Block it.** `raea make framing` renders every shot's first, middle and last frame onto `review/framing.png`,
stamped with the name and time. Look at every row: the subject in frame at the start and the end, nothing through
a wall.
a wall. Ask it (`raea ask review/framing.png --std make.framing.through_wall --std make.framing.subject_lost`) and
judge it (`raea judge review --kind shot`: framing, move, focus, clearance, continuity, grade).
5. **Clearance.** `raea scene stage SHOT.tsx --clearance 0.45` holds the camera 0.45 m (a carried camera) off every solid part on every frame
(`--clearance 0.15` for a camera on a rig). Glass, decals, volumes and parts under 5 cm are passed over.
6. **Grade.** `<Grade {...gradeLook("cinematic")} />` from `raea/post_process`: clean, cinematic, gritty or vintage,
+2 -3
View File
@@ -16,9 +16,8 @@ Before you say a piece is done, every line here is true of the last render, not
- **Text stays out of the app's buttons.** In a vertical frame with the platform unknown, keep the top 220 px, the
bottom 420, the right 140 and the left 60 clear (TikTok: top 108, bottom 320, right 120; Reels: top 210, bottom 310,
right 84; Shorts: top 120, bottom 300, right 96). A 4:5 feed frame needs top 110, bottom 170, sides 60; a 1:1 frame
top 70, bottom 120, sides 60; 16:9 top and bottom 120, sides 60. The right zone is the app's buttons, which start 45%
down the frame: above them the right edge keeps the left's 60. `<Region>` and `<Captions>` place inside these zones.
These zones are only where text can't go. Where it should go is a design choice.
top 70, bottom 120, sides 60; 16:9 top and bottom 120, sides 60. These zones are only where text can't go. Where it
should go is a design choice.
- **Nothing flashes past the limit.** No more than three flashes in any one second over a sizable part of the frame
(WCAG 2.3.1): past that, flashing can cause seizures. A strobe or a fast flicker needs slowing, shrinking or less contrast.
- **Cues land on their words.** A cut, a move or a caption tied to speech starts on the word, timed from the
+7 -5
View File
@@ -33,13 +33,15 @@ is only context, and context gets lost. Run `pdftotext -layout BRIEF.pdf media/b
- `cta`: the exact line every cut ends on;
- `open`: each [TO CONFIRM], gap or contradiction in it, as a question for the review.
Every rule carries `from`, the brief's own words for it, copied exactly. `raea check` finds each one in
Every rule carries `from`, the brief's own words for it, copied exactly. `raea goal check` finds each one in
media/brief.txt, so a rule can't be made up and a line can't be paraphrased away. Then it holds every file at
out/cuts/ID_WxH.mp4 (name each cut's id client_concept_variant_v#, so the file is client_concept_variant_v#_9x16.mp4):
its shape, size and name; what it says, heard after its last change, for each `say`, `never` and the CTA; a word
clipped or missing; a face cut by the frame's edge; text over a face, a sign or the app's buttons; captions over
talking. Every render ends with that check (`raea check CUT --at render`), kept beside the cut; the job isn't done,
and the Stop hook won't let you end, until `raea check --at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
its shape and length; what it says, heard after its last change, for each `say`, `never` and the CTA; its words
against CUT.lines.txt beside it; its edit points, line levels and effects; its faces, text sizes and text placement;
and that you looked at it since its last render: its contact sheet for what happens, and its frames at full size
(CUT.looks/) for how it looks, since a sheet's tiles are too small to judge type, captions and cards on (`raea goal
seen CUT`, then `raea goal seen CUT "..." --look "its design beside a reference, and what you changed"`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
you end, until `--at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
pack off on the contract (`packs: { place: false }`) only when the brief says so.
## The decisions
+23 -9
View File
@@ -28,7 +28,7 @@ A goal made with `cut({...})` or `rules({...})` takes these fields:
| Field | What it is |
| --- | --- |
| `aim` | what the goal is, in the person's words |
| `rules` | `{ id, run?, timeout?, file? }[]`: what must hold before you stop (below) |
| `rules` | `{ id, run? , timeout?, file?, says? }[]`: what must hold before you stop (below) |
| `cut` | a cut job's contract, the brief as rules (below) |
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
@@ -57,9 +57,11 @@ A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<for
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
one of the brief's hook types, as the brief names it.
A cut's `beats` are optional and yours, never the brief's: plan them in your own notes, not in brief.ts, unless the
brief itself sets the cut's pace. When it does, `{ at, asl?, tempo? }[]` (`asl` the beat's average shot length in
seconds, `tempo` `"build"`, `"release"` or `"hold"`) is measured by the montage check, which the brief switches on.
A cut's `beats` are decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
(longer) or `"hold"` (even). The montage check holds the cut to them.
## Rules
@@ -67,9 +69,11 @@ seconds, `tempo` `"build"`, `"release"` or `"hold"`) is measured by the montage
| --- | --- | --- |
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
Nothing else is a rule: a sentence that must be true of the work ("the wordmark is on screen at the end") is how you
build it, not something a model grades after (raea docs/check.feature). Where it can be measured, make it a `run`
rule or a `file`; otherwise leave it to the person's review.
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
is read.
## An example
@@ -90,7 +94,14 @@ export default brief({
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{ id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions" },
{
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
beats: [
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
],
},
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
],
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
@@ -105,8 +116,11 @@ export default brief({
},
],
},
rules: [
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
],
}),
})
```
Write it, then run `raea check`. It names each rule that doesn't hold and the line of the brief it came from.
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
+1 -2
View File
@@ -5,8 +5,7 @@
- Write one file (usually `edit.tsx` at the space's root) that exports the piece's component as its default and
ends with `registerRoot(Root)`. `Root` returns one `<Composition>` per output.
- Give each `<Composition>` an `id`, its `component`, `width`, `height`, `fps` and `durationInFrames`:
- `id` uses letters, digits, hyphens and underscores only (no spaces) and is unique in the root: a deliverable's
name (client_concept_variant_v1) is a good id.
- `id` uses letters, digits and hyphens only (no spaces, no underscores) and is unique in the root.
- `width`, `height` and `durationInFrames` are positive whole numbers, and `fps` is a positive number.
- `defaultProps` (optional) is a plain object of JSON values, which the component receives as its props.
- `controls` (optional) says which of those props a person may tune: see "Controls" below.
+7 -6
View File
@@ -1,14 +1,15 @@
# Rendering and checking: raea render, its one check, stills
# Rendering and checking: raea render, raea check, stills
## What to do
- **The render checks itself, once.** `raea render edit.tsx -o final.mp4 --manifest render.json` ends with `raea
check` on the export and keeps what it found as final.check.json; publishing and a stop read that, and nothing runs
it again (`raea check final.mp4` reads it back). It measures clipped text, text under a platform's buttons, text over the face, captions on too briefly to read,
- **`raea check` after every real change.** Render with the manifest, then check the export against the floor:
`raea render edit.tsx -o final.mp4 --manifest render.json` and
`raea check final.mp4 --manifest render.json --words words.json --perception perception.json [--platform tiktok]`.
It measures clipped text, text under a platform's buttons, text over the face, captions on too briefly to read,
caption contrast against the pixels behind them, frozen stretches, flashing past the limit, cues that miss their word, loudness, a sound that
stops dead or (with `--words`) fights the voice, and encoder blotching in the darks. Each finding is ranked P0 to P3
with its fix; an ERROR is a fault in the export, a warning a note for the person. Fix every ERROR in one pass
before rendering again. `raea floor final.mp4 --words words.json` measures a file raea didn't render. A finding that ends `[also in …]` was in the earlier export too: what you changed
with its fix; it exits 1 while a P0 or P1 stands, and `-o check.json` writes them for the critique. Fix every error
in one pass before rendering again. A finding that ends `[also in …]` was in the earlier export too: what you changed
didn't move it, so don't repeat that change; try another, or say why it stands. A note is for the person, not a
reason to render again. An
exception in the composition (an unclamped value going NaN, keyframes out of order, a phrase `word()` can't find, a
+4 -4
View File
@@ -46,14 +46,14 @@
6 dB under the talking that comes back up where nobody talks, so a wordless end card keeps its music. It is slight
on purpose: set the bed's own level from the table below. `bus="master"` keeps a sound out of it; your own
`Tone.buses` are never changed by it. The check is on the export: the voice at least 10 dB above what's under it
between words (the voice check, which a brief switches on).
between words (`raea goal check`'s voice check).
- Air between words reads as dead air in social cuts and ads, most of all in the first 3 seconds. `tighten(words,
{ levels })` (`import { tighten, airGaps } from "raea"`) returns the spans of a take to keep: each gap cut down to
about 0.15 s in the hook and 0.25 s after, only between words, 80 ms kept either side, and pulled back wherever the
take is still loud (a transcript often ends a word early). Run it on the source take's words (`raea words TAKE`) and
levels, never the mixed export, lay each span as its own `<Video startFrom endAt>`, and read the words pass after.
A hook opens on its first word within about 0.3 s; a board or a sign held in silence for people to read is dead
air, not a hook (the hook and airgaps checks, which a brief switches on).
air, not a hook (`raea goal check`'s hook and airgaps checks).
- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a
sound in the middle of the list can split the ones after it.
- Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of
@@ -104,8 +104,8 @@ everyone else. Two checks, both cheap:
sound loops only between `startFrom` and `endAt`, and that loop is a hard jump. Tile it instead: copies of the take
end to end, each in its own Sequence, crossfading over 1.5 s (`fadeIn`/`fadeOut`), or make the take as long as the
span.
- **Check the finished file.** Its render's check (`raea floor FILM.mp4 --words words.json` on a file raea didn't
render, with the voice's words on the film's clock) reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade it out over 100 ms or more;
- **Check the finished file.** `raea check FILM.mp4 --words words.json` (the voice's words on the film's clock)
reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade it out over 100 ms or more;
a voice ending its word isn't one), stretches with no voice louder than
the voice, music closer than 12 dB to the voice over it, and a true peak over -1 dBTP. Fix every line it prints, or
say why it stands.
+5 -4
View File
@@ -19,9 +19,9 @@ cut({ aim: "Three TikTok ads for Choreo", cut: { brief: "brief.md", formats: ["9
] } })
```
Each beat's `feel` and `story` are your plan for the cut: what you build it to do, never a rule it's graded on. `asl`
(the beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are
measured by the montage pack, when the brief switches it on (`packs: { montage: true }`).
Each beat's `feel` and `story` are rules a fresh critic judges on the cut as it plays (`raea goal judge`). `asl` (the
beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are
measured by the montage pack (`raea goal check`).
## Murch's order: what to give up first
@@ -56,4 +56,5 @@ fine to leave; say why in the cut's notes. One broken at most of a file's cuts i
1. Write each beat's `feel` and `story` first: Murch's top two carry three quarters of his weight.
2. Set each beat's pace (`asl`, `tempo`) for the build-ups and releases you want.
3. Cut on motion and match light across cuts inside a beat.
4. Fix eye trace, screen direction and tone where they don't cost a higher reason, and read the render's check.
4. Run `raea goal check`, then fix eye trace, screen direction and tone where they don't cost a higher reason.
5. Run `raea goal judge` so a fresh critic watches each beat in sequence.
+2 -3
View File
@@ -1,13 +1,12 @@
# critique
When the person asks "is it good?": look at the piece as it rendered, not as you meant it. It's no step in making the
piece: the render's own check (`raea check`) is the only check.
Judge the piece as it rendered, not as you meant it, before you call it done or when the person asks "is it good?".
## How
- Watch the export once, all the way through, at the size it ships, with sound. Then pull stills at the moments that
matter and look at them together.
- Judge it against the brief (`believe:`, `audience:`), the person's taste, the mode's guide and the floor.
- Read the render's check (OUT.check.json) for what was measured, and the rest by the rubric (`raea guide rubric`).
- Run `raea check` for what can be measured, and judge the rest by the rubric (`raea guide rubric`).
## Decide
- Judge against the brief and the mode first, and the person's taste second. Your own taste is the easy default.
+12 -24
View File
@@ -2,7 +2,7 @@
// "3D in the same tree", "Toon surfaces and ink outlines", "The camera's lens", "Motion blur", "Page layers under and
// over the 3D", "Games: state from input, frame by frame").
import { beforeEach, describe, expect, test } from "bun:test";
import { Audio, Captions, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
import { Audio, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
import { Canvas3D, Cylinder, Fisheye, LensDistortion, Model, MotionBlur, Sphere } from "../src/3d";
import { DirectionalLight, Mesh, MeshStandardMaterial, MeshToonMaterial, PointLight } from "@raea/render/three";
// the retired three.js shapes, compared against (M5: no longer exported from raea)
@@ -19,28 +19,29 @@ const near = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6
describe("Region", () => {
test("auto takes the taller band clear of the face", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
// m = 65; the app's UI zones (top 220, bottom 420, right 140 where the band reaches its buttons): top band
// 220..435, bottom band 1045..1500
// m = 65; clear of the UI zones (220 top, 420 bottom, 140 right): top band 220..435, bottom band 1045..1500
expect(got.name).toBe("auto");
expect(got.x).toBe(65); expect(got.w).toBe(1080 - 65 - 140);
expect(got.x).toBe(65); expect(got.w).toBe(875);
near(got.y, 1045); near(got.h, 455);
});
test("keepOut={false}: the older bands, 0.08 H to 0.80 H, inset by the margin alone", () => {
renderFrame(<Region keepOut={false}><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
expect(got.x).toBe(65); expect(got.w).toBe(950);
near(got.y, 1045); near(got.h, 491);
});
test("top and center by name", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 220); near(got.h, 435 - 220);
renderFrame(<Region name="center"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 0.33 * 1920); near(got.h, 0.34 * 1920);
});
test("without a face: top is the app's top zone (220 px) to 0.45 H, and auto picks it; above the buttons both sides keep the margin", () => {
test("without a face: top is the top zone's edge to 0.45 H, and auto picks it", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0 });
near(got.y, 220); near(got.h, 864 - 220);
expect(got.x).toBe(65); expect(got.w).toBe(950);
});
test("the safe area moves the edges in, never into the app's zones", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 300, bottom: 1400 } } });
near(got.y, 300); near(got.h, 564);
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 100, bottom: 1700 } } });
near(got.y, 220);
test("the safe area moves the edges", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 200, bottom: 1500 } } });
near(got.y, 200); near(got.h, 664);
});
test("no room renders nothing and says why", () => {
const big = { x: 100, y: 100, w: 880, h: 1500 };
@@ -299,16 +300,3 @@ test("an input changed far back refolds from a let-go state correctly", () => {
for (let g = 0; g < 2999; g++) s = step(s, { keys: input[g]?.keys ?? [] }, g);
expect(got).toBe(s);
});
describe("Captions", () => {
test("a cut's own words (said) caption it inside the app's zones, when the edit's words are another cut's", () => {
const said = [{ text: "So", from: 0, to: 6 }, { text: "fresh.", from: 7, to: 20 }];
const html = renderFrame(<Captions said={said} />, { ...base, frame: 3, words: [{ text: "other", from: 0, to: 30 }] });
expect(html).toContain('data-raea-role="caption"');
expect(html).toContain("So");
expect(html).not.toContain("other");
// the bottom band ends 420 px over the bottom, and its right side keeps the buttons' 140
expect(html).toContain("width:875px");
expect(html).toContain('data-band-bottom="1500"');
});
});
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more