mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ecf1b8b1e |
No files matched your search
Generated
-1
@@ -13820,7 +13820,6 @@ dependencies = [
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
|
||||
@@ -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
@@ -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\"`"));
|
||||
|
||||
@@ -213,13 +213,12 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
continue;
|
||||
}
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let color = r.middle_color();
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
|
||||
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
|
||||
let Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
|
||||
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
|
||||
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
|
||||
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
|
||||
]);
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
|
||||
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
|
||||
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
|
||||
|
||||
#[test]
|
||||
fn a_caption_is_timed_from_the_first_word_it_shows() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
|
||||
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
|
||||
|
||||
#[test]
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
|
||||
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
@@ -425,11 +425,10 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
#[test]
|
||||
fn a_moving_text_is_read_where_it_is() {
|
||||
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 };
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
|
||||
let (t, b) = run.middle(30.0);
|
||||
assert_eq!(t, 4.0);
|
||||
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
|
||||
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
|
||||
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
|
||||
}
|
||||
|
||||
@@ -43,10 +43,6 @@ pub struct Run {
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub boxes: Vec<[f64; 4]>,
|
||||
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
|
||||
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
|
||||
pub colors: Vec<String>,
|
||||
/// its colour on its last frame
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
}
|
||||
@@ -61,15 +57,6 @@ impl Run {
|
||||
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
|
||||
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
|
||||
}
|
||||
|
||||
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
|
||||
pub fn middle_color(&self) -> &str {
|
||||
let n = self.boxes.len();
|
||||
match self.colors.get(n / 2) {
|
||||
Some(c) if n > 1 && self.colors.len() == n => c,
|
||||
_ => &self.color,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
|
||||
@@ -127,21 +114,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
});
|
||||
let mut r = match found {
|
||||
Some(i) => open.remove(i),
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
|
||||
};
|
||||
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
if text.len() > r.text.len() {
|
||||
r.boxes.clear();
|
||||
r.colors.clear();
|
||||
}
|
||||
if text.len() >= r.text.len() {
|
||||
r.text = text;
|
||||
r.box_ = b;
|
||||
r.boxes.push(ink.unwrap_or(b));
|
||||
r.colors.push(color.clone());
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = color;
|
||||
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
r.size = x["size"].as_f64().unwrap_or(0.0);
|
||||
next.push(r);
|
||||
}
|
||||
@@ -192,10 +176,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 +208,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") });
|
||||
@@ -315,35 +294,3 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
|
||||
passed.push(format!("cues: {checked} texts land on their words"));
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
#[test]
|
||||
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
|
||||
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
|
||||
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs.len(), 1);
|
||||
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
|
||||
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
||||
raea-app-double = { path = "../double" }
|
||||
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
|
||||
@@ -21,13 +21,13 @@ use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||
|
||||
/// The flags each verb takes, and whether each takes a value
|
||||
pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
pub(crate) const FLAGS: [(&str, bool); 31] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
@@ -51,6 +51,7 @@ pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
("--as", true),
|
||||
("--against", true),
|
||||
("--profile", true),
|
||||
("--by", true),
|
||||
("--ask", true),
|
||||
("--tally", false),
|
||||
("--bad", false),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
|
||||
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
|
||||
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
|
||||
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
|
||||
@@ -99,9 +99,30 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
|
||||
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
|
||||
raea_io_clef::critic::ask(cwd, p)
|
||||
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||
let mut c = std::process::Command::new(by);
|
||||
match by {
|
||||
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
|
||||
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
|
||||
o => return Err(format!("--by {o}: kimi or claude")),
|
||||
};
|
||||
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
|
||||
let mut text = String::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
|
||||
match content {
|
||||
Value::String(s) => text += s,
|
||||
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
|
||||
_ => {}
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
@@ -112,12 +133,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
|
||||
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// `raea fingerprint read PROJECT`
|
||||
/// `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let run = || -> Result<String, String> {
|
||||
let w = words(args)?;
|
||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let by = "agent";
|
||||
let by = flag(args, "--by").unwrap_or("kimi");
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||
let mut notes = pinned(&project);
|
||||
@@ -127,15 +148,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||
}
|
||||
for chunk in notes.chunks_mut(40) {
|
||||
let text = ask(&project, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
|
||||
let text = ask(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
fold(chunk, &fp, &ans, by);
|
||||
eprintln!("read {} notes", chunk.len());
|
||||
}
|
||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
@@ -264,7 +285,7 @@ mod tests {
|
||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
||||
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
|
||||
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
|
||||
fold(&mut n, &fp, &ans, "agent");
|
||||
fold(&mut n, &fp, &ans, "kimi");
|
||||
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
|
||||
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
|
||||
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||
|
||||
+72
-17
@@ -1,9 +1,8 @@
|
||||
//! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 12-03: never a harness raea
|
||||
//! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
|
||||
//! cloud's box, the raea app) offers as RAEA_JUDGE_URL. Each call is a new session, run in DIR with only the sheets to
|
||||
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
|
||||
//! the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
|
||||
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
|
||||
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
|
||||
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
|
||||
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
|
||||
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
|
||||
//! its reading as the eye clef is calibrated against.
|
||||
|
||||
use std::path::Path;
|
||||
@@ -12,10 +11,7 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{BAR, scores};
|
||||
|
||||
/// Whether this session has a critic to ask: where it has, the agent judges; else clef.
|
||||
pub fn critic() -> bool {
|
||||
raea_io_clef::critic::here()
|
||||
}
|
||||
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||
|
||||
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
|
||||
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
|
||||
@@ -129,11 +125,70 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
|
||||
(out, defects, photo)
|
||||
}
|
||||
|
||||
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
|
||||
/// verdict JSON.
|
||||
pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
eprintln!("judge: a fresh session of this project's agent is reading the sheets");
|
||||
let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
|
||||
last_verdict(&text).ok_or_else(|| format!("judge: the critic gave no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
|
||||
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
|
||||
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
|
||||
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
|
||||
use std::io::BufRead as _;
|
||||
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
|
||||
let p = prompt(kind, &dir, brief, target);
|
||||
let mut cmd = match by {
|
||||
"kimi" => {
|
||||
let mut c = std::process::Command::new("kimi");
|
||||
c.args(["-p", &p, "--output-format", "stream-json"]);
|
||||
c
|
||||
}
|
||||
"claude" => {
|
||||
let mut c = std::process::Command::new("claude");
|
||||
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
|
||||
c
|
||||
}
|
||||
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
|
||||
};
|
||||
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
|
||||
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
|
||||
let mut said = Vec::new();
|
||||
let mut last = String::new();
|
||||
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
|
||||
said.extend(texts(&v));
|
||||
let step = match (v["role"].as_str(), v["type"].as_str()) {
|
||||
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
|
||||
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
|
||||
_ => continue,
|
||||
};
|
||||
if step != last {
|
||||
eprintln!("judge ({by}): {}", step.replace('\n', " "));
|
||||
last = step;
|
||||
}
|
||||
}
|
||||
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
|
||||
let text = said.join("\n");
|
||||
if !out.status.success() && last_verdict(&text).is_none() {
|
||||
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
|
||||
}
|
||||
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
|
||||
}
|
||||
|
||||
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
|
||||
/// {content: [{type: text, text}]}} and its final {type: result, result}.
|
||||
fn texts(v: &Value) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if v["role"] == "assistant"
|
||||
&& let Some(s) = v["content"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
for c in v["message"]["content"].as_array().into_iter().flatten() {
|
||||
if c["type"] == "text"
|
||||
&& let Some(s) = c["text"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
if v["type"] == "result"
|
||||
&& let Some(s) = v["result"].as_str()
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
|
||||
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
|
||||
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
|
||||
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -46,10 +46,9 @@ pub fn record(args: &[String]) -> Result<String, String> {
|
||||
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
|
||||
let kind = kind_in(&verdict);
|
||||
let cats = scores(kind);
|
||||
// the session's agent's reading as the eye (`--read`): a fresh session's scores, and its pass by the same rule in code
|
||||
if args.iter().any(|a| a == "--read") {
|
||||
let by = "agent";
|
||||
let v = crate::agent::ask(kind, &dir, &json!({}), None)?;
|
||||
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
|
||||
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
|
||||
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
|
||||
let (eye, defects, _) = crate::agent::read(kind, &v);
|
||||
if eye.len() < cats.len() {
|
||||
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
|
||||
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
|
||||
//!
|
||||
//! raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --read: the session's agent's reading as the eye)
|
||||
//! Who judges is never asked: a fresh session of the project's own agent where its host offers one (agent.rs), else
|
||||
//! clef-omni.
|
||||
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
|
||||
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
|
||||
//! raea judge calibrate [--kind scene|kit|shot] [--json]
|
||||
//!
|
||||
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
|
||||
@@ -24,6 +22,7 @@ pub fn kind_gates(kind: &str) -> bool {
|
||||
}
|
||||
pub mod rubric;
|
||||
|
||||
pub use agent::BY;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -31,7 +30,7 @@ use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_bundle::flag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
|
||||
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
|
||||
|
||||
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
|
||||
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
|
||||
@@ -108,12 +107,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let brief = brief_of(flag(args, "--brief").as_deref())?;
|
||||
let target = flag(args, "--target").map(PathBuf::from);
|
||||
let dry = args.iter().any(|a| a == "--dry");
|
||||
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
|
||||
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
|
||||
if by != "clef" {
|
||||
if dry {
|
||||
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
|
||||
}
|
||||
let v = agent::ask(kind, &dir, &brief, target.as_deref())?;
|
||||
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
|
||||
let (scores, defects, photo) = agent::read(kind, &v);
|
||||
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
|
||||
}
|
||||
@@ -191,7 +190,7 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
|
||||
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
|
||||
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
|
||||
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
|
||||
let found = findings(&defects, by, advice);
|
||||
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
|
||||
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
|
||||
|
||||
@@ -70,10 +70,10 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
|
||||
assert!(!pass && why[0].starts_with("blocking"));
|
||||
assert!(crate::agent::last_verdict("no json here").is_none());
|
||||
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
|
||||
let f = &crate::findings(&defects, "agent", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (agent)"));
|
||||
let f = &crate::findings(&defects, "kimi", false)[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
|
||||
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
|
||||
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
|
||||
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -60,7 +60,7 @@ enum Sounds {
|
||||
/// What a page carries beside the game and the host, as the lint found the game needs it
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
struct Carry {
|
||||
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
|
||||
/// three.js, for a game with a 3D kind (PA15)
|
||||
with_3d: bool,
|
||||
sounds: Sounds,
|
||||
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
|
||||
@@ -68,15 +68,15 @@ struct Carry {
|
||||
}
|
||||
|
||||
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
|
||||
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
|
||||
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
|
||||
/// already Bevy's), the game, then the host started with three.js as its 3D drawer only for a game with 3D (PA15: a
|
||||
/// 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
|
||||
/// raea/tone graph (PA6)
|
||||
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
|
||||
let Carry { with_3d, sounds, ecs } = carry;
|
||||
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
|
||||
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
|
||||
if with_3d {
|
||||
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
|
||||
e.push_str(&format!("import {{ three3d }} from {:?};\n", spec(&host.join("three.ts"))));
|
||||
}
|
||||
if sounds != Sounds::None {
|
||||
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
|
||||
@@ -84,9 +84,9 @@ fn entry(game: &Path, host: &Path, carry: Carry) -> String {
|
||||
if sounds == Sounds::Tone {
|
||||
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
|
||||
}
|
||||
let d3 = if with_3d { "bevy3d" } else { "undefined" };
|
||||
let d3 = if with_3d { "three3d" } else { "undefined" };
|
||||
e.push_str(&match sounds {
|
||||
Sounds::None if with_3d => "start(bevy3d);\n".into(),
|
||||
Sounds::None if with_3d => "start(three3d);\n".into(),
|
||||
Sounds::None => "start();\n".into(),
|
||||
Sounds::Media => format!("start({d3}, sound());\n"),
|
||||
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
|
||||
@@ -217,7 +217,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_3d_game_starts_with_three() {
|
||||
let e = e(true, Sounds::None, false);
|
||||
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
|
||||
assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -225,7 +225,7 @@ mod tests {
|
||||
let media = e(false, Sounds::Media, false);
|
||||
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
|
||||
let tone = e(true, Sounds::Tone, false);
|
||||
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
|
||||
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(three3d, sound(tone));"), "{tone}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -242,13 +242,4 @@ mod tests {
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
|
||||
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
|
||||
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ pub struct CutPlan {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "CutBeat")]
|
||||
#[ts(rename = "Beat")]
|
||||
pub struct Beat {
|
||||
/// where it starts, in seconds from the cut's start (0 for the first)
|
||||
pub at: f64,
|
||||
|
||||
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
|
||||
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
|
||||
pub fn goal_declarations() -> String {
|
||||
let cfg = Config::new();
|
||||
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
|
||||
// a cut's beats are a script's (script.rs Beat)
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
|
||||
out.extend(decls!(cfg;
|
||||
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
|
||||
@@ -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
|
||||
@@ -103,20 +103,6 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
|
||||
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
|
||||
And every other raea command runs on the box
|
||||
|
||||
Scenario: CL16. raea cloud's boxes are Fly Machines
|
||||
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
|
||||
read and stopped at 8 cores and 16 GB (12-03)
|
||||
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
|
||||
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
|
||||
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
|
||||
project's folders and paths are the same
|
||||
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
|
||||
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
|
||||
proxy starts it again at the next request
|
||||
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
|
||||
straight to the new box's file API), and puts every box on a release (latest)
|
||||
And a file PUT to a box streams to disk and lands whole, never held in memory
|
||||
|
||||
Rule: it is proven end to end
|
||||
Scenario: CL12. A stand-in agent, then a real one
|
||||
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
|
||||
@@ -124,37 +110,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
|
||||
@@ -13,12 +13,9 @@ every project to import as `@shared/components/NAME`. `raea part` is the old nam
|
||||
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
|
||||
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
|
||||
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
|
||||
type (`text/reveal`), a name or the name it had upstream, the phrases people ask for it with (`"chat input"`,
|
||||
`composer`, `"lower third"`, `template`), or words in what it does (`"count up"`). `show NAME` tells one in full: what
|
||||
it draws and how it moves, when to use it and when not, the size and length it was designed at, and each prop with its
|
||||
type, default and what it does; `--json` gives the same as JSON, for every hit of a `list`. `add NAME` copies the
|
||||
component into `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's
|
||||
first line names the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
|
||||
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
|
||||
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
|
||||
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
|
||||
|
||||
```sh
|
||||
raea make component list
|
||||
@@ -26,8 +23,6 @@ raea make component add captions end-card
|
||||
raea make component add reel --shared
|
||||
raea make component list text/reveal
|
||||
raea make component list count up
|
||||
raea make component list chat input
|
||||
raea make component show prompt-send
|
||||
raea make component add soft-blur-in
|
||||
```
|
||||
|
||||
@@ -36,7 +31,7 @@ raea make component add soft-blur-in
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, "count up", "chat input", template; show tells one in full: what it draws, when to use it and when not, its props)
|
||||
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -46,7 +41,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
|
||||
| `--json` | – | The library's items as JSON (`list`: every hit, best first; `show`: the one), each with its props, when to use it and when not, and the phrases it's asked for with. |
|
||||
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -37,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -54,6 +54,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| `--axis` | `A` | The axis a label is for, by name, such as blur or clip |
|
||||
| `--bad` | – | The moment has the problem the axis names (the default) |
|
||||
| `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |
|
||||
| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude |
|
||||
| `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own |
|
||||
| `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default |
|
||||
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
|
||||
|
||||
@@ -54,13 +54,11 @@ findings are then warnings.
|
||||
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
|
||||
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
|
||||
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
|
||||
work, judged by a fresh critic that may only read. `raea goal check` asks for the verdict itself when it's missing or
|
||||
older than the work (`raea goal judge` asks now), and keeps it in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
|
||||
newest file. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files it
|
||||
names, in its "from A s to B s" window if it has one, else every video under out/) goes to clef-omni, as `raea ask`
|
||||
reaches it; any other goes to a fresh session of the agent this project runs on, which the raea app or raea cloud
|
||||
started (it offers the session's critic as `RAEA_JUDGE_URL`). Outside such a session a rule with nothing to watch
|
||||
stays open and says why.
|
||||
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and
|
||||
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
|
||||
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
|
||||
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it
|
||||
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
|
||||
|
||||
```ts
|
||||
import { brief, rules } from "raea/brief"
|
||||
@@ -100,7 +98,7 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
|
||||
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 judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
|
||||
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
|
||||
```
|
||||
@@ -113,6 +111,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| --- | --- | --- |
|
||||
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
|
||||
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
|
||||
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
|
||||
| `--goal` | `NAME` | only this goal of the brief's (by its name) |
|
||||
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
|
||||
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
|
||||
|
||||
@@ -6,9 +6,8 @@ sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/a
|
||||
---
|
||||
|
||||
`raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them
|
||||
judged without the code or the conversation that made them: by a fresh session of the agent this project runs on,
|
||||
on the judge prompt, where the raea app or raea cloud started that agent; else by clef-omni on a frozen rubric. Who
|
||||
judges is raea's to settle: there's no flag for it. The scores come back as data, and whether the scene passes is
|
||||
judged without the code or the conversation that made them: by clef-omni on a frozen rubric (the default), or by a
|
||||
fresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes is
|
||||
decided in code from them. clef only advises until it has been calibrated against a person's or an agent's eye.
|
||||
|
||||
`--kind scene|kit|shot` judges on that kind's own rubric, for a scene, kit or shot goal ([`raea goal`](goal.md)): a scene on layout,
|
||||
@@ -22,8 +21,8 @@ own.
|
||||
```sh
|
||||
raea render scene.tsx --review review/
|
||||
raea judge review/ --brief brief.ts
|
||||
raea judge review/ --target reference.png --json
|
||||
raea judge review/r3 --kind kit --brief brief.ts # a kit job's round, on the kit rubric
|
||||
raea judge review/ --by claude --target reference.png --json
|
||||
raea judge review/r3 --kind kit --by claude --brief brief.ts # a kit job's round, on the kit rubric
|
||||
raea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
|
||||
raea judge calibrate
|
||||
```
|
||||
@@ -33,7 +32,7 @@ raea judge calibrate
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)
|
||||
raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -43,11 +42,11 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
|
||||
| `--by` | `clef\|kimi\|claude` | Who judges: clef-omni on the rubric (default), or a fresh Kimi or Claude session. With `judge eye`, the agent whose eye is recorded. |
|
||||
| `--dry` | – | Print what the judge would be asked, with its images, without asking. |
|
||||
| `--json` | – | Print the verdict as JSON: each score, the defects found and the pass. |
|
||||
| `--kind` | `scene\|kit\|shot` | The rubric: `scene`, `kit` or `shot` (the make loop's categories), instead of the film rubric. |
|
||||
| `--pass` | `yes\|no` | With `judge eye`: whether you'd pass it, recorded with your scores. |
|
||||
| `--read` | – | With `judge eye`: a fresh session of the project's agent reads the round, recorded as its eye. |
|
||||
| `--target` | `T.png` | A reference image the colour sheet is judged against. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -20,9 +20,8 @@ import the file instead), URLs and network calls, modules that need the native e
|
||||
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
|
||||
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
|
||||
|
||||
The 3D is drawn by Bevy's own PBR shaders, translated to WebGL2 when raea is built, with Bevy's light units,
|
||||
shadows, fog and TonyMcMapface tone mapping. three.js reads the page's 3D parts into a scene for them, so it comes from
|
||||
the project (`raea add [email protected]`). A game with no 3D ships without either.
|
||||
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
|
||||
project (`raea add [email protected]`).
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ comment read as asks is a note: it closes when the person retires it, and the ap
|
||||
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
|
||||
raea show out/cut.mp4 --replaces i-show-2f9c
|
||||
raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
|
||||
raea show --choose "Warm grade" out/warm-1.png out/warm-2.png --choose "Cool grade" out/cool-1.png --recommend 2
|
||||
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
|
||||
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
|
||||
raea show --on i-show-2f9c --working c-3 --sub "grade pass"
|
||||
@@ -52,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {"kind":"answer","choice":LABEL}; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
|
||||
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
|
||||
```
|
||||
|
||||
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
|
||||
@@ -64,7 +63,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
|
||||
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
|
||||
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
|
||||
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
|
||||
| `--choose` | `LABEL FILE...` | One option for the person to pick, named, its files after it; give it once per option, 2 to 6. Their pick comes back as `{"kind":"answer","choice":LABEL}`. |
|
||||
| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
|
||||
| `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. |
|
||||
| `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. |
|
||||
@@ -78,7 +76,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
|
||||
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
|
||||
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
|
||||
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
|
||||
| `--recommend` | `N` | With `--choose`: the option you'd pick, from 1, marked on it. Nothing is picked for the person. |
|
||||
| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
|
||||
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
|
||||
| `--role` | `ROLE` | With `--as`: the role shown beside the name. |
|
||||
|
||||
+4
-33
@@ -185,7 +185,7 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
|
||||
the shading itself (the bricks' side faces a touch darker), PA11's job
|
||||
|
||||
@done @needs:PA9
|
||||
@needs:PA9
|
||||
Scenario: PA11. Bevy's own shading in the light renderer
|
||||
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
|
||||
export time, and the light renderer draws with them instead of three.js's own materials
|
||||
@@ -204,35 +204,6 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
|
||||
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
|
||||
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
|
||||
# Status 12-03: built. tools/bevy-glsl composes the three programs with Bevy's own ShaderCache (raea's vendored
|
||||
# bevy_pbr, bevy_render and bevy_core_pipeline 0.20.0, WebGL2's defs, 10 directional lights, Gaussian shadow
|
||||
# filtering, MSAA, distance fog, the projection's kind read from the view) and naga 30 translates them;
|
||||
# sdk/playable/bevy/build.sh writes them into host/bevy/programs.ts (105 KB, 21 KB gzipped) with each block's field offsets and which of Bevy's bindings each
|
||||
# block and sampler is, and apps/playable's test fails when Bevy's shaders or the translator change and it isn't
|
||||
# rebuilt. host/bevy.ts replaces three.js's renderer (three.ts and tonemap.ts are gone): it reads raea's three.js
|
||||
# scene graph (scene.ts) for the parts, geometry and transforms, and fills Bevy's blocks as Bevy's render world
|
||||
# does (bevy/fill.ts: prepare_view_uniforms, prepare_lights, MeshUniform::new, StandardMaterial's uniform; the
|
||||
# lights back in Bevy's units through units.ts): reverse Z, one 1x1x1 light cluster packed as Bevy packs it for
|
||||
# WebGL2, one directional shadow cascade (as Bevy on WebGL2 has) fitted to what the camera sees of the scene,
|
||||
# point and spot lights, distance fog (Bevy's GpuFog from the scene's Fog: linear from near to far, or
|
||||
# exponential for a density, as the native engine makes it), a forward pass into half float with 4x MSAA, then
|
||||
# TonyMcMapface through Bevy's table. A Plane3d is drawn as its one face (Bevy's PlaneMeshBuilder), not as the
|
||||
# flat Box three.js was given, whose top face three points down. Not drawn yet, each warned once in the
|
||||
# console: an environment's light, a camera's own <Fog> (Bevy's DistanceFog component), normal maps, transmission, vertex colours, point and
|
||||
# spot shadows, rect lights, a shadow catcher, a paint look
|
||||
# Measured on brick-rush against `raea render --frame` (mean difference over the drawn pixels / 255, both pages
|
||||
# against the same native frames; landscape frame 300 rendered with --despite type-over-part): portrait frame 90
|
||||
# three.js 6.1 -> Bevy 4.3 (PA10 recorded 5.4), landscape frame 300 9.8 -> 7.7, what is left in landscape mostly
|
||||
# the page's pulsing hint text. star-catch portrait frame 150: 17.0 -> 15.6 over the frame, 6.7 -> 5.0 over the
|
||||
# 3D above the hint text. A scene of a floor, six boxes, a ball, a sun with shadows, a point light and a spot
|
||||
# light (frame 10): perspective portrait 1.3, orthographic landscape 0.8, with linear fog 0.7, with exponential
|
||||
# fog 0.7. The page: brick-rush 1,889 -> 1,794 KB (three's renderer out, the programs in).
|
||||
# First frame in a fresh WebKit (served from localhost, to the GPU finishing it, 25 interleaved runs): three.js
|
||||
# median 131 ms, mean 129.8; Bevy median 131 ms, mean 131.8. The GL work is about 5 ms on both pages; the rest
|
||||
# is script and the page. Chrome's 4x CPU throttle isn't used (raea doesn't test in Chrome); with every WebKit
|
||||
# process clamped to the efficiency cores at background priority (taskpolicy -b), 142 and 145 ms over 11 runs.
|
||||
# brick-rush and star-catch play to their end cards and store taps in WebKit (tools/check.ts) in portrait and
|
||||
# landscape, with instant and 150 ms taps
|
||||
|
||||
@done
|
||||
Scenario: PA12. Bevy systems in a playable
|
||||
@@ -274,9 +245,9 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
Scenario: PA15. A 2D playable carries no three.js
|
||||
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
|
||||
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
|
||||
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); a drawer (three.ts then,
|
||||
# Bevy's programs in bevy.ts since PA11) draws it, and the export's entry passes it to start() only when the lint
|
||||
# found a 3D kind, so a 2D game's bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
|
||||
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); three.ts draws it with
|
||||
# three.js, and the export's entry passes it to start() only when the lint found a 3D kind, so a 2D game's
|
||||
# bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
|
||||
# tiles 1,345 -> 378 KB, gates 1,347 -> 380 KB, three 2D brand playables 2,752 -> 1,782, 3,409 -> 2,440 and
|
||||
# 2,693 -> 1,724 KB; brick-rush (3D, keeps three.js) 1,384 -> 1,478 KB. Each of the six played to its end card
|
||||
# and its store tap in WebKit (tools/check.ts), with instant taps (TAP_MS=0) and 150 ms taps.
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
|
||||
// in it lands on a file of the library, nothing imports another video framework, the search finds by use and by the
|
||||
// words people ask with, and each item carries what an agent picks by (tools/library-meta.sh writes it).
|
||||
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, normalize } from "node:path";
|
||||
import { listed, searched, shown, terms, type Item } from "../src/catalog";
|
||||
import { listed, type Item } from "../src/catalog";
|
||||
|
||||
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
|
||||
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
|
||||
@@ -46,37 +45,4 @@ describe("the component library", () => {
|
||||
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
|
||||
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
|
||||
});
|
||||
|
||||
test("each item says what it draws, when to use it and not, how it's asked for, and its props", () => {
|
||||
const thin = cat.items.filter((i) => !i.what || !i.use_when?.length || !i.avoid_when?.length || !i.asked_as?.length || !Array.isArray(i.props) || !i.aspect);
|
||||
expect(thin.map((i) => i.name)).toEqual([]);
|
||||
// its props are the ones its file declares
|
||||
const flash = cat.items.find((i) => i.name === "flash-count")!;
|
||||
expect(flash.props!.find((p) => p.name === "value")).toMatchObject({ type: "number", default: "3600" });
|
||||
});
|
||||
|
||||
test("its words name no other library or its tooling: the components are raea's", () => {
|
||||
const named = cat.items.flatMap((i) => [i.what ?? "", ...(i.use_when ?? []), ...(i.avoid_when ?? [])].filter((s) => /\b(remotion|remocn|snapcn|snap-cn|shadcn)\b/i.test(s)).map((s) => `${i.name}: ${s}`));
|
||||
expect(named).toEqual([]);
|
||||
});
|
||||
|
||||
test("search by the words people use: a product's UI, a composer, a chat input, a template, an AI prompt", () => {
|
||||
const top = (q: string, n = 3) => searched(cat.items, terms([q])).slice(0, n).map((i) => `${i.category}/${i.name}`);
|
||||
expect(top("claude code").every((n) => /terminal|agent/.test(n))).toBe(true);
|
||||
expect(top("composer")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
|
||||
expect(top("chat input", 5)).toEqual(expect.arrayContaining(["ui/input", "ui/prompt-send"]));
|
||||
expect(top("AI prompt").every((n) => n.startsWith("ui/prompt-"))).toBe(true);
|
||||
expect(top("composer animations with claude")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
|
||||
// the upstream name is a search alias: snapcn's terminal-simulator is ui/terminal-session here
|
||||
expect(top("terminal simulator", 2).sort()).toEqual(["ui/terminal-session", "ui/terminal-simulator"]);
|
||||
// "template" alone: the items that are one, and how to narrow it
|
||||
expect(listed(cat.items, ["template"])).toContain("say what it shows to narrow it");
|
||||
expect(listed(cat.items, ["cli"])).not.toContain("click-type");
|
||||
});
|
||||
|
||||
test("show: one item in full, with its props and when to use it", () => {
|
||||
const i = cat.items.find((i) => i.name === "prompt-send")!;
|
||||
const s = shown(i);
|
||||
for (const want of ["ui/prompt-send", "use it when:", "not when:", "props:", "text?: string", "raea make component add prompt-send", 'import { PromptSend } from "./components/ui/prompt-send"']) expect(s).toContain(want);
|
||||
});
|
||||
});
|
||||
@@ -1,68 +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, pace, 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);
|
||||
});
|
||||
@@ -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] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
+24
-88
@@ -6,15 +6,7 @@
|
||||
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
/** One of a component's props, read from its Props type: its type as written, its default, a line on what it does */
|
||||
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
|
||||
/** An item; the fields after `from` are tools/library-meta.sh's: the upstream component it was matched to by content
|
||||
* (a search alias, never its name here), what it draws and how it moves, when to use it and when not, the phrases
|
||||
* people ask for it with, its props, and the length, frame rate, size, aspect and feel it was designed at */
|
||||
export type Item = {
|
||||
name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string;
|
||||
upstream?: string; what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; props?: Prop[]; length?: number; fps?: number; size?: string; aspect?: string; vibe?: string;
|
||||
};
|
||||
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
|
||||
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
|
||||
export type Got = { item: Item; licence: string; files: Record<string, string> };
|
||||
|
||||
@@ -25,9 +17,6 @@ function home(raea: string, env: Record<string, string | undefined>): string | u
|
||||
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
|
||||
}
|
||||
|
||||
/** An item by its name, category/name or category/type/name */
|
||||
export const found = (items: Item[], want: string) => items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
|
||||
|
||||
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
|
||||
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
|
||||
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
|
||||
@@ -36,99 +25,46 @@ export function componentsHost(raea: string, env: Record<string, string | undefi
|
||||
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
|
||||
if (a.op !== "get") return cat.items;
|
||||
const want = String(a.name).replace(/^\/+|\/+$/g, "");
|
||||
const item = found(cat.items, want);
|
||||
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
|
||||
if (!item) return null;
|
||||
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
|
||||
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
|
||||
}
|
||||
|
||||
// what a row says: the item's own line, or what it draws when that line is a few words
|
||||
const line = (i: Item) => (i.says.length >= 40 || !i.what ? i.says : i.what).split(". ")[0];
|
||||
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${line(i).slice(0, 110)}`;
|
||||
|
||||
// words that say nothing about which one ("a", "animation", "component") are skipped; "template", "effect" and
|
||||
// "preset" narrow to the items that are one when they're all a search says, and only rank otherwise
|
||||
const FILLER = new Set(["a", "an", "the", "with", "for", "of", "and", "in", "on", "to", "my", "our", "some", "please", "use", "using", "raea", "component", "components", "animation", "animations", "animated", "thing", "something", "from", "like", "one"]);
|
||||
const SOFT = new Set(["template", "templates", "effect", "effects", "preset", "presets"]);
|
||||
const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// a word at a word's start ("count" finds "counter"); a short one only whole ("cli" isn't "click", "ai" isn't "aim")
|
||||
const finds = (w: string) => (w.length <= 3 ? new RegExp(`(^|[^a-z0-9])${esc(w)}(s|es)?($|[^a-z0-9])`, "i") : new RegExp(`(^|[^a-z0-9])${esc(w.replace(/s$/, ""))}`, "i"));
|
||||
|
||||
/** How well an item answers the words: 0 when a word that matters isn't anywhere in it. The name, the upstream name
|
||||
* and the phrases people ask for it with count most; what it does and when to use it count once */
|
||||
export function scored(i: Item, ws: string[]): number {
|
||||
const asked = (i.asked_as ?? []).join(" | ");
|
||||
const told = [i.says, i.what ?? "", ...(i.use_when ?? [])].join(" ");
|
||||
const named = (n: string | undefined, w: string) => (!n ? 0 : n.split("-").includes(w) ? 3 : w.length > 3 && n.includes(w) ? 2 : 0);
|
||||
const key = ws.filter((w) => !SOFT.has(w));
|
||||
let s = 0;
|
||||
// the words together, as written: a phrase people ask with, a name, or a sentence of what it does
|
||||
const phrase = key.join(" ");
|
||||
if (key.length > 1) s += (i.asked_as ?? []).some((a) => a.toLowerCase().includes(phrase)) ? 6 : [i.name, i.upstream ?? ""].includes(key.join("-")) ? 6 : told.toLowerCase().includes(phrase) ? 3 : 0;
|
||||
for (const w of ws) {
|
||||
const [c, t] = w.split("/");
|
||||
const re = finds(w);
|
||||
let got = 0;
|
||||
if (w.includes("/")) got = i.category === c && (!t || i.type === t) ? 4 : 0;
|
||||
else if (i.category === w || i.type === w) got = 4;
|
||||
// its name (or upstream's), the phrases it's asked for with, and its own words each add
|
||||
else got = Math.max(named(i.name, w), named(i.upstream, w)) + (re.test(asked) ? 3 : 0) + (re.test(told) || i.from === w ? 1 : 0);
|
||||
if (!got && !SOFT.has(w)) return 0;
|
||||
s += got;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
|
||||
|
||||
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
|
||||
* items they name. A word is a category ("text"), a category/type ("text/reveal"), a name or upstream name, or
|
||||
* anything in the phrases people ask with, what it does or when to use it; every word that matters must be found */
|
||||
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
|
||||
* an item does; every word must be found, and a name's own words count first. */
|
||||
export function listed(items: Item[], words: string[]): string {
|
||||
if (!items.length) return "";
|
||||
const ws = terms(words);
|
||||
if (!ws.length) {
|
||||
if (!words.length) {
|
||||
const cats = [...new Set(items.map((i) => i.category))].sort();
|
||||
const line = (c: string) => {
|
||||
const of = items.filter((i) => i.category === c);
|
||||
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
|
||||
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
|
||||
};
|
||||
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
|
||||
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
|
||||
}
|
||||
const found = searched(items, ws);
|
||||
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const phrase = ws.join(" ");
|
||||
const score = (i: Item) => {
|
||||
// the words together, as written, in what it does: ahead of the same words scattered
|
||||
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
|
||||
for (const w of ws) {
|
||||
const [c, t] = w.split("/");
|
||||
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
|
||||
else if (i.name.split("-").includes(w)) s += 3;
|
||||
else if (i.name.includes(w)) s += 2;
|
||||
else if (i.says.toLowerCase().includes(w)) s += 1;
|
||||
else return 0;
|
||||
}
|
||||
return s;
|
||||
};
|
||||
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
|
||||
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
|
||||
// "template" or "effect" alone: the items that are one, a page of them, and how to narrow it
|
||||
if (ws.every((w) => SOFT.has(w))) {
|
||||
const top = found.slice(0, 30);
|
||||
return `${found.length} components are a ${ws[0].replace(/s$/, "")}; say what it shows to narrow it (list ${ws[0]} chat, list ${ws[0]} logo, list "${ws[0]} product demo"):\n${top.map(row).join("\n")}\n${found.length > top.length ? `... and ${found.length - top.length} more\n` : ""}`;
|
||||
}
|
||||
return found.map(row).join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** A search's words that matter, in lower case */
|
||||
export const terms = (words: string[]) => words.join(" ").toLowerCase().split(/\s+/).filter((w) => w && !FILLER.has(w));
|
||||
|
||||
/** The items the words find, best first */
|
||||
export function searched(items: Item[], ws: string[]): Item[] {
|
||||
// equal scores: the one more of whose asked-for phrases the words are in is more about them
|
||||
const res = ws.filter((w) => !w.includes("/")).map(finds);
|
||||
const fit = (i: Item) => (i.asked_as ?? []).filter((a) => res.some((re) => re.test(a))).length;
|
||||
return items
|
||||
.map((i) => [scored(i, ws), fit(i), i] as const)
|
||||
.filter(([s]) => s > 0)
|
||||
.sort((a, b) => b[0] - a[0] || b[1] - a[1] || a[2].name.localeCompare(b[2].name))
|
||||
.map(([, , i]) => i);
|
||||
}
|
||||
|
||||
/** `raea make component show NAME`: everything an agent picks by, without opening the file */
|
||||
export function shown(i: Item, from = "./components"): string {
|
||||
const list = (head: string, xs?: string[]) => (xs?.length ? `${head}\n${xs.map((x) => ` - ${x}`).join("\n")}\n` : "");
|
||||
const made = [i.size && `${i.size} (${i.aspect})`, !i.size && i.aspect, i.length && `${i.length} frames at ${i.fps ?? 30} fps`, i.vibe && `feels ${i.vibe}`].filter(Boolean).join(", ");
|
||||
const props = (i.props ?? []).map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.default !== undefined ? ` = ${p.default}` : ""}${p.says ? `\n ${p.says}` : ""}`);
|
||||
return `${i.category}/${i.name} (${i.type}; from ${i.from}${i.upstream ? `, ${i.upstream} there` : ""})
|
||||
${i.what ?? i.says}
|
||||
${list("use it when:", i.use_when)}${list("not when:", i.avoid_when)}${i.asked_as?.length ? `asked for as: ${i.asked_as.join("; ")}\n` : ""}${made ? `designed at: ${made}\n` : ""}${props.length ? `props:\n${props.join("\n")}\n` : "props: none (its words and colours are written in the file)\n"}add it: raea make component add ${i.name}
|
||||
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}";
|
||||
`;
|
||||
return found.map(([, i]) => row(i)).join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
|
||||
|
||||
+15
-14
@@ -136,7 +136,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
IN_HELP.set(was);
|
||||
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
|
||||
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
|
||||
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {{\"kind\":\"answer\",\"choice\":LABEL}}; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
|
||||
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
|
||||
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
|
||||
let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)");
|
||||
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
|
||||
@@ -149,7 +149,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
|
||||
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
|
||||
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
|
||||
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
|
||||
}
|
||||
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
|
||||
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
|
||||
@@ -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
|
||||
|
||||
@@ -1,94 +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 { 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;
|
||||
|
||||
/** 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 = (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 };
|
||||
}
|
||||
+40
-84
@@ -28,7 +28,7 @@ import { absolute, fromCwd, labelsIn, showVerb } from "./show";
|
||||
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
|
||||
import { clothesVerb } from "./clothes";
|
||||
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
|
||||
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog";
|
||||
import { added, listed, type Got, type Item } from "./catalog";
|
||||
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
|
||||
import { bugVerb } from "./bug";
|
||||
|
||||
@@ -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.
|
||||
`;
|
||||
@@ -226,18 +199,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
|
||||
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
|
||||
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
|
||||
const ws = clean(args.slice(2));
|
||||
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from
|
||||
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
|
||||
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
|
||||
// show: one item in full, so it can be picked without opening its file
|
||||
if (args[1] === "show") {
|
||||
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
|
||||
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
|
||||
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
|
||||
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
|
||||
}
|
||||
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
|
||||
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
|
||||
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
|
||||
const names = clean(args.slice(2));
|
||||
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
|
||||
const force = args.includes("--force");
|
||||
@@ -313,19 +276,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");
|
||||
|
||||
@@ -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..]),
|
||||
_ => {
|
||||
|
||||
+78
-80
@@ -10,8 +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, markJumps, speechOf, toSound, type PaceOptions } from "./pace";
|
||||
import { timing } from "./cutplan";
|
||||
import { harness, library, show, task } from "./app";
|
||||
import { fromCwd } from "./show";
|
||||
import { clothesHost } from "./wardrobe";
|
||||
@@ -45,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();
|
||||
}
|
||||
|
||||
@@ -69,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;
|
||||
}
|
||||
|
||||
@@ -124,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 */
|
||||
|
||||
@@ -1,434 +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 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");
|
||||
}
|
||||
@@ -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"
|
||||
};
|
||||
+4
-29
@@ -32,9 +32,6 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
|
||||
raea show FILE... --fyi
|
||||
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
|
||||
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
|
||||
raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png [--recommend 2] [--title T] [--ask TEXT]
|
||||
The person picks one: 2 to 6 options, each named, its files after it. --recommend N marks the one you'd pick (from
|
||||
1); nothing is picked for them. Their pick comes back as {"kind":"answer","choice":"Cool grade"}.
|
||||
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
|
||||
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
|
||||
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
|
||||
@@ -61,7 +58,7 @@ raea show FILE... --replaces ITEM --done ID...
|
||||
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
|
||||
`;
|
||||
|
||||
const WITH_VALUE = new Set(["--group", "--choose", "--recommend", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
|
||||
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
|
||||
|
||||
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
|
||||
@@ -121,26 +118,6 @@ export function parseShow(args: string[], cwd: string) {
|
||||
});
|
||||
const empty = groups.find((g) => !g.files.length);
|
||||
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
|
||||
// the options to choose from (raea-platform home.feature HM5): each --choose "Label" holds the files after it
|
||||
const options: { label: string; files: string[]; recommended?: true }[] = [];
|
||||
args.forEach((a, i) => {
|
||||
if (a === "--choose" && args[i + 1] !== undefined) options.push({ label: args[i + 1].trim(), files: [] });
|
||||
else if (a === "--group" && options.length) throw new Error(`--choose and --group don't mix: each option is its own group\n${SHOW_USAGE}`);
|
||||
else if (options.length && isFile(a, i)) options.at(-1)!.files.push(abs(a));
|
||||
});
|
||||
if (options.length) {
|
||||
if (options.length < 2 || options.length > 6) throw new Error(`--choose gives 2 to 6 options, each with its files\n${SHOW_USAGE}`);
|
||||
const bare = options.find((o) => !o.label || !o.files.length);
|
||||
if (bare) throw new Error(`the option "${bare.label}" ${bare.label ? "has no files: put its files after its --choose" : "needs a name"}\n${SHOW_USAGE}`);
|
||||
if (files.length !== options.flatMap((o) => o.files).length) throw new Error(`with --choose, every file goes after the option it's in\n${SHOW_USAGE}`);
|
||||
if (args.includes("--question") || args.includes("--fyi")) throw new Error(`--choose is its own question: no --question or --fyi with it\n${SHOW_USAGE}`);
|
||||
}
|
||||
const recommend = one("--recommend");
|
||||
if (recommend !== undefined) {
|
||||
const n = Number(recommend);
|
||||
if (!options.length || !Number.isInteger(n) || n < 1 || n > options.length) throw new Error(`--recommend N names one of the --choose options, from 1${options.length ? ` to ${options.length}` : ""}\n${SHOW_USAGE}`);
|
||||
options[n - 1].recommended = true;
|
||||
}
|
||||
const despite = args.flatMap((a, i) => {
|
||||
if (a !== "--despite") return [];
|
||||
const [check, why] = [args[i + 1], args[i + 2]];
|
||||
@@ -180,7 +157,7 @@ export function parseShow(args: string[], cwd: string) {
|
||||
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
|
||||
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
|
||||
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
|
||||
return { groups, options, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
|
||||
}
|
||||
|
||||
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
|
||||
@@ -241,7 +218,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
|
||||
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
|
||||
}
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : a.options.length ? { intent: "choose", options: a.options } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
|
||||
| { opened: string[] }
|
||||
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
|
||||
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
|
||||
@@ -265,9 +242,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
|
||||
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
|
||||
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
|
||||
...settled,
|
||||
a.options.length
|
||||
? `They pick one of ${a.options.length}: {"kind":"answer","choice":"<the option's name>"} comes to ${inbox}. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and carry on with their pick.`
|
||||
: a.fyi
|
||||
a.fyi
|
||||
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
|
||||
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} 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).
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"];
|
||||
|
||||
@@ -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,28 +0,0 @@
|
||||
//! The critic a project's rules are judged by when the judgement needs reading rather than watching (Shane, 12-03:
|
||||
//! never a harness raea picks or the agent names): a fresh session of the agent this project runs on, which the host
|
||||
//! that started the agent (raea cloud's box, sdk/cloud/server/critic.ts; the raea app) offers as RAEA_JUDGE_URL, with
|
||||
//! the session's RAEA_JUDGE_TOKEN. `raea judge`, `raea fingerprint read` and `raea goal judge` (sdk/goal) ask it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// What a person reads when there's no critic here: no tool, agent or model named, because none is theirs to pick.
|
||||
pub const NONE_HERE: &str = "an agent's reading is a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has";
|
||||
|
||||
/// Whether this session has a critic to ask.
|
||||
pub fn here() -> bool {
|
||||
std::env::var("RAEA_JUDGE_URL").is_ok_and(|u| !u.is_empty())
|
||||
}
|
||||
|
||||
/// One question to a fresh session of this project's agent, in `cwd`: what it says back.
|
||||
pub fn ask(cwd: &std::path::Path, prompt: &str) -> Result<String, String> {
|
||||
let url = std::env::var("RAEA_JUDGE_URL").ok().filter(|u| !u.is_empty()).ok_or(NONE_HERE)?;
|
||||
let token = std::env::var("RAEA_JUDGE_TOKEN").unwrap_or_default();
|
||||
let r = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(15 * 60))
|
||||
.send_json(json!({"cwd": cwd.display().to_string(), "prompt": prompt}));
|
||||
let body: Value = match r {
|
||||
Ok(r) => r.into_json().map_err(|e| format!("the critic's answer: {e}"))?,
|
||||
Err(ureq::Error::Status(_, r)) => return Err(format!("the critic couldn't: {}", r.into_json::<Value>().ok().and_then(|v| v["error"].as_str().map(String::from)).unwrap_or_default())),
|
||||
Err(e) => return Err(format!("the critic: {e}")),
|
||||
};
|
||||
body["text"].as_str().map(String::from).ok_or_else(|| "the critic gave no text".into())
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
pub mod cache;
|
||||
pub mod client;
|
||||
pub mod critic;
|
||||
pub mod media;
|
||||
pub mod route;
|
||||
|
||||
|
||||
@@ -2,6 +2,3 @@ node_modules
|
||||
deploy
|
||||
test
|
||||
README.md
|
||||
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
|
||||
!deploy/git
|
||||
!deploy/fly/start.sh
|
||||
@@ -1,81 +0,0 @@
|
||||
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
|
||||
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
|
||||
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
|
||||
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
|
||||
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
|
||||
# deploy/fly/box.sh builds it from sdk/cloud:
|
||||
#
|
||||
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
|
||||
FROM ubuntu:26.04
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
|
||||
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
|
||||
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
|
||||
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 \
|
||||
&& 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 \
|
||||
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG NODE=24.22.0
|
||||
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
|
||||
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
|
||||
|
||||
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
|
||||
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
|
||||
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
|
||||
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
|
||||
&& ln -s /home/raea /home/sprite
|
||||
|
||||
# raea, checked against its release's .sha256
|
||||
ARG RAEA_VERSION
|
||||
ARG RAEA_REPO=shinyobjectz/raea
|
||||
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
|
||||
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
|
||||
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
|
||||
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
|
||||
&& /opt/raea/bin/raea --version
|
||||
|
||||
WORKDIR /opt/raea-cloud
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
|
||||
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
|
||||
COPY server server
|
||||
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
|
||||
# the entrypoint 711, and it re-runs itself as raea)
|
||||
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
|
||||
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
|
||||
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
|
||||
&& git lfs install --system --skip-repo > /dev/null
|
||||
|
||||
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
|
||||
ARG COMMIT=unknown
|
||||
ARG DIRTY=false
|
||||
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
|
||||
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
|
||||
|
||||
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
|
||||
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/bin/bash
|
||||
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
|
||||
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
|
||||
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
|
||||
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
|
||||
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
|
||||
#
|
||||
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
|
||||
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
|
||||
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
|
||||
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
|
||||
# settings and Machine, then its health
|
||||
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
|
||||
# changes address) and its home folder copied, then listed in raea cloud
|
||||
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
|
||||
# deploy/fly/box.sh status NAME its address, Machine and health
|
||||
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
|
||||
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
|
||||
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
|
||||
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
|
||||
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
|
||||
#
|
||||
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
|
||||
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
|
||||
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
|
||||
set -euo pipefail
|
||||
REPO=shinyobjectz/raea
|
||||
HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
CONF=$HOME/.config/raea-cloud
|
||||
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
|
||||
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
|
||||
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
|
||||
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
|
||||
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
|
||||
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
|
||||
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
|
||||
fi
|
||||
REGION=${RAEA_FLY_REGION:-iad}
|
||||
SIZE=${RAEA_BOX_SIZE:-performance-8x}
|
||||
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
|
||||
IMAGE_APP=raea-box-image
|
||||
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
|
||||
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
|
||||
NAME=${2:-}
|
||||
app() { echo "raea-box-${1#raea-}"; }
|
||||
url() { echo "https://$(app "$1").fly.dev"; }
|
||||
envfile() { echo "$CONF/boxes/$1.env"; }
|
||||
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
|
||||
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
|
||||
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
|
||||
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
|
||||
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
|
||||
print(m[0]["id"] if m else "")'; }
|
||||
healthy() {
|
||||
local u t
|
||||
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
|
||||
for _ in $(seq 1 60); do
|
||||
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
|
||||
sleep 5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
image)
|
||||
version=${2:-${RAEA_VERSION:-$(newest)}}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
src=$HERE
|
||||
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
|
||||
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
|
||||
src=$(mktemp -d)
|
||||
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
|
||||
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
|
||||
src=$src/sdk/cloud
|
||||
commit=$RAEA_CLOUD_REF dirty=false
|
||||
else
|
||||
commit=$(git -C "$HERE" rev-parse HEAD)
|
||||
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
|
||||
fi
|
||||
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
|
||||
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
|
||||
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
|
||||
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
|
||||
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
|
||||
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
|
||||
;;
|
||||
up)
|
||||
need_name
|
||||
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
|
||||
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
|
||||
a=$(app "$NAME") f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
if [ ! -s "$f" ]; then
|
||||
# a new box: its own token, and the farm's settings
|
||||
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
|
||||
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
|
||||
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
|
||||
fi
|
||||
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
|
||||
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
|
||||
fly ips allocate-v4 --shared -a "$a" > /dev/null
|
||||
fly ips allocate-v6 -a "$a" > /dev/null
|
||||
}
|
||||
# the box's settings as Fly secrets, from the file (never on a command line)
|
||||
fly secrets import --stage -a "$a" < "$f" > /dev/null
|
||||
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
|
||||
id=$(machine "$NAME")
|
||||
if [ -z "$id" ]; then
|
||||
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
|
||||
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
|
||||
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
|
||||
# ~/.raea-cloud.env on its volume (start.sh)
|
||||
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
|
||||
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
|
||||
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
|
||||
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
|
||||
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
|
||||
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
|
||||
fi
|
||||
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
|
||||
"$0" status "$NAME"
|
||||
;;
|
||||
move)
|
||||
need_name
|
||||
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
|
||||
. "$(dirname "$0")/../sprites/org.sh"
|
||||
f=$(envfile "$NAME")
|
||||
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
|
||||
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
|
||||
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
|
||||
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
|
||||
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
|
||||
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
|
||||
# sprite exec it came at about 4 MB/s), then unpacked there
|
||||
a=$(app "$NAME")
|
||||
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
|
||||
healthy "$NAME" > /dev/null || true
|
||||
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
|
||||
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
|
||||
else
|
||||
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
|
||||
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
|
||||
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
|
||||
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
|
||||
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
|
||||
sending=$!
|
||||
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
|
||||
# out (12-03, Shane: fail fast at every step)
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
|
||||
got=-1 since=$SECONDS
|
||||
while kill -0 "$sending" 2> /dev/null; do
|
||||
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
|
||||
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
|
||||
except Exception: print(-1)')
|
||||
if [ "${n:--1}" -gt "$got" ]; then
|
||||
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
|
||||
got=$n since=$SECONDS
|
||||
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
|
||||
kill "$sending" 2> /dev/null
|
||||
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
|
||||
exit 1
|
||||
fi
|
||||
sleep 15
|
||||
done
|
||||
wait "$sending"
|
||||
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
|
||||
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
|
||||
fi
|
||||
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
|
||||
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
|
||||
# first, as fly ssh doesn't start a stopped Machine
|
||||
healthy "$NAME" > /dev/null || true
|
||||
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
|
||||
# real-path match
|
||||
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
|
||||
# its own settings on its disk too, as a Sprite kept them
|
||||
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
|
||||
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
|
||||
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
|
||||
;;
|
||||
register)
|
||||
need_name
|
||||
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
|
||||
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
|
||||
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
|
||||
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
|
||||
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
|
||||
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
|
||||
;;
|
||||
status)
|
||||
need_name
|
||||
echo "$(url "$NAME") machine $(machine "$NAME")"
|
||||
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
|
||||
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
|
||||
echo
|
||||
;;
|
||||
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
|
||||
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
|
||||
latest)
|
||||
version=${2:-$(newest)}
|
||||
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
linux=raea-$version-linux-x86_64.tar.gz
|
||||
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
|
||||
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
|
||||
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
|
||||
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
|
||||
failed=""
|
||||
for b in $names; do
|
||||
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
|
||||
echo "fly box: $b onto raea $version (${ref:0:10})"
|
||||
"$0" up "$b" > /dev/null || failed+=" $b"
|
||||
done
|
||||
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
|
||||
echo "fly box: every Fly box is on raea $version"
|
||||
;;
|
||||
key)
|
||||
need_name
|
||||
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
|
||||
k=$(printf %s "$k" | tr -d '[:space:]')
|
||||
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
|
||||
f=$(envfile "$NAME")
|
||||
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
|
||||
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
|
||||
;;
|
||||
sh)
|
||||
need_name
|
||||
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
|
||||
;;
|
||||
*)
|
||||
sed -n '2,25p' "$0"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -1,7 +0,0 @@
|
||||
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
|
||||
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
|
||||
app = "raea-box-image"
|
||||
primary_region = "iad"
|
||||
|
||||
[build]
|
||||
dockerfile = "Dockerfile"
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/bin/bash
|
||||
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
|
||||
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
|
||||
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
|
||||
# stopped until Fly's proxy starts it for the next request.
|
||||
set -uo pipefail
|
||||
H=/home/raea
|
||||
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
|
||||
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
|
||||
BOX=${BOX/raea-box-/raea-}
|
||||
mkdir -p "$H/work"
|
||||
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
|
||||
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
|
||||
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
|
||||
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
|
||||
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
|
||||
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
|
||||
if [ -s "$H/.raea-cloud.env" ]; then
|
||||
while IFS='=' read -r k v; do
|
||||
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
|
||||
[ -n "${!k:-}" ] || export "$k=$v"
|
||||
done < "$H/.raea-cloud.env"
|
||||
fi
|
||||
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
|
||||
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
|
||||
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
|
||||
[ -n "${!k:-}" ] && echo "$k=${!k}"
|
||||
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
|
||||
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
|
||||
# the folders and paths of projects made on a Sprite are the same here
|
||||
export RAEA_CLOUD_WORK=/home/sprite/work
|
||||
# the box's commits say which box made them
|
||||
[ -s "$H/.gitconfig" ] || {
|
||||
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
|
||||
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
|
||||
sudo -u raea HOME=$H git config --global init.defaultBranch main
|
||||
}
|
||||
python3 - "$BOX" << 'PY'
|
||||
import json, sys
|
||||
p = "/opt/raea-cloud/BUILD.json"
|
||||
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
|
||||
PY
|
||||
exec /opt/raea-cloud/image/entrypoint.sh
|
||||
+15
-100
@@ -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":
|
||||
@@ -264,10 +247,8 @@ class Log:
|
||||
SCALEDOWN = 2
|
||||
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
|
||||
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 180 since
|
||||
# 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
|
||||
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
|
||||
CPU_SCALEDOWN = 180
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
|
||||
CPU_SCALEDOWN = 60
|
||||
|
||||
|
||||
def on(gpus, job):
|
||||
@@ -355,43 +336,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 +356,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 +572,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 +589,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 +610,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 +729,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 +764,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):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -94,19 +94,6 @@ PARTS = 4
|
||||
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
|
||||
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
|
||||
CPU_PARTS = 2
|
||||
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
|
||||
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
|
||||
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
|
||||
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
|
||||
# the bill by.
|
||||
FLAT_PART = 24
|
||||
FLAT_FRAME_S = 0.6
|
||||
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
|
||||
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
|
||||
# 81 s where the others took 11-15, and the whole render waited on it)
|
||||
HEDGE_SHARE = 0.7
|
||||
HEDGE_AFTER = 1.5
|
||||
HEDGE_MIN_S = 8.0
|
||||
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
|
||||
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
|
||||
PART_START = 5.0
|
||||
@@ -267,81 +254,6 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
|
||||
return code
|
||||
|
||||
|
||||
def _ready(h):
|
||||
"""a spawned run's answer, the exception it raised, or None while it's still running"""
|
||||
try:
|
||||
return h.get(timeout=0)
|
||||
except Exception as e:
|
||||
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
|
||||
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
|
||||
return None
|
||||
return e
|
||||
|
||||
|
||||
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
|
||||
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
|
||||
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
|
||||
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
|
||||
to the same files wherever it runs, so either answer is the run's."""
|
||||
if not calls:
|
||||
return 0
|
||||
pause = pause or time.sleep
|
||||
if most and len(calls) > most:
|
||||
fn = fn.with_options(max_containers=most)
|
||||
code = 0
|
||||
t0 = clock()
|
||||
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
|
||||
took = []
|
||||
while out:
|
||||
for first in list(out):
|
||||
o = out[first]
|
||||
r = None
|
||||
for h in o["h"]:
|
||||
r = _ready(h)
|
||||
if r is not None:
|
||||
break
|
||||
if r is None:
|
||||
continue
|
||||
for h in o["h"]:
|
||||
try:
|
||||
h.cancel()
|
||||
except Exception:
|
||||
pass
|
||||
del out[first]
|
||||
took.append(clock() - o["at"])
|
||||
if isinstance(r, Exception):
|
||||
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
|
||||
if again is not None:
|
||||
again.append(o["call"])
|
||||
else:
|
||||
code = code or 1
|
||||
continue
|
||||
if bill:
|
||||
bill.add(r)
|
||||
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
|
||||
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
|
||||
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
|
||||
again.append(o["call"])
|
||||
continue
|
||||
if got is not None:
|
||||
got.append(r)
|
||||
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
|
||||
if r["code"]:
|
||||
log(r["out"], err=True)
|
||||
code = code or r["code"]
|
||||
if not out:
|
||||
break
|
||||
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
|
||||
slow = max(took)
|
||||
for first, o in out.items():
|
||||
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
|
||||
o["again"] = True
|
||||
o["h"].append(fn.spawn(*o["call"]))
|
||||
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
|
||||
pause(wait_s)
|
||||
return code
|
||||
|
||||
|
||||
def timed(r, n):
|
||||
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
|
||||
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
|
||||
@@ -365,7 +277,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,14 +321,9 @@ 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"))
|
||||
if quick:
|
||||
n0 = 0
|
||||
first = list(range(at0, at0 + n0))
|
||||
if flat and n0:
|
||||
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
|
||||
@@ -437,22 +344,17 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
if r0 and r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
|
||||
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
|
||||
left = todo - n0
|
||||
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
|
||||
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
|
||||
if quick:
|
||||
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
|
||||
else:
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
k = gpus_for(left, frame_s, cold_s, most)
|
||||
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
|
||||
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
|
||||
parts = f" in {k * m} parts" if m > 1 else ""
|
||||
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
|
||||
if r0:
|
||||
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
|
||||
elif quick and left:
|
||||
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
|
||||
else:
|
||||
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
|
||||
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
|
||||
@@ -463,38 +365,24 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
got = [r0] if r0 else []
|
||||
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
|
||||
again = [] if flat else None
|
||||
code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
if again:
|
||||
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
|
||||
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
|
||||
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
|
||||
if code:
|
||||
return code
|
||||
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
|
||||
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
|
||||
def took(what, t0):
|
||||
if time.time() - t0 >= 1:
|
||||
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
|
||||
|
||||
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
|
||||
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
|
||||
if video:
|
||||
t0 = time.time()
|
||||
t.join()
|
||||
took("the sound", t0)
|
||||
t0 = time.time()
|
||||
reload() # the other containers' frames
|
||||
took("reloading the volume", t0)
|
||||
frames = f"{os.path.dirname(work)}/frames"
|
||||
dest = os.path.join(work, out)
|
||||
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
|
||||
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
|
||||
t0 = time.time()
|
||||
farm_keys.put(store, keyed["keys"], got, frames)
|
||||
took("keeping the runs drawn", t0)
|
||||
t0 = time.time()
|
||||
got += farm_keys.take(hits, frames)
|
||||
took(f"bringing {len(hits)} kept runs", t0)
|
||||
if manifest and p.get("manifest"):
|
||||
path = os.path.join(work, manifest)
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
@@ -541,10 +429,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:
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 } : {}) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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)))
|
||||
@@ -1,27 +0,0 @@
|
||||
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
|
||||
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
|
||||
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
|
||||
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
|
||||
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
|
||||
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
|
||||
// idle, went on an hour running goal checks on raea-5).
|
||||
import type { WebSocket } from "ws"
|
||||
|
||||
export const CALLER_GONE_MS = 3 * 60_000
|
||||
const EVERY_MS = 20_000
|
||||
|
||||
/** the keepalive's timer: clear it when the socket closes */
|
||||
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
|
||||
let pong = Date.now()
|
||||
ws.on("pong", () => (pong = Date.now()))
|
||||
return setInterval(() => {
|
||||
if (ws.readyState !== ws.OPEN) return
|
||||
if (Date.now() - pong > goneMs) {
|
||||
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
|
||||
ws.terminate()
|
||||
return
|
||||
}
|
||||
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
|
||||
ws.ping()
|
||||
}, everyMs)
|
||||
}
|
||||
@@ -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 */
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
// The critic a project's rules are judged by on this box (Shane, 12-03: "nothing should judge or check with another
|
||||
// harness ... the context should never tell the agent to even have to decide what harness or model or provider"):
|
||||
// a fresh session of the same agent the project runs on, with the same sign-in, asked one question and given nothing
|
||||
// it could change. Each agent session started here (WS /v1/acp) gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN in its
|
||||
// environment; `raea goal judge` and `raea judge` in that agent's shell POST to it, and the critic runs as that agent.
|
||||
//
|
||||
// POST /host/judge {cwd, prompt} authorization: Bearer RAEA_JUDGE_TOKEN -> {text}
|
||||
//
|
||||
// The token is the session's: it names the agent and environment to start, and is forgotten when the session ends.
|
||||
import { spawn } from "node:child_process"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import path from "node:path"
|
||||
|
||||
interface Critic {
|
||||
command: string
|
||||
args: string[]
|
||||
env: NodeJS.ProcessEnv
|
||||
root: string
|
||||
}
|
||||
|
||||
const critics = new Map<string, Critic>()
|
||||
|
||||
/** the environment an agent session adds so its shell can ask for a critic: the URL and the session's token */
|
||||
export function register(c: Critic, port: number): { env: Record<string, string>; forget: () => void } {
|
||||
const token = randomBytes(24).toString("hex")
|
||||
critics.set(token, c)
|
||||
return { env: { RAEA_JUDGE_URL: `http://127.0.0.1:${port}/host/judge`, RAEA_JUDGE_TOKEN: token }, forget: () => critics.delete(token) }
|
||||
}
|
||||
|
||||
/** the critic a token names, or null */
|
||||
export const criticFor = (token: string | null | undefined): Critic | null => (token ? (critics.get(token) ?? null) : null)
|
||||
|
||||
/** a permission the critic asks for: what only reads is allowed once, anything else refused (it judges, it changes nothing) */
|
||||
type Option = { optionId: string; kind: string }
|
||||
export function answerPermission(p: { options: Option[]; toolCall?: { kind?: string } }): string {
|
||||
const reads = ["read", "search", "fetch", "think"].includes(String(p.toolCall?.kind ?? ""))
|
||||
const want = reads ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]
|
||||
return (p.options.find((o) => want.includes(o.kind)) ?? p.options.find((o) => (reads ? o.kind.startsWith("allow") : o.kind.startsWith("reject"))) ?? p.options[0]).optionId
|
||||
}
|
||||
|
||||
/** one question to a fresh session of the critic's agent in `cwd`: what it says back */
|
||||
export function ask(c: Critic, cwd: string, prompt: string, timeoutMs = 10 * 60_000): Promise<string> {
|
||||
const dir = path.resolve(c.root, cwd)
|
||||
if (dir !== c.root && !dir.startsWith(c.root + path.sep)) return Promise.reject(new Error(`${cwd} isn't in the workspace`))
|
||||
return new Promise((done, fail) => {
|
||||
const child = spawn(c.command, c.args, { cwd: dir, env: c.env, stdio: ["pipe", "pipe", "pipe"], detached: true })
|
||||
let said = ""
|
||||
let err = ""
|
||||
let n = 0
|
||||
let finished = false
|
||||
const waiting = new Map<number, (m: { result?: unknown; error?: { message?: string } }) => void>()
|
||||
const stop = () => {
|
||||
try {
|
||||
if (child.pid) process.kill(-child.pid, "SIGTERM")
|
||||
} catch {}
|
||||
}
|
||||
const end = (e: Error | null) => {
|
||||
if (finished) return
|
||||
finished = true
|
||||
clearTimeout(timer)
|
||||
stop()
|
||||
e ? fail(e) : done(said)
|
||||
}
|
||||
const timer = setTimeout(() => end(new Error(`the critic said nothing final in ${Math.round(timeoutMs / 60_000)} min`)), timeoutMs)
|
||||
const send = (m: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}\n`)
|
||||
const call = (method: string, params: object) =>
|
||||
new Promise<any>((ok, no) => {
|
||||
const id = ++n
|
||||
waiting.set(id, (m) => (m.error ? no(new Error(m.error.message ?? JSON.stringify(m.error))) : ok(m.result)))
|
||||
send({ id, method, params })
|
||||
})
|
||||
let buf = ""
|
||||
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
|
||||
buf += chunk
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {
|
||||
let m: any
|
||||
try {
|
||||
m = JSON.parse(buf.slice(0, i))
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (m.id != null && !m.method && waiting.has(m.id)) {
|
||||
const w = waiting.get(m.id)!
|
||||
waiting.delete(m.id)
|
||||
w(m)
|
||||
} else if (m.method === "session/update") {
|
||||
const u = m.params?.update
|
||||
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
|
||||
} else if (m.method === "session/request_permission") {
|
||||
send({ id: m.id, result: { outcome: { outcome: "selected", optionId: answerPermission(m.params) } } })
|
||||
} else if (m.id != null && m.method) {
|
||||
// a client method this critic doesn't offer (it reads with its own tools)
|
||||
send({ id: m.id, error: { code: -32601, message: `${m.method} isn't offered here` } })
|
||||
}
|
||||
}
|
||||
})
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => (err = (err + c).slice(-4000)))
|
||||
child.on("error", (e) => end(new Error(`the critic didn't start: ${e.message}`)))
|
||||
child.on("exit", (code) => end(finished ? null : new Error(`the critic ended (${code}) before it answered: ${err.trim().slice(-300)}`)))
|
||||
;(async () => {
|
||||
await call("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } })
|
||||
const s = await call("session/new", { cwd: dir, mcpServers: [] })
|
||||
await call("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: prompt }] })
|
||||
end(null)
|
||||
})().catch((e) => end(e as Error))
|
||||
})
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
|
||||
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
|
||||
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { pipeline } from "node:stream/promises"
|
||||
|
||||
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
|
||||
|
||||
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
|
||||
const { json } = o
|
||||
const p = o.resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT") {
|
||||
// to disk as it comes, beside the file, then put in its place whole
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
const part = `${p}.part-${process.pid}-${Date.now()}`
|
||||
return pipeline(req, createWriteStream(part)).then(
|
||||
() => {
|
||||
renameSync(part, p)
|
||||
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
|
||||
},
|
||||
(e) => {
|
||||
rmSync(part, { force: true })
|
||||
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
|
||||
},
|
||||
)
|
||||
}
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
|
||||
return pipeline(createReadStream(p), res).catch(() => res.destroy())
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
|
||||
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
|
||||
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
|
||||
// the Machine (restart policy on-failure) stays stopped.
|
||||
//
|
||||
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
|
||||
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
|
||||
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
|
||||
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
|
||||
//
|
||||
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
|
||||
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
|
||||
import type { Server } from "node:http"
|
||||
import path from "node:path"
|
||||
|
||||
export const HOLD_FILE = ".raea-hold"
|
||||
|
||||
/** a process other than this one (and its parents) whose working folder is under `work` */
|
||||
export function workingIn(work: string, self = process.pid): number[] {
|
||||
const mine = new Set<number>()
|
||||
for (let p = self; p > 1; ) {
|
||||
mine.add(p)
|
||||
try {
|
||||
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
|
||||
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
|
||||
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
|
||||
} catch {
|
||||
break
|
||||
}
|
||||
}
|
||||
const out: number[] = []
|
||||
let pids: string[] = []
|
||||
try {
|
||||
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
|
||||
} catch {
|
||||
return out
|
||||
}
|
||||
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
|
||||
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
|
||||
// idle and the box stopped under it)
|
||||
const roots = [path.resolve(work) + "/"]
|
||||
try {
|
||||
roots.push(realpathSync(work) + "/")
|
||||
} catch {}
|
||||
for (const d of pids) {
|
||||
const pid = Number(d)
|
||||
if (mine.has(pid)) continue
|
||||
try {
|
||||
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
|
||||
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
|
||||
} catch {}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface IdleOptions {
|
||||
server: Server
|
||||
work: string
|
||||
home: string
|
||||
/** whether the server itself has something running (an agent, a shell, a job) */
|
||||
busy: () => boolean
|
||||
quietMs: number
|
||||
holdMs?: number
|
||||
everyMs?: number
|
||||
log?: (line: string) => void
|
||||
exit?: () => void
|
||||
}
|
||||
|
||||
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
|
||||
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
|
||||
let last = Date.now()
|
||||
const holdMs = o.holdMs ?? 10 * 60_000
|
||||
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
|
||||
const exit = o.exit ?? (() => process.exit(0))
|
||||
const why = (): string | null => {
|
||||
if (Date.now() - last < o.quietMs) return "a request came lately"
|
||||
if (o.busy()) return "the server runs something"
|
||||
try {
|
||||
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
|
||||
if (Date.now() - held < holdMs) return "a project holds it"
|
||||
} catch {}
|
||||
const w = workingIn(o.work)
|
||||
if (w.length) return `${w.length} processes work in ${o.work}`
|
||||
return null
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
o.server.getConnections((e, n) => {
|
||||
if (!e && n > 0) return
|
||||
if (why()) return
|
||||
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
|
||||
clearInterval(timer)
|
||||
o.server.close()
|
||||
exit()
|
||||
})
|
||||
}, o.everyMs ?? 30_000)
|
||||
timer.unref()
|
||||
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
|
||||
}
|
||||
+27
-41
@@ -19,8 +19,6 @@
|
||||
// browser): {credential, email?}, handed back once, or {pending: true}
|
||||
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
|
||||
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
|
||||
// POST /host/judge {cwd, prompt} a fresh session of the asking agent session's own agent, as the critic its rules are
|
||||
// judged by: {text}. Its token is the session's RAEA_JUDGE_TOKEN (critic.ts)
|
||||
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
|
||||
// each line it prints is one frame back. A caller signing the agent in as one of
|
||||
// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
|
||||
@@ -39,13 +37,9 @@
|
||||
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { homedir } from "node:os"
|
||||
import { keepAlive } from "./alive.ts"
|
||||
import { files } from "./files.ts"
|
||||
import { stopWhenIdle } from "./idle.ts"
|
||||
import { WebSocketServer } from "ws"
|
||||
import { installed, spawnFor } from "./agents.ts"
|
||||
import { guard } from "./memguard.ts"
|
||||
@@ -56,7 +50,6 @@ import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackC
|
||||
import { connect as tcp } from "node:net"
|
||||
import { login, loginState } from "./login.ts"
|
||||
import { Outside, resolve, WORK } from "./workspace.ts"
|
||||
import { ask as askCritic, criticFor, register as registerCritic } from "./critic.ts"
|
||||
|
||||
const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""
|
||||
if (TOKEN.length < 16) {
|
||||
@@ -177,6 +170,24 @@ async function body(req: IncomingMessage): Promise<Buffer> {
|
||||
return Buffer.concat(parts)
|
||||
}
|
||||
|
||||
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
const p = resolve(url.searchParams.get("path") ?? ".")
|
||||
if (req.method === "PUT")
|
||||
return body(req).then((b) => {
|
||||
mkdirSync(path.dirname(p), { recursive: true })
|
||||
writeFileSync(p, b)
|
||||
json(res, { path: path.relative(WORK, p), bytes: b.length })
|
||||
})
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
|
||||
}
|
||||
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
|
||||
}
|
||||
|
||||
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
|
||||
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
|
||||
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
|
||||
@@ -239,23 +250,7 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
||||
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
|
||||
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
|
||||
// box stopped as idle the moment it ended (12-03)
|
||||
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
|
||||
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
|
||||
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
|
||||
if (url.pathname === "/host/judge" && req.method === "POST") {
|
||||
const c = criticFor(/^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1])
|
||||
if (!c) return json(res, { error: "no agent session with that token here" }, 401)
|
||||
try {
|
||||
const b = JSON.parse(String(await body(req)))
|
||||
if (typeof b.prompt !== "string" || !b.prompt) return json(res, { error: "prompt is the question" }, 400)
|
||||
return json(res, { text: await askCritic(c, typeof b.cwd === "string" ? b.cwd : ".", b.prompt) })
|
||||
} catch (e) {
|
||||
return json(res, { error: (e as Error).message }, 502)
|
||||
}
|
||||
}
|
||||
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
|
||||
try {
|
||||
if (url.pathname === "/v1/health" && req.method === "GET") {
|
||||
@@ -283,7 +278,7 @@ const server = createServer(async (req, res) => {
|
||||
running: running.size,
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
|
||||
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
|
||||
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
|
||||
if (url.pathname === "/v1/jobs" && req.method === "POST") {
|
||||
@@ -375,10 +370,7 @@ server.on("upgrade", (req, socket, head) => {
|
||||
} catch (e) {
|
||||
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
|
||||
}
|
||||
const base = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
|
||||
// this session's critic (critic.ts): the same agent, sign-in and environment, which `raea goal judge` in its shell asks
|
||||
const critic = registerCritic({ command: agent.command, args: agent.args, env: base, root: WORK }, PORT)
|
||||
const env = { ...base, ...critic.env }
|
||||
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
// its own process group, so what it started (a render left running in the background) stops with it: a killed
|
||||
// agent's renders went on as orphans, 4 GB of them on raea-2 (11-25)
|
||||
@@ -396,7 +388,11 @@ server.on("upgrade", (req, socket, head) => {
|
||||
}
|
||||
running.add(child)
|
||||
agentSockets.add(ws)
|
||||
const beat = keepAlive(ws, agent.id)
|
||||
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
|
||||
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
|
||||
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
|
||||
// never sees it
|
||||
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
|
||||
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
|
||||
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
|
||||
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
|
||||
@@ -408,7 +404,7 @@ server.on("upgrade", (req, socket, head) => {
|
||||
ws.terminate()
|
||||
stopAll()
|
||||
}, Math.min(60_000, IDLE_AGENT_MS / 2))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle), critic.forget()))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
|
||||
child.on("exit", () => (running.delete(child), clearInterval(idle)))
|
||||
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
|
||||
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
|
||||
@@ -475,16 +471,6 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
|
||||
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
|
||||
const idle =
|
||||
idleMin > 0
|
||||
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
|
||||
: null
|
||||
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
|
||||
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
|
||||
server.requestTimeout = 0
|
||||
server.headersTimeout = 60_000
|
||||
server.listen(PORT, async () => {
|
||||
await versionKnown
|
||||
const d = device(childEnv())
|
||||
|
||||
+14
-66
@@ -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
@@ -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)
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
+1
-15
@@ -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
|
||||
}
|
||||
@@ -94,15 +91,6 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
|
||||
throw new Error(`${what} ended without an exit code`)
|
||||
}
|
||||
|
||||
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
|
||||
export const onSprite = (url: string): boolean => {
|
||||
try {
|
||||
return new URL(url).hostname.endsWith(".sprites.app")
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export class RaeaCloud {
|
||||
readonly url: string
|
||||
private token: string
|
||||
@@ -115,8 +103,7 @@ export class RaeaCloud {
|
||||
constructor(o: { url: string; token: string; spriteToken?: string }) {
|
||||
this.url = o.url.replace(/\/+$/, "")
|
||||
this.token = o.token
|
||||
// only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
|
||||
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
|
||||
this.spriteToken = o.spriteToken
|
||||
}
|
||||
|
||||
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
|
||||
@@ -172,7 +159,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
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
|
||||
@@ -69,11 +69,6 @@ class FakeGpu:
|
||||
def starmap(self, calls, order_outputs=False, return_exceptions=True):
|
||||
return [self.remote(*c) for c in calls]
|
||||
|
||||
def spawn(self, *a, **kw):
|
||||
# a run spawned on its own (farm_plan.hedged, waited): answered at once
|
||||
r = self.remote(*a, **kw)
|
||||
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
|
||||
|
||||
|
||||
lines = []
|
||||
log = lambda t, err=False: lines.append(t)
|
||||
@@ -128,14 +123,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 +250,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)
|
||||
@@ -365,50 +344,3 @@ assert not any("waiting" in l for l in lines), lines
|
||||
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
|
||||
class Call:
|
||||
def __init__(self, answer_at, r, clock):
|
||||
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
|
||||
|
||||
def get(self, timeout=None):
|
||||
if self.clock() >= self.answer_at:
|
||||
return self.r
|
||||
raise TimeoutError()
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
|
||||
class Straggly:
|
||||
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock, self.spawned = clock, []
|
||||
|
||||
def with_options(self, **kw):
|
||||
return self
|
||||
|
||||
def spawn(self, id, args, frames, first, *rest):
|
||||
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
|
||||
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
|
||||
self.spawned.append((first, c))
|
||||
return c
|
||||
|
||||
|
||||
now = [0.0]
|
||||
clock = lambda: now[0]
|
||||
def tick(_s):
|
||||
now[0] += 1
|
||||
st = Straggly(clock)
|
||||
lines.clear()
|
||||
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
|
||||
got = []
|
||||
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
|
||||
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
|
||||
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
|
||||
assert now[0] < 100, now
|
||||
assert any("sent again" in l for l in lines), lines
|
||||
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
|
||||
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
|
||||
@@ -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")
|
||||
+1
-55
@@ -4,7 +4,7 @@
|
||||
|
||||
import assert from "node:assert/strict"
|
||||
import { execSync } from "node:child_process"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { parseSummary, pick } from "../server/gpu.ts"
|
||||
@@ -13,8 +13,6 @@ import { shellEnv } from "../server/shell-os.ts"
|
||||
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
|
||||
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
|
||||
import { localSources } from "../server/media.ts"
|
||||
import { keepAlive } from "../server/alive.ts"
|
||||
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
|
||||
|
||||
const L4 = `Devices:
|
||||
========
|
||||
@@ -213,57 +211,5 @@ 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")
|
||||
}
|
||||
|
||||
{
|
||||
// the critic (critic.ts): a session's token names its agent; a fresh session of it answers; reads only
|
||||
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "critic-")))
|
||||
mkdirSync(path.join(root, "proj"))
|
||||
const agent = { command: process.execPath, args: [path.join(import.meta.dirname, "echo-agent.mjs")], env: { ...process.env }, root }
|
||||
const r = registerCritic(agent, 8080)
|
||||
assert.equal(r.env.RAEA_JUDGE_URL, "http://127.0.0.1:8080/host/judge")
|
||||
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), agent)
|
||||
assert.equal(criticFor("nope"), null)
|
||||
const said = await askCritic(agent, "proj", "is the plan complete?")
|
||||
assert.match(said, /echo: is the plan complete\?/)
|
||||
assert.match(said, new RegExp(`cwd: ${path.join(root, "proj").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`))
|
||||
// the echo agent's permission names no kind of tool: refused, as anything but a read is
|
||||
assert.match(said, /permission: no/)
|
||||
await assert.rejects(askCritic(agent, "../elsewhere", "x"), /isn't in the workspace/)
|
||||
assert.equal(answerPermission({ toolCall: { kind: "read" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "a")
|
||||
assert.equal(answerPermission({ toolCall: { kind: "edit" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "r")
|
||||
r.forget()
|
||||
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), null)
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
console.log("ok critic")
|
||||
}
|
||||
|
||||
{
|
||||
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
|
||||
const { WebSocketServer, WebSocket } = await import("ws")
|
||||
const wss = new WebSocketServer({ port: 0 })
|
||||
const port = (wss.address() as { port: number }).port
|
||||
const ended: boolean[] = []
|
||||
wss.on("connection", (ws) => {
|
||||
const beat = keepAlive(ws, "test", 120, 20)
|
||||
ws.on("close", () => (clearInterval(beat), ended.push(true)))
|
||||
})
|
||||
const live = new WebSocket(`ws://127.0.0.1:${port}`)
|
||||
await new Promise((ok) => live.on("open", ok))
|
||||
await new Promise((ok) => setTimeout(ok, 400))
|
||||
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
|
||||
live.close()
|
||||
await new Promise((ok) => setTimeout(ok, 50))
|
||||
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
|
||||
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
|
||||
await new Promise((ok) => gone.on("open", ok))
|
||||
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
|
||||
assert.ok(closed, "a caller that answered no ping wasn't ended")
|
||||
wss.close()
|
||||
console.log("ok an agent socket's caller gone is ended")
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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,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"
|
||||
|
||||
@@ -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` }
|
||||
@@ -226,8 +208,7 @@ const HOOK_S = 5
|
||||
* had none, read from its brief's "captions OR a text hook"): a cut with talking and no captions at all is an error,
|
||||
* 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, onCard: (w: Word) => boolean = () => false): Finding[] {
|
||||
heard = asDigits(heard)
|
||||
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false): Finding[] {
|
||||
// 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) => {
|
||||
@@ -237,9 +218,7 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
|
||||
if (said.length < BARE.error.words) return []
|
||||
const fix = "caption every line from the words file (whole phrases in the brand's caption style); a text hook goes with the captions, never instead of them. If the brief asks for no captions, render with --despite captions WHY"
|
||||
if (!shown.length) return [{ level: "error", kind: "uncaptioned", at: said[0].start, says: `no captions over the talking: ${said.length} words, ${(said[said.length - 1].end - said[0].start).toFixed(1)} s, and no caption track (captions one after another under ${Math.round(TRACK * 100)}% of what's said, or fewer than ${CARDS} of them). ${fix}` }]
|
||||
// a word is up when a caption is, or when text the render drew says it there (an end card with the line being said:
|
||||
// captionsOf takes a frame full of text for a card, not captions; 12-05, run 28's Elfster end cards)
|
||||
const up = (w: Word) => shown.some((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3) || onCard(w)
|
||||
const up = (w: Word) => shown.some((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
|
||||
const out: Finding[] = []
|
||||
for (let i = 0; i < said.length; ) {
|
||||
if (up(said[i])) { i++; continue }
|
||||
@@ -255,70 +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)
|
||||
// only the render's own texts say a word on screen: the footage's own (a sign, a phone) never caption anything
|
||||
const onCard = (w: Word) => {
|
||||
if (!own) return false
|
||||
const k = letters(w.text)
|
||||
const at = (t: number) => letters((frames[Math.round(t * rate)]?.lines ?? []).map((l) => l[4]).join(" "))
|
||||
return k.length > 0 && [w.start, (w.start + w.end) / 2, w.end].some((t) => at(t).includes(k))
|
||||
}
|
||||
for (const x of [...uncaptioned(shown, heard, textUp, onCard), ...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
@@ -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}")` })
|
||||
}
|
||||
})
|
||||
@@ -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) => {
|
||||
|
||||
@@ -6,22 +6,16 @@
|
||||
// (no one reads it on a phone), under 48 px a warning.
|
||||
// faces: frames two a second through the scene reader (raea cloud's farm). A face of a person in the shot (5% of the
|
||||
// frame's height or more) touching an edge or a split screen's seam: a second or more is an error, shorter a
|
||||
// warning. The reader takes a hand or a bag at the edge for a face now and then (12-05, run 28: Elfster's "face cut by
|
||||
// the left edge" was a hand at 0.79 then 0.65, where the people in the shot read 0.92 and over), so a run it's less
|
||||
// than FACE_SURE sure of is a warning, never an error. A split screen with a face in one half only is a warning.
|
||||
// warning. A split screen with a face in one half only is a warning.
|
||||
// A face at the edge that's meant (someone walking out of shot) is said, with its reason, in OUT.despite.txt beside
|
||||
// the video: its findings are then warnings.
|
||||
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
|
||||
/** a cut face is an error only when the reader is this sure, over its run, that it's a face (a face's score; 1 when the
|
||||
* reader gives none) */
|
||||
export const FACE_SURE = 0.8
|
||||
/** least font sizes, in pixels of a frame 1080 wide (its shorter side): the Direct Response skill's table */
|
||||
export const TEXT_ERROR = 40
|
||||
export const TEXT_WARN = 48
|
||||
@@ -48,21 +42,17 @@ export function splitsOf(fr: NonNullable<Faces>): Split[] {
|
||||
const near = (a: Split, b: Split) => a.axis === b.axis && Math.abs(a.at - b.at) <= 6
|
||||
const big = (fr: NonNullable<Faces>) => fr.faces.filter((f) => f[3] >= fr.h * FACE_MIN)
|
||||
|
||||
/** what cuts a face in a frame (an edge of the frame, or a split screen's seam), with how sure the reader is it's a face */
|
||||
function cutBy(fr: NonNullable<Faces>, splits: Split[]): { by: string; score: number } | null {
|
||||
for (const [x, y, fw, fh, s] of big(fr)) {
|
||||
const score = Number.isFinite(s) ? s : 1
|
||||
const by =
|
||||
x <= 1 ? "the left edge"
|
||||
: x + fw >= fr.w - 1 ? "the right edge"
|
||||
: y <= 1 ? "the top edge"
|
||||
: y + fh >= fr.h - 1 ? "the bottom edge"
|
||||
: splits.some((sp) => {
|
||||
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
|
||||
return (a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3
|
||||
}) ? "the split screen's seam"
|
||||
: null
|
||||
if (by) return { by, score }
|
||||
/** what cuts a face in a frame: an edge of the frame, or a split screen's seam */
|
||||
function cutBy(fr: NonNullable<Faces>, splits: Split[]): string | null {
|
||||
for (const [x, y, fw, fh] of big(fr)) {
|
||||
if (x <= 1) return "the left edge"
|
||||
if (x + fw >= fr.w - 1) return "the right edge"
|
||||
if (y <= 1) return "the top edge"
|
||||
if (y + fh >= fr.h - 1) return "the bottom edge"
|
||||
for (const sp of splits) {
|
||||
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
|
||||
if ((a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3) return "the split screen's seam"
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -92,12 +82,10 @@ export function cutFaces(frames: Faces[], rate = RATE): Finding[] {
|
||||
const held = raw.map((ss, i) => ss.filter((s) => (raw[i - 1] ?? []).some((o) => near(s, o)) || (raw[i + 1] ?? []).some((o) => near(s, o))))
|
||||
const out: Finding[] = []
|
||||
const hits = frames.map((fr, i) => (fr ? cutBy(fr, held[i]) : null))
|
||||
for (const [i, j, { by }] of runs(hits, (a, b) => a.by === b.by)) {
|
||||
for (const [i, j, by] of runs(hits)) {
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
const sure = hits.slice(i, j).reduce((n, h) => n + (h?.score ?? 0), 0) / (j - i)
|
||||
const doubt = sure < FACE_SURE ? ` (the reader is ${Math.round(sure * 100)}% sure it's a face: look)` : ""
|
||||
out.push({ level: to - from >= 1 && !doubt ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face${doubt} is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
|
||||
out.push({ level: to - from >= 1 ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
|
||||
}
|
||||
const split = held.map((ss) => ss[0] ?? null)
|
||||
for (const [i, j, sp] of runs(split, near)) {
|
||||
@@ -139,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)` })
|
||||
}
|
||||
|
||||
+206
-4
@@ -1,15 +1,217 @@
|
||||
// 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 { spawnSync } 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
|
||||
const v = verdict(j.root, j.contract!)
|
||||
const changed = newest(j.root)
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
const fresh = !!v && (changed === null || v.at >= Math.floor(changed / 1000))
|
||||
for (const r of says) {
|
||||
const one = v?.rules?.[r.id]
|
||||
const fix = `raea goal judge${j.contract?.name ? ` --goal ${j.contract.name}` : ""}`
|
||||
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): string {
|
||||
const rules = saysOf(g).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
|
||||
}
|
||||
|
||||
export const BY = ["claude", "kimi", "clef"] as const
|
||||
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
|
||||
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
|
||||
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
|
||||
|
||||
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
|
||||
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
|
||||
const all = made(dir)
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of saysOf(g)) {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
const files = named.length ? named : all.slice(0, CLEF_PIECES)
|
||||
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 }[]>()
|
||||
for (const k of groups.values()) {
|
||||
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
|
||||
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 saysOf(g)) {
|
||||
const a = got.get(r.id) ?? []
|
||||
const open = a.filter((x) => !x.pass)
|
||||
rules[r.id] = !pieces.get(r.id)?.length
|
||||
? { pass: false, why: "clef watches and hears a piece, and this rule names no file on disk while out/ holds no video: name the file in the rule, or judge it --by claude where Claude Code is signed in" }
|
||||
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||
}
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
|
||||
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) throw 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 rows
|
||||
}
|
||||
|
||||
/** one fresh critic over a goal's `says` rules (`raea goal judge`): 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 function judge(g: Contract, dir: string, by: string): Verdict {
|
||||
if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
|
||||
const p = prompt(g, dir)
|
||||
const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
|
||||
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
|
||||
let words = String(r.stdout ?? "")
|
||||
try {
|
||||
const o = JSON.parse(words)
|
||||
if (typeof o.result === "string") words = o.result
|
||||
} catch {}
|
||||
const v = lastVerdict(words)
|
||||
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
|
||||
return keep(g, dir, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) })
|
||||
}
|
||||
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)))
|
||||
@@ -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],
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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 [] } })
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import type { Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { type Faces, Unmet } from "../media.ts"
|
||||
import { cutOf } from "./cut.ts"
|
||||
|
||||
@@ -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(" ")
|
||||
@@ -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) */
|
||||
@@ -36,8 +35,6 @@ const SUBJECT_MIN = 0.25
|
||||
const FACE_IN_SHOT = 0.05
|
||||
/** a thing this share of the frame's area or more is what the shot shows (a dog at someone's feet, a phone held up) */
|
||||
const THING_MIN = 0.006
|
||||
/** words in the shot are hidden (text over them an error) when a text covers this share of them or more */
|
||||
export const SIGN_HIDDEN = 0.3
|
||||
/** a text is badly placed when it costs this much or more, and a clear place costs this much less */
|
||||
export const BAD = 1.6
|
||||
export const BETTER = 1.2
|
||||
@@ -125,11 +122,7 @@ function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[]
|
||||
const [x, y, w, h] = [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
|
||||
const ix = Math.max(0, Math.min(b[0] + b[2], x + w) - Math.max(b[0], x))
|
||||
const iy = Math.max(0, Math.min(b[1] + b[3], y + h) - Math.max(b[1], y))
|
||||
if (!(ix * iy > 0.12 * Math.min(w * h, b[2] * b[3]))) continue
|
||||
// words in the shot are covered when a good part of them is hidden; a caption over a sign's top edge leaves them read
|
||||
// (12-05, run 28: Dutch's "Would" and "this." sat on the edge of a handwritten sign, its words all clear)
|
||||
if (t[4] === "text") out.add(ix * iy >= SIGN_HIDDEN * w * h ? "words in the shot (a sign)" : "the edge of a sign")
|
||||
else out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : `a ${t[4].replace(/_/g, " ")}`)
|
||||
if (ix * iy > 0.12 * Math.min(w * h, b[2] * b[3])) out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : t[4] === "text" ? "words in the shot (a sign)" : `a ${t[4].replace(/_/g, " ")}`)
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
@@ -262,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` })
|
||||
|
||||
@@ -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 })
|
||||
},
|
||||
|
||||
@@ -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 })
|
||||
})
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 } : {}) })
|
||||
}
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user