mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb4908243d | ||
|
|
95c6f119fc | ||
|
|
6878541985 | ||
|
|
b529274c3b | ||
|
|
0ed4fa9b27 | ||
|
|
53401e075e | ||
|
|
cec3a10d78 | ||
|
|
2695da12f5 | ||
|
|
3033dedc2c | ||
|
|
dff1371cb0 | ||
|
|
fc962be9cb | ||
|
|
6306036238 | ||
|
|
9a4a4683db | ||
|
|
1f90722f95 | ||
|
|
a0d102bdbc | ||
|
|
66caf538dc | ||
|
|
3b75c22100 | ||
|
|
3a6e207f81 | ||
|
|
9a22e47fcc | ||
|
|
d4cc49ffcb | ||
|
|
35285f3c80 | ||
|
|
55c577ba42 | ||
|
|
d2f6a81563 | ||
|
|
14964235a8 | ||
|
|
90af3c0338 | ||
|
|
0a8379c123 | ||
|
|
bec1ab1947 | ||
|
|
c261ecdfbc | ||
|
|
712e5ba3a0 | ||
|
|
51e2d87c76 | ||
|
|
9fed1783dc | ||
|
|
23918c2c23 | ||
|
|
c5c87e2cfb | ||
|
|
743b35677c | ||
|
|
80562f9ef7 | ||
|
|
5f407a1cc2 | ||
|
|
b0437d2d08 | ||
|
|
230f817543 | ||
|
|
8dfd71eb92 | ||
|
|
2cbfa8c608 | ||
|
|
c3765a13bb | ||
|
|
5301beb62f | ||
|
|
5c2a524369 | ||
|
|
4044e442c2 | ||
|
|
d4e39d41f0 | ||
|
|
c7e5534d38 | ||
|
|
788444e127 | ||
|
|
5b72d2e4dc | ||
|
|
33d34e51b5 | ||
|
|
7cd22cecfc | ||
|
|
76e6b00e04 | ||
|
|
88cacbe7f7 | ||
|
|
4fd7210cfe |
No files matched your search
@@ -107,5 +107,7 @@ sdk/raea/.scratch-*/
|
||||
# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/)
|
||||
/examples/materials/wear/media/
|
||||
/examples/materials/wear/assets/
|
||||
# a playable example's generated sounds, made beside it the first time it's rendered or exported (raea's asset store)
|
||||
/examples/playables/assets/
|
||||
# tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path)
|
||||
/sdk/raea/bench/bevy-parity/**/assets
|
||||
Generated
+4
@@ -13820,6 +13820,7 @@ dependencies = [
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
@@ -13978,7 +13979,10 @@ dependencies = [
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"raea-core-fonts",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"regex",
|
||||
|
||||
@@ -213,7 +213,8 @@ 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 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 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 Some(ratio) = ratio else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.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]], 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 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 (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![], 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![], colors: 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![], 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![], colors: 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,10 +425,11 @@ 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(), 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(), colors: vec![], 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,6 +43,10 @@ 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,
|
||||
}
|
||||
@@ -57,6 +61,15 @@ 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
|
||||
@@ -114,18 +127,21 @@ 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(), color: String::new(), size: 0.0 },
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: 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 = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
r.color = color;
|
||||
r.size = x["size"].as_f64().unwrap_or(0.0);
|
||||
next.push(r);
|
||||
}
|
||||
@@ -294,3 +310,21 @@ 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 {
|
||||
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,6 +15,8 @@ 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 [--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)";
|
||||
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)";
|
||||
|
||||
/// 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); 31] = [
|
||||
pub(crate) const FLAGS: [(&str, bool); 30] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
@@ -51,7 +51,6 @@ pub(crate) const FLAGS: [(&str, bool); 31] = [
|
||||
("--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 [--by kimi|claude]`
|
||||
//! has a fresh agent session 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` 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
|
||||
//! 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,30 +99,9 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
/// 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)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
@@ -133,12 +112,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 [--by kimi|claude]`
|
||||
/// `raea fingerprint read PROJECT`
|
||||
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 = flag(args, "--by").unwrap_or("kimi");
|
||||
let by = "agent";
|
||||
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);
|
||||
@@ -148,15 +127,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(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
let text = ask(&project, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
|
||||
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 {by}, 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 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()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
@@ -285,7 +264,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, "kimi");
|
||||
fold(&mut n, &fp, &ans, "agent");
|
||||
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");
|
||||
|
||||
+17
-72
@@ -1,8 +1,9 @@
|
||||
//! 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
|
||||
//! 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
|
||||
//! its reading as the eye clef is calibrated against.
|
||||
|
||||
use std::path::Path;
|
||||
@@ -11,7 +12,10 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::rubric::{BAR, scores};
|
||||
|
||||
pub const BY: [&str; 2] = ["kimi", "claude"];
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -125,70 +129,11 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
|
||||
(out, defects, photo)
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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>()))
|
||||
}
|
||||
@@ -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 --by kimi|claude` records a
|
||||
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
|
||||
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -46,9 +46,10 @@ 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);
|
||||
// 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)?;
|
||||
// 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)?;
|
||||
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,8 +2,10 @@
|
||||
//! 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] [--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 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 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,
|
||||
@@ -22,7 +24,6 @@ pub fn kind_gates(kind: &str) -> bool {
|
||||
}
|
||||
pub mod rubric;
|
||||
|
||||
pub use agent::BY;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -30,7 +31,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] [--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)";
|
||||
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)";
|
||||
|
||||
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
|
||||
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
|
||||
@@ -107,12 +108,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 = flag(args, "--by").unwrap_or_else(|| "clef".into());
|
||||
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
|
||||
if by != "clef" {
|
||||
if dry {
|
||||
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
|
||||
}
|
||||
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
|
||||
let v = agent::ask(kind, &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"]}));
|
||||
}
|
||||
@@ -190,7 +191,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 { format!("{by} cli") };
|
||||
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
|
||||
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, "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)"));
|
||||
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)"));
|
||||
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
|
||||
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
|
||||
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -142,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
let what = match job.make.kind {
|
||||
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
|
||||
goal::Kind::Shot => "raea make framing --out review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules | goal::Kind::Playable => "raea render EDIT.tsx --review review/r1",
|
||||
};
|
||||
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use image::{Rgba, RgbaImage};
|
||||
use raea_core_brief::{make::Make, read};
|
||||
use raea_core_brief::{goal::Goal as Make, read};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
|
||||
// a shot with no composition can't be framed, and says what's needed
|
||||
let d = dir("framing");
|
||||
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
|
||||
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
}
|
||||
|
||||
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
|
||||
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
|
||||
|
||||
#[test]
|
||||
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
|
||||
use raea_core_brief::make::Object;
|
||||
use raea_core_brief::goal::Object;
|
||||
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
|
||||
// long across (x) where the plan's is front to back (z): a quarter turn
|
||||
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
|
||||
|
||||
@@ -14,4 +14,9 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "1"
|
||||
serde_json = "1"
|
||||
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
|
||||
raea-core-fonts = { path = "../../core/fonts" }
|
||||
# a game's generated sounds made at export, as a render makes them, and FFmpeg to compress them (PA6)
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
base64 = "0.22"
|
||||
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
|
||||
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
|
||||
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
|
||||
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
|
||||
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
|
||||
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
|
||||
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
|
||||
//! own default family is Inter, the native page's.
|
||||
|
||||
use base64::Engine;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The family a page with no family of its own draws in
|
||||
const DEFAULT: &str = "Inter";
|
||||
|
||||
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
|
||||
/// bundled family raea draws it as; the default first
|
||||
pub fn families(script: &str) -> Vec<(String, &'static str)> {
|
||||
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
|
||||
let res = [
|
||||
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
|
||||
r#"font-family\s*:\s*([^;"'`}]+)"#,
|
||||
];
|
||||
for re in res {
|
||||
let re = regex::Regex::new(re).expect("a valid pattern");
|
||||
for cap in re.captures_iter(script) {
|
||||
for name in cap[1].split(',') {
|
||||
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
|
||||
if let Some(c) = raea_core_fonts::canonical(name) {
|
||||
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
|
||||
out.push((name.to_string(), c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
|
||||
/// the halfway weight to the lighter face
|
||||
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
|
||||
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
|
||||
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
|
||||
if *f == canonical {
|
||||
by_style
|
||||
.entry(st)
|
||||
.or_default()
|
||||
.push((w.parse().unwrap_or(400), bytes));
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (st, mut ws) in by_style {
|
||||
ws.sort_by_key(|(w, _)| *w);
|
||||
let mut lo = 1u16;
|
||||
for (i, (w, bytes)) in ws.iter().enumerate() {
|
||||
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
|
||||
out.push(((lo, hi), st, *bytes));
|
||||
lo = hi + 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
|
||||
/// page's default family
|
||||
pub fn style(script: &str) -> String {
|
||||
let b64 = base64::engine::general_purpose::STANDARD;
|
||||
let mut css = String::from("<style>\n");
|
||||
for (name, canonical) in families(script) {
|
||||
for ((lo, hi), st, bytes) in faces(canonical) {
|
||||
css.push_str(&format!(
|
||||
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
|
||||
name.replace('"', ""),
|
||||
b64.encode(bytes)
|
||||
));
|
||||
}
|
||||
}
|
||||
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
|
||||
css
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
|
||||
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
|
||||
let f = families(script);
|
||||
assert_eq!(
|
||||
f,
|
||||
[
|
||||
("Inter".to_string(), "inter"),
|
||||
("Helvetica Neue".into(), "inter"),
|
||||
("Georgia".into(), "eb-garamond")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_weight_takes_the_face_the_native_page_takes() {
|
||||
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
|
||||
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
|
||||
// the native pick for each weight is the face whose range holds it
|
||||
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
|
||||
let native = raea_core_fonts::face("Inter", w, false).unwrap();
|
||||
let ours = faces("inter")
|
||||
.into_iter()
|
||||
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
|
||||
.unwrap()
|
||||
.2;
|
||||
assert!(native == ours, "weight {w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_style_holds_inter_and_sets_the_default() {
|
||||
let css = style("var x=1;");
|
||||
assert_eq!(css.matches("@font-face").count(), 3);
|
||||
assert!(
|
||||
css.contains("font-weight:801 1000")
|
||||
&& css.contains("html,body{font-family:\"Inter\"}")
|
||||
);
|
||||
assert!(css.len() < 110_000, "{} bytes", css.len());
|
||||
}
|
||||
}
|
||||
+170
-18
@@ -1,15 +1,19 @@
|
||||
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
|
||||
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
|
||||
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
|
||||
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
|
||||
//! in the script; three.js only when the lint found a 3D kind, PA15; a sound player only for a game with sound, Tone.js
|
||||
//! only for a raea/tone graph, and its generated sounds made and carried in the page, PA6), and written as each
|
||||
//! network's page or ZIP (pages.rs), each checked against its cap.
|
||||
mod fonts;
|
||||
mod lint;
|
||||
mod pages;
|
||||
mod sound;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
|
||||
|
||||
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
|
||||
@@ -19,12 +23,13 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
|
||||
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone
|
||||
/// graph): the project's own (`raea add [email protected]`), else the copy beside sdk/playable or sdk/r3f in raea's own files
|
||||
fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<PathBuf> {
|
||||
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
|
||||
let mut d = game.parent();
|
||||
while let Some(dir) = d {
|
||||
if dir.join("node_modules/three/package.json").is_file() {
|
||||
if has(dir) {
|
||||
return Ok(dir.to_path_buf());
|
||||
}
|
||||
d = dir.parent();
|
||||
@@ -32,21 +37,80 @@ fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
["sdk/playable", "sdk/r3f"]
|
||||
.iter()
|
||||
.map(|p| home.join(p))
|
||||
.find(|d| d.join("node_modules/three/package.json").is_file())
|
||||
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
|
||||
.find(|d| has(d))
|
||||
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
|
||||
}
|
||||
|
||||
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
|
||||
fn ecs_wasm(home: &Path) -> R<String> {
|
||||
use base64::Engine;
|
||||
let f = home.join("sdk/playable/src/host/ecs.wasm");
|
||||
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(b))
|
||||
}
|
||||
|
||||
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Sounds {
|
||||
None,
|
||||
Media,
|
||||
Tone,
|
||||
}
|
||||
|
||||
/// 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)
|
||||
with_3d: bool,
|
||||
sounds: Sounds,
|
||||
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
|
||||
ecs: bool,
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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"))));
|
||||
}
|
||||
if sounds != Sounds::None {
|
||||
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
|
||||
}
|
||||
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" };
|
||||
e.push_str(&match sounds {
|
||||
Sounds::None if with_3d => "start(bevy3d);\n".into(),
|
||||
Sounds::None => "start();\n".into(),
|
||||
Sounds::Media => format!("start({d3}, sound());\n"),
|
||||
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
|
||||
});
|
||||
e
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host/main.tsx");
|
||||
if !host.is_file() {
|
||||
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
|
||||
let Carry { with_3d, sounds, .. } = carry;
|
||||
let host = home.join("sdk/playable/src/host");
|
||||
if !host.join("main.tsx").is_file() {
|
||||
return Err(format!("{}: raea's playable host isn't there", host.display()));
|
||||
}
|
||||
let three = three_dir(game, home)?;
|
||||
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
|
||||
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
|
||||
let alias = format!("three/={}", three.display());
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
|
||||
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
|
||||
if with_3d {
|
||||
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]);
|
||||
}
|
||||
if sounds == Sounds::Tone {
|
||||
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
|
||||
}
|
||||
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
|
||||
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
|
||||
let _ = std::fs::remove_file(&out);
|
||||
js
|
||||
@@ -66,7 +130,12 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
}
|
||||
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
|
||||
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
|
||||
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
|
||||
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
|
||||
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
|
||||
if name.is_empty() || name.contains(['/', '\\']) {
|
||||
return Err(format!("--name {name:?}: a file name, no folders"));
|
||||
}
|
||||
|
||||
let mut report = Vec::new();
|
||||
let found = lint::lint(&game)?;
|
||||
@@ -83,16 +152,45 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let js = bundle(&game, &raea_io_home::home())?;
|
||||
let is = |k: &str| found.sound[k].as_bool() == Some(true);
|
||||
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
|
||||
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
|
||||
let home = raea_io_home::home();
|
||||
let js = bundle(&game, &home, carry)?;
|
||||
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
|
||||
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
|
||||
let made = sound::make(&game, &assets)?;
|
||||
report.push(match sounds {
|
||||
Sounds::None => "sound: none".into(),
|
||||
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
|
||||
});
|
||||
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
|
||||
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
|
||||
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
|
||||
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
|
||||
let js = format!("{ecs}{}{js}", made.script);
|
||||
// the faces the native page draws with, for the families the game names (PA8)
|
||||
let style = fonts::style(&js);
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut over = false;
|
||||
let mut written = Vec::new();
|
||||
for net in networks {
|
||||
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
|
||||
let w = pages::write(net, &name, &script, &out, orientation)?;
|
||||
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
|
||||
let ok = w.bytes <= pages::CAP;
|
||||
over |= !ok;
|
||||
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
|
||||
written.push(w);
|
||||
}
|
||||
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
|
||||
let manifest = serde_json::json!({
|
||||
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
|
||||
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
|
||||
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
|
||||
"cap": pages::CAP,
|
||||
});
|
||||
let mf = out.join(format!("{name}.playable.json"));
|
||||
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
|
||||
if over {
|
||||
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
|
||||
return Err(report.join("\n"));
|
||||
@@ -100,3 +198,57 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
|
||||
Ok(report.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Carry, Sounds, entry};
|
||||
use std::path::Path;
|
||||
|
||||
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
|
||||
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_game_starts_with_no_drawer() {
|
||||
let e = e(false, Sounds::None, false);
|
||||
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
|
||||
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}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
|
||||
let e = e(false, Sounds::None, true);
|
||||
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/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/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");
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ pub struct Found {
|
||||
pub kinds: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
pub refusals: Vec<String>,
|
||||
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
|
||||
pub sound: Value,
|
||||
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
|
||||
pub ecs: bool,
|
||||
}
|
||||
|
||||
const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
@@ -27,7 +31,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
|
||||
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
|
||||
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
|
||||
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
|
||||
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
|
||||
(r"<(Video|OffthreadVideo)\b", "<Video> plays footage through the native media stack, which a playable doesn't carry: render the clip as frames or an image sequence"),
|
||||
];
|
||||
|
||||
/// The game's source and its compositions, judged
|
||||
@@ -48,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
let walked = match walk(game) {
|
||||
Ok(w) => w,
|
||||
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
|
||||
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let comps: Vec<Comp> = walked["comps"]
|
||||
@@ -73,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
|
||||
for k in strings("refused") {
|
||||
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
|
||||
}
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
|
||||
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
|
||||
}
|
||||
|
||||
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
|
||||
|
||||
@@ -43,9 +43,10 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, head, body, script);
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
|
||||
/// `style` (the fonts, fonts.rs) first in the head
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
|
||||
let file = match network {
|
||||
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
|
||||
"google" => {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! A playable's generated sounds (docs/playables.feature PA6). A game's `sao(...)` effects and TokenSynth notes are
|
||||
//! made by the native renderer the first time a render meets them (runtime/sound: raea's asset store, beside the edit).
|
||||
//! A playable makes no requests, so the export makes each one the game describes (sdk/playable walk.ts lists them,
|
||||
//! each with its model, prompt, seed and params as the renderer passes them, so the store's cache is shared with
|
||||
//! renders) and carries it in the page as a data URL under its src (`asset:sao/...`), AAC at 64 kb/s mono when FFmpeg
|
||||
//! is there (a two-second effect is about 16 KB), else the file as made. The host plays it after the first touch.
|
||||
|
||||
use super::R;
|
||||
use base64::Engine;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// The page's sounds: a script that sets `__raeaSounds` (src -> data URL), how many and their bytes
|
||||
pub struct Made {
|
||||
pub script: String,
|
||||
pub count: usize,
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
/// Each generated sound the game describes, made (or found made) beside the game and inlined
|
||||
pub fn make(game: &Path, assets: &[Value]) -> R<Made> {
|
||||
let store = raea_io_assets::Store::beside(game);
|
||||
let ffmpeg = raea_io_assets::ffmpeg_tool("ffmpeg", false).ok();
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut bytes = 0;
|
||||
for a in assets {
|
||||
let (Some(src), Some(model), Some(prompt)) =
|
||||
(a["src"].as_str(), a["model"].as_str(), a["prompt"].as_str())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let seed = a["seed"].as_u64().unwrap_or(1);
|
||||
let made = store
|
||||
.make(model, prompt, seed, &a["params"])
|
||||
.map_err(|e| format!("the sound {model} \"{prompt}\" couldn't be made: {e}"))?;
|
||||
let file = store.path(&made);
|
||||
let (mime, data) = match ffmpeg.as_deref().and_then(|f| aac(f, &file)) {
|
||||
Some(d) => ("audio/mp4", d),
|
||||
None => (
|
||||
mime(&made.ext),
|
||||
std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?,
|
||||
),
|
||||
};
|
||||
bytes += data.len();
|
||||
out.insert(
|
||||
src.into(),
|
||||
Value::from(format!(
|
||||
"data:{mime};base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(&data)
|
||||
)),
|
||||
);
|
||||
}
|
||||
let count = out.len();
|
||||
let script = if count == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
format!("globalThis.__raeaSounds={};", Value::Object(out))
|
||||
};
|
||||
Ok(Made {
|
||||
script,
|
||||
count,
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// The file as AAC in an MP4 (what WebKit and every other browser decode), mono at 64 kb/s
|
||||
fn aac(ffmpeg: &Path, file: &Path) -> Option<Vec<u8>> {
|
||||
let to = std::env::temp_dir().join(format!("raea-playable-sound-{}.m4a", std::process::id()));
|
||||
let ok = std::process::Command::new(ffmpeg)
|
||||
.args(["-v", "error", "-y", "-i"])
|
||||
.arg(file)
|
||||
.args(["-vn", "-ac", "1", "-c:a", "aac", "-b:a", "64k", "-f", "mp4"])
|
||||
.arg(&to)
|
||||
.status()
|
||||
.is_ok_and(|s| s.success());
|
||||
let data = if ok { std::fs::read(&to).ok() } else { None };
|
||||
let _ = std::fs::remove_file(&to);
|
||||
data
|
||||
}
|
||||
|
||||
fn mime(ext: &str) -> &'static str {
|
||||
match ext {
|
||||
"mp3" => "audio/mpeg",
|
||||
"ogg" => "audio/ogg",
|
||||
"flac" => "audio/flac",
|
||||
"m4a" | "mp4" | "aac" => "audio/mp4",
|
||||
_ => "audio/wav",
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ mkdir -p "$OUT"
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
expected() { case $1 in
|
||||
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
|
||||
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
|
||||
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
@@ -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 = "Beat")]
|
||||
#[ts(rename = "CutBeat")]
|
||||
pub struct Beat {
|
||||
/// where it starts, in seconds from the cut's start (0 for the first)
|
||||
pub at: f64,
|
||||
|
||||
+18
-5
@@ -1,8 +1,8 @@
|
||||
//! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief" before anything is
|
||||
//! built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that belong
|
||||
//! together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), and
|
||||
//! rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before
|
||||
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that
|
||||
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a
|
||||
//! playable (a game exported as a playable ad, playable.rs), and rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
|
||||
//! size and whether it came from the reference or was invented; every dial its value, where the value came from, and
|
||||
//! what it meant here. `raea goal check` (sdk/goal) holds each goal to it.
|
||||
|
||||
@@ -25,6 +25,9 @@ pub enum Kind {
|
||||
Cut,
|
||||
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
|
||||
Rules,
|
||||
/// a game exported as a playable ad by `raea playable`: each network's page, the preview, both orientations unless
|
||||
/// the brief says one (playable.rs, docs/playables.feature PA19)
|
||||
Playable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
@@ -74,6 +77,8 @@ pub struct Goal {
|
||||
pub rounds: Option<u32>,
|
||||
/// a cut job's contract: the brief as rules (cut.rs)
|
||||
pub cut: Option<crate::cut::Cut>,
|
||||
/// a playable job's game, networks and orientation (playable.rs)
|
||||
pub playable: Option<crate::playable::Playable>,
|
||||
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
|
||||
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
#[serde(default)]
|
||||
@@ -227,7 +232,7 @@ impl Kind {
|
||||
/// as brief.ts writes it, and as raea judge's rubrics are named
|
||||
pub fn name(self) -> &'static str {
|
||||
// in the enum's order
|
||||
["scene", "kit", "shot", "cut", "rules"][self as usize]
|
||||
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +244,7 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
|
||||
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
|
||||
Kind::Cut => &["look"],
|
||||
Kind::Rules => &[],
|
||||
Kind::Playable => &["look"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +282,7 @@ fn by_kind(m: &Goal) -> Vec<String> {
|
||||
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
|
||||
// only its `file` rules, added above
|
||||
Kind::Rules => vec![],
|
||||
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +314,12 @@ pub fn doctor(m: &Goal) -> Vec<String> {
|
||||
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
match (&m.playable, m.kind) {
|
||||
(Some(p), Kind::Playable) => out.extend(crate::playable::doctor(p)),
|
||||
(None, Kind::Playable) => out.push("no `playable`: the game's TSX (`game`), and its networks and orientation when the brief names them".into()),
|
||||
(Some(_), k) => out.push(format!("`playable` is for a playable job, not a {k:?}: drop it, or make this `playable({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
out.extend(crate::rules::doctor(&m.rules));
|
||||
if m.kind == Kind::Rules {
|
||||
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
|
||||
|
||||
+22
-4
@@ -7,6 +7,7 @@ pub mod brief;
|
||||
pub mod cut;
|
||||
pub mod goal;
|
||||
pub mod parts;
|
||||
pub mod playable;
|
||||
pub mod rules;
|
||||
pub mod script;
|
||||
pub mod taste;
|
||||
@@ -30,18 +31,35 @@ macro_rules! decls {
|
||||
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
|
||||
}
|
||||
|
||||
/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
|
||||
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
|
||||
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them)
|
||||
pub const GOAL_FILE: &str = "brief-goal.gen";
|
||||
|
||||
/// The TypeScript declarations of every schema, two files' worth (a file stays under 500 lines, tools/size.sh):
|
||||
/// sdk/raea/src/brief.gen.ts is this, the goal's (`goal_declarations`) re-exported from it, each checked by a test,
|
||||
/// and `raea/brief` (sdk/raea/src/brief.ts) types its builders with them, so the declarations ship with the SDK.
|
||||
pub fn declarations() -> String {
|
||||
let cfg = Config::new();
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
|
||||
let mut out = vec![format!(
|
||||
"// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.\nimport type {{ Goals }} from \"./{GOAL_FILE}\";\nexport type * from \"./{GOAL_FILE}\";"
|
||||
)];
|
||||
out.extend(decls!(cfg;
|
||||
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
|
||||
script::Script, script::Scene, script::Beat, script::Line,
|
||||
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
|
||||
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
}
|
||||
|
||||
/// 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()];
|
||||
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::Phrase, cut::Cta, cut::Open,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! A playable goal (docs/playables.feature PA19): a raea game exported as a playable ad by `raea playable`, held to its
|
||||
//! pages. The game is one TSX that renders as the video ad and exports for each network; the goal names it, the
|
||||
//! networks it ships to and its orientation (both, unless the brief says one), and its deliverables are what the export
|
||||
//! writes into out/playable/: each network's page or ZIP, the preview, and the export's manifest, which raea goal's
|
||||
//! playable pack reads (sizes, compositions, when it was exported).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
|
||||
/// The networks `raea playable` writes for (apps/playable pages.rs NETWORKS, preview last)
|
||||
pub const NETWORKS: &[&str] = &[
|
||||
"applovin",
|
||||
"unity",
|
||||
"google",
|
||||
"meta",
|
||||
"moloco",
|
||||
"mintegral",
|
||||
"tiktok",
|
||||
"liftoff",
|
||||
];
|
||||
/// The networks whose package is a ZIP (the rest are one HTML page)
|
||||
const ZIPPED: &[&str] = &["google", "mintegral", "tiktok"];
|
||||
/// Where the export writes, relative to the brief
|
||||
pub const OUT: &str = "out/playable";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[ts(rename = "PlayableOrientation")]
|
||||
pub enum Orientation {
|
||||
/// a portrait and a landscape composition, the host playing the one nearest the screen
|
||||
Both,
|
||||
Portrait,
|
||||
Landscape,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields, rename = "PlayableGoal")]
|
||||
pub struct Playable {
|
||||
/// the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
|
||||
pub game: String,
|
||||
/// the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
|
||||
pub name: Option<String>,
|
||||
/// the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
|
||||
/// left out. The preview page is always made: it's what the review plays
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub networks: Vec<String>,
|
||||
/// both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
|
||||
pub orientation: Option<Orientation>,
|
||||
/// [least, most] seconds of play before the end card (15 to 60 by default)
|
||||
pub seconds: Option<[f64; 2]>,
|
||||
/// the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
|
||||
pub video: Option<bool>,
|
||||
}
|
||||
|
||||
/// The name its files land as: its own, else the game's file name, as `raea playable` names them
|
||||
pub fn name(p: &Playable) -> String {
|
||||
p.name.clone().unwrap_or_else(|| {
|
||||
std::path::Path::new(&p.game)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("playable")
|
||||
.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
/// The networks it ships to, in raea's order
|
||||
pub fn networks(p: &Playable) -> Vec<&'static str> {
|
||||
NETWORKS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|n| p.networks.is_empty() || p.networks.iter().any(|m| m == n))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the export must have written: each network's page or ZIP, the preview and the manifest, and the video ad
|
||||
pub fn deliverables(p: &Playable) -> Vec<String> {
|
||||
let n = name(p);
|
||||
let mut out: Vec<String> = networks(p)
|
||||
.iter()
|
||||
.map(|net| {
|
||||
format!(
|
||||
"{OUT}/{n}-{net}.{}",
|
||||
if ZIPPED.contains(net) { "zip" } else { "html" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out.push(format!("{OUT}/{n}-preview.html"));
|
||||
out.push(format!("{OUT}/{n}.playable.json"));
|
||||
if p.video == Some(true) {
|
||||
out.push(format!("out/cuts/{n}_9x16.mp4"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the playable still lacks before it can be built against
|
||||
pub fn doctor(p: &Playable) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if !p.game.ends_with(".tsx") {
|
||||
out.push(format!(
|
||||
"`game` {:?}: the game's TSX beside the brief (playable.tsx)",
|
||||
p.game
|
||||
));
|
||||
}
|
||||
if let Some(n) = p.name.as_deref().filter(|n| !crate::goal::is_name(n)) {
|
||||
out.push(format!("playable name `{n}`: names are [a-z0-9_]"));
|
||||
}
|
||||
for n in p
|
||||
.networks
|
||||
.iter()
|
||||
.filter(|n| !NETWORKS.contains(&n.as_str()))
|
||||
{
|
||||
out.push(format!(
|
||||
"network `{n}` isn't one raea exports to ({})",
|
||||
NETWORKS.join(", ")
|
||||
));
|
||||
}
|
||||
if let Some([a, b]) = p.seconds {
|
||||
if !(a > 0.0 && a <= b) {
|
||||
out.push(format!("seconds [{a}, {b}]: least then most, both over 0"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+45
-7
@@ -1,14 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn declarations_match_the_committed_file() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
|
||||
let now = declarations();
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
std::fs::write(path, &now).unwrap();
|
||||
fn declarations_match_the_committed_files() {
|
||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src");
|
||||
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] {
|
||||
let path = format!("{dir}/{file}");
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
std::fs::write(&path, &now).unwrap();
|
||||
}
|
||||
let committed = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
assert!(committed == now, "sdk/raea/src/{file} is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
|
||||
let lines = now.lines().count();
|
||||
assert!(lines <= 500, "sdk/raea/src/{file} is {lines} lines: split it (tools/size.sh)");
|
||||
}
|
||||
let committed = std::fs::read_to_string(path).unwrap_or_default();
|
||||
assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -153,3 +157,37 @@ fn several_goals_are_a_workflow_and_each_is_held_to_its_rules() {
|
||||
let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap();
|
||||
assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_playable_goal_delivers_each_networks_page_the_preview_and_the_manifest() {
|
||||
let g: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"a runner for a tea brand","playable":{"game":"playable.tsx","networks":["applovin","google"],"video":true}}"#).unwrap();
|
||||
assert_eq!(
|
||||
crate::goal::deliverables(&g),
|
||||
[
|
||||
"out/playable/playable-applovin.html",
|
||||
"out/playable/playable-google.zip",
|
||||
"out/playable/playable-preview.html",
|
||||
"out/playable/playable.playable.json",
|
||||
"out/cuts/playable_9x16.mp4"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
crate::goal::doctor(&g).is_empty(),
|
||||
"{:?}",
|
||||
crate::goal::doctor(&g)
|
||||
);
|
||||
// both orientations unless the brief names one: `raea playable`'s own default
|
||||
assert_eq!(g.playable.as_ref().unwrap().orientation, None);
|
||||
let bad: crate::goal::Goal = serde_json::from_str(
|
||||
r#"{"kind":"playable","aim":"x","playable":{"game":"game.ts","networks":["vungle"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let d = crate::goal::doctor(&bad).join("\n");
|
||||
assert!(d.contains("game.ts") && d.contains("vungle"), "{d}");
|
||||
let none: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"x"}"#).unwrap();
|
||||
assert!(
|
||||
crate::goal::doctor(&none)
|
||||
.iter()
|
||||
.any(|l| l.starts_with("no `playable`"))
|
||||
);
|
||||
}
|
||||
@@ -99,3 +99,27 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
When StreetTalk's four Drive syncs run from empty
|
||||
Then every file has a picture, a description and tags; the three client folders are related to their client
|
||||
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
|
||||
|
||||
Rule: every video has a light copy to watch and cut from
|
||||
Scenario: IG14. A video's proxy is made once, from the download its index already makes
|
||||
(built 12-02: raea-platform index-run.ts submitProxy/proxyDue, sdk/cloud/deploy/modal/proxy.py)
|
||||
Given a video in a library, uploaded or synced from Drive
|
||||
Then raea makes a 540p proxy of it on Modal (540 lines on the short side and never more than the original,
|
||||
H.264 CRF 28 with a keyframe every second, AAC 96 kbps, faststart) from the same address its index job
|
||||
fetches, so a synced file is downloaded through its tool once for both
|
||||
And the proxy is kept in R2 by the original's SHA-256, written through a ticket for the workspace's proxies
|
||||
alone (the job holds no raea credential), so footage kept twice is made once
|
||||
And an original already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy
|
||||
And a library indexed before proxies gets them a few at a time, 8 running a workspace
|
||||
|
||||
Scenario: IG15. People watch the proxy
|
||||
When a person opens a video in the library
|
||||
Then it plays from its proxy: no copy of a Drive original through its tool, and no 4K HEVC in the browser
|
||||
And its original stays one click away (Open)
|
||||
|
||||
Scenario: IG16. Agents look and cut from proxies, and finish from originals
|
||||
When an agent searches its libraries for footage
|
||||
Then it finds videos by what's in them (what's seen, heard and said, with the seconds where) and by name
|
||||
And each video comes with its proxy, whose times are the original's, to fetch, watch, transcribe and rough-cut
|
||||
And the original (an upload's link, or a synced file through library_original) is fetched only for the master
|
||||
And drafts on the farm read clip copies at the size they're drawn (CR36); masters read the originals
|
||||
@@ -103,6 +103,20 @@ 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
|
||||
|
||||
@@ -353,3 +353,14 @@ notes and is worth shipping without it: a person gets word scores, checks and bo
|
||||
5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines
|
||||
of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer
|
||||
(100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999.
|
||||
6. **Pro and Studio include checks and content intelligence** (Shane, 11-20). Each month's pool (about 8,000 frames
|
||||
checked on Pro, ten times that on Studio) stops when it's spent and is never billed past. It pays for two things:
|
||||
- **clef-omni answering the fingerprint's questions** about a render's frames (`POST /v1/clef/ask`), so the agent
|
||||
reads answers in words and opens only the frames they flag. Its verdicts are another eye's (FP6d), and it serves
|
||||
the axes with no labels yet.
|
||||
- **content intelligence for references** (`GET /v1/intel/...`): public posts, videos, transcripts and ads, to find
|
||||
a videoform's references by what performs and keep them current (docs/videoform.md). A source's views and
|
||||
engagement are another eye's evidence too, never the person's taste. A reference found this way is still read
|
||||
once, as VF1 reads any link, and VF1's rights confirmation still applies.
|
||||
|
||||
Without a pool, everything here still works locally, and clef runs on the person's own Cloudflare account.
|
||||
@@ -13,9 +13,12 @@ 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`), 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.
|
||||
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.
|
||||
|
||||
```sh
|
||||
raea make component list
|
||||
@@ -23,6 +26,8 @@ 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
|
||||
```
|
||||
|
||||
@@ -31,7 +36,7 @@ raea make component add soft-blur-in
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
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")
|
||||
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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -41,6 +46,7 @@ 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 [--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)
|
||||
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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -54,7 +54,6 @@ 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,11 +54,13 @@ 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 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`.
|
||||
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.
|
||||
|
||||
```ts
|
||||
import { brief, rules } from "raea/brief"
|
||||
@@ -98,7 +100,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] [--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 judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
|
||||
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)
|
||||
```
|
||||
@@ -111,7 +113,6 @@ 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,8 +6,9 @@ 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 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
|
||||
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
|
||||
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,
|
||||
@@ -21,8 +22,8 @@ own.
|
||||
```sh
|
||||
raea render scene.tsx --review review/
|
||||
raea judge review/ --brief brief.ts
|
||||
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 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 eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
|
||||
raea judge calibrate
|
||||
```
|
||||
@@ -32,7 +33,7 @@ raea judge calibrate
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
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)
|
||||
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)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -42,11 +43,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,15 +20,16 @@ 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 three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
|
||||
project (`raea add [email protected]`).
|
||||
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.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
|
||||
raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
|
||||
@@ -38,6 +38,7 @@ 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"
|
||||
@@ -51,7 +52,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 --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)
|
||||
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)
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -63,6 +64,7 @@ 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. |
|
||||
@@ -76,6 +78,7 @@ 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. |
|
||||
|
||||
+96
-1
@@ -130,14 +130,35 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
|
||||
Rule: Next
|
||||
|
||||
@done
|
||||
Scenario: PA6. Sound in a playable
|
||||
Given networks keep sound off until the first touch and most players never turn it on
|
||||
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
|
||||
URLs after input.onFirstTouch, inside the size budget
|
||||
# Status 12-03: built. The lint no longer refuses <Audio>; its walk renders raea/tone's output beside each
|
||||
# composition (as the native entry does) and lists every generated sound the game describes (raea/asset keeps
|
||||
# them by src). The export makes each one with the asset store a render uses (apps/playable sound.rs), AAC at
|
||||
# 64 kb/s mono, and carries it as a data URL; it bundles host/sound.ts only for a game with sound and Tone.js
|
||||
# (host/tone.ts, the project's `raea add [email protected]`) only for a raea/tone graph, which it builds from Tone's
|
||||
# own classes and replays event by event. Sound starts in the first gesture, pauses while hidden and fades at
|
||||
# the end card; a frame stepped past on a slow phone still renders its page, so an <Sfx> on it sounds.
|
||||
# brick-rush now has a square-wave blip on the paddle and each brick and a generated crack (5 KB) under each
|
||||
# brick: 1,844 KB a page. Checked in WebKit: nothing sounds before the first touch; after it the context runs,
|
||||
# six raea/tone events started six oscillators and three cracks played, with no errors. tools/check.ts
|
||||
# reports sound and fails a page whose sound doesn't decode or never plays.
|
||||
|
||||
@done
|
||||
Scenario: PA8. Fonts inlined
|
||||
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
|
||||
Then the export inlines the subset of each font the page uses, as the native render draws it
|
||||
# Status 12-03: built (apps/playable fonts.rs). The native page draws with core/fonts' faces (Fontsource latin
|
||||
# subsets, Inter 400/700/900), each family it names aliased (Helvetica, Arial, SF Pro as Inter, Times as EB
|
||||
# Garamond) and each weight drawn by the nearest face. The export inlines, for the page's default (Inter) and
|
||||
# every family the game's script names that raea aliases, those same faces under that name, each face's weight
|
||||
# a range (Inter 1-550, 551-800, 801-1000) so the browser picks the face core/fonts `face` picks; a test holds
|
||||
# the two picks equal at every weight. Inter adds about 95 KB a page. Checked: brick-rush's weight-900 "Drag to
|
||||
# play" draws the same face and weight in WebKit as in `raea render --frame` (it drew Inter SemiBold, then a
|
||||
# serif, before); parity at frame 90 went from 8.4 to 6.1/255.
|
||||
|
||||
@done @needs:PA1
|
||||
Scenario: PA9. The playable is held to the native render
|
||||
@@ -164,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
|
||||
|
||||
@needs:PA9
|
||||
@done @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
|
||||
@@ -183,11 +204,51 @@ 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
|
||||
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
|
||||
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
|
||||
playable, its world drawn by the light renderer
|
||||
And the status (12-03): runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh,
|
||||
253 KB, 105 KB gzipped, no imports) into sdk/playable/src/host/ecs.wasm, with the hash of its sources beside it
|
||||
(apps/playable's test fails when runtime/ecs changes and it isn't rebuilt). The lint's walk sees a World made;
|
||||
the export carries the wasm and its entry loads host/ecs.ts before the game, so raea/ecs's calls (native.ts
|
||||
ecsCall) reach Bevy's world in the page as they reach it in the engine. World.copy() is a game's next state, and
|
||||
a store nothing holds frees its world. examples/playables/star-catch.tsx (spawn, aim and catch systems on a
|
||||
World) exports at 1,824 KB, plays to its end card in WebKit in both orientations with instant and held taps
|
||||
(7,724 calls answered), and its frame 150 holds the same stars, basket and score as `raea render --frame`
|
||||
(shading 17.0/255 over the 3D pixels, 0.19% of the frame past 8%: PA11's). conformance/ecs-wasm.test.ts runs
|
||||
one world's life on the wasm and on the TypeScript tables and finds them equal
|
||||
|
||||
@done
|
||||
Scenario: PA13. `raea playable`
|
||||
@@ -209,9 +270,16 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
|
||||
SKILL.md routes "a playable ad" to it
|
||||
|
||||
@done
|
||||
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):
|
||||
# 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.
|
||||
|
||||
Scenario: PA16. Playables in the review (raea cloud and the desktop)
|
||||
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
|
||||
@@ -241,4 +309,31 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
|
||||
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
|
||||
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
|
||||
# Status 12-03: the cause: the fast path (runtime/scene fast.rs `put`) rounded every column but a placement's
|
||||
# to 6 decimals, a light's rotation quaternion too, while the full rows (parts.rs) write it exact; a sun that
|
||||
# never moved differed on the first fast frame. A rotation and a colour column now go through exact on both.
|
||||
# runtime/scene/tests/live_light.rs panicked before the change and passes after; corpus.sh no longer skips
|
||||
# brick-rush.
|
||||
|
||||
@done
|
||||
Scenario: PA19. A brief that asks for a playable
|
||||
Given a brief's goal was a cut, a shot, a kit, a scene or rules, so a brief asking for a playable planned a cut
|
||||
Then core/brief has a playable goal (playable.rs: the game's TSX, its name, networks, orientation, seconds, and the
|
||||
video ad too when asked) whose deliverables are what `raea playable` writes into out/playable/: each network's
|
||||
page or ZIP, the preview and the export's manifest (NAME.playable.json)
|
||||
And raea goal's playable pack reads that manifest at publish and done: every page under the 5 MB cap, the
|
||||
compositions in the orientations asked for (both unless the brief names one), every network written, and the
|
||||
game unchanged since its export
|
||||
# Status 12-03: built (core/brief playable.rs, sdk/goal packs/playable.ts, `raea playable --name`, the manifest).
|
||||
# The generated declarations split in two to stay under 500 lines a file: brief.gen.ts re-exports
|
||||
# brief-goal.gen.ts. raea cloud's Ideate and brief form write `playable({ playable: {...} })` (raea-platform).
|
||||
|
||||
@done
|
||||
Scenario: PA20. A tap shorter than a frame still reaches the game
|
||||
Given the host handed the game only what was held when a step read the input, so a tap that went down and up
|
||||
between two steps never arrived (instant taps left the attract demo running)
|
||||
Then a press, a finger and a key count as held for the step after they went down, and the next step sees them
|
||||
let go
|
||||
# Status 12-03: #310 (host/input.ts). tools/check.ts plays with TAP_MS (0 is an instant tap, 150 by default);
|
||||
# every playable above was checked both ways.
|
||||
|
||||
+22
-6
@@ -12,8 +12,8 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
references, its vocabulary, its template and its rules. It's found, inherited, taught and shared as a
|
||||
fingerprint is.
|
||||
2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules
|
||||
into a controller's rule fields (DR4, DR8), its structure into a NAME.script.ts template, its references into
|
||||
brief.ts's `references` shape.
|
||||
into the section's `rules`, each in a taste line's shape (words, a check, its values, a level; DR4, DR8), its
|
||||
structure into a NAME.script.ts template, its references into brief.ts's `references` shape.
|
||||
3. A reference is read once, from the local drive or streamed from a URL, and never needed again: its per-shot rows,
|
||||
its vocabulary's vectors, its ranges, its structure and its rules are all that following and checking read.
|
||||
4. What stays the same across the references is the videoform; what varies is content. A rule's strength is its
|
||||
@@ -23,13 +23,26 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
6. Checks start from the composition: a videoform's rules run in `raea check PROJECT` before any render, and
|
||||
embeddings only for shots that changed.
|
||||
|
||||
Start here (the order of work, and where it touches what exists):
|
||||
- The order: VF1 and VF2 (a reference in, a videoform made), VF3 (each reference read once into the kept rows), then
|
||||
VF4 with VF12 (the ranges, judged on the test bench). That pair is the gate: it passes on at least five of the
|
||||
person's sets before VF1b's platform pages or anything in VF9-VF11 is built.
|
||||
- New crates hold the work: raea-app-videoform (apps/videoform: ingest, rights, reading, the verbs, the bench),
|
||||
raea-sys-videoform (systems/videoform: the maths over kept rows) and raea-io-resolve (io/resolve, VF1b). The
|
||||
videoform section's types are core/brief's videoform.rs.
|
||||
- Three small hooks into what exists: fingerprint.ts's optional `videoform` field (systems/fingerprint taxonomy.rs,
|
||||
VF2), `raea context` printing a project's videoform (engine/cli guide.rs, VF2), and `raea check PROJECT` holding
|
||||
the rules of the fingerprint that judges the piece (apps/direction check.rs, VF8).
|
||||
- The bench (VF12) runs after every step, on every set, from the kept files alone; its numbers are the progress.
|
||||
|
||||
Background:
|
||||
Given the readers raea has: footage perception (systems/footage), Fingerprint's columns (systems/columns: SigLIP 2,
|
||||
CLAP, YAMNet, cached by content hash), Parakeet's words, Beat This!, HTDemucs and Silero VAD (systems/song), OCR,
|
||||
Depth Anything 3, and raea check's one decode of the picture (raea-app-check-read once.rs)
|
||||
And Fingerprint's fingerprint.ts (`about`, `extends`, `applies`, axes, encoder pins), its profiles (FP6e: ranges by
|
||||
measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c)
|
||||
And controllers' `rule` fields and raea/check's `.ts` checks over the world (DR4), run by `raea check PROJECT`
|
||||
And taste lines' checks (raea's six forms, a check by name, a `.ts` check written with raea/check over the world;
|
||||
DR4), run by `raea check PROJECT`
|
||||
And the crate limits (a file at most 500 lines, a crate at most 2,000): raea-sys-fingerprint, -fingerprint-use and
|
||||
raea-app-fingerprint are each within 150 lines of theirs, so a videoform's code is its own crates, and the
|
||||
fingerprint crates grow only by a field and a map
|
||||
@@ -149,12 +162,15 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
And the template is a NAME.script.ts a project made to the videoform starts from, checked by `raea spec`
|
||||
|
||||
@needs:VF6,VF7
|
||||
Scenario: VF8. Rules, with their strength, into a controller
|
||||
Scenario: VF8. Rules, with their strength, in the videoform's rules
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written as rule fields of the controller `videoform.rules` names |
|
||||
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written into the section's `rules`, each a taste line with its check and values |
|
||||
| raea-app-direction | apps/direction/src/check.rs | 15 | tastes(): the rules of the fingerprint `which` names for the project, after the person's, the workspace's and the project's taste |
|
||||
Then a rule that holds in most references (a punch-in when a number is said; a close-up of the counters in every
|
||||
kitchen) is a rule field with its strength and its check
|
||||
kitchen) is a line in the section's `rules`, with its strength and its check
|
||||
And `raea check PROJECT` holds a piece to the rules of the fingerprint that judges it (raea-sys-fingerprint-use
|
||||
`which`), beside the person's, the workspace's and the project's taste
|
||||
And the person confirms the strongest rules once, on a contact sheet of shot-kind stills, and each answer is
|
||||
evidence in the videoform
|
||||
|
||||
|
||||
+7
-8
@@ -49,11 +49,10 @@ not only what was corrected. Notes still matter. They teach what the numbers can
|
||||
| Fingerprint: `fingerprint.ts` with `about`, `extends`, `applies` kinds and tags; `which` finds one by project, workspace and account; a child inherits its parent's evidence, its own counted more; notes teach the one that judged (FP14a-e) | the home: a videoform is one of these | the fields a kind of video needs |
|
||||
| Fingerprint's frozen encoders (SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2, Depth Anything 3), columns cached by content hash, word and learned heads, evidence in f16 rows (FP1-FP4) | the per-shot vectors and measures, and where they're kept | no shot vocabulary, no structure |
|
||||
| Fingerprint profiles: ranges from admired work, critique against them, a leave-one-out test (FP6e, `raea fingerprint profile`) | a videoform's ranges, and its validation | few measures (loudness, tilt, cut rate, motion, light, colour, sharpness) |
|
||||
| Controllers' `rule` fields, a check by name or a `.ts` check on raea/check's world (DR4) | rules that `raea check PROJECT` and every agent hold work to | none written from references |
|
||||
| Notes become checks, and climb to project, workspace and taste (DR5-DR8, `raea notes keep`) | the path a correction takes to becoming a rule | a videoform's rules start from evidence, not notes |
|
||||
| `raea check`: findings and the record (DR3); who can fix what, carried findings, one decode (raea-app-check-cause, PR #205) | the check every pass runs | a videoform's rules join it as more rules |
|
||||
| `NAME.script.ts` (scenes, beats, lines, cut); `brief.ts` (`references`, `look`, `mode`, `deliver`) | a storyboard spec, and a brief that names references | no template made from references; references named, never read |
|
||||
| `taste.ts`, six checked forms | the person's standing lines | the forms are fixed: mined rules go to controllers, not here |
|
||||
| `taste.ts` lines: words, and a check that holds them (one of six forms, a check by name, or a `.ts` check on raea/check's world; DR4) | the person's, the workspace's and the project's standing lines, which `raea check PROJECT` and every agent hold work to | none written from references |
|
||||
| Footage perception (`systems/footage`: shots, cuts, camera, faces, words on screen, scene labels, performance, facts.json) | what each reference shot is | read for raw footage, not for references |
|
||||
| Transcription (Parakeet), beats, stems and voice activity (`raea song`, HTDemucs, Silero VAD), OCR | words, pauses, cuts against beats, music under voice, captions | not gathered into a videoform |
|
||||
| Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — |
|
||||
@@ -83,7 +82,7 @@ Each part of a videoform flows into the part of raea that already does that job:
|
||||
|---|---|---|
|
||||
| ranges (pace, pauses, shot lengths, loudness, colour, captions) | its own profile (FP6e) | `raea fingerprint score --profile` critiques a cut against them, and leave-one-out is already built |
|
||||
| the taste taught later | its own evidence and heads (FP2, FP14b-d) | a note on a piece it judged teaches it, never the person's general fingerprint unless they move it up |
|
||||
| rules (coverage, order, event rules, limits) | a controller's `rule` fields, which `videoform.rules` names | `raea check PROJECT` runs them, and they're edited in the app like any controller |
|
||||
| rules (coverage, order, event rules, limits) | the section's `rules`, each in a taste line's shape (words, check, values, level) | `raea check PROJECT` runs them for a piece the videoform judges (`which`), beside the taste |
|
||||
| structure (slots, their order and lengths) | a `NAME.script.ts` template, which `videoform.template` names | a project made to the videoform starts from it, and agents plan from it as from any storyboard |
|
||||
| references | `brief.ts`'s existing `references` shape, `{ target, note }`, with the source kept by content hash | a reference is named the way a brief already names one |
|
||||
|
||||
@@ -161,7 +160,7 @@ Following and checking need four kinds of thing from the references, and a video
|
||||
| per-shot rows | each reference shot's SigLIP 2 vector (one pooled vector, a few frames averaged), its CLAP vector over the shot's sound, and its measures (length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video) | the shot vocabulary; matching new footage to shot kinds; the embedding checks |
|
||||
| the vocabulary's vectors | each term's phrasings through the text towers, as word heads store them (FP2e) | naming shot kinds; finding domain things in new footage |
|
||||
| the profile | the ranges of every measure across the references (FP6e) | the critique, and composition-first range checks |
|
||||
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the controller rules `raea check` runs |
|
||||
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the rules `raea check` runs |
|
||||
|
||||
Also kept: one small still for each shot kind (a thumbnail, a few kilobytes), so the person can see what a kind is when
|
||||
confirming rules, and the evidence the person adds over time. The reference videos aren't kept.
|
||||
@@ -226,8 +225,8 @@ working as it was. This is the one time a reference is needed again, and it's th
|
||||
(open, sections, close), each with its length range, its shot kinds and what's on screen. This becomes the script
|
||||
template.
|
||||
5. **The event rules.** How often one thing comes with another across the references ("a punch-in when a number is
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become controller rules,
|
||||
each stating how strongly it holds.
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become the videoform's
|
||||
rules, each stating how strongly it holds.
|
||||
6. **The person confirms the strongest rules once,** on a contact sheet ("countertop close-up in every kitchen: 9 of
|
||||
10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint.
|
||||
|
||||
@@ -247,7 +246,7 @@ working as it was. This is the one time a reference is needed again, and it's th
|
||||
- shot lengths and pauses (the voice's cut points are in the composition);
|
||||
- caption places and sizes.
|
||||
|
||||
These are the controller rules, run by `raea check PROJECT` as today.
|
||||
These are the videoform's rules, run by `raea check PROJECT` with the taste.
|
||||
2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea
|
||||
fingerprint score --profile`).
|
||||
3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot);
|
||||
@@ -298,7 +297,7 @@ The sets, their answers and their verdicts are kept as fixtures, so each step of
|
||||
| | VF5 | the vocabulary loop with the person's AI, as word heads | medium-high | word heads already score from text; the report is new |
|
||||
| | VF6 | the shot vocabulary (clusters named from the vocabulary) | medium | clustering is plain; naming quality varies by domain |
|
||||
| | VF7 | the structure template | medium | alignment across varied videos is the hard part |
|
||||
| | VF8 | event rules into controller rules, with strength, confirmed by the person | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | VF8 | event rules into the videoform's rules, with strength, confirmed by the person; `raea check` holds them | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | VF8b | when it doesn't hold together: too few, mixed kinds (split into videoforms), traits that vary, outliers | medium-high | groups and spreads come from the kept rows |
|
||||
| | VF8c | adding and removing references from kept rows; encoder pins and `refresh` | high | Fingerprint keeps evidence across upgrades the same way (FP8c) |
|
||||
| 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist |
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// 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, and the search finds by use.
|
||||
// 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).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, normalize } from "node:path";
|
||||
import { listed, type Item } from "../src/catalog";
|
||||
import { listed, searched, shown, terms, 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[] };
|
||||
@@ -45,4 +46,37 @@ 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);
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,7 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
|
||||
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 judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
|
||||
|
||||
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
|
||||
|
||||
+88
-24
@@ -6,7 +6,15 @@
|
||||
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
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 };
|
||||
/** 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;
|
||||
};
|
||||
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
|
||||
export type Got = { item: Item; licence: string; files: Record<string, string> };
|
||||
|
||||
@@ -17,6 +25,9 @@ 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 {
|
||||
@@ -25,46 +36,99 @@ 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 = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
|
||||
const item = found(cat.items, 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 };
|
||||
}
|
||||
|
||||
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
|
||||
// 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;
|
||||
}
|
||||
|
||||
/** `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"), or anything in a name or in what
|
||||
* an item does; every word must be found, and a name's own words count first. */
|
||||
* 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 */
|
||||
export function listed(items: Item[], words: string[]): string {
|
||||
if (!items.length) return "";
|
||||
if (!words.length) {
|
||||
const ws = terms(words);
|
||||
if (!ws.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 "count up"; 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 "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
|
||||
}
|
||||
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));
|
||||
const found = searched(items, ws);
|
||||
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
|
||||
return found.map(([, i]) => row(i)).join("\n") + "\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}";
|
||||
`;
|
||||
}
|
||||
|
||||
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
|
||||
|
||||
@@ -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 --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)");
|
||||
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)");
|
||||
// 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] | 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)));
|
||||
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)));
|
||||
}
|
||||
// `--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") {
|
||||
|
||||
+13
-3
@@ -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, listed, type Got, type Item } from "./catalog";
|
||||
import { added, found, listed, searched, shown as inFull, terms, 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";
|
||||
|
||||
@@ -199,8 +199,18 @@ 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);
|
||||
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 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`);
|
||||
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");
|
||||
|
||||
+29
-4
@@ -32,6 +32,9 @@ 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.
|
||||
@@ -58,7 +61,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", "--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", "--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 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
|
||||
@@ -118,6 +121,26 @@ 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]];
|
||||
@@ -157,7 +180,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, 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, 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") };
|
||||
}
|
||||
|
||||
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
|
||||
@@ -218,7 +241,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.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.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
|
||||
| { 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`;
|
||||
@@ -242,7 +265,9 @@ 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.fyi
|
||||
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
|
||||
? `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.`,
|
||||
"",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
|
||||
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
|
||||
// one touches it: the paddle follows the ball, and the same file is the video ad.
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { AbsoluteFill, Audio, Composition, Sequence, registerRoot, sao, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { Sphere } from "raea/3d";
|
||||
import { LinearRgba, Srgba } from "raea/color";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
@@ -12,6 +12,7 @@ import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { EndCard } from "raea/playable";
|
||||
import { Sfx, Synth } from "raea/tone";
|
||||
|
||||
const FPS = 30;
|
||||
const COLS = 6, ROWS = 4, LIVES = 3;
|
||||
@@ -21,6 +22,12 @@ const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
|
||||
|
||||
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
|
||||
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
|
||||
// its sound (docs/playables.feature PA6): a square blip on the paddle and each brick, a low one on a miss, and a
|
||||
// generated crack under each brick that breaks
|
||||
const blip = new Synth({ oscillator: { type: "square" }, envelope: { attack: 0.002, decay: 0.09, sustain: 0, release: 0.05 }, volume: -14 }).toDestination();
|
||||
const CRACK = sao("short dry ceramic brick crack, arcade game hit, no reverb", { seconds: 0.6 });
|
||||
const NOTES = ["E6", "C6", "A5", "E5"];
|
||||
|
||||
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
|
||||
|
||||
/** The camera's distance that fits the whole field on a screen of this aspect */
|
||||
@@ -102,6 +109,15 @@ function BrickRush() {
|
||||
{`👆 Drag to play`}
|
||||
</div>
|
||||
) : null}
|
||||
{/* the state shown at a frame is the step's of the frame before (useGameState), so an event stamped f shows at f + 1 */}
|
||||
<Sfx name="paddle" when={g.hit === now - 1} play={(t) => blip.triggerAttackRelease("C5", "32n", t)} />
|
||||
<Sfx name="brick" when={last === now - 1} play={(t) => blip.triggerAttackRelease(NOTES[Math.floor(g.broke.indexOf(last) / COLS)] ?? "E5", "16n", t)} />
|
||||
<Sfx name="miss" when={g.missed === now - 1} play={(t) => blip.triggerAttackRelease("C3", "8n", t, 0.8)} />
|
||||
{last >= 0 ? (
|
||||
<Sequence key={last} from={last}>
|
||||
<Audio src={CRACK} volume={0.5} />
|
||||
</Sequence>
|
||||
) : null}
|
||||
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// A playable whose rules are raea/ecs systems (docs/playables.feature PA12): stars fall, a basket catches them, and
|
||||
// every rule (where a star starts, how it falls, what the basket catches, the score) runs on a World. Natively the
|
||||
// World's tables are Bevy's, in raea's engine; in the playable they're Bevy's too, carried in the page as wasm, so the
|
||||
// game plays the same in both. Each frame's state is the World copied and stepped once, with where the person points
|
||||
// written into it as a resource. Rendered with `raea render`, no one touches it: the basket follows the lowest star.
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
|
||||
import { createWorld, type World } from "raea/ecs";
|
||||
import { Sphere } from "raea/3d";
|
||||
import { LinearRgba, Srgba } from "raea/color";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Cuboid, Mesh3d } from "raea/mesh";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { EndCard } from "raea/playable";
|
||||
|
||||
const FPS = 30;
|
||||
const W = 6, TOP = 8; // field: x in [-W/2, W/2], y from 0 (the basket) to TOP
|
||||
const FOV = 0.733; // radians, vertical
|
||||
const GOAL = 10, MISSES = 3;
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
|
||||
|
||||
/** The game's rules: a World with a basket, the score and misses as resources, and its systems */
|
||||
function rules(): World {
|
||||
const w = createWorld();
|
||||
w.spawn("basket", { x: 0 });
|
||||
for (const r of ["score", "missed"]) w.resource(r, 0);
|
||||
for (const r of ["caught", "lost"]) w.resource(r, -99);
|
||||
// a star every 20 frames, where the frame number puts it
|
||||
w.system((world, f) => {
|
||||
if (f % 20 === 0) world.spawn("star", { x: (((f * 7919) % 97) / 97 - 0.5) * (W - 1), y: TOP, v: 0.05 + ((f * 31) % 7) * 0.006 });
|
||||
});
|
||||
// the basket eases toward where the person points, or toward the lowest star before they touch
|
||||
w.system((world) => {
|
||||
const [b] = world.query("basket");
|
||||
const x = world.get(b).x as number;
|
||||
let want = world.resource<number>("aim");
|
||||
if (typeof want !== "number") {
|
||||
const low = world.query("star").map((id) => world.get(id)).sort((a, c) => (a.y as number) - (c.y as number))[0];
|
||||
want = low ? (low.x as number) : 0;
|
||||
}
|
||||
world.set(b, { x: clamp(x + clamp(want - x, -0.3, 0.3), -W / 2 + 0.8, W / 2 - 0.8) });
|
||||
});
|
||||
// each star falls; the basket catches one at its height, and one past it is missed
|
||||
w.system((world, f) => {
|
||||
const bx = world.get(world.query("basket")[0]).x as number;
|
||||
for (const id of world.query("star")) {
|
||||
const s = world.get(id);
|
||||
const y = (s.y as number) - (s.v as number);
|
||||
if (y < 0.35 && y > -0.15 && Math.abs((s.x as number) - bx) < 0.85) {
|
||||
world.despawn(id);
|
||||
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
|
||||
world.resource("caught", f);
|
||||
} else if (y < -1) {
|
||||
world.despawn(id);
|
||||
world.resource("missed", (world.resource<number>("missed") ?? 0) + 1);
|
||||
world.resource("lost", f);
|
||||
} else world.set(id, { y });
|
||||
}
|
||||
});
|
||||
return w;
|
||||
}
|
||||
|
||||
interface Game { w: World; touched: boolean; over: "" | "won" | "lost" }
|
||||
|
||||
/** The camera's distance that fits the whole field on a screen of this aspect */
|
||||
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
|
||||
|
||||
/** A pointer's x on screen, in field units at the basket's depth */
|
||||
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
|
||||
const p = input.touches?.[0] ?? input.pointer;
|
||||
if (!p) return undefined;
|
||||
const halfH = Math.tan(FOV / 2) * distance(width / height);
|
||||
return ((p.x / width) * 2 - 1) * halfH * (width / height);
|
||||
}
|
||||
|
||||
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
|
||||
if (s.over) return s;
|
||||
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
|
||||
const w = s.w.copy();
|
||||
const x = touched ? fieldX(input, width, height) : undefined;
|
||||
if (x !== undefined) w.resource("aim", x);
|
||||
w.step(frame);
|
||||
const over = (w.resource<number>("score") ?? 0) >= GOAL ? "won" : (w.resource<number>("missed") ?? 0) >= MISSES ? "lost" : "";
|
||||
return { w, touched, over };
|
||||
};
|
||||
|
||||
const steps = new Map<string, ReturnType<typeof stepFor>>();
|
||||
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
|
||||
let first: Game | null = null;
|
||||
|
||||
function StarCatch() {
|
||||
const { width, height } = useVideoConfig();
|
||||
first ??= { w: rules(), touched: false, over: "" };
|
||||
const g = useGameState(first, stepOf(width, height));
|
||||
const now = useCurrentFrame();
|
||||
const bx = g.w.get(g.w.query("basket")[0]).x as number;
|
||||
const score = g.w.resource<number>("score") ?? 0;
|
||||
const missed = g.w.resource<number>("missed") ?? 0;
|
||||
const pop = Math.max(0, 1 - (now - (g.w.resource<number>("caught") ?? -99)) / 8);
|
||||
const flash = Math.max(0, 1 - (now - (g.w.resource<number>("lost") ?? -99)) / 12);
|
||||
const d = distance(width / height);
|
||||
const s = width / 1080;
|
||||
return (
|
||||
<AbsoluteFill style={{ background: `rgb(${12 + 80 * flash}, 16, ${40 + 20 * pop})` }}>
|
||||
<Camera3d transform={Transform.fromXyz(0, TOP / 2, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
|
||||
<AmbientLight brightness={200} />
|
||||
<DirectionalLight transform={Transform.fromXyz(2, 10, 6).lookingAt([0, 0, 0])} illuminance={9000} />
|
||||
<Mesh3d transform={Transform.fromXyz(bx, 0, 0).withScale([1 + 0.2 * pop, 1 - 0.3 * pop, 1])} name="basket">
|
||||
<Cuboid half_size={[0.8, 0.15, 0.3]} />
|
||||
<StandardMaterial base_color="#2ec4b6" perceptual_roughness={0.45} />
|
||||
</Mesh3d>
|
||||
{g.w.query("star").map((id) => {
|
||||
const st = g.w.get(id);
|
||||
return (
|
||||
<Mesh3d key={id} transform={Transform.fromXyz(st.x as number, st.y as number, 0)} name={`star-${id}`}>
|
||||
<Sphere radius={0.22} />
|
||||
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.7)} />
|
||||
</Mesh3d>
|
||||
);
|
||||
})}
|
||||
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
|
||||
{`★ ${score} / ${GOAL}`}
|
||||
</div>
|
||||
<div style={{ position: "absolute", right: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#ef476f" }}>
|
||||
{"✕".repeat(missed)}
|
||||
</div>
|
||||
{!g.touched ? (
|
||||
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
|
||||
{"👆 Drag to catch"}
|
||||
</div>
|
||||
) : null}
|
||||
<EndCard show={!!g.over} title={g.over === "won" ? "Ten stars!" : "So close!"} subtitle={g.over === "won" ? "The night sky is waiting" : "Can you catch ten?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => (
|
||||
<>
|
||||
<Composition id="star-catch-portrait" component={StarCatch} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 40} />
|
||||
<Composition id="star-catch-landscape" component={StarCatch} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 40} />
|
||||
</>
|
||||
));
|
||||
@@ -0,0 +1,28 @@
|
||||
//! 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,6 +4,7 @@
|
||||
|
||||
pub mod cache;
|
||||
pub mod client;
|
||||
pub mod critic;
|
||||
pub mod media;
|
||||
pub mod route;
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod wasm;
|
||||
|
||||
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! The ecs.* calls as a wasm module (docs/playables.feature PA12): a playable carries Bevy's own world, so a game on
|
||||
//! raea/ecs keeps the tables, queries and parent/child it has natively. sdk/playable/ecs/build.sh builds it as a
|
||||
//! cdylib for wasm32-unknown-unknown; the page's host/ecs.ts calls `raea_call` the way raea's V8 calls `__raea_call`.
|
||||
//! Strings cross as UTF-8 in memory the page asks for with `raea_alloc`; the answer is `o` and the value's JSON, or
|
||||
//! `e` and the message, where `raea_call` returns (its address in the high 32 bits, its length in the low), until the
|
||||
//! next call.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
thread_local! {
|
||||
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// `len` bytes the page writes a call's name or arguments into, freed by `raea_free`
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn raea_alloc(len: usize) -> *mut u8 {
|
||||
let mut v = Vec::<u8>::with_capacity(len.max(1));
|
||||
let p = v.as_mut_ptr();
|
||||
std::mem::forget(v);
|
||||
p
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `p` came from `raea_alloc(len)` and isn't used after
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn raea_free(p: *mut u8, len: usize) {
|
||||
// SAFETY: raea_alloc made it with this capacity
|
||||
drop(unsafe { Vec::from_raw_parts(p, 0, len.max(1)) });
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// each pointer holds that many bytes of UTF-8 the page wrote (raea_alloc's)
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn raea_call(
|
||||
name: *const u8,
|
||||
name_len: usize,
|
||||
args: *const u8,
|
||||
args_len: usize,
|
||||
) -> u64 {
|
||||
// SAFETY: the page wrote these bytes where raea_alloc said
|
||||
let (name, args) = unsafe {
|
||||
(
|
||||
std::slice::from_raw_parts(name, name_len),
|
||||
std::slice::from_raw_parts(args, args_len),
|
||||
)
|
||||
};
|
||||
let answer = match (
|
||||
std::str::from_utf8(name),
|
||||
serde_json::from_slice::<serde_json::Value>(args),
|
||||
) {
|
||||
(Ok(n), Ok(a)) => super::call(n, &a).map(|v| v.to_string()),
|
||||
_ => Err("a call's name and arguments are UTF-8 JSON".into()),
|
||||
};
|
||||
OUT.with(|o| {
|
||||
let mut o = o.borrow_mut();
|
||||
*o = match answer {
|
||||
Ok(v) => format!("o{v}"),
|
||||
Err(e) => format!("e{e}"),
|
||||
}
|
||||
.into_bytes();
|
||||
((o.as_ptr() as u64) << 32) | o.len() as u64
|
||||
})
|
||||
}
|
||||
@@ -87,8 +87,10 @@ impl LiveScene {
|
||||
let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT];
|
||||
let mut nw = 0usize;
|
||||
let mut put = |k: &'static str, v: f64| {
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), the rest to 6 decimals
|
||||
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") { v } else { r6(v) }));
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), and a light's own rotation exact as parts.rs
|
||||
// writes it (rot_q*: rounded here, a still sun was sent again on the first fast frame, PA18); the rest
|
||||
// to 6 decimals
|
||||
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") || k.starts_with("rot_q") { v } else { r6(v) }));
|
||||
nw += 1;
|
||||
};
|
||||
let mut color: Option<std::borrow::Cow<str>> = None;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! A sun placed by its own rotation (a Bevy Transform's, as brick-rush's `Transform.fromXyz(2, 8, 6).lookingAt(...)`)
|
||||
//! keeps that rotation exact on live play's fast rows as on the full rows (docs/playables.feature PA18): the fast path
|
||||
//! rounded it to 6 decimals, so a sun that never moved was sent again on the first fast frame, and RAEA_LIVE3D_CHECK
|
||||
//! panicked there.
|
||||
use raea_core_scene::Node3;
|
||||
use raea_runtime_scene::{LiveScene, Shot};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A part as a frame's scene hands it on: its kind, props, shape and children
|
||||
fn part(kind: &str, props: Value, shape: Option<&str>, kids: Vec<Node3>) -> Node3 {
|
||||
let props = std::sync::Arc::new(props.as_object().cloned().unwrap_or_default());
|
||||
Node3 {
|
||||
kind: kind.into(),
|
||||
props,
|
||||
shape: shape.map(Into::into),
|
||||
at: None,
|
||||
kids: kids.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn scene(q: [f64; 4]) -> Vec<Node3> {
|
||||
let sun = json!({ "position": [2, 8, 6], "rotation": q, "illuminance": 9600, "shadow_maps_enabled": true });
|
||||
let paint = part(
|
||||
"MeshStandardMaterial",
|
||||
json!({ "color": "#ff6a3d" }),
|
||||
None,
|
||||
vec![],
|
||||
);
|
||||
vec![
|
||||
part("DirectionalLight", sun, None, vec![]),
|
||||
part(
|
||||
"Mesh",
|
||||
json!({ "name": "brick" }),
|
||||
Some("box(1,0.4,0.5)"),
|
||||
vec![paint],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sun_placed_by_its_rotation_is_the_same_on_both_paths() {
|
||||
// SAFETY: the only test in this binary, set before anything reads the environment
|
||||
unsafe { std::env::set_var("RAEA_LIVE3D_CHECK", "1") };
|
||||
// looking from (2, 8, 6) at the origin: digits past the sixth decimal
|
||||
let q = [
|
||||
-0.42470818758010864,
|
||||
0.33985114097595215,
|
||||
0.17591990530490875,
|
||||
0.8204732537269592,
|
||||
];
|
||||
let mut ls = LiveScene::default();
|
||||
let s = scene(q);
|
||||
ls.open(
|
||||
Shot {
|
||||
scene: &s,
|
||||
clear: None,
|
||||
},
|
||||
64,
|
||||
64,
|
||||
30.0,
|
||||
);
|
||||
for f in 0..3 {
|
||||
let (set, gone) = ls.frame(Shot {
|
||||
scene: &s,
|
||||
clear: None,
|
||||
});
|
||||
assert!(gone.is_empty(), "frame {f}: nothing dropped: {gone:?}");
|
||||
assert!(
|
||||
set.iter()
|
||||
.all(|t| !t.vals.keys().any(|k| k.starts_with("rot_q"))),
|
||||
"frame {f}: a still sun is never sent again: {set:?}"
|
||||
);
|
||||
}
|
||||
// a sun that turns sends the part of its rotation that changed, exact
|
||||
let q2 = [
|
||||
-0.42470818758010864,
|
||||
0.3398512,
|
||||
0.17591990530490875,
|
||||
0.8204732537269592,
|
||||
];
|
||||
let s2 = scene(q2);
|
||||
let (set, _) = ls.frame(Shot {
|
||||
scene: &s2,
|
||||
clear: None,
|
||||
});
|
||||
let sun = set
|
||||
.iter()
|
||||
.find(|t| t.vals.contains_key("rot_qy"))
|
||||
.expect("the turned sun's rotation is sent");
|
||||
assert_eq!(
|
||||
sun.vals.get("rot_qy"),
|
||||
Some(&raea_core_program::ir::V::N(q2[1]))
|
||||
);
|
||||
}
|
||||
+43
-28
@@ -4,7 +4,7 @@
|
||||
// same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under
|
||||
// plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere.
|
||||
|
||||
import { hasNative, native } from "./native";
|
||||
import { ecsCall, hasEcs } from "./native";
|
||||
|
||||
export type Value = number | string | boolean;
|
||||
export type Cols = Record<string, Value>;
|
||||
@@ -52,76 +52,83 @@ interface Store {
|
||||
free(): void;
|
||||
}
|
||||
|
||||
/** A store's tables freed when nothing holds it any more: a game's kept states are let go (games.ts KEEP), and the
|
||||
* engine's (or a playable's wasm) worlds aren't collected with them. Freeing one twice is harmless. */
|
||||
const unheld = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((world) => ecsCall("ecs.free", { world })) : null;
|
||||
|
||||
class NativeStore implements Store {
|
||||
constructor(readonly world: number) {}
|
||||
constructor(readonly world: number) {
|
||||
unheld?.register(this, world, this);
|
||||
}
|
||||
static create(): NativeStore {
|
||||
return new NativeStore(native("ecs.new", {}).world);
|
||||
return new NativeStore(ecsCall("ecs.new", {}).world);
|
||||
}
|
||||
spawn(kind: string, cols: Cols) {
|
||||
return native("ecs.spawn", { world: this.world, kind, cols }).id;
|
||||
return ecsCall("ecs.spawn", { world: this.world, kind, cols }).id;
|
||||
}
|
||||
spawnComponents(components: Components, parent?: number) {
|
||||
return native("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
|
||||
return ecsCall("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
|
||||
}
|
||||
insert(id: number, components: Components) {
|
||||
native("ecs.insert", { world: this.world, id, components });
|
||||
ecsCall("ecs.insert", { world: this.world, id, components });
|
||||
}
|
||||
remove(id: number, names: string[]) {
|
||||
native("ecs.remove", { world: this.world, id, names });
|
||||
ecsCall("ecs.remove", { world: this.world, id, names });
|
||||
}
|
||||
components(id: number) {
|
||||
return native("ecs.components", { world: this.world, id }) as Components;
|
||||
return ecsCall("ecs.components", { world: this.world, id }) as Components;
|
||||
}
|
||||
find(f: Find) {
|
||||
return native("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
|
||||
return ecsCall("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
|
||||
}
|
||||
setParent(id: number, parent: number | null) {
|
||||
native("ecs.parent", { world: this.world, id, parent });
|
||||
ecsCall("ecs.parent", { world: this.world, id, parent });
|
||||
}
|
||||
parent(id: number) {
|
||||
return native("ecs.parent", { world: this.world, id }) as number | null;
|
||||
return ecsCall("ecs.parent", { world: this.world, id }) as number | null;
|
||||
}
|
||||
children(id: number) {
|
||||
return native("ecs.children", { world: this.world, id });
|
||||
return ecsCall("ecs.children", { world: this.world, id });
|
||||
}
|
||||
resource(name: string, value?: unknown) {
|
||||
return native("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
|
||||
return ecsCall("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
|
||||
}
|
||||
send(name: string, value: unknown) {
|
||||
native("ecs.send", { world: this.world, name, value });
|
||||
ecsCall("ecs.send", { world: this.world, name, value });
|
||||
}
|
||||
events(name: string) {
|
||||
return native("ecs.events", { world: this.world, name });
|
||||
return ecsCall("ecs.events", { world: this.world, name });
|
||||
}
|
||||
clearEvents() {
|
||||
native("ecs.clear_events", { world: this.world });
|
||||
ecsCall("ecs.clear_events", { world: this.world });
|
||||
}
|
||||
set(id: number, cols: Cols) {
|
||||
native("ecs.set", { world: this.world, id, cols });
|
||||
ecsCall("ecs.set", { world: this.world, id, cols });
|
||||
}
|
||||
get(id: number) {
|
||||
return native("ecs.get", { world: this.world, id });
|
||||
return ecsCall("ecs.get", { world: this.world, id });
|
||||
}
|
||||
despawn(id: number) {
|
||||
native("ecs.despawn", { world: this.world, id });
|
||||
ecsCall("ecs.despawn", { world: this.world, id });
|
||||
}
|
||||
query(kind: string, where: Where) {
|
||||
return native("ecs.query", { world: this.world, kind, where }).ids;
|
||||
return ecsCall("ecs.query", { world: this.world, kind, where }).ids;
|
||||
}
|
||||
column(kind: string, col: string) {
|
||||
return native("ecs.column", { world: this.world, kind, col });
|
||||
return ecsCall("ecs.column", { world: this.world, kind, col });
|
||||
}
|
||||
count(kind: string) {
|
||||
return native("ecs.count", { world: this.world, kind });
|
||||
return ecsCall("ecs.count", { world: this.world, kind });
|
||||
}
|
||||
rows() {
|
||||
return native("ecs.rows", { world: this.world });
|
||||
return ecsCall("ecs.rows", { world: this.world });
|
||||
}
|
||||
clone() {
|
||||
return new NativeStore(native("ecs.clone", { world: this.world }).world);
|
||||
return new NativeStore(ecsCall("ecs.clone", { world: this.world }).world);
|
||||
}
|
||||
free() {
|
||||
native("ecs.free", { world: this.world });
|
||||
unheld?.unregister(this);
|
||||
ecsCall("ecs.free", { world: this.world });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +283,9 @@ export class World {
|
||||
|
||||
/** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */
|
||||
constructor(store?: Store) {
|
||||
this.native = store ? store instanceof NativeStore : hasNative();
|
||||
this.native = store ? store instanceof NativeStore : hasEcs();
|
||||
// a playable's export reads this to carry Bevy's world (sdk/playable export/walk.ts, PA12)
|
||||
(globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed = true;
|
||||
this.store = store ?? (this.native ? NativeStore.create() : new JsStore());
|
||||
}
|
||||
|
||||
@@ -367,7 +376,7 @@ export class World {
|
||||
* hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web),
|
||||
* the same list as runtime/calls ecs.scene makes. */
|
||||
scene(): unknown[] {
|
||||
if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world });
|
||||
if (this.store instanceof NativeStore) return ecsCall("ecs.scene", { world: this.store.world });
|
||||
const store = this.store;
|
||||
const out: unknown[] = [];
|
||||
for (const id of store.find({ with: ["Mesh"] })) {
|
||||
@@ -394,6 +403,12 @@ export class World {
|
||||
this.store.clearEvents();
|
||||
for (const s of this.systems) s(this, frame);
|
||||
}
|
||||
/** A copy of the world as it is now, with its systems: a game's next state (`useGameState`), stepped on its own. */
|
||||
copy(): World {
|
||||
const w = new World(this.store.clone());
|
||||
w.systems = this.systems;
|
||||
return w;
|
||||
}
|
||||
/** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */
|
||||
at(frame: number): World {
|
||||
if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`);
|
||||
@@ -442,7 +457,7 @@ function compose(p: number[], c: number[]): number[] {
|
||||
|
||||
export function createWorld(opts: { native?: boolean } = {}): World {
|
||||
if (opts.native === false) return new World(new JsStore());
|
||||
if (opts.native === true && !hasNative()) throw new Error("createWorld({ native: true }) needs the raea engine");
|
||||
if (opts.native === true && !hasEcs()) throw new Error("createWorld({ native: true }) needs the raea engine");
|
||||
return new World();
|
||||
}
|
||||
|
||||
|
||||
+17
-1
@@ -20,12 +20,28 @@ export function hasNative(): boolean {
|
||||
|
||||
/** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */
|
||||
export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
|
||||
const call = bridge();
|
||||
return through(bridge(), name, args);
|
||||
}
|
||||
|
||||
function through<K extends NativeName>(call: NativeCall | null, name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
|
||||
if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`);
|
||||
const out = call(name, JSON.stringify(args));
|
||||
return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"];
|
||||
}
|
||||
|
||||
/** raea/ecs's calls: the engine's, else a playable's (Bevy's world as wasm, sdk/playable host/ecs.ts, PA12) */
|
||||
function ecsBridge(): NativeCall | null {
|
||||
return bridge() ?? (globalThis as { __raeaEcs?: NativeCall }).__raeaEcs ?? null;
|
||||
}
|
||||
/** Whether raea/ecs's calls are here: in the engine, or in a playable that carries Bevy's world. */
|
||||
export function hasEcs(): boolean {
|
||||
return ecsBridge() !== null;
|
||||
}
|
||||
/** One of raea/ecs's calls (an `ecs.*` name), wherever its world is. */
|
||||
export function ecsCall<K extends NativeName & `ecs.${string}`>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
|
||||
return through(ecsBridge(), name, args);
|
||||
}
|
||||
|
||||
/** Print a line from a headless run (raea run). */
|
||||
export function print(...parts: unknown[]): void {
|
||||
const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ");
|
||||
|
||||
@@ -38,14 +38,20 @@ function describe(kind: AssetKind, prompt: string, seconds: number): GeneratedAs
|
||||
return { kind, prompt, seconds, id, src: `asset:${kind}/${id}` };
|
||||
}
|
||||
|
||||
/** Every asset described so far, by src (`raea playable` makes each one at export and carries it in the page, PA6) */
|
||||
export function describedAssets(): Map<string, GeneratedAsset> {
|
||||
return ((globalThis as { __raeaGeneratedAssets?: Map<string, GeneratedAsset> }).__raeaGeneratedAssets ??= new Map());
|
||||
}
|
||||
const described = (a: GeneratedAsset) => (describedAssets().set(a.src, a), a);
|
||||
|
||||
/** Music an older edit generated (30 seconds by default). Retired: a take already made plays, a new one is refused. */
|
||||
export function lyria(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
|
||||
return describe("lyria", prompt, options.seconds ?? 30);
|
||||
return described(describe("lyria", prompt, options.seconds ?? 30));
|
||||
}
|
||||
|
||||
/** A sound effect to generate (2 seconds by default). */
|
||||
export function sao(prompt: string, options: { seconds?: number } = {}): GeneratedAsset {
|
||||
return describe("sao", prompt, options.seconds ?? 2);
|
||||
return described(describe("sao", prompt, options.seconds ?? 2));
|
||||
}
|
||||
|
||||
/** Retired on 2026-11-05: Fish narration is no longer part of raea. Narrate with `<Speech text start>` from
|
||||
@@ -63,7 +69,7 @@ export function tokensynthNote(timbre: string, midi: number, options: { seconds?
|
||||
// params, so the cache key says which precision made the note
|
||||
const o = { midi, velocity: options.velocity ?? 100, seed: options.seed ?? 1234, device: "cpu", precision: options.precision ?? "fp16" };
|
||||
const key = `${a.id}:${midi}:${o.velocity}:${o.seed}:${o.precision}`;
|
||||
return { ...a, id: key, src: `asset:tokensynth/${key}`, options: o };
|
||||
return described({ ...a, id: key, src: `asset:tokensynth/${key}`, options: o });
|
||||
}
|
||||
|
||||
/** Whether a value is a generated asset (what sao, tokensynthNote and lyria return), not a file path. */
|
||||
|
||||
@@ -2,3 +2,6 @@ node_modules
|
||||
deploy
|
||||
test
|
||||
README.md
|
||||
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
|
||||
!deploy/git
|
||||
!deploy/fly/start.sh
|
||||
@@ -0,0 +1,98 @@
|
||||
# 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)
|
||||
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 changed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
||||
# only while the installed SDK still lacks them, so a release that has them keeps its own. 12-04: the one check (raea
|
||||
# #335, docs/check.feature): goal/src whole (a render's check kept and reused, no critic, no clef, and no async spawn,
|
||||
# which 0.1.17-rc4's goal.ts named-imported and raea's runtime hasn't got), <Captions /> in raea/video and raea, and
|
||||
# the craft guides without judge, ask or self-graded beats. Every overlaid file differs from rc4 by that change alone
|
||||
RUN if ! grep -q 'keptCheck' /opt/raea/share/raea/sdk/goal/src/run.ts; then \
|
||||
rm -rf /opt/raea/share/raea/sdk/goal/src && cp -R image/sdk-overlay/goal/src /opt/raea/share/raea/sdk/goal/src && \
|
||||
cp image/sdk-overlay/video/src/captions.tsx image/sdk-overlay/video/src/index.ts image/sdk-overlay/video/src/region.tsx image/sdk-overlay/video/src/zones.ts image/sdk-overlay/video/src/registry.tsx /opt/raea/share/raea/sdk/video/src/ && \
|
||||
cp image/sdk-overlay/video/package.json /opt/raea/share/raea/sdk/video/package.json && \
|
||||
cp image/sdk-overlay/raea/src/index.tsx /opt/raea/share/raea/sdk/raea/src/index.tsx && \
|
||||
cp -R image/sdk-overlay/guides/. /opt/raea/share/raea/sdk/guides/ && echo "overlay: one check"; \
|
||||
fi
|
||||
# raea's CLI host file after the release (image/cli-overlay, share/raea/engine/cli/src): 12-04, raea cut keeps a take's
|
||||
# jump cuts (raea #335), so a second cut on a take takes 0.5 s, not 43. It differs from rc4's by that change alone
|
||||
RUN if ! grep -q 'jumpCuts' /opt/raea/share/raea/engine/cli/src/native.ts; then \
|
||||
cp image/cli-overlay/native.ts /opt/raea/share/raea/engine/cli/src/native.ts && echo "overlay: cut cache"; \
|
||||
fi
|
||||
# and the AGENTS.md a project gets (raea #335's index.ts, which differs from rc4's in that text alone): 12-05, rc4's told
|
||||
# box agents to use framing="face" (the farm refuses it: two Elfster cuts failed their first render), to make music in
|
||||
# Tone.js (the skill says the generate tool) and to run raea check after each render (the render runs it once)
|
||||
RUN if grep -q 'framing="face" keeps the' /opt/raea/share/raea/engine/cli/src/index.ts; then \
|
||||
cp image/cli-overlay/index.ts /opt/raea/share/raea/engine/cli/src/index.ts && echo "overlay: agents text"; \
|
||||
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"]
|
||||
Executable
+234
@@ -0,0 +1,234 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,7 @@
|
||||
# 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"
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/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
|
||||
@@ -93,7 +93,7 @@ image = (
|
||||
modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
|
||||
.apt_install(
|
||||
"ca-certificates", "curl", "xz-utils", "zstd", "procps", "ffmpeg",
|
||||
"libasound2t64", "libfontconfig1", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools",
|
||||
"libasound2t64", "libfontconfig1", "fonts-noto-color-emoji", "libvulkan1", "mesa-vulkan-drivers", "vulkan-tools",
|
||||
"libxext6", "libx11-6", "libgl1", "libegl1",
|
||||
"libxi6", "libxxf86vm1", "libxfixes3", "libxrender1", "libxkbcommon0", "libsm6", "libice6",
|
||||
)
|
||||
@@ -158,8 +158,15 @@ models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2
|
||||
logs = modal.Dict.from_name("raea-farm-logs", create_if_missing=True)
|
||||
# the farm's token (RAEA_CLOUD_TOKEN), its own: a CPU box names it as RAEA_CLOUD_GPU_TOKEN
|
||||
secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_SECRET", "raea-farm"))
|
||||
# /v1/words hears with this Modal app (words.py), in the languages Parakeet TDT v3 knows (its 25 European ones);
|
||||
# others, and any failure, go to Whisper on OpenRouter
|
||||
WORDS_APP = os.environ.get("RAEA_WORDS_APP", "raea-words")
|
||||
WORDS_LANGUAGES = {"bg", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "hu", "it", "lv", "lt", "mt", "pl", "pt", "ro", "sk", "sl", "es", "sv", "ru", "uk"}
|
||||
# OPENROUTER_API_KEY for /v1/words: raea cloud's own key, the one its library index transcribes with
|
||||
words_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_WORDS_SECRET", "raea-farm-words"))
|
||||
# GROQ_API_KEY (12-03, Shane: "if we are going to use whisper, use groq"): the same Whisper large-v3, many times faster
|
||||
groq_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_GROQ_SECRET", "raea-farm-groq"))
|
||||
GROQ_WHISPER = os.environ.get("RAEA_GROQ_WHISPER", "whisper-large-v3")
|
||||
# a CPU render (the coordinator's sound pass) on lavapipe, with EGL's vendors hidden (docs/cloud.feature CL13)
|
||||
CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"}
|
||||
|
||||
@@ -204,16 +211,21 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
|
||||
|
||||
|
||||
def snapshot(d):
|
||||
out = {}
|
||||
for base, _, files in os.walk(d):
|
||||
for f in files:
|
||||
p = os.path.join(base, f)
|
||||
try:
|
||||
s = os.stat(p)
|
||||
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
|
||||
continue
|
||||
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
|
||||
return out
|
||||
# each file's stat is a trip to the volume (about 19 ms): one after another, 511 files took 9.7 s at each end of
|
||||
# every job, drawn or not (12-01). Asked 32 at once
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
paths = [os.path.join(base, f) for base, _, files in os.walk(d) for f in files]
|
||||
|
||||
def one(p):
|
||||
try:
|
||||
s = os.stat(p)
|
||||
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
|
||||
return None
|
||||
return os.path.relpath(p, d), f"{s.st_size}:{s.st_mtime_ns}"
|
||||
|
||||
with ThreadPoolExecutor(32) as pool:
|
||||
return dict(x for x in pool.map(one, paths) if x)
|
||||
|
||||
|
||||
class Log:
|
||||
@@ -235,8 +247,10 @@ 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
|
||||
CPU_SCALEDOWN = 60
|
||||
# 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
|
||||
|
||||
|
||||
def on(gpus, job):
|
||||
@@ -417,7 +431,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
|
||||
log = Log(id)
|
||||
log(f"raea farm: raea {' '.join(args)}")
|
||||
t_start = [time.time()]
|
||||
vol.reload()
|
||||
t_start.append(time.time())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
try:
|
||||
farm_media.fetch(work, f"{ROOT}/blobs", log)
|
||||
@@ -429,8 +445,15 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
return
|
||||
# the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without
|
||||
# this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25)
|
||||
t_start.append(time.time())
|
||||
vol.commit()
|
||||
t_start.append(time.time())
|
||||
before = snapshot(work)
|
||||
t_start.append(time.time())
|
||||
# where a job's start goes, said when it's slow, as its end is
|
||||
if t_start[-1] - t_start[0] > 5:
|
||||
d = [b - a for a, b in zip(t_start, t_start[1:])]
|
||||
log(f"raea farm: the job's start took {sum(d):.0f} s: reloading {d[0]:.1f} s, its media {d[1]:.1f} s, saving {d[2]:.1f} s, listing its files {d[3]:.1f} s")
|
||||
try:
|
||||
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's
|
||||
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
|
||||
@@ -533,7 +556,7 @@ def scene_run(frames: list[str]) -> list:
|
||||
return read_scenes(frames)
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret, groq_secret], timeout=3600)
|
||||
@modal.concurrent(max_inputs=32)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
@@ -613,8 +636,8 @@ def api():
|
||||
return {"raea": RAEA, "blender": BLENDER, "device": {"renders": "gpu", "name": f"raea on {'/'.join(RAEA_GPUS)}, Blender on {'/'.join(BLENDER_GPUS)}, up to {GPUS} at once"}, "farm": True, "jobs": []}
|
||||
|
||||
# what's said in a piece of sound, word by word, for a box's `raea words` (server/words.ts): a box has no
|
||||
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same Whisper large-v3 on OpenRouter that raea
|
||||
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
|
||||
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same model on a GPU hears it here (raea-words),
|
||||
# Whisper large-v3 on OpenRouter when that can't. The body is one MP3 piece (16 kHz mono,
|
||||
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
|
||||
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
|
||||
|
||||
@@ -648,8 +671,9 @@ def api():
|
||||
|
||||
check(req)
|
||||
key = os.environ.get("OPENROUTER_API_KEY", "")
|
||||
if not key:
|
||||
raise HTTPException(503, "the farm has no OpenRouter key for words (Modal secret raea-farm-words)")
|
||||
groq = os.environ.get("GROQ_API_KEY", "")
|
||||
if not key and not groq:
|
||||
raise HTTPException(503, "the farm has no Whisper key for words (Modal secrets raea-farm-groq, raea-farm-words)")
|
||||
mp3 = await req.body()
|
||||
if not mp3:
|
||||
raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes")
|
||||
@@ -659,7 +683,26 @@ def api():
|
||||
if req.query_params.get("language"):
|
||||
body["language"] = req.query_params["language"]
|
||||
|
||||
def ask_groq():
|
||||
fields = [("model", GROQ_WHISPER), ("response_format", "verbose_json"), ("timestamp_granularities[]", "word"), ("timestamp_granularities[]", "segment")]
|
||||
if req.query_params.get("language"):
|
||||
fields.append(("language", req.query_params["language"]))
|
||||
b = "raea" + os.urandom(12).hex()
|
||||
data = b"".join(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode() for k, v in fields)
|
||||
data += f'--{b}\r\nContent-Disposition: form-data; name="file"; filename="piece.mp3"\r\nContent-Type: audio/mpeg\r\n\r\n'.encode() + mp3 + f"\r\n--{b}--\r\n".encode()
|
||||
r = urllib.request.Request("https://api.groq.com/openai/v1/audio/transcriptions", data=data, headers={"authorization": f"Bearer {groq}", "content-type": f"multipart/form-data; boundary={b}", "user-agent": "raea-farm"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=300) as f:
|
||||
return 200, _json.load(f)
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
|
||||
|
||||
def ask():
|
||||
if groq:
|
||||
code, got = ask_groq()
|
||||
if code == 200 or not key:
|
||||
return code, {**got, "_model": f"groq/{GROQ_WHISPER}"}
|
||||
print(f"words: Groq said {code}, so OpenRouter hears it: {got.get('error', '')[:200]}", flush=True)
|
||||
r = urllib.request.Request("https://openrouter.ai/api/v1/audio/transcriptions", data=_json.dumps(body).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json", "x-title": "raea cloud words"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=300) as f:
|
||||
@@ -667,11 +710,19 @@ def api():
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
|
||||
|
||||
# raea-words first (words.py, 12-03): Parakeet on a GPU, each word's edges on its sound, as raea hears on a Mac.
|
||||
# Whisper's word times are guessed (StreetTalk's out points sat on them, mid-word); it stays as the fallback
|
||||
if not req.query_params.get("language") or req.query_params["language"] in WORDS_LANGUAGES:
|
||||
try:
|
||||
hear = modal.Cls.from_name(WORDS_APP, "Hear")
|
||||
return await hear().words.remote.aio(mp3)
|
||||
except Exception as e:
|
||||
print(f"words: {WORDS_APP} failed, so Whisper hears it: {str(e)[-300:]}", flush=True)
|
||||
code, got = await asyncio.to_thread(ask)
|
||||
if code != 200:
|
||||
raise HTTPException(502, f"OpenRouter's Whisper said {code}: {got.get('error', '')}")
|
||||
raise HTTPException(502, f"Whisper said {code}: {got.get('error', '')}")
|
||||
ws = [{"text": w.get("word", "").strip(), "start": float(w.get("start", 0)), "end": float(w.get("end", w.get("start", 0)))} for w in got.get("words") or [] if w.get("word", "").strip()]
|
||||
return {"model": "openai/whisper-large-v3", "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
|
||||
return {"model": got.get("_model", "openai/whisper-large-v3"), "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
|
||||
|
||||
@web.post("/v1/jobs")
|
||||
async def start(req: Request):
|
||||
|
||||
@@ -94,6 +94,19 @@ 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
|
||||
@@ -254,6 +267,81 @@ 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
|
||||
@@ -324,6 +412,10 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
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))
|
||||
@@ -344,17 +436,22 @@ 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 (0.0, 0.0)
|
||||
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick 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)
|
||||
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)
|
||||
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)
|
||||
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"]:
|
||||
@@ -365,24 +462,38 @@ 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 = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
|
||||
code = (hedged if quick else 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)
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
# raea cloud's library proxies on Modal (index-run.ts, 12-02): a video's 540p copy, made once per version of the file and
|
||||
# kept in R2 by its source's SHA-256. Its own app, beside raea-ingest's indexer, so it deploys without the indexer's
|
||||
# bundle. From sdk/cloud:
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/proxy.py
|
||||
#
|
||||
# POST /v1/proxy-jobs {url, put, ticket} a job: the file fetched from url, its proxy written through the Worker's
|
||||
# put (/u/<prefix>/) with ticket (exp=&sig=) -> {id}
|
||||
# GET /v1/proxy-jobs/ID {state: running} | {state: done, sha256, proxy, bytes...} | {state: failed, error}
|
||||
# GET /healthz
|
||||
#
|
||||
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest, as raea-ingest's).
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
app = modal.App("raea-proxy", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
|
||||
secret = modal.Secret.from_name("raea-ingest")
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=1024, secrets=[secret], timeout=300, scaledown_window=120)
|
||||
@modal.concurrent(max_inputs=16)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
web = FastAPI()
|
||||
token = os.environ["RAEA_INGEST_TOKEN"]
|
||||
|
||||
def check(req: Request):
|
||||
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
|
||||
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
|
||||
|
||||
@web.post("/v1/proxy-jobs")
|
||||
async def submit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
if not isinstance(b.get("put"), str) or not b["put"].startswith("https://") or not b["put"].endswith("/") or not isinstance(b.get("ticket"), str):
|
||||
raise HTTPException(400, "put is the Worker's /u/<prefix>/ and ticket its exp=&sig=")
|
||||
call = await proxy_job.spawn.aio(b["url"], b["put"], b["ticket"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/proxy-jobs/{job}")
|
||||
async def collect(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except modal.exception.FunctionTimeoutError:
|
||||
return {"state": "failed", "error": "the file took over an hour"}
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
|
||||
|
||||
@web.get("/healthz")
|
||||
def healthz():
|
||||
return PlainTextResponse("ok")
|
||||
|
||||
return web
|
||||
|
||||
|
||||
# ---- the proxy ----
|
||||
# What people watch and agents look, search and rough-cut from: 540 lines on the short side (never larger than the
|
||||
# original), H.264 CRF 28 veryfast, a keyframe every second so a seek lands anywhere, AAC 96 kbps stereo, faststart. On
|
||||
# one StreetTalk take (4K HEVC, 254 s, 726 MB) it was 45 MB. Written into R2 by its source's SHA-256 through the
|
||||
# Worker's /u/<prefix>/<file id> with a ticket (files.ts putTicket): the job holds no raea credential, and footage kept
|
||||
# twice is made once. A video already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy.
|
||||
PROXY_SHORT = 540
|
||||
PROXY_LIGHT_BPS = 2_500_000
|
||||
PART = 64 << 20
|
||||
AGENT = {"user-agent": "raea-ingest/1"}
|
||||
|
||||
|
||||
def _probe(path: str) -> dict:
|
||||
import json
|
||||
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path], capture_output=True, text=True, timeout=120)
|
||||
try:
|
||||
return json.loads(r.stdout or "{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
|
||||
def _picture(info: dict):
|
||||
"""(width, height as shown, codec) of its first video stream, or None"""
|
||||
v = next((s for s in info.get("streams", []) if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic") != 1), None)
|
||||
if not v:
|
||||
return None
|
||||
w, h = int(v.get("width") or 0), int(v.get("height") or 0)
|
||||
rot = 0
|
||||
for sd in v.get("side_data_list", []) or []:
|
||||
if "rotation" in sd:
|
||||
rot = int(float(sd["rotation"]))
|
||||
rot = rot or int(float((v.get("tags") or {}).get("rotate", 0) or 0))
|
||||
if abs(rot) % 180 == 90:
|
||||
w, h = h, w
|
||||
return w, h, v.get("codec_name", "")
|
||||
|
||||
|
||||
def _http(method: str, url: str, body=None, json_body=None, timeout=600) -> dict:
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
headers = dict(AGENT)
|
||||
data = body
|
||||
if json_body is not None:
|
||||
data = json.dumps(json_body).encode()
|
||||
headers["content-type"] = "application/json"
|
||||
if data is not None:
|
||||
headers["content-length"] = str(len(data))
|
||||
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method, headers=headers), timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}")
|
||||
|
||||
|
||||
@app.function(cpu=8, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=60)
|
||||
def proxy_job(url: str, put: str, ticket: str) -> dict:
|
||||
import hashlib
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src, out = os.path.join(d, "in.media"), os.path.join(d, "proxy.mp4")
|
||||
h, got = hashlib.sha256(), 0
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=AGENT), timeout=300) as r, open(src, "wb") as f:
|
||||
while chunk := r.read(8 << 20):
|
||||
h.update(chunk)
|
||||
got += len(chunk)
|
||||
f.write(chunk)
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"couldn't fetch the file: {e.code}", "fetched": e.code}
|
||||
except Exception as e:
|
||||
return {"error": f"couldn't fetch the file: {e}"[:300]}
|
||||
sha = h.hexdigest()
|
||||
info = _probe(src)
|
||||
pic = _picture(info)
|
||||
fmt = info.get("format", {})
|
||||
bps = int(float(fmt.get("bit_rate") or 0)) or (int(got * 8 / float(fmt["duration"])) if float(fmt.get("duration") or 0) > 0 else 0)
|
||||
base = {"sha256": sha, "source_bytes": got, "seconds": round(float(fmt.get("duration") or 0), 2)}
|
||||
if not pic:
|
||||
return {**base, "proxy": None, "why": "no picture in it"}
|
||||
w, hgt, codec = pic
|
||||
if min(w, hgt) <= PROXY_SHORT and codec == "h264" and "mp4" in fmt.get("format_name", "") and 0 < bps <= PROXY_LIGHT_BPS:
|
||||
return {**base, "proxy": None, "why": "light enough to be its own", "width": w, "height": hgt}
|
||||
fid = f"file-{sha[:24]}"
|
||||
at = f"{put}{fid}?{ticket}"
|
||||
try:
|
||||
began = _http("POST", f"{at}&step=begin", json_body={})
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"the Worker refused the proxy's upload: {e.code}"}
|
||||
if began.get("have"):
|
||||
return {**base, "proxy": fid, "kept": True}
|
||||
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", "-movflags", "+faststart", out],
|
||||
capture_output=True, text=True, timeout=3300,
|
||||
)
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
return {"error": f"ffmpeg stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
|
||||
size, parts = os.path.getsize(out), []
|
||||
with open(out, "rb") as f:
|
||||
n = 1
|
||||
while chunk := f.read(PART):
|
||||
parts.append(_http("PUT", f"{at}&upload={began['upload']}&part={n}", body=chunk))
|
||||
n += 1
|
||||
done = _http("POST", f"{at}&step=complete&upload={began['upload']}", json_body={"parts": parts})
|
||||
pw = _picture(_probe(out))
|
||||
return {**base, "proxy": done.get("id", fid), "bytes": size, "width": pw[0] if pw else None, "height": pw[1] if pw else None}
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# raea cloud's ears (12-03): what's said in a piece of sound, word by word, timed to its sound. NVIDIA's Parakeet TDT
|
||||
# 0.6B v3 (CC-BY-4.0; NeMo, Apache-2.0) on a GPU: the model raea hears with on a Mac (parakeet-mlx), so a cut's words
|
||||
# are timed the same in the cloud as at home. Whisper large-v3 on OpenRouter, which this replaces, guessed its word
|
||||
# times and heard a clipped word whole, and StreetTalk's cuts put their out points on those times ("really goo-").
|
||||
# Parakeet hears the words; Qwen3-ForcedAligner-0.6B (Apache-2.0) then times each one on the sound, where it knows the
|
||||
# language; each word is then widened onto the gaps around its sound (words_edges.py), so a cut on its edge is in a
|
||||
# pause. Measured 12-03 on StreetTalk's takes against the sound's own edges: word ends early (a cut there clips the
|
||||
# word) 12% of the time, against Whisper's 57% and Parakeet's own 28%; starts within 35 ms (median); and a word clipped
|
||||
# in the take is timed to where its sound stops (3 of 25 placed past it, Whisper 22). About 1.3 s for 20 s of sound.
|
||||
# The farm's POST /v1/words calls it (farm.py), falling back to Whisper (Groq) when it can't be reached.
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/words.py
|
||||
# Hear().words.remote(mp3_bytes) -> {model, duration, text, words: [{text, start, end}]} (s)
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
MODEL = "nvidia/parakeet-tdt-0.6b-v3"
|
||||
app = modal.App(os.environ.get("RAEA_WORDS_APP", "raea-words"))
|
||||
# the weights once, in the models volume the farm already keeps
|
||||
models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2)
|
||||
image = (
|
||||
modal.Image.debian_slim(python_version="3.11")
|
||||
.apt_install("ffmpeg", "libsndfile1")
|
||||
.pip_install("nemo_toolkit[asr]==2.7.3", "numpy<2.3")
|
||||
.env({"HF_HOME": "/models/hf", "TOKENIZERS_PARALLELISM": "false"})
|
||||
.add_local_python_source("words_edges")
|
||||
)
|
||||
align_image = (
|
||||
modal.Image.debian_slim(python_version="3.11")
|
||||
.apt_install("ffmpeg", "libsndfile1")
|
||||
.pip_install("qwen-asr==0.0.6", "torch==2.6.0", "torchaudio==2.6.0")
|
||||
.env({"HF_HOME": "/models/hf"})
|
||||
)
|
||||
# the aligner's languages, by the ISO code a caller gives
|
||||
ALIGNS = {"en": "English", "zh": "Chinese", "yue": "Cantonese", "fr": "French", "de": "German", "it": "Italian", "ja": "Japanese", "ko": "Korean", "pt": "Portuguese", "ru": "Russian", "es": "Spanish"}
|
||||
|
||||
|
||||
@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):
|
||||
import torch
|
||||
from qwen_asr import Qwen3ForcedAligner
|
||||
|
||||
self.m = Qwen3ForcedAligner.from_pretrained("Qwen/Qwen3-ForcedAligner-0.6B", dtype=torch.bfloat16, device_map="cuda:0")
|
||||
models.commit()
|
||||
|
||||
@modal.method()
|
||||
def align(self, pcm: bytes, text: str, language: str) -> list:
|
||||
import numpy as np
|
||||
|
||||
x = np.frombuffer(pcm, np.int16).astype(np.float32) / 32768
|
||||
r = self.m.align(audio=(x, 16000), text=text, language=language)[0]
|
||||
return [{"text": u.text, "start": float(u.start_time), "end": float(u.end_time)} for u in r]
|
||||
|
||||
|
||||
def aligned(heard: list, got: list) -> "list | None":
|
||||
"""the heard words (their spelling and punctuation) on the aligner's times, matched in order by their letters; a
|
||||
word the aligner split or spelt otherwise keeps Parakeet's times. None if under 80% of the words matched"""
|
||||
import difflib
|
||||
import re
|
||||
|
||||
key = lambda t: re.sub(r"[^\w]", "", t.lower())
|
||||
got = [g for g in got if key(g["text"])]
|
||||
sm = difflib.SequenceMatcher(None, [key(h["text"]) for h in heard], [key(g["text"]) for g in got], autojunk=False)
|
||||
out = [dict(h) for h in heard]
|
||||
n = 0
|
||||
for a, b, size in sm.get_matching_blocks():
|
||||
for k in range(size):
|
||||
g = got[b + k]
|
||||
out[a + k].update(start=g["start"], end=max(g["end"], g["start"] + 0.02))
|
||||
n += 1
|
||||
return out if heard and n / len(heard) >= 0.8 else None
|
||||
|
||||
|
||||
# full attention holds about this much sound on a T4; longer pieces read with local attention (NeMo's own advice)
|
||||
FULL_S = 180
|
||||
|
||||
|
||||
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
|
||||
class Hear:
|
||||
@modal.enter()
|
||||
def load(self):
|
||||
import nemo.collections.asr as asr
|
||||
|
||||
self.m = asr.models.ASRModel.from_pretrained(MODEL)
|
||||
self.m.eval()
|
||||
self.local = False
|
||||
models.commit()
|
||||
|
||||
def attention(self, local: bool):
|
||||
if local != self.local:
|
||||
self.m.change_attention_model("rel_pos_local_attn", [256, 256]) if local else self.m.change_attention_model("rel_pos")
|
||||
self.local = local
|
||||
|
||||
@modal.method()
|
||||
def words(self, sound: bytes, language: str = "") -> dict:
|
||||
import numpy as np
|
||||
import words_edges
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src, wav = f"{d}/in", f"{d}/in.wav"
|
||||
open(src, "wb").write(sound)
|
||||
r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav], capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
raise ValueError(f"the sound couldn't be read: {r.stderr.strip()[-300:]}")
|
||||
pcm = np.fromfile(wav, dtype=np.int16, offset=44).astype(np.float32) / 32768
|
||||
duration = len(pcm) / 16000
|
||||
self.attention(duration > FULL_S)
|
||||
h = self.m.transcribe([wav], timestamps=True, batch_size=1, verbose=False)[0]
|
||||
heard = [{"text": w["word"].strip(), "start": float(w["start"]), "end": float(w["end"])} for w in (h.timestamp or {}).get("word", []) if w.get("word", "").strip()]
|
||||
model = MODEL
|
||||
# timed by the aligner where it knows the language (English when none is given and the words read as Latin)
|
||||
lang = ALIGNS.get(language.lower()[:3].rstrip("-_")) or ALIGNS.get(language.lower()[:2]) or ("English" if not language and heard and all(ord(c) < 0x250 for c in h.text) else None)
|
||||
if lang and heard:
|
||||
try:
|
||||
got = aligned(heard, Align().align.remote((pcm * 32768).clip(-32768, 32767).astype(np.int16).tobytes(), " ".join(w["text"] for w in heard), lang))
|
||||
if got:
|
||||
heard, model = got, f"{MODEL}+Qwen/Qwen3-ForcedAligner-0.6B"
|
||||
else:
|
||||
print("words: the aligner's words didn't pair with Parakeet's, so Parakeet's times stand", flush=True)
|
||||
except Exception as e:
|
||||
print(f"words: the aligner failed, so Parakeet's times stand: {str(e)[-300:]}", flush=True)
|
||||
words = words_edges.edges(heard, words_edges.levels(pcm, 16000))
|
||||
return {"model": model, "duration": duration, "text": h.text, "words": words}
|
||||
@@ -0,0 +1,62 @@
|
||||
# Each heard word's edges moved onto its sound (12-03): a transcriber's word times are its frames' (Parakeet's 80 ms,
|
||||
# Whisper's guesses), so a cut put on a word's end can land on its tail. StreetTalk's Elfster cuts said "really goo-",
|
||||
# "ever sin-": each out point came from words.json. Here a word ends where its sound falls into a gap and starts where it
|
||||
# comes out of one, read every 10 ms, with the same gap the sound check holds edit points to (sdk/goal packs/sound.ts:
|
||||
# 18 dB under the speech, or in a street's noise within 6 dB of its quietest, never closer than 8 dB to the speech).
|
||||
# A word with no gap near it (said straight into the next) keeps the transcriber's time.
|
||||
import numpy as np
|
||||
|
||||
FRAME = 0.01 # s
|
||||
SPEECH_Q = 90
|
||||
FLOOR_Q = 10
|
||||
GAP = 18.0
|
||||
GAP_FLOOR = 6.0
|
||||
GAP_LEAST = 8.0
|
||||
QUIET = 3 # frames under the gap that make a gap: 30 ms
|
||||
LOOK = 0.25 # s a word's end may move later, its start earlier, at most
|
||||
|
||||
|
||||
def levels(x: np.ndarray, rate: int) -> np.ndarray:
|
||||
"""dB of each 10 ms of mono samples in [-1, 1]"""
|
||||
n = int(rate * FRAME)
|
||||
k = len(x) // n
|
||||
if not k:
|
||||
return np.zeros(0)
|
||||
fr = x[: k * n].reshape(k, n).astype(np.float64)
|
||||
return 20 * np.log10(np.sqrt((fr**2).mean(1)) + 1e-9)
|
||||
|
||||
|
||||
def gap_level(db: np.ndarray) -> float:
|
||||
"""the level under which sound is a gap between words"""
|
||||
speech = float(np.percentile(db, SPEECH_Q))
|
||||
floor = float(np.percentile(db, FLOOR_Q))
|
||||
return min(speech - GAP_LEAST, max(speech - GAP, floor + GAP_FLOOR))
|
||||
|
||||
|
||||
def edges(words: list[dict], db: np.ndarray, gap: float | None = None) -> list[dict]:
|
||||
"""words [{text, start, end}] (s), each widened onto the gaps around its sound: its end moved later to where its sound
|
||||
has fallen into a gap, its start earlier to where it came out of one. Never narrowed: a word's quiet edges (an
|
||||
"f", an "s", a breath) sit under the speech's level but are heard, so a cut is never put inside what the
|
||||
transcriber called the word. Not past the words beside it, nor more than LOOK."""
|
||||
if not len(db) or not words:
|
||||
return words
|
||||
g = gap_level(db) if gap is None else gap
|
||||
loud = db >= g
|
||||
n = len(db)
|
||||
at = lambda t: min(n, max(0, int(round(t / FRAME))))
|
||||
quiet = lambda f: f + QUIET <= n and not loud[f : f + QUIET].any()
|
||||
out = [dict(w) for w in words]
|
||||
for i, w in enumerate(out):
|
||||
prev_end = out[i - 1]["end"] if i else 0.0
|
||||
next_start = words[i + 1]["start"] if i + 1 < len(words) else n * FRAME
|
||||
# the end: the first gap at or after the heard end
|
||||
for f in range(at(w["end"]), at(min(w["end"] + LOOK, max(next_start, w["end"]))) + 1):
|
||||
if quiet(f):
|
||||
w["end"] = round(max(f * FRAME, w["end"]), 3)
|
||||
break
|
||||
# the start: the last gap that ends at or before the heard start
|
||||
for f in range(at(w["start"]), at(max(w["start"] - LOOK, prev_end)) - 1, -1):
|
||||
if f - QUIET >= 0 and not loud[f - QUIET : f].any():
|
||||
w["start"] = round(min(f * FRAME, w["start"]), 3)
|
||||
break
|
||||
return out
|
||||
@@ -21,6 +21,12 @@ say packages
|
||||
sudo -E apt-get update -qq
|
||||
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
|
||||
# what every agent reached for and installed itself at each project's start (12-02: `which ffmpeg`, a search of the
|
||||
# disk, then apt, minutes in all): ffmpeg and ffprobe (the montage check reads frames with them too) and the PDF tools a
|
||||
# brief or brand guide is read with
|
||||
for f in ffmpeg poppler-utils; do
|
||||
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
|
||||
done
|
||||
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
|
||||
# open families brands are closest to, each taken when this Ubuntu has it
|
||||
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
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// 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;
|
||||
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`), else the one nearest the last chosen, else the largest
|
||||
const f = last === undefined ? fs[0] : fs.reduce((p, q) => (Math.abs(q[0] - last!) < Math.abs(p[0] - last!) ? q : p));
|
||||
if (near === undefined) last = f[0];
|
||||
out.push([t, f[0], f[1], f[2]]);
|
||||
for (const o of fs) if (o !== f) others.push([t, o[0] - o[2] / 2, o[0] + o[2] / 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, Body Shop: 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, 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}
|
||||
playbackRate={playbackRate}
|
||||
muted={muted}
|
||||
style={{ width: "100%", height: "100%", objectFit: "cover", ...style, objectPosition: pos, ...(transform ? { transform, transformOrigin: origin } : {}) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// <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 } 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;
|
||||
};
|
||||
|
||||
export default function Title({ children, region = "top", size = 64, style }: Props) {
|
||||
const align = region === "bottom" ? "flex-end" : region === "center" ? "center" : "flex-start";
|
||||
return (
|
||||
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: align, alignItems: "center" }}>
|
||||
<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>
|
||||
</Region>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// @raea/cli: the agent shell's own verbs of `raea` (init, cut, frame, part, brand), the project's files for editing video
|
||||
// as a React + TypeScript project. The native raea runs this handler for the verbs in its SHELL list (motion.rs shell(),
|
||||
// through src/native.ts on its JavaScriptCore); what needs perception, ffmpeg or raea's API is asked of `host`
|
||||
// (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there
|
||||
// is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest.
|
||||
import { REGISTRY, TEMPLATE } from "./registry.gen";
|
||||
import { FEATURE_DIRS, featureLayout } from "./layout";
|
||||
|
||||
/** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */
|
||||
export type Host = (op: string, args: Record<string, unknown>) => any;
|
||||
|
||||
/** The engine's own command line (the native `raea`: render FILE.tsx, play, guide, song, add PKG ...), run in the shell's
|
||||
* folder. The shell gives it; without one, those verbs say so. */
|
||||
export type Engine = (args: string[], ctx: unknown) => Promise<{ stdout: string; stderr: string; exitCode: number }>;
|
||||
|
||||
type Fs = {
|
||||
exists(p: string): Promise<boolean>;
|
||||
readFile(p: string, enc?: string): Promise<string>;
|
||||
writeFile(p: string, data: string): Promise<void>;
|
||||
mkdir(p: string, o?: { recursive?: boolean }): Promise<void>;
|
||||
};
|
||||
type Ctx = { cwd: string; fs: Fs };
|
||||
const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode });
|
||||
// `raea library` (library.ts), kept apart from the imports above
|
||||
import { libraryVerb } from "./library";
|
||||
// `raea show` (show.ts): what a session shows the person, in the raea app
|
||||
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";
|
||||
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
|
||||
import { bugVerb } from "./bug";
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name);
|
||||
return i >= 0 ? args[i + 1] : undefined;
|
||||
}
|
||||
|
||||
const clean = (args: string[], ...withValue: string[]) =>
|
||||
args.filter((a, i) => !a.startsWith("--") && !withValue.includes(args[i - 1] ?? ""));
|
||||
|
||||
/** A clip of a take: seconds in the take's own time, and the line it carries. */
|
||||
export interface Cut {
|
||||
take: string;
|
||||
file: string;
|
||||
from: number;
|
||||
to: number;
|
||||
line: string;
|
||||
/** a sound-only take's clip plays as <Audio> (#89); absent means video */
|
||||
kind?: "video" | "audio";
|
||||
}
|
||||
|
||||
/** 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 }): string {
|
||||
const files = [...new Set(clips.map((c) => c.file))];
|
||||
const id = (f: string) => "m_" + f.replace(/\W/g, "_");
|
||||
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" };
|
||||
export const cuts: Cut[] = [
|
||||
${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);
|
||||
`;
|
||||
}
|
||||
|
||||
const NOTES = `# This project
|
||||
|
||||
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). 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.
|
||||
|
||||
## raea (everything there is; import from "raea")
|
||||
|
||||
Time: useCurrentFrame() (frames, from 0 inside the nearest Sequence), useVideoConfig() {width, height, fps,
|
||||
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. <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.
|
||||
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.
|
||||
Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
|
||||
Not there: React hooks come from "react" (useMemo, useState), not from raea.
|
||||
`;
|
||||
|
||||
/** The workspace a folder is in: the nearest folder at or above it holding .raea/workspace, through the shell's fs. */
|
||||
async function workspaceAbove(c: Ctx, from: string): Promise<string | undefined> {
|
||||
// up to the root, / or on Windows C:
|
||||
for (let d = from.replace(/[\\/]+$/, ""); d; ) {
|
||||
if (await c.fs.exists(`${d}/.raea/workspace`)) return d;
|
||||
const up = Math.max(d.lastIndexOf("/"), d.lastIndexOf("\\"));
|
||||
if (up < 0) break;
|
||||
d = d.slice(0, up);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The `raea` command's handler (the shell wraps it with just-bash's defineCommand, so this package needs no dependency). */
|
||||
export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
return async (args: string[], ctx: unknown) => {
|
||||
const c = ctx as unknown as Ctx;
|
||||
const p = (rel: string) => fromCwd(c.cwd, rel);
|
||||
const ask = (op: string, a: Record<string, unknown> = {}) => {
|
||||
if (!host) throw new Error(`raea ${op} needs a host (the native raea's src/native.ts); this shell has none`);
|
||||
return host(op, a);
|
||||
};
|
||||
const text = (v: unknown) => (typeof v === "string" ? v : JSON.stringify(v, null, 2)) + "\n";
|
||||
const native = (a: string[] = args) => {
|
||||
if (!engine) throw new Error(`raea ${a[0]} is the engine's (the native raea), and this shell has none`);
|
||||
return engine(a, ctx);
|
||||
};
|
||||
// a set is a folder of examples/components (`raea make component add reel` copies it whole); a component is one file of a
|
||||
// set that says `// raea make component add NAME: ...` at its top (`raea make component add`, before 11-12), and copies alone
|
||||
const said = (src: string) => (/^\/\/ raea (?:make )?component add [\w-]+: (.*)$/m.exec(src)?.[1] ?? "").split(". ")[0];
|
||||
const single = (n: string) => Object.values(REGISTRY).map((set) => set[`${n}.tsx`]).find((src) => src && new RegExp(`^// raea (?:make )?component add ${n}:`, "m").test(src));
|
||||
const parts = () =>
|
||||
Object.entries(REGISTRY)
|
||||
.flatMap(([set, files]) => [
|
||||
`${set.padEnd(14)} the whole set, ${Object.keys(files).length} files, into components/${set}/`,
|
||||
...Object.entries(files).filter(([f, src]) => single(f.replace(/\.tsx$/, "")) === src).map(([f, src]) => `${f.replace(/\.tsx$/, "").padEnd(14)} ${said(src)}`),
|
||||
])
|
||||
.join("\n") + "\n";
|
||||
try {
|
||||
switch (args[0]) {
|
||||
// the native raea's help lists the shell's verbs with its own: one list
|
||||
case undefined:
|
||||
case "help":
|
||||
case "--help":
|
||||
return await native(["help"]);
|
||||
case "init": {
|
||||
const made: string[] = [];
|
||||
const put = async (name: string, body: string) => {
|
||||
if (await c.fs.exists(p(name))) return;
|
||||
await c.fs.writeFile(p(name), body);
|
||||
made.push(name);
|
||||
};
|
||||
const shape = ask("shape", {}) as { width: number; height: number; fps: number };
|
||||
// by feature, as a Bevy project is (S5a): opt-in until it's the default
|
||||
if (args.includes("--layout") && args[args.indexOf("--layout") + 1] !== "feature") return out("", 2, "raea init [--layout feature]\n");
|
||||
if (args.includes("--layout")) {
|
||||
for (const d of FEATURE_DIRS) await c.fs.mkdir(p(d), { recursive: true });
|
||||
const name = c.cwd.replace(/[\\/]$/, "").split(/[\\/]/).pop() || "project";
|
||||
for (const [f, body] of Object.entries(featureLayout(name, shape))) await put(f, body);
|
||||
return out(made.length ? `made ${made.join(", ")}; render it with raea render src/main.tsx\n` : "nothing to make: the project's files are here\n");
|
||||
}
|
||||
await c.fs.mkdir(p("components"), { recursive: true });
|
||||
await put("edit.tsx", TEMPLATE["edit.tsx"]);
|
||||
await put("cuts.ts", cutsModule([], shape));
|
||||
await put("styles.gen.ts", `export const css = "";\n`);
|
||||
// AGENTS.md is raea's own notes: an older generated copy (it opens with this header) is brought up to date, a
|
||||
// person's own file is left alone
|
||||
const notes = p("AGENTS.md");
|
||||
if (await c.fs.exists(notes)) {
|
||||
const was = await c.fs.readFile(notes, "utf8");
|
||||
if (was !== NOTES && was.startsWith("# This project\n\nA video edit as a React + TypeScript project")) {
|
||||
await c.fs.writeFile(notes, NOTES);
|
||||
made.push("AGENTS.md (updated)");
|
||||
}
|
||||
} else await put("AGENTS.md", NOTES);
|
||||
return out(made.length ? `made ${made.join(", ")}\n` : "nothing to make: the project's files are here\n");
|
||||
}
|
||||
// `raea make component` copies raea's sets and components into the project's components/ (docs/layout.feature
|
||||
// LY4), or with --shared into the workspace's shared/components/, which every project imports as @shared/components/
|
||||
case "component": {
|
||||
const was = "";
|
||||
// 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`);
|
||||
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");
|
||||
let home = "components";
|
||||
// what imports it: a composition in compositions/ reaches ../components/, one at the root ./components/
|
||||
let from = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
|
||||
if (args.includes("--shared")) {
|
||||
const ws = await workspaceAbove(c, c.cwd);
|
||||
if (!ws) return out("", 1, `${was}raea make component add --shared: no workspace above ${c.cwd} (no .raea/workspace): add it to the project instead\n`);
|
||||
home = `${ws}/shared/components`;
|
||||
from = "@shared/components";
|
||||
}
|
||||
await c.fs.mkdir(p(home), { recursive: true });
|
||||
const done: string[] = [];
|
||||
const shown = (rel: string) => (absolute(home) ? `shared/components/${rel.slice(home.length + 1)}` : rel);
|
||||
for (const n of names) {
|
||||
const set = REGISTRY[n];
|
||||
if (set) {
|
||||
// a set is the project's own once copied: never overwritten unasked, and said so loudly
|
||||
const dir = `${home}/${n}`;
|
||||
if (!force && (await c.fs.exists(p(dir)))) return out(done.join(""), 1, `raea make component add: ${shown(dir)}/ is already here (yours now; --force replaces its files)\n`);
|
||||
await c.fs.mkdir(p(dir), { recursive: true });
|
||||
for (const [f, src] of Object.entries(set)) await c.fs.writeFile(p(`${dir}/${f}`), src);
|
||||
done.push(`${shown(dir)}/ ${Object.keys(set).length} files; import from "${from}/${n}"\n`);
|
||||
continue;
|
||||
}
|
||||
const src = single(n);
|
||||
// a library component: its folder under components/CATEGORY/NAME/, with the shared files it needs
|
||||
const got = src || !host ? null : (host("components", { op: "get", name: n }) as Got | null);
|
||||
if (got) {
|
||||
let wrote = 0;
|
||||
let kept = 0;
|
||||
for (const [f, text] of Object.entries(got.files)) {
|
||||
const dest = p(`${home}/${f}`);
|
||||
if (!force && (await c.fs.exists(dest))) kept++;
|
||||
else {
|
||||
await c.fs.mkdir(dest.slice(0, dest.lastIndexOf("/")), { recursive: true });
|
||||
await c.fs.writeFile(dest, text);
|
||||
wrote++;
|
||||
}
|
||||
}
|
||||
// its npm packages (culori and the like), installed by the engine's package manager when there is one
|
||||
let installed = "";
|
||||
if (got.item.packages?.length && engine) {
|
||||
const r = await native(["add", ...got.item.packages]);
|
||||
installed = r.exitCode ? `raea add failed: ${(r.stderr || r.stdout).trim().split("\n")[0]}` : "installed";
|
||||
}
|
||||
done.push(added(got, absolute(home) ? "shared/components" : home, from, wrote, kept, installed));
|
||||
continue;
|
||||
}
|
||||
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them, list WORDS searches the library)\n`);
|
||||
const dest = p(`${home}/${n}.tsx`);
|
||||
if (!force && (await c.fs.exists(dest))) {
|
||||
done.push(`${shown(`${home}/${n}.tsx`)} is already here (yours now; --force replaces it)\n`);
|
||||
continue;
|
||||
}
|
||||
await c.fs.writeFile(dest, src);
|
||||
done.push(`${shown(`${home}/${n}.tsx`)} import it: import ${n.replace(/(^|-)(\w)/g, (_, __, ch) => ch.toUpperCase())} from "${from}/${n}";\n`);
|
||||
}
|
||||
return out(done.join(""), 0, was);
|
||||
}
|
||||
// `add` is npm packages (the engine's package manager); a registry component's name is pointed at `raea make component add`
|
||||
case "add": {
|
||||
const r = await native();
|
||||
const part = clean(args.slice(1)).find((n) => REGISTRY[n] || single(n));
|
||||
return r.exitCode && part ? { ...r, stderr: r.stderr + `(a raea component? raea make component add ${part})\n` } : r;
|
||||
}
|
||||
case "cut": {
|
||||
const spans: number[][] = [];
|
||||
args.forEach((a, i) => {
|
||||
if (a === "--at" && args[i + 1]) {
|
||||
const m = /^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)$/.exec(args[i + 1]);
|
||||
if (m) spans.push([Number(m[1]), Number(m[2])]);
|
||||
}
|
||||
});
|
||||
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");
|
||||
return out(r.said.endsWith("\n") ? r.said : r.said + "\n");
|
||||
}
|
||||
// what a file says, word by word (raea goal check's words, say, never and CTA packs hear through it)
|
||||
case "words": {
|
||||
const file = clean(args.slice(1), "-o").find((a) => a !== "-o");
|
||||
if (!file) return out("", 2, "raea words FILE [-o OUT.words.json]\n");
|
||||
return out(text(ask("words", { file, out: flag(args, "-o") })));
|
||||
}
|
||||
case "frame": {
|
||||
const take = clean(args.slice(1), "--at")[0];
|
||||
if (!take) return out("", 2, "raea frame TAKE [--at SECONDS]\n");
|
||||
const at = flag(args, "--at");
|
||||
return out(text(ask("frame", { take, at: at === undefined ? undefined : Number(at) })));
|
||||
}
|
||||
case "brand": {
|
||||
const q = clean(args.slice(1)).join(" ");
|
||||
if (!q) return out("", 2, "raea brand DOMAIN|URL (stripe.com, or the site's URL: read on this machine)\n");
|
||||
return out(text(ask("brand", { brand: q })));
|
||||
}
|
||||
case "library":
|
||||
return out(libraryVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
||||
case "show": {
|
||||
// --labels FILE.json: read here, where the shell's files are (show.ts labelsIn)
|
||||
const at = args.lastIndexOf("--labels");
|
||||
const file = at > 0 ? args[at + 1] : undefined;
|
||||
let listed: unknown[] | undefined;
|
||||
try {
|
||||
listed = file === undefined ? undefined : labelsIn(await c.fs.readFile(p(file), "utf8"), file);
|
||||
} catch (e) {
|
||||
return out("", 2, `raea show: ${(e as Error).message.startsWith("--labels") ? (e as Error).message : `--labels ${file}: ${(e as Error).message}`}\n`);
|
||||
}
|
||||
return out(showVerb(ask, args.slice(1), c.cwd, (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}, listed));
|
||||
}
|
||||
case "clothes":
|
||||
return out(clothesVerb(ask, args.slice(1)));
|
||||
case "bug":
|
||||
return out(bugVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
||||
default:
|
||||
return await native();
|
||||
}
|
||||
} catch (e) {
|
||||
return out("", 1, `raea ${args[0] ?? ""}: ${String((e as Error)?.message ?? e)}\n`);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
// The agent shell's own verbs (init ...) on the native `raea`, which runs this file on its JavaScriptCore with Node's core
|
||||
// (runtime/react/src/scene.rs shell(), raea_native::js::run_node), so each verb has one source: this package's handler.
|
||||
// The host's ops it needs are answered here, one more with each verb ported (docs/agent-surfaces.md); the rest refuse.
|
||||
//
|
||||
// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { basename, delimiter, dirname, extname } from "node:path";
|
||||
import { brandKit, pixelsOf } from "./brand";
|
||||
import { readSite, stylesOf } from "./scrape";
|
||||
import { wordsOf } from "./heard";
|
||||
import { harness, library, show, task } from "./app";
|
||||
import { fromCwd } from "./show";
|
||||
import { clothesHost } from "./wardrobe";
|
||||
import { componentsHost } from "./catalog";
|
||||
import { raeaHandler, type Engine, type Host } from "./index";
|
||||
|
||||
const [raea, ...args] = process.argv.slice(2);
|
||||
const cwd = process.cwd();
|
||||
const at = (p: string) => fromCwd(cwd, p);
|
||||
|
||||
/** The project's shape: its cut's (cuts.json's edit), else a 1080x1920 vertical at 30 fps */
|
||||
function shape() {
|
||||
const file = at("cuts.json");
|
||||
const edit = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as { edit?: { width?: number; height?: number; fps?: number } }).edit : undefined;
|
||||
return edit?.width && edit.height && edit.fps ? { width: edit.width, height: edit.height, fps: edit.fps } : { width: 1080, height: 1920, fps: 30 };
|
||||
}
|
||||
|
||||
/** The engine's own verb run for its effect (`raea media still ...`); its answer, or why it refused */
|
||||
function engineRun(a: string[]): string {
|
||||
const r = spawnSync(raea, a, { cwd, encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`raea ${a.join(" ")}: ${(r.stdout + r.stderr).trim()}`);
|
||||
return r.stdout;
|
||||
}
|
||||
|
||||
/** The engine's own answer as JSON (`raea media probe|cuts ...`) */
|
||||
const engineJson = (a: string[]): any => JSON.parse(engineRun(a));
|
||||
|
||||
const VIDEO = ["mp4", "mov", "m4v", "mkv", "webm"];
|
||||
/** a take with sound alone (a voice recording, a bed): cut on its words as a video is, played as <Audio> (#89) */
|
||||
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/: 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()) walk(p);
|
||||
else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
|
||||
}
|
||||
};
|
||||
walk("media");
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
/** A take named by its path (with or without its extension), file name, stem or folder */
|
||||
function takeOf(name: string): string {
|
||||
const t = name.trim().replace(/^\.?\//, "");
|
||||
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/ (${all.join(", ") || "none"})`);
|
||||
return found;
|
||||
}
|
||||
|
||||
type Word = { text: string; from: number; to: number };
|
||||
|
||||
/** A take's transcript: its words.json (TAKE.words.json, or words.json in its folder), [{text, start_ms, end_ms}] */
|
||||
function wordsFile(take: string): string {
|
||||
const own = at(`${take.slice(0, take.length - extname(take).length)}.words.json`);
|
||||
const folder = at(`${dirname(take)}/words.json`);
|
||||
return existsSync(own) || !existsSync(folder) ? own : folder;
|
||||
}
|
||||
|
||||
/** A take's words in its own seconds; with `hear`, a take with no transcript is transcribed first (parakeet-mlx, local),
|
||||
* into TAKE.words.json, kept */
|
||||
function words(take: string, hear = false): Word[] {
|
||||
const file = wordsFile(take);
|
||||
if (!existsSync(file)) {
|
||||
if (!hear) return [];
|
||||
hearTake(take, file);
|
||||
}
|
||||
return (JSON.parse(readFileSync(file, "utf8")) as { text: string; start_ms: number; end_ms: number }[])
|
||||
.filter((w) => w.text?.trim())
|
||||
.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 }));
|
||||
}
|
||||
|
||||
/** A tool a clean Mac lacks, found or installed once by raea's tools/ensure.sh (docs/app.feature AP6), which sits in
|
||||
* share/raea/tools beside a release's bin/raea, or in the tree a built raea is in; the bare name if there's none */
|
||||
function ensure(name: string): string {
|
||||
const real = realpathSync(raea);
|
||||
const script = [`${dirname(real)}/../share/raea/tools/ensure.sh`, `${dirname(real)}/../../tools/ensure.sh`].find(existsSync);
|
||||
if (!script) return name;
|
||||
const r = spawnSync("bash", [script, name], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
|
||||
return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : name;
|
||||
}
|
||||
|
||||
function hearTake(take: string, out: string) {
|
||||
// parakeet-mlx is Apple silicon's (MLX); elsewhere raea has no transcriber yet, so the two ways that work there
|
||||
if (process.platform !== "darwin")
|
||||
throw new Error(`cutting ${take} by its words needs its transcript, and raea transcribes only on a Mac so far: give it one as ${basename(out)} ([{ "text", "start_ms", "end_ms" }], beside it), or cut it by time: --at A-B`);
|
||||
const dir = mkdtempSync(`${tmpdir()}/raea-hear-`);
|
||||
try {
|
||||
const wav = `${dir}/take.wav`;
|
||||
const a = spawnSync(raea, ["media", "audio", at(take), "--rate", "16000", "--mono", "-o", wav], { encoding: "utf8" });
|
||||
if (a.status !== 0) throw new Error(`no sound to transcribe in ${take}: ${(a.stdout + a.stderr).trim()}`);
|
||||
const p = spawnSync(ensure("parakeet-mlx"), [wav, "--output-format", "json", "--output-dir", dir], { encoding: "utf8" });
|
||||
if (p.status !== 0) throw new Error(`transcribing ${take} needs parakeet-mlx (tools/ensure.sh installs it: ${(p.stderr ?? "").trim().split("\n").pop()}), or cut it by time: --at A-B`);
|
||||
const heard = JSON.parse(readFileSync(`${dir}/take.json`, "utf8")) as { sentences: { tokens: { text: string; start: number; end: number }[] }[] };
|
||||
const ws = heard.sentences.flatMap((s) => wordsOf(s.tokens)).map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }));
|
||||
writeFileSync(out, JSON.stringify(ws) + "\n");
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 = 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;
|
||||
}
|
||||
|
||||
/** 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) ? [] : jumpCuts(take);
|
||||
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" };
|
||||
|
||||
/** `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;
|
||||
const clips: Clip[] = [...a.keep];
|
||||
let notes: string[] = [];
|
||||
if (a.lines.length) {
|
||||
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)`);
|
||||
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 });
|
||||
}
|
||||
// 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 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;
|
||||
});
|
||||
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 */
|
||||
function perceive(): string {
|
||||
// raea's path (a bare name, as a test may pass, is found on PATH)
|
||||
const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea;
|
||||
// raea-perceive.exe on Windows (#43)
|
||||
const name = process.platform === "win32" ? "raea-perceive.exe" : "raea-perceive";
|
||||
const beside = existsSync(self) ? `${dirname(realpathSync(self))}/${name}` : "";
|
||||
return process.env.RAEA_PERCEIVE || (existsSync(beside) ? beside : name);
|
||||
}
|
||||
|
||||
/** `raea frame`'s host step: how a take fits the edit's shape, from where its face is at a moment (raea-perceive's
|
||||
* layout of one still): a talking take (FaceFrame), a screen wider than the edit (ScreenFit), or a plain cover */
|
||||
type Box = { x: number; y: number; w: number; h: number };
|
||||
|
||||
/** Where the face is in a take at a moment, as shares of its picture (raea-perceive's layout of a still), if there's one */
|
||||
function faceAt(file: string, t: number): Box | undefined {
|
||||
const dir = mkdtempSync(`${tmpdir()}/raea-face-`);
|
||||
try {
|
||||
const still = `${dir}/still.jpg`;
|
||||
engineRun(["media", "still", at(file), "--at", t.toFixed(2), "-o", still]);
|
||||
const r = spawnSync(perceive(), ["see-layout", still], { encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`finding the face needs raea-perceive (beside raea; RAEA_PERCEIVE names another): ${(r.stderr || r.error?.message || "").trim()}`);
|
||||
const zones = (JSON.parse(r.stdout.split("\n")[0] || "{}").layout?.zones ?? []) as { face?: Box }[];
|
||||
return zones.find((z) => z.face)?.face;
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** The take's length and picture size (raea media probe) */
|
||||
function probeOf(file: string): { dur: number; sw: number; sh: number } {
|
||||
const p = engineJson(["media", "probe", at(file)]);
|
||||
return { dur: (p.duration as number) || 0, sw: (p.video?.width as number) || 0, sh: (p.video?.height as number) || 0 };
|
||||
}
|
||||
|
||||
/** perception.json for the clips (what <Region> and the checks place parts by): for each clip, keyed by its first frame,
|
||||
* the face at its middle mapped through the edit's centred cover crop into the edit's pixels, and the safe band (220 px
|
||||
* under the top, 420 over the bottom at 1920 high). A take raea-perceive can't read gets the band alone. */
|
||||
function perception(edit: { width: number; height: number; fps: number }, clips: Clip[]) {
|
||||
const k = edit.height / 1920;
|
||||
const safe = { top: Math.round(220 * k), bottom: Math.round(edit.height - 420 * k) };
|
||||
const seen = new Map<string, Box | undefined>();
|
||||
const out: Record<string, { safe: typeof safe; face?: Box }> = {};
|
||||
let t = 0;
|
||||
for (const c of clips) {
|
||||
const mid = (c.from + c.to) / 2;
|
||||
const key = `${c.file}|${Math.floor(mid * 10)}`;
|
||||
// a sound-only clip has no face to find: the band alone
|
||||
if (!seen.has(key) && (c.kind === "audio" || isAudio(c.file))) seen.set(key, undefined);
|
||||
if (!seen.has(key)) {
|
||||
let face: Box | undefined;
|
||||
try {
|
||||
const f = faceAt(c.file, mid);
|
||||
const { sw, sh } = probeOf(c.file);
|
||||
if (f && sw && sh) {
|
||||
const s = Math.max(edit.width / sw, edit.height / sh);
|
||||
const [ox, oy] = [(edit.width - sw * s) / 2, (edit.height - sh * s) / 2];
|
||||
face = { x: Math.round(f.x * sw * s + ox), y: Math.round(f.y * sh * s + oy), w: Math.round(f.w * sw * s), h: Math.round(f.h * sh * s) };
|
||||
}
|
||||
} catch {
|
||||
face = undefined;
|
||||
}
|
||||
seen.set(key, face);
|
||||
}
|
||||
const face = seen.get(key);
|
||||
out[String(t)] = face ? { safe, face } : { safe };
|
||||
t += framesOf(c.from, c.to, edit.fps);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function frame(a: { take: string; at?: number }): string {
|
||||
const file = takeOf(a.take);
|
||||
const { dur, sw, sh } = probeOf(file);
|
||||
const t = Math.min(Math.max(a.at ?? dur / 2, 0), Math.max(dur - 0.1, 0));
|
||||
const edit = shape();
|
||||
const face = faceAt(file, t);
|
||||
const [aspect, editAspect] = [sw / Math.max(sh, 1), edit.width / edit.height];
|
||||
const pct = (v: number) => `${Math.round(v * 100)}%`;
|
||||
const lines = [`${file} at ${t.toFixed(1)} s: ${sw}x${sh} (${aspect.toFixed(2)}:1); the edit is ${edit.width}x${edit.height}`];
|
||||
if (face)
|
||||
lines.push(`a face at x ${pct(face.x + face.w / 2)} y ${pct(face.y + face.h / 2)}, ${pct(face.h)} of the height: a talking take. <FaceFrame src={...} /> (raea make component add face-frame) finds the face and keeps it framed for the edit's shape as it moves; punchIn={1.15} to tighten on a key line`);
|
||||
else if (aspect > editAspect * 1.3)
|
||||
lines.push(`no face, and wider than the edit: a cover crop keeps only the middle ${pct(editAspect / aspect)} of its width. <ScreenFit src={...} aspect={${aspect.toFixed(3)}} /> (raea make component add screen-fit) shows it whole, with room above and below for a headline and captions`);
|
||||
else lines.push(`no face here: it fills the frame as it is (a <Video> with objectFit "cover"); try another --at if a person should be in it`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** `raea bug`'s report (bug.ts) to raea's server, with raea's version and the OS added; RAEA_API names the server
|
||||
* (https://raea.io, where raea's server takes reports). No account: the server takes a report from anyone. */
|
||||
function bug(a: { report: Record<string, unknown>; dry?: boolean }) {
|
||||
const version = (spawnSync(raea, ["--version"], { encoding: "utf8" }).stdout ?? "").trim().split(/\s+/).pop() || undefined;
|
||||
const mac = process.platform === "darwin" ? (spawnSync("sw_vers", ["-productVersion"], { encoding: "utf8" }).stdout ?? "").trim() : "";
|
||||
const sent = { ...a.report, raea: version, os: mac ? `macOS ${mac}` : `${process.platform} ${process.arch}` };
|
||||
if (a.dry) return { sent };
|
||||
const api = (process.env.RAEA_API ?? "https://raea.io").replace(/\/$/, "");
|
||||
const r = spawnSync("curl", ["-sS", "--max-time", "20", "-X", "POST", "-H", "content-type: application/json", "--data-binary", "@-", "-w", "\n%{http_code}", `${api}/v1/bugs/agent`], { input: JSON.stringify(sent), encoding: "utf8" });
|
||||
const text = r.stdout ?? "";
|
||||
const cut = text.lastIndexOf("\n");
|
||||
const status = Number(text.slice(cut + 1)) || 0;
|
||||
let answer: { id?: string; count?: number; known?: boolean; message?: string } = {};
|
||||
try {
|
||||
answer = JSON.parse(text.slice(0, cut));
|
||||
} catch {
|
||||
answer = { message: (r.stderr ?? "").trim() || text.slice(0, 200) };
|
||||
}
|
||||
return { ...answer, status, sent };
|
||||
}
|
||||
|
||||
/** One request by curl (the host steps are synchronous): its body and where it ended up, or why it failed */
|
||||
function curl(url: string, o: { out?: string; secs?: number } = {}): { body: string; url: string } {
|
||||
// a browser's agent: some sites send a bare page, or none, to anything else
|
||||
const a = ["-sS", "-L", "--compressed", "--max-time", String(o.secs ?? 30), "-w", "\n%{http_code} %{url_effective}", "-A", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15"];
|
||||
if (o.out) a.push("-o", o.out);
|
||||
const r = spawnSync("curl", [...a, url], { encoding: "utf8", maxBuffer: 64 << 20 });
|
||||
const text = r.stdout ?? "";
|
||||
const cut = text.lastIndexOf("\n");
|
||||
const [body, tail] = [text.slice(0, cut), text.slice(cut + 1)];
|
||||
const [code, final] = [Number(tail.split(" ")[0]), tail.slice(tail.indexOf(" ") + 1)];
|
||||
if (r.status !== 0 || !(code >= 200 && code < 300)) throw Object.assign(new Error(`${url}: ${code || r.stderr.trim()} ${body.slice(0, 200)}`), { code });
|
||||
return { body, url: final || url };
|
||||
}
|
||||
|
||||
/** A logo's size: an SVG's viewBox or width/height, a raster's pixels from its header (else, on a Mac, by sips) */
|
||||
function sizeOf(file: string): { width?: number; height?: number } {
|
||||
if (file.endsWith(".svg")) {
|
||||
const head = readFileSync(file, "utf8").slice(0, 2000);
|
||||
const vb = /viewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(head);
|
||||
return vb ? { width: Math.round(+vb[1]), height: Math.round(+vb[2]) } : {};
|
||||
}
|
||||
const own = pixelsOf(readFileSync(file));
|
||||
if (own || process.platform !== "darwin") return own ?? {};
|
||||
const r = spawnSync("sips", ["-g", "pixelWidth", "-g", "pixelHeight", file], { encoding: "utf8" });
|
||||
const n = (k: string) => Number(new RegExp(`${k}: (\\d+)`).exec(r.stdout ?? "")?.[1]) || undefined;
|
||||
return { width: n("pixelWidth"), height: n("pixelHeight") };
|
||||
}
|
||||
|
||||
/** `raea brand DOMAIN|URL`: the brand's website read on this machine (scrape.ts: its HTML and CSS, no raea API), its
|
||||
* logos saved in media/brand/ and the kit written (brand.ts: BRAND.md, brand/brand.json, brand/brand.css,
|
||||
* brand/styleguide.json). What a plain fetch couldn't see is said, and a kit with nothing in it refuses. */
|
||||
function brand(a: { brand: string }): string {
|
||||
const q = a.brand.trim();
|
||||
if (!/[.:]/.test(q)) throw new Error(`raea brand: give the brand's website (its domain or URL, e.g. ${q.toLowerCase().replace(/\s+/g, "")}.com); raea reads the site itself`);
|
||||
const page = curl(/^https?:\/\//.test(q) ? q : `https://${q}`);
|
||||
const { links, inline } = stylesOf(page.body, page.url);
|
||||
const sheets = [...inline];
|
||||
for (const l of links.slice(0, 16)) {
|
||||
try {
|
||||
const sheet = curl(l);
|
||||
sheets.push(sheet.body);
|
||||
// one level of @import (a theme's tokens are often a sheet of their own)
|
||||
for (const m of sheet.body.matchAll(/@import\s+(?:url\()?["']?([^"')\s;]+)/g))
|
||||
if (!/fonts\.googleapis/.test(m[1])) sheets.push(curl(new URL(m[1], sheet.url).href).body);
|
||||
} catch {
|
||||
// a sheet the CDN won't give is left out
|
||||
}
|
||||
}
|
||||
const site = readSite(page.body, sheets, page.url);
|
||||
const d = site.brand.domain;
|
||||
mkdirSync(at("media/brand"), { recursive: true });
|
||||
const logos: { file: string; type?: string; mode?: string; width?: number; height?: number }[] = [];
|
||||
for (const l of site.logos) {
|
||||
const ext = l.svg ? "svg" : (/\.(svg|png|jpe?g|webp|ico|gif)$/i.exec(l.url.split(/[?#]/)[0])?.[1] ?? "png").toLowerCase();
|
||||
const file = `media/brand/${d}-${l.type}${logos.some((x) => x.type === l.type) ? `-${logos.length + 1}` : ""}.${ext}`;
|
||||
try {
|
||||
if (l.svg) writeFileSync(at(file), l.svg.includes("xmlns") ? l.svg : l.svg.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"'));
|
||||
else curl(l.url, { out: at(file) });
|
||||
logos.push({ file, type: l.type, ...sizeOf(at(file)) });
|
||||
} catch {
|
||||
// a logo the site won't give is left out, not guessed
|
||||
}
|
||||
}
|
||||
const kit = brandKit({ brand: site.brand, styleguide: site.styleguide, logos, thin: site.thin });
|
||||
for (const [f, text] of Object.entries(kit.files)) {
|
||||
mkdirSync(dirname(at(f)), { recursive: true });
|
||||
writeFileSync(at(f), text);
|
||||
}
|
||||
if (!site.styleguide)
|
||||
throw new Error(`raea brand: ${page.url} gave no colours or faces to a plain fetch (${site.thin.join("; ")}). BRAND.md says what to do: open the site in your browser tool, read the live page's computed styles, and write brand/brand.css and brand/brand.json yourself`);
|
||||
return kit.said;
|
||||
}
|
||||
|
||||
const host: Host = (op, a) => {
|
||||
switch (op) {
|
||||
case "shape":
|
||||
return shape();
|
||||
case "words": {
|
||||
const { file, out } = a as { file: string; out?: string };
|
||||
const dest = out ? at(out) : at(`${file.slice(0, file.length - extname(file).length)}.words.json`);
|
||||
hearTake(file, dest);
|
||||
return `${basename(dest)}: ${(JSON.parse(readFileSync(dest, "utf8")) as unknown[]).length} words`;
|
||||
}
|
||||
case "frame":
|
||||
return frame(a as Parameters<typeof frame>[0]);
|
||||
case "cut":
|
||||
return cut(a as Parameters<typeof cut>[0]);
|
||||
case "brand":
|
||||
return brand(a as Parameters<typeof brand>[0]);
|
||||
case "library":
|
||||
return library(a);
|
||||
case "show":
|
||||
return show(a);
|
||||
case "playable":
|
||||
return playable(a as { file: string });
|
||||
case "clothes":
|
||||
return clothesHost(raea, cwd, process.env, a);
|
||||
case "components":
|
||||
return componentsHost(raea, process.env, a);
|
||||
case "bug":
|
||||
return bug(a as { report: Record<string, unknown>; dry?: boolean });
|
||||
case "harness":
|
||||
return harness();
|
||||
case "task":
|
||||
return task(a);
|
||||
default:
|
||||
throw new Error(`raea: this step (${op}) isn't in the native raea yet`);
|
||||
}
|
||||
};
|
||||
|
||||
const engine: Engine = async (a) => {
|
||||
const r = spawnSync(raea, a, { cwd, encoding: "utf8" });
|
||||
return { stdout: r.stdout ?? "", stderr: r.stderr ?? "", exitCode: r.status ?? 1 };
|
||||
};
|
||||
|
||||
const fs = {
|
||||
exists: async (p: string) => existsSync(p),
|
||||
readFile: async (p: string) => readFileSync(p, "utf8"),
|
||||
writeFile: async (p: string, data: string) => writeFileSync(p, data),
|
||||
mkdir: async (p: string, o?: { recursive?: boolean }) => void mkdirSync(p, o),
|
||||
};
|
||||
|
||||
const r = await raeaHandler(host, engine)(args, { cwd, fs });
|
||||
process.stdout.write(r.stdout);
|
||||
process.stderr.write(r.stderr);
|
||||
process.exitCode = r.exitCode;
|
||||
|
||||
/** `raea show GAME.tsx --playable` (show.ts): the game's preview page, exported by `raea playable` into a folder of its
|
||||
* own (the show copies it into the app's media) */
|
||||
function playable(a: { file: string }): { page: string } {
|
||||
const out = mkdtempSync(`${tmpdir()}/raea-playable-`);
|
||||
const r = spawnSync(raea, ["playable", a.file, "-o", out, "--networks", "preview"], { encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`raea playable refused ${basename(a.file)}: ${`${r.stdout ?? ""}${r.stderr ?? ""}`.trim().slice(0, 1200)}`);
|
||||
const page = readdirSync(out).find((f) => f.endsWith("-preview.html"));
|
||||
if (!page) throw new Error(`raea playable made no preview page for ${basename(a.file)}`);
|
||||
return { page: `${out}/${page}` };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/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
|
||||
Dutch's 36 takes). 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:]))
|
||||
@@ -0,0 +1,119 @@
|
||||
// A goal (docs/goal.feature): one step of the work, `goal` on brief.ts, one or several in order (a workflow inline, or
|
||||
// a workflow() module the brief imports). cut, shot, kit, scene, playable and rules are presets of it, each turning its kind's
|
||||
// packs on; any goal carries `rules` (commands, files, words a critic judges) and an `aim`; `packs` switches any of
|
||||
// raea's by name and `checks` adds the project's own (raea/check `check()`s, imported into brief.ts). `name`, `step`
|
||||
// and `after` place it in a workflow. Pure: brief.ts imports this, and `raea spec` reads brief.ts with no Node.
|
||||
//
|
||||
// import { brief, cut, rules } from "raea/brief"
|
||||
// import clearOfButtons from "./checks/clear.ts"
|
||||
// export default brief({ title: "Dutch", goal: [
|
||||
// cut({ name: "cut", step: "edit", cut: {...}, packs: { surprise: true }, checks: [clearOfButtons] }),
|
||||
// rules({ name: "deliver", after: ["cut"], aim: "each size uploaded", rules: [{ id: "sizes", file: "out/dutch_4x5.mp4" }] }),
|
||||
// ] })
|
||||
import type { Check, Moment } from "raea/check"
|
||||
import type { Goal as Data, GoalKind } from "raea/brief.gen"
|
||||
|
||||
export type { Moment }
|
||||
/** a goal: one of brief.ts's `goal`, with its own checks as functions (Rust reads only their declarations) */
|
||||
export type Contract = Omit<Data, "checks"> & { checks?: Check[] }
|
||||
/** brief.ts's `goal`: one, or several in order */
|
||||
export type Goals = Contract | Contract[]
|
||||
/** a shared workflow: its steps, each a goal; a brief imports it as its `goal`, or as the goals one step of it holds */
|
||||
export interface Workflow {
|
||||
name: string
|
||||
steps: Contract[]
|
||||
}
|
||||
|
||||
/** raea's packs by name (packs/index.ts): what each holds a job to */
|
||||
export const PACKS = {
|
||||
words: "every word a cut's lines say is heard whole in its export, none faded under a crossfade",
|
||||
captions: "every caption on screen says exactly what's heard there: nothing added or changed, no words dropped from a captioned line",
|
||||
voice: "the dialogue on top of the mix (10 dB over what's under it) and every line as loud as the others, measured on the export",
|
||||
hook: "the hook opens on words and picture together: no dead air before the first word",
|
||||
airgaps: "no air between words: gaps tightened in the hook's first 3 s, no long pause after (tighten() cuts between words only)",
|
||||
reading: "every block of text that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture",
|
||||
sound: "edit points in the pauses, every line within 6 dB of the others, every effect heard",
|
||||
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",
|
||||
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",
|
||||
count: "as many cuts as the brief asks for, or a person's answer saying why not",
|
||||
open: "every open item answered by a person",
|
||||
say: "every phrase the brief says each cut says, heard or shown; one cut enough where it says so",
|
||||
never: "no banned phrase heard or shown",
|
||||
cta: "each cut ends on the CTA",
|
||||
shape: "each cut in its format and length",
|
||||
run: "each command rule exits 0",
|
||||
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",
|
||||
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. */
|
||||
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"],
|
||||
}
|
||||
|
||||
/** 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")
|
||||
for (const [k, v] of Object.entries(c?.packs ?? {})) {
|
||||
if (!(k in PACKS)) continue
|
||||
if (v) on.add(k as PackName)
|
||||
else on.delete(k as PackName)
|
||||
}
|
||||
return [...on]
|
||||
}
|
||||
|
||||
/** what the packs that need it can't run without, said by doctor: a name `packs` gives that raea hasn't */
|
||||
export function unknownPacks(c: Contract): string[] {
|
||||
return Object.keys(c.packs ?? {}).filter((k) => !(k in PACKS))
|
||||
}
|
||||
|
||||
type Kindless = Omit<Contract, "kind">
|
||||
/** a goal as written */
|
||||
export const goal = (m: Contract): Contract => m
|
||||
/** a scene: a dressed, lit place from references or a brief */
|
||||
export const scene = (m: Kindless): Contract => ({ kind: "scene", ...m })
|
||||
/** a kit: a set of props that belong together, from style references */
|
||||
export const kit = (m: Kindless): Contract => ({ kind: "kit", ...m })
|
||||
/** shots: stills or camera moves of a built scene */
|
||||
export const shot = (m: Kindless): Contract => ({ kind: "shot", ...m })
|
||||
/** cuts of footage from a client's brief: the brief as rules (`cut: {...}`) */
|
||||
export const cut = (m: Kindless): Contract => ({ kind: "cut", ...m })
|
||||
/** a game exported as a playable ad: `playable({ aim, playable: { game: "playable.tsx" } })`, both orientations and
|
||||
* every network unless it names them (docs/playables.feature PA19) */
|
||||
export const playable = (m: Kindless): Contract => ({ kind: "playable", ...m })
|
||||
/** any other work, held only to its rules: `rules({ aim: "the person's words", rules: [...] })` */
|
||||
export const rules = (m: Kindless): Contract => ({ kind: "rules", ...m })
|
||||
/** a shared workflow: its steps in order, each a goal (`after` orders them past it) */
|
||||
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] : []
|
||||
/** a goal's name: its own, else its kind's */
|
||||
export const nameOf = (c: Contract) => c.name ?? c.kind
|
||||
|
||||
/** the moments a check runs at: its own, else done alone */
|
||||
export const momentsOf = (c: Check): Moment[] => c.at ?? ["done"]
|
||||
@@ -0,0 +1,155 @@
|
||||
// What a file or job check is run on (raea/check `over: "file" | "job"`, docs/goal.feature MK30): a delivered file with
|
||||
// what's known of it, and the job, its contract and its files. What costs (a transcript, the scene, levels, a sheet) is
|
||||
// read the first time a check asks and kept for the others.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, readFileSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import type { Moment } from "raea/check"
|
||||
import type { Contract } from "./contract.ts"
|
||||
import * as media from "./media.ts"
|
||||
import type { Faces, Levels, Word } from "./media.ts"
|
||||
import type { Scene } from "./packs/place.ts"
|
||||
import type { Project } from "./project.ts"
|
||||
|
||||
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
|
||||
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
|
||||
/** a text on a frame, in render pixels: its layout box and its ink */
|
||||
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
|
||||
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
|
||||
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
|
||||
|
||||
export interface FileFacts {
|
||||
/** as the project names it (relative to its folder) */
|
||||
path: string
|
||||
/** on this machine */
|
||||
abs: string
|
||||
/** the project's folder (brief.ts's) */
|
||||
root: string
|
||||
kind: "video" | "image" | "audio" | "other"
|
||||
/** made here: not under media/, which holds what was handed over */
|
||||
made: boolean
|
||||
/** when it last changed (ms) and its size, which a look is tied to */
|
||||
stamp: string
|
||||
seconds: number | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
fps: number
|
||||
manifest: Manifest | null
|
||||
moment: Moment
|
||||
contract: Contract | null
|
||||
/** what it says, word by word */
|
||||
words(): Promise<Word[]>
|
||||
/** what a source take says, and where it is on this machine (a farm's /work/ path read under the project) */
|
||||
take(src: string): string | null
|
||||
takeWords(src: string): Promise<Word[]>
|
||||
/** a file's level every 10 ms over [a, b] s (this file's when `src` is unset) */
|
||||
levels(a?: number, b?: number, src?: string): Levels
|
||||
/** what's in its frames, RATE a second (or at those seconds) */
|
||||
scene(at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }>
|
||||
/** its contact sheet's path */
|
||||
sheet(): string
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
root: string
|
||||
brief: string | null
|
||||
/** the brief's text (cut.brief), when it has one */
|
||||
briefText: string | null
|
||||
contract: Contract | null
|
||||
/** the brief's run, and what it reaches (project.ts) */
|
||||
project: Project
|
||||
moment: Moment
|
||||
/** the deliverables it names, relative to root, and the ones there now */
|
||||
deliverables: string[]
|
||||
files: FileFacts[]
|
||||
/** a command run in the project's folder, stopped at its timeout */
|
||||
run(cmd: string, secs: number): Promise<{ ok: boolean; said: string }>
|
||||
}
|
||||
|
||||
const KIND = [[/\.(mp4|mov|m4v|webm|mkv)$/i, "video"], [/\.(png|jpe?g|webp|gif)$/i, "image"], [/\.(wav|mp3|m4a|aac|flac|ogg)$/i, "audio"]] as const
|
||||
export const kindOf = (f: string): FileFacts["kind"] => KIND.find(([re]) => re.test(f))?.[1] ?? "other"
|
||||
/** what was handed over (a take, a logo): under media/ */
|
||||
export const given = (rel: string) => /^(\.\/)?media\//.test(rel)
|
||||
|
||||
/** the render's manifest beside a file: FILE.render.json (raea cloud's, the render tool's), else FILE.manifest.json */
|
||||
export function manifestOf(abs: string): Manifest | null {
|
||||
const p = [`${media.stem(abs)}.render.json`, `${media.stem(abs)}.manifest.json`].find(existsSync)
|
||||
if (!p) return null
|
||||
try {
|
||||
return JSON.parse(readFileSync(p, "utf8")) as Manifest
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** a source a manifest names, on this machine: its own path, or the part after a farm job's work/ under the project */
|
||||
export function onMachine(src: string, roots: string[]): string | null {
|
||||
if (existsSync(src)) return src
|
||||
const rel = src.includes("/work/") ? src.slice(src.lastIndexOf("/work/") + 6) : src.replace(/^\/+/, "")
|
||||
for (const r of roots) {
|
||||
const p = path.resolve(r, rel)
|
||||
if (existsSync(p)) return p
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const once = <T>(f: () => Promise<T>) => {
|
||||
let p: Promise<T> | null = null
|
||||
return () => (p ??= f())
|
||||
}
|
||||
|
||||
export function fileFacts(rel: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
|
||||
const abs = path.resolve(root, rel)
|
||||
const st = statSync(abs)
|
||||
const kind = kindOf(abs)
|
||||
const shape = kind === "video" || kind === "image" ? media.shape(abs) : null
|
||||
const manifest = kind === "video" || kind === "audio" ? manifestOf(abs) : null
|
||||
const roots = [root, ...[path.dirname(abs)]]
|
||||
const takeWords = new Map<string, Promise<Word[]>>()
|
||||
const scenes = new Map<string, Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }>>()
|
||||
const p = path.relative(root, abs) || rel
|
||||
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
|
||||
return {
|
||||
path: p,
|
||||
abs,
|
||||
root,
|
||||
kind,
|
||||
made: !given(p),
|
||||
stamp,
|
||||
seconds: kind === "video" || kind === "audio" ? media.seconds(abs) : null,
|
||||
width: shape?.width ?? manifest?.width ?? null,
|
||||
height: shape?.height ?? manifest?.height ?? null,
|
||||
fps: manifest?.fps ?? shape?.fps ?? 30,
|
||||
manifest,
|
||||
moment,
|
||||
contract,
|
||||
words: once(() => media.words(abs)),
|
||||
take: (src) => onMachine(src, roots),
|
||||
takeWords: (src) => {
|
||||
const f = onMachine(src, roots)
|
||||
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
|
||||
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
|
||||
return takeWords.get(f)!
|
||||
},
|
||||
levels: (a, b, src) => media.levels(src ? (onMachine(src, roots) ?? src) : abs, a, b),
|
||||
scene: (at) => {
|
||||
const k = at?.join(",") ?? ""
|
||||
if (!scenes.has(k)) scenes.set(k, media.scene(abs, at))
|
||||
return scenes.get(k)!
|
||||
},
|
||||
sheet: () => media.sheet(abs),
|
||||
}
|
||||
}
|
||||
|
||||
/** a command in `dir` through the system's shell, stopped at its timeout: whether it passed, and its last line */
|
||||
export function runIn(dir: string) {
|
||||
return async (cmd: string, secs: number) => {
|
||||
const win = process.platform === "win32"
|
||||
const r = spawnSync(win ? "cmd" : "sh", win ? ["/C", cmd] : ["-c", cmd], { cwd: dir, encoding: "utf8", timeout: secs * 1000, maxBuffer: 1 << 26 })
|
||||
const text = `${r.stdout ?? ""}${r.stderr ?? ""}`
|
||||
const last = text.split("\n").reverse().find((l) => l.trim())?.trim().slice(0, 200) ?? ""
|
||||
if ((r.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") return { ok: false, said: `still running after ${secs} s: stopped (give the rule a longer \`timeout\`, or make it quicker)` }
|
||||
if (r.error) return { ok: false, said: `couldn't start it: ${r.error.message}` }
|
||||
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// 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
|
||||
// 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"
|
||||
export { check, found } from "raea/check"
|
||||
export type { Check, Found } from "raea/check"
|
||||
@@ -0,0 +1,292 @@
|
||||
// What a check reads that costs (raea/check's Need: words, levels, scene, sheet), got once a file and kept beside it
|
||||
// (docs/goal.feature MK30). On a raea cloud box the farm hears and sees (RAEA_CLOUD_GPU_URL: POST /v1/words, Whisper
|
||||
// large-v3; POST /v1/scene, people, faces, things and words in the shot); elsewhere raea's own `raea words` hears, and a
|
||||
// need nothing here can meet throws `Unmet`, which makes its check wait and say why, as a render need does.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import type { Scene } from "./packs/place.ts"
|
||||
|
||||
export type Word = { text: string; start: number; end: number }
|
||||
/** a file's level every 10 ms (dB) from `start` s on */
|
||||
export type Levels = { start: number; db: number[] }
|
||||
/** a split screen's seam as the farm finds it: its axis (h, a row), where, and its share of the frame */
|
||||
export type Seam = [string, number, number]
|
||||
/** what the farm saw in one frame: its size, its faces as [x, y, w, h, score] and its seams */
|
||||
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
|
||||
|
||||
/** a need this machine can't meet: the check that has it waits, and this says what for */
|
||||
export class Unmet extends Error {
|
||||
override name = "Unmet"
|
||||
}
|
||||
|
||||
/** the raea binary this runs beside: RAEA_REAL (the box's wrapper sets it), else `raea` on the PATH */
|
||||
export const RAEA = process.env.RAEA_REAL ?? "raea"
|
||||
const farm = () => (process.env.RAEA_CLOUD_GPU_URL ? { url: process.env.RAEA_CLOUD_GPU_URL.replace(/\/$/, ""), token: process.env.RAEA_CLOUD_GPU_TOKEN ?? "" } : null)
|
||||
|
||||
export const stem = (f: string) => f.slice(0, f.length - path.extname(f).length)
|
||||
const changed = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
|
||||
/** a file beside `f` that is no older than `f` (a report from before its last change says nothing about it now) */
|
||||
export const freshBeside = (f: string, ext: string) => [`${stem(f)}.${ext}`, `${f}.${ext}`].find((p) => existsSync(p) && changed(p) >= changed(f))
|
||||
|
||||
/** ffmpeg, raea's own (`raea media ffmpeg`), else the system's */
|
||||
export function ffmpeg(args: string[]): void {
|
||||
const r = spawnSync(RAEA, ["media", "ffmpeg", ...args], { encoding: "utf8" })
|
||||
if (r.status === 0) return
|
||||
const r2 = spawnSync("ffmpeg", args, { encoding: "utf8" })
|
||||
if (r2.status !== 0) throw new Error(`ffmpeg ${args.slice(0, 6).join(" ")}...: ${(r2.stderr || r.stderr || "").slice(-300)}`)
|
||||
}
|
||||
|
||||
/** a file's length in seconds, or null when it has none (a still, a text) */
|
||||
export function seconds(file: string): number | null {
|
||||
for (const [cmd, pre] of [[RAEA, ["media", "ffprobe"]], ["ffprobe", []]] as const) {
|
||||
const r = spawnSync(cmd, [...pre, "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
|
||||
const s = Number.parseFloat(r.stdout ?? "")
|
||||
if (Number.isFinite(s)) return s
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** a video's width, height and frame rate (ffprobe's first video stream), or null */
|
||||
export function shape(file: string): { width: number; height: number; fps: number } | null {
|
||||
for (const [cmd, pre] of [[RAEA, ["media", "ffprobe"]], ["ffprobe", []]] as const) {
|
||||
const r = spawnSync(cmd, [...pre, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate", "-of", "json", file], { encoding: "utf8" })
|
||||
try {
|
||||
const s = JSON.parse(r.stdout ?? "").streams?.[0]
|
||||
if (!s?.width) continue
|
||||
const [n, d] = String(s.r_frame_rate ?? "30/1").split("/").map(Number)
|
||||
return { width: s.width, height: s.height, fps: d ? n / d : n || 30 }
|
||||
} catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** the level every 10 ms, in dB, of 16 kHz mono 16-bit samples */
|
||||
export function levelsOf(pcm: Int16Array): number[] {
|
||||
const hop = 160
|
||||
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(10 * Math.log10(e / hop + 1e-10))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** a file's sound level every 10 ms over [a, b] seconds (all of it when unset) */
|
||||
export function levels(file: string, a = 0, b?: number): Levels {
|
||||
const start = Math.max(0, a)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-levels-"))
|
||||
try {
|
||||
const raw = path.join(dir, "a.raw")
|
||||
const span = b === undefined ? [] : ["-t", String(Math.max(0.05, b - start))]
|
||||
try {
|
||||
ffmpeg(["-v", "error", "-y", "-ss", String(start), ...span, "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw])
|
||||
} catch {
|
||||
return { start, db: [] }
|
||||
}
|
||||
if (!existsSync(raw)) return { start, db: [] }
|
||||
const buf = readFileSync(raw)
|
||||
return { start, db: levelsOf(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2))) }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** Whisper sometimes hands back two words as one ("for $60"): one word each, sharing its time by their lengths */
|
||||
export function split(ws: Word[]): Word[] {
|
||||
return ws.flatMap((w) => {
|
||||
const parts = w.text.split(/\s+/).filter(Boolean)
|
||||
if (parts.length < 2) return [w]
|
||||
const total = parts.reduce((n, p) => n + p.length, 0)
|
||||
let t = w.start
|
||||
return parts.map((p) => {
|
||||
const d = ((w.end - w.start) * p.length) / total
|
||||
const x = { text: p, start: t, end: t + d }
|
||||
t += d
|
||||
return x
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** a words.json as raea writes it ([{text, start_ms, end_ms}], or {words: [...]}, or seconds) */
|
||||
export function readWords(file: string): Word[] {
|
||||
const raw = JSON.parse(readFileSync(file, "utf8")) as unknown
|
||||
const list = (Array.isArray(raw) ? raw : ((raw as { words?: unknown[] }).words ?? [])) as Record<string, unknown>[]
|
||||
return list
|
||||
.map((w) => {
|
||||
const text = String(w.text ?? w.word ?? "")
|
||||
const start = typeof w.start_ms === "number" ? w.start_ms / 1000 : Number(w.start)
|
||||
const end = typeof w.end_ms === "number" ? w.end_ms / 1000 : Number(w.end ?? start)
|
||||
return { text, start, end }
|
||||
})
|
||||
.filter((w) => w.text && Number.isFinite(w.start))
|
||||
}
|
||||
|
||||
const asRaea = (ws: Word[]) => ws.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }))
|
||||
/** the farm's answer: its status and body */
|
||||
export type Answer = { status: number; ok: boolean; text: string }
|
||||
/** how a POST is sent: fetch where there is one (Node, Bun, a test's stand-in), else curl (raea's own engine has no
|
||||
* network of its own; the token goes in a header file, never on a command line) */
|
||||
export type Post = (url: string, body: Uint8Array | string, type: string, token: string) => Promise<Answer>
|
||||
|
||||
const viaFetch: Post = async (url, body, type, token) => {
|
||||
const r = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": type }, body: body as BodyInit })
|
||||
return { status: r.status, ok: r.ok, text: await r.text() }
|
||||
}
|
||||
const viaCurl: Post = async (url, body, type, token) => {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-post-"))
|
||||
try {
|
||||
const head = path.join(dir, "h")
|
||||
const data = path.join(dir, "b")
|
||||
writeFileSync(head, `authorization: Bearer ${token}\ncontent-type: ${type}\n`, { mode: 0o600 })
|
||||
writeFileSync(data, body)
|
||||
const r = spawnSync("curl", ["-sS", "-X", "POST", "-H", `@${head}`, "--data-binary", `@${data}`, "--max-time", "600", "-w", "\n%{http_code}", url], { encoding: "utf8", maxBuffer: 1 << 28 })
|
||||
if (r.status !== 0) return { status: 0, ok: false, text: (r.stderr || "curl failed").slice(-300) }
|
||||
const out = String(r.stdout)
|
||||
const cut = out.lastIndexOf("\n")
|
||||
const status = Number(out.slice(cut + 1)) || 0
|
||||
return { status, ok: status >= 200 && status < 300, text: out.slice(0, cut) }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** the sender in use (tests set their own) */
|
||||
export let send: Post = typeof globalThis.fetch === "function" ? viaFetch : viaCurl
|
||||
export const useSender = (p: Post) => {
|
||||
send = p
|
||||
}
|
||||
|
||||
/** the farm's POST, tried again on a 5xx or a dropped connection */
|
||||
async function post(route: string, body: Uint8Array | string, type: string): Promise<Answer> {
|
||||
const fm = farm()!
|
||||
let why = ""
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const r = await send(`${fm.url}${route}`, body, type, fm.token)
|
||||
if (r.ok || r.status === 404) return r
|
||||
why = `${r.status || "no answer"} ${r.text.slice(0, 300)}`
|
||||
if (r.status >= 400 && r.status < 500) break
|
||||
}
|
||||
throw new Error(`the farm's ${route}: ${why}`)
|
||||
}
|
||||
|
||||
/** the first line a program said, its usage or REFUSED head cut to what it's about */
|
||||
const firstLine = (s: string | null | undefined) => (s ?? "").split("\n").map((l) => l.trim()).find(Boolean)?.slice(0, 160) ?? ""
|
||||
|
||||
/** what a file says, word by word: its words.json beside it when no older than it, else heard (the farm's Whisper on a
|
||||
* box, `raea words` elsewhere) and written there */
|
||||
export async function words(file: string, anyAge = false): Promise<Word[]> {
|
||||
const kept = anyAge ? [`${stem(file)}.words.json`, `${file}.words.json`].find(existsSync) : freshBeside(file, "words.json")
|
||||
if (kept) return readWords(kept)
|
||||
const out = `${stem(file)}.words.json`
|
||||
if (!farm()) {
|
||||
const r = spawnSync(RAEA, ["words", file, "-o", out], { encoding: "utf8" })
|
||||
if (r.status !== 0 || !existsSync(out)) throw new Unmet(`no transcript of ${path.basename(file)}: \`raea words\` couldn't hear it here (${firstLine(r.stderr || r.stdout) || `exit ${r.status}`})`)
|
||||
return readWords(out)
|
||||
}
|
||||
const len = seconds(file) ?? 0
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
|
||||
try {
|
||||
const heard: Word[] = []
|
||||
for (let at = 0; at < len; at += 600) {
|
||||
const mp3 = path.join(dir, `p${at}.mp3`)
|
||||
ffmpeg(["-v", "error", "-y", "-ss", String(at), "-t", "600", "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-b:a", "32k", mp3])
|
||||
if (!existsSync(mp3)) throw new Unmet(`${path.basename(file)} has no sound to hear`)
|
||||
const r = await post("/v1/words", readFileSync(mp3), "audio/mpeg")
|
||||
if (!r.ok) throw new Unmet(`the farm hears no words (POST /v1/words: ${r.status})`)
|
||||
const b = JSON.parse(r.text) as { words: Word[] }
|
||||
heard.push(...split(b.words).map((w) => ({ text: w.text, start: at + w.start, end: at + w.end })))
|
||||
}
|
||||
writeFileSync(out, `${JSON.stringify(asRaea(heard))}\n`)
|
||||
return heard
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */
|
||||
export const RATE = 2
|
||||
const SIDE = 540
|
||||
/** a video's scene reading, kept beside it */
|
||||
export const SCENE_EXT = "scene.json"
|
||||
|
||||
/** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene
|
||||
* (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */
|
||||
export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
|
||||
// a video's whole reading is kept beside it, as its words are, and read again only when the file is newer: a cut
|
||||
// checked at its render was read again at publish and again at done, 30 s a file each time, so a done check of 11
|
||||
// files took 334 s (12-01)
|
||||
const whole = !at?.length && !/\.(png|jpe?g|webp)$/i.test(file)
|
||||
if (whole) {
|
||||
const kept = freshBeside(file, SCENE_EXT)
|
||||
try {
|
||||
const k = kept ? (JSON.parse(readFileSync(kept, "utf8")) as { rate: number; side: number; faces: Faces[]; scenes: Scene[] }) : null
|
||||
if (k && k.rate === RATE && k.side === SIDE && Array.isArray(k.scenes) && k.scenes.length) return { rate: k.rate, faces: k.faces, scenes: k.scenes }
|
||||
} catch {}
|
||||
}
|
||||
if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
|
||||
try {
|
||||
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
|
||||
if (/\.(png|jpe?g|webp)$/i.test(file)) ffmpeg(["-v", "error", "-y", "-i", file, "-vf", scale, "-q:v", "4", path.join(dir, "f00001.jpg")])
|
||||
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
|
||||
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
|
||||
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
|
||||
const faces: Faces[] = []
|
||||
const scenes: Scene[] = []
|
||||
for (let i = 0; i < jpgs.length; i += 300) {
|
||||
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
|
||||
const r = await post("/v1/scene", body, "application/json")
|
||||
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
|
||||
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
|
||||
if (!g) {
|
||||
faces.push(null)
|
||||
scenes.push(null)
|
||||
continue
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
}
|
||||
if (whole && scenes.length) {
|
||||
try {
|
||||
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
|
||||
} catch {}
|
||||
}
|
||||
return { rate: at?.length ? 0 : RATE, faces, scenes }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
|
||||
export function sheet(file: string): string {
|
||||
const out = `${stem(file)}.sheet.jpg`
|
||||
if (freshBeside(file, "sheet.jpg")) return out
|
||||
const r = spawnSync(RAEA, ["media", "sheet", file, "-o", out], { encoding: "utf8" })
|
||||
if (r.status !== 0 || !existsSync(out)) throw new Unmet(`couldn't make ${path.basename(file)}'s contact sheet: ${(r.stderr || r.stdout || "").trim().slice(-200)}`)
|
||||
return out
|
||||
}
|
||||
|
||||
/** how many full-size frames a look is made of */
|
||||
export const LOOKS = 6
|
||||
|
||||
/** a video's frames at full size beside it (FILE.looks/1.jpg ...), made again when older than the video. Type, cards
|
||||
* and captions are judged on these: a contact sheet's tiles are too small to judge design on (12-01, Shane on Dutch:
|
||||
* "why do components not look good. is it even proofing or reviewing the work?") */
|
||||
export function looks(file: string): string[] {
|
||||
const dir = `${stem(file)}.looks`
|
||||
const out = Array.from({ length: LOOKS }, (_, i) => path.join(dir, `${i + 1}.jpg`))
|
||||
if (out.every((p) => changed(p) >= changed(file))) return out
|
||||
const d = seconds(file)
|
||||
if (!d) throw new Unmet(`couldn't read ${path.basename(file)}'s length for its full-size frames`)
|
||||
mkdirSync(dir, { recursive: true })
|
||||
out.forEach((p, i) => ffmpeg(["-v", "error", "-y", "-ss", ((d * (i + 0.5)) / LOOKS).toFixed(2), "-i", file, "-frames:v", "1", "-q:v", "3", p]))
|
||||
return out
|
||||
}
|
||||
|
||||
/** whether FILE's full-size frames were made since it last changed */
|
||||
export const looksFresh = (file: string) => Array.from({ length: LOOKS }, (_, i) => path.join(`${stem(file)}.looks`, `${i + 1}.jpg`)).every((p) => changed(p) >= changed(file))
|
||||
@@ -0,0 +1,315 @@
|
||||
// The captions pack (11-30, Shane: "running a transcription and ocr pass on the final output as fast as possible would
|
||||
// be helpful because it also helps catch if audio captions pick up something else that's not supposed to be there or if
|
||||
// we cut off words"): what an export SHOWS against what it SAYS, both read off the export itself, so it can't be passed
|
||||
// by what the edit meant to show. Elfster's captions, typed by hand, said "for a bad gift" (said: "when they get a bad
|
||||
// gift"), "Oh my god" (said: "Oh my"), dropped half a line and two words of the brief's own call to action; every
|
||||
// check passed them, since none read the picture.
|
||||
//
|
||||
// read: the scene reader (raea cloud's farm, POST /v1/scene) reads the text in each frame, two a second (PP-OCRv4).
|
||||
// heard: the words pass's transcript of the same export.
|
||||
// captions: a line of text whose letters mostly match what's said around it (within 2.5 s before to 1 s after) is a
|
||||
// caption; hook text, a title, a logo or a sign isn't, and is left alone.
|
||||
// shown, not said: a run of three letters or more in the captions that nothing heard near it accounts for is an
|
||||
// error (a word added or changed: "god").
|
||||
// said, not shown: while captions are up, a heard word the captions leave out is a warning, two or more in a row an
|
||||
// error (words dropped: "when they get"). Fillers (um, uh) aren't counted.
|
||||
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import 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
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none" | "uncaptioned"; at: number; says: string }
|
||||
|
||||
/** a word or a line as it's compared: lower case letters and digits, nothing else */
|
||||
export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
|
||||
/** what's said that a caption may leave out without changing what's said */
|
||||
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
|
||||
/** least score a read line counts at */
|
||||
export const LEAST = 0.6
|
||||
|
||||
/** a caption against what's said around it: the caption's letters aligned to the stretch of the heard letters they fit
|
||||
* best (an edit distance with the heard text's start and end free). dist: the edits; bad: for each caption letter,
|
||||
* whether it was changed or added (no heard letter matches it) */
|
||||
export function fit(cap: string, said: string): { dist: number; bad: boolean[]; from: number; to: number } {
|
||||
const n = cap.length
|
||||
const m = said.length
|
||||
// D[i][j]: edits to make cap[0..i) end at said[j); a free start anywhere in said
|
||||
const D = Array.from({ length: n + 1 }, (_, i) => new Uint16Array(m + 1).fill(i))
|
||||
for (let i = 1; i <= n; i++)
|
||||
for (let j = 1; j <= m; j++) D[i][j] = Math.min(D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1), D[i - 1][j] + 1, D[i][j - 1] + 1)
|
||||
let j = 0
|
||||
for (let k = 1; k <= m; k++) if (D[n][k] < D[n][j]) j = k
|
||||
const dist = D[n][j]
|
||||
const to = j
|
||||
const bad = new Array<boolean>(n).fill(false)
|
||||
let i = n
|
||||
while (i > 0 && j > 0) {
|
||||
const d = D[i][j]
|
||||
if (d === D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1)) {
|
||||
if (cap[i - 1] !== said[j - 1]) bad[i - 1] = true
|
||||
i--
|
||||
j--
|
||||
} else if (d === D[i - 1][j] + 1) bad[--i] = true
|
||||
else j--
|
||||
}
|
||||
while (i > 0) bad[--i] = true
|
||||
return { dist, bad, from: j, to }
|
||||
}
|
||||
|
||||
/** 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)
|
||||
|
||||
/** 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) */
|
||||
export type Shown = { text: string; key: string; from: number; to: number; y: number }
|
||||
/** a frame's lines, and the frame's height */
|
||||
export type Frame = { h: number; lines: Read[] }
|
||||
/** lines whose middles are this close (a share of the frame's height) are the same line in the next frame */
|
||||
const ROW = 0.03
|
||||
/** a showing longer than this (s) is a title, a badge or a card, not a caption */
|
||||
const HELD = 4.5
|
||||
/** a caption fits what's said while it's up with at most this share of its letters edited; a line in capitals (a
|
||||
* badge's style: "BODY BUTTER · UP TO 96 HOURS" over "Body Butter delivers up to 96 hours") with at most CAPS_FIT */
|
||||
const FIT = 0.45
|
||||
const CAPS_FIT = 0.3
|
||||
/** captions are a track: up for at least this share of what's said, else the cut has none (hook text alone) */
|
||||
const TRACK = 0.4
|
||||
const CARDS = 8
|
||||
/** more lines than this in a frame is a screen or a card */
|
||||
const BUSY = 3
|
||||
/** words a transcriber often leaves out of what it hears (so a caption that has them may be right) */
|
||||
const SOFT = new Set(["yeah", "yes", "okay", "like", "wow", "hey", "right", "sorry", "well"])
|
||||
/** words this close are one line (s) */
|
||||
const LINE = 0.7
|
||||
|
||||
/** the frames' captions. First every line, the same line in consecutive frames joined into one showing (a line the
|
||||
* reader garbled a little in one frame still joins its neighbours); then the showings that are captions: short, and
|
||||
* 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))
|
||||
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))
|
||||
if (last) {
|
||||
last.to = t + 1 / rate
|
||||
// the longest reading of the line is kept (a frame mid-fade reads part of it)
|
||||
if (key.length > last.key.length) Object.assign(last, { text, key })
|
||||
} else all.push({ text, key, from: t, to: t + 1 / rate, y: mid, caps: false })
|
||||
}
|
||||
})
|
||||
const caps = (t: string) => /[A-Z]/.test(t) && !/[a-z]/.test(t)
|
||||
const fitted = all.filter((s) => {
|
||||
if (s.to - s.from > HELD) return false
|
||||
const said = heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join("")
|
||||
return fit(s.key, said).dist / s.key.length <= (caps(s.text) ? CAPS_FIT : FIT)
|
||||
}).map(({ caps: _, ...s }) => s)
|
||||
// kept to caption rows: where three captions or more sit (a label beside a product, a sign, sits on its own)
|
||||
const rowed = fitted.filter((s) => fitted.filter((o) => Math.abs(o.y - s.y) <= ROW).length >= 3)
|
||||
const talk = heard.filter((w) => !FILLER.has(letters(w.text)))
|
||||
const out = rowed
|
||||
const up = talk.filter((w) => out.some((s) => w.end >= s.from - 0.3 && w.start <= s.to + 0.3)).length
|
||||
// and a sequence: captions come one after another (CARDS showings at least, each starting apart), where hook text
|
||||
// that echoes the host is one card of a few lines at once
|
||||
const starts = [...new Set(out.map((s) => Math.round(s.from * 2)))].sort((a, b) => a - b)
|
||||
const cards = starts.filter((x, i) => i === 0 || x - starts[i - 1] >= 1).length
|
||||
if (!talk.length || up / talk.length < TRACK || cards < CARDS) return []
|
||||
return out.sort((a, b) => a.from - b.from)
|
||||
}
|
||||
|
||||
export const similar = (a: string, b: string) => {
|
||||
const [s, l] = a.length <= b.length ? [a, b] : [b, a]
|
||||
return fit(s, l).dist / Math.max(1, s.length) <= 0.25 && s.length / l.length >= 0.6
|
||||
}
|
||||
|
||||
/** letters [i, j) of a line's key are a whole word of the line as read (its spaces kept) */
|
||||
function wholeWord(text: string, key: string, i: number, j: number): boolean {
|
||||
let k = 0
|
||||
for (const w of text.split(/\s+/)) {
|
||||
const lw = letters(w)
|
||||
if (k === i && k + lw.length === j) return true
|
||||
k += lw.length
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 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)
|
||||
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
|
||||
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
|
||||
for (let i = 0; i < f.bad.length; ) {
|
||||
if (!f.bad[i]) { i++; continue }
|
||||
let j = i
|
||||
while (j < f.bad.length && f.bad[j]) j++
|
||||
if (j - i >= 3) out.push({ level: (j - i >= 5 || wholeWord(s.text, s.key, i, j)) && !SOFT.has(s.key.slice(i, j)) ? "error" : "warn", kind: "shown", at: s.from, says: `the caption "${s.text}" at ${s.from.toFixed(1)} s shows "${s.key.slice(i, j)}", which isn't said there: a caption is the speaker's exact words, built from the words file, never retyped` })
|
||||
i = j
|
||||
}
|
||||
}
|
||||
// said, not shown: a heard word while a caption is up whose letters none of the captions up around it holds
|
||||
const dropped: { w: Word; k: number }[] = []
|
||||
heard.forEach((w, k) => {
|
||||
const key = letters(w.text)
|
||||
if (!key || FILLER.has(key)) return
|
||||
const up = shown.filter((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
|
||||
if (!up.length) return
|
||||
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
|
||||
const allowed = key.length >= 5 ? 1 : 0
|
||||
if (fit(key, near).dist > allowed) dropped.push({ w, k })
|
||||
})
|
||||
// read two frames a second, a caption up for under a second can be missed between frames: words dropped are held as
|
||||
// errors only where the captions are phrases (up a second or more, typically), and only three or more in a row
|
||||
const lasts = shown.map((x) => x.to - x.from).sort((x, y) => x - y)
|
||||
const phrases = lasts[Math.floor(lasts.length / 2)] >= 1
|
||||
// a run inside captioned speech (the words either side of it are shown, within a line of it) is words a caption
|
||||
// left out: an error. A run at a line's edge is a line left uncaptioned, which an editor may mean (the CTA under its
|
||||
// badges): a warning
|
||||
const lost = new Set(dropped.map((d) => d.k))
|
||||
const shownAt = (k: number) => k >= 0 && k < heard.length && !lost.has(k) && shown.some((s) => heard[k].end >= s.from - 0.6 && heard[k].start <= s.to + 0.3)
|
||||
for (let i = 0; i < dropped.length; ) {
|
||||
let j = i + 1
|
||||
while (j < dropped.length && dropped[j].k === dropped[j - 1].k + 1) j++
|
||||
const run = dropped.slice(i, j).map((d) => d.w)
|
||||
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` }
|
||||
: { level: "warn", kind: "dropped", at: run[0].start, says: `"${words}" at ${run[0].start.toFixed(1)} s has no caption while the captions around it run: caption it from the words file, unless it's meant to go uncaptioned` })
|
||||
i = j
|
||||
}
|
||||
return out.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
/** speech this long (s) and this many words with no caption up is an error, the shorter a warning */
|
||||
const BARE = { error: { s: 3, words: 6 }, warn: { s: 1.5, words: 3 } }
|
||||
/** the opening a text hook may hold without captions under it (s) */
|
||||
const HOOK_S = 5
|
||||
|
||||
/** captions are a must wherever someone talks (12-03, Shane: "captions are mandatory"; Elfster's cuts with a text hook
|
||||
* 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): Finding[] {
|
||||
heard = asDigits(heard)
|
||||
// a brief's "captions OR a text hook, never both" means not both in one frame (12-03, Shane): the hook may hold the
|
||||
// opening alone, so words in the first HOOK_S with other text up are covered by it; anywhere later it's no caption
|
||||
const said = heard.filter((w) => {
|
||||
const k = letters(w.text)
|
||||
return k && !FILLER.has(k) && !(w.start < HOOK_S && textUp(w.start))
|
||||
})
|
||||
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}` }]
|
||||
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 }
|
||||
let j = i
|
||||
// a bare stretch: words with no caption up, none more than a second after the last
|
||||
while (j + 1 < said.length && !up(said[j + 1]) && said[j + 1].start - said[j].end < 1) j++
|
||||
const run = said.slice(i, j + 1)
|
||||
const long = run[run.length - 1].end - run[0].start
|
||||
const level = long >= BARE.error.s && run.length >= BARE.error.words ? "error" : long >= BARE.warn.s && run.length >= BARE.warn.words ? "warn" : null
|
||||
if (level) out.push({ level, kind: "uncaptioned", at: run[0].start, says: `${long.toFixed(1)} s of talking from ${run[0].start.toFixed(1)} s has no caption ("${run.slice(0, 8).map((w) => w.text).join(" ")}${run.length > 8 ? " ..." : ""}"): ${fix}` })
|
||||
i = j + 1
|
||||
}
|
||||
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())
|
||||
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 textUp = (t: number) => (frames[Math.round(t * rate)]?.lines ?? []).some(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4)
|
||||
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,196 @@
|
||||
// The cut packs (docs/goal.feature MK25-MK27, MK38; Rust's cut gates until 11-29, now here alone): a client's brief as rules
|
||||
// (`goal: cut({ cut: {...} })`), held from what's on disk and heard, never from what the agent says.
|
||||
// quotes every rule's `from` is in the brief's text, word for word
|
||||
// count as many cuts as the brief asks for, or an `open` item about "count" a person answered
|
||||
// open each open item answered, with who answered it
|
||||
// shape each delivered cut in its format and length
|
||||
// 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, 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 */
|
||||
export const CTA_SHARE = 0.85
|
||||
|
||||
export const ratio = (f: string): [number, number] | null => {
|
||||
const [w, h] = f.split(":").map((x) => Number(x.trim()))
|
||||
return w > 0 && h > 0 ? [w, h] : null
|
||||
}
|
||||
export const formatsOf = (c: CutGoal, p: CutPlan) => (p.formats?.length ? p.formats : (c.formats ?? []))
|
||||
export const secondsOf = (c: CutGoal, p: CutPlan) => p.seconds ?? c.seconds ?? null
|
||||
/** where a cut lands: out/cuts/ID_WxH.mp4 */
|
||||
export const fileOf = (p: CutPlan, format: string) => `out/cuts/${p.id}_${format.replace(":", "x")}.mp4`
|
||||
export const deliverables = (c: CutGoal) => (c.cuts ?? []).flatMap((p) => formatsOf(c, p).map((f) => fileOf(p, f)))
|
||||
|
||||
/** every rule and the brief's words it quotes */
|
||||
export function quotes(c: CutGoal): [string, string][] {
|
||||
const q: [string, string][] = []
|
||||
if (c.count) q.push(["count", c.count.from])
|
||||
for (const [what, list] of [["say", c.say ?? []], ["never", c.never ?? []]] as const) for (const p of list) q.push([`${what} "${p.text}"`, p.from])
|
||||
if (c.cta) {
|
||||
q.push(["cta", c.cta.from])
|
||||
for (const line of c.cta.also ?? []) q.push([`cta "${line}"`, line])
|
||||
}
|
||||
for (const o of c.open ?? []) q.push([`open "${o.question}"`, o.from])
|
||||
return q
|
||||
}
|
||||
|
||||
/** the cut a delivered file is, and its format, when it's one of the brief's */
|
||||
export function cutOf(c: CutGoal, rel: string): { plan: CutPlan; format: string } | null {
|
||||
for (const p of c.cuts ?? []) for (const format of formatsOf(c, p)) if (fileOf(p, format) === rel) return { plan: p, format }
|
||||
return null
|
||||
}
|
||||
|
||||
/** what a file shows: each text of its render manifest, normed, and the second it's first on screen */
|
||||
export function shown(m: Manifest | null): [string, number][] {
|
||||
if (!m) return []
|
||||
const fps = m.fps && m.fps > 0 ? m.fps : 30
|
||||
const out: [string, number][] = []
|
||||
for (const fr of m.frames ?? [])
|
||||
for (const t of fr.text ?? []) {
|
||||
const s = norm(t.text ?? "")
|
||||
if (s && (t.opacity ?? 1) > 0.05 && !out.some(([o]) => o === s)) out.push([s, fr.frame / fps])
|
||||
}
|
||||
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
|
||||
const at = c ? cutOf(c, f.path) : null
|
||||
return c && at ? { c, ...at } : null
|
||||
}
|
||||
|
||||
/** 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 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) }
|
||||
}
|
||||
const onScreen = (s: string, p: string, gap: number) => saidAt(s.split(" "), p, gap) !== null
|
||||
|
||||
export const quotesPack = check<Job>({ id: "quotes", text: "every rule quotes the brief's own words", over: "job", at: ["edit", "done"] }, async (j) => {
|
||||
const c = cutJob(j)
|
||||
if (!c) return
|
||||
const file = path.resolve(j.root, c.brief)
|
||||
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("; ")}` })
|
||||
})
|
||||
|
||||
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) => {
|
||||
const c = cutJob(j)
|
||||
if (!c?.count) return
|
||||
const have = c.cuts?.length ?? 0
|
||||
if (have >= c.count.value) return
|
||||
// answered: it holds nothing here, but it's said, so raea cloud can show a person a brief made smaller by an answer
|
||||
// the agent may have written itself (the brief is gospel: only a person lowers its numbers)
|
||||
const answer = (c.open ?? []).find((o) => o.about === "count" && o.answer?.trim())
|
||||
if (answer) return found({ level: "note", says: `${have} of the brief's ${c.count.value} cuts, as answered: ${answer.answer}${answer.by ? ` (${answer.by})` : ""}` })
|
||||
found({ says: `${have} cuts planned; the brief asks for ${c.count.value} ("${c.count.from}"): plan them, or add an \`open\` item about "count" and have a person answer it` })
|
||||
})
|
||||
|
||||
export const openPack = check<Job>({ id: "open", text: "every open item answered by a person", over: "job", at: ["publish", "done"] }, async (j) => {
|
||||
for (const o of cutJob(j)?.open ?? []) if (!o.answer?.trim()) found({ says: `unanswered: ${o.question} (brief: "${o.from}"): ask at the review, then write the answer and who gave it`, about: o.about ? [o.about] : [] })
|
||||
})
|
||||
|
||||
export const shapePack = check<FileFacts>({ id: "shape", text: "each cut in its format and length", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
const at = cutFile(f)
|
||||
if (!at) return
|
||||
const want = ratio(at.format)
|
||||
if (!f.width || !f.height) return found({ says: "not an MP4 or MOV with a video track" })
|
||||
const wrong: string[] = []
|
||||
if (want && Math.abs(f.width / f.height / (want[0] / want[1]) - 1) > 0.02) wrong.push(`${f.width}x${f.height} isn't ${at.format}`)
|
||||
const len = secondsOf(at.c, at.plan)
|
||||
if (len && f.seconds !== null && (f.seconds + 0.05 < len[0] || f.seconds > len[1] + 0.05)) wrong.push(`${f.seconds.toFixed(1)} s isn't ${len[0]}-${len[1]} s`)
|
||||
if (wrong.length) found({ says: wrong.join("; ") })
|
||||
})
|
||||
|
||||
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 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(", ")}` })
|
||||
})
|
||||
|
||||
export const neverPack = check<FileFacts>({ id: "never", text: "no banned phrase heard or shown", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
|
||||
const at = cutFile(f)
|
||||
if (!at?.c.never?.length) return
|
||||
const { spoken, times, screen } = await heardOf(f)
|
||||
for (const p of at.c.never) {
|
||||
const n = norm(p.text)
|
||||
const i = saidAt(spoken, n, 1)
|
||||
if (i !== null) {
|
||||
found({ says: `"${p.text}" heard at ${times[i].start.toFixed(1)} s (brief: ${p.from})`, seconds: times[i].start })
|
||||
continue
|
||||
}
|
||||
const s = screen.find(([s]) => onScreen(s, n, 1))
|
||||
if (s) found({ says: `"${p.text}" on screen at ${s[1].toFixed(1)} s (brief: ${p.from})`, seconds: s[1] })
|
||||
}
|
||||
})
|
||||
|
||||
export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the CTA", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
|
||||
const at = cutFile(f)
|
||||
const cta = at?.c.cta
|
||||
if (!cta) return
|
||||
const { times } = 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))
|
||||
const share = (line: string, got: string[]) => {
|
||||
const want = norm(line).split(" ")
|
||||
return inOrder(want, joined(got, want).map(([w]) => w))
|
||||
}
|
||||
const lines = [cta.text, ...(cta.also ?? [])]
|
||||
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) 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] })
|
||||
})
|
||||
|
||||
/** 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) })))
|
||||
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)))
|
||||
if (!by) found({ says: `no cut says or shows "${p.text}" (brief: "${p.from}")` })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
// The floor packs: raea's own measures of a picture, from its Rust (apps/check), held at their moments.
|
||||
// floor a made video against the floor (`raea check VIDEO`, with its render manifest): clipped text, contrast, safe
|
||||
// areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit
|
||||
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
|
||||
// the text rules and the person's text taste on them; what it can't see waits for the export's floor
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
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"
|
||||
|
||||
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
|
||||
|
||||
/** raea's measure of a file, its findings as it wrote them (-o) */
|
||||
function measure(args: string[], cwd: string): Measured[] {
|
||||
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)}`)
|
||||
return (JSON.parse(readFileSync(out, "utf8")).findings ?? []) as Measured[]
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** a video's floor report, kept beside it */
|
||||
export const FLOOR_EXT = "floor.json"
|
||||
let version: string | undefined
|
||||
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
|
||||
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
|
||||
|
||||
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
|
||||
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
|
||||
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
|
||||
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
|
||||
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
|
||||
const kept = `${stem(abs)}.${FLOOR_EXT}`
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
|
||||
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
|
||||
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
|
||||
} catch {}
|
||||
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
|
||||
try {
|
||||
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
|
||||
} catch {}
|
||||
return findings
|
||||
}
|
||||
|
||||
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
|
||||
|
||||
/** 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)
|
||||
})
|
||||
|
||||
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) => {
|
||||
if (!f.path.endsWith(".tsx")) return
|
||||
if (!readFileSync(f.abs, "utf8").includes("registerRoot")) return
|
||||
for (const x of measure([f.abs, "--quick"], f.root)) say(x)
|
||||
})
|
||||
@@ -0,0 +1,154 @@
|
||||
// The frames pack (docs/goal.feature MK37; the box's frames check of 11-25): what an export's pictures get wrong that a
|
||||
// viewer sees at once, measured (Shane: "it cuts out faces all the time and also does split frame shots when they make
|
||||
// no sense", "it makes text too small on some things, we should have a text/glyph readability check").
|
||||
//
|
||||
// text: each text the render's manifest shows, its font size in pixels of a 1080-wide frame: under 40 px is an error
|
||||
// (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. 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
|
||||
/** 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
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small" | "text-over"; at: number | null; until?: number; says: string }
|
||||
type Split = { axis: "h" | "v"; at: number }
|
||||
|
||||
/** a frame's split-screen seams: lone lines in its middle 60% (a bar's two edges close together are a caption's box, a
|
||||
* badge or a letterbox, not a seam) */
|
||||
export function splitsOf(fr: NonNullable<Faces>): Split[] {
|
||||
const out: Split[] = []
|
||||
for (const axis of ["h", "v"] as const) {
|
||||
const dim = axis === "h" ? fr.h : fr.w
|
||||
const at = [...new Set((fr.seams ?? []).filter((x) => x[0] === axis).map((x) => x[1]))].sort((a, b) => a - b)
|
||||
const lines = at.filter((y, i) => i === 0 || y - at[i - 1] > 4)
|
||||
for (const y of lines) {
|
||||
const bar = lines.some((o) => o !== y && Math.abs(o - y) < dim * 0.15)
|
||||
if (!bar && y > dim * 0.2 && y < dim * 0.8) out.push({ axis, at: y })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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 */
|
||||
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
|
||||
}
|
||||
|
||||
/** runs of the same thing in consecutive frames, as [from, to) in frames */
|
||||
function runs<T>(xs: (T | null)[], same: (a: T, b: T) => boolean = (a, b) => a === b): [number, number, T][] {
|
||||
const out: [number, number, T][] = []
|
||||
for (let i = 0; i < xs.length; ) {
|
||||
const x = xs[i]
|
||||
if (x === null) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
let j = i + 1
|
||||
while (j < xs.length && xs[j] !== null && same(x, xs[j] as T)) j++
|
||||
out.push([i, j, x])
|
||||
i = j
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** faces cut by the frame's edges or a split screen's seam (a second or more an error, shorter a warning), and split
|
||||
* screens that hold one person (a split is for two things at once) */
|
||||
export function cutFaces(frames: Faces[], rate = RATE): Finding[] {
|
||||
const raw = frames.map((fr) => (fr ? splitsOf(fr) : []))
|
||||
// a seam held for a second or more: a split screen; a line for a frame is a cut or a flash
|
||||
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)) {
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
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)) {
|
||||
if (j - i < 2) continue
|
||||
// whose face is on each side of the seam, frame by frame
|
||||
let one = 0
|
||||
let any = 0
|
||||
for (let k = i; k < j; k++) {
|
||||
const fr = frames[k]
|
||||
if (!fr) continue
|
||||
const sides = new Set(big(fr).map(([x, y, fw, fh]) => ((sp.axis === "h" ? y + fh / 2 : x + fw / 2) < sp.at ? 0 : 1)))
|
||||
if (sides.size) any++
|
||||
if (sides.size === 1) one++
|
||||
}
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
const where = sp.axis === "h" ? "top and bottom" : "side by side"
|
||||
if (any && one * 2 > any) out.push({ level: "warn", kind: "split", at: from, until: to, says: `a split screen (${where}) from ${from.toFixed(1)} s to ${to.toFixed(1)} s shows a face in only one half: split only for two things at once (two people reacting, a face and the product), else cut between singles` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** texts under the size floor, from a render manifest: each text once, at its first frame */
|
||||
export function smallText(manifest: any): Finding[] {
|
||||
const w = Number(manifest?.width) || 1080
|
||||
const h = Number(manifest?.height) || 1920
|
||||
const fps = Number(manifest?.fps) || 30
|
||||
const scale = 1080 / Math.min(w, h)
|
||||
const seen = new Map<string, { at: number; px: number }>()
|
||||
for (const fr of (manifest?.frames ?? []) as any[]) {
|
||||
for (const t of (fr?.text ?? []) as any[]) {
|
||||
const text = String(t?.text ?? "").trim()
|
||||
if (!text || (t?.opacity ?? 1) <= 0.05) continue
|
||||
const px = Number(t?.size) * scale
|
||||
if (!Number.isFinite(px) || px <= 0) continue
|
||||
const was = seen.get(text)
|
||||
if (!was || px > was.px) seen.set(text, { at: was?.at ?? Number(fr?.frame ?? 0) / fps, px })
|
||||
}
|
||||
}
|
||||
const out: Finding[] = []
|
||||
for (const [text, { at, px }] of seen) {
|
||||
const q = `"${quote(text, 40)}"`
|
||||
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)` })
|
||||
}
|
||||
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
|
||||
}
|
||||
|
||||
/** why a face at the edge is meant, from OUT.despite.txt beside the video */
|
||||
export const despite = (abs: string) => {
|
||||
const p = `${stem(abs)}.despite.txt`
|
||||
return existsSync(p) ? readFileSync(p, "utf8").trim().slice(0, 200) : ""
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
|
||||
// the text's sizes are said even where the faces wait for a scene reader
|
||||
const why = despite(f.abs)
|
||||
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
// 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").
|
||||
import { check, found } from "raea/check"
|
||||
import type { Job } from "../facts.ts"
|
||||
|
||||
export const TIMEOUT = 300
|
||||
|
||||
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 ?? []) {
|
||||
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] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
// The hook and air-gap packs (11-30, Shane), on the export's own words and levels.
|
||||
//
|
||||
// hook: the first seconds have sound and picture working together. Elfster's Voted cut opened on 1.5 s of whiteboard
|
||||
// with nothing said (-27 dB): "a whiteboard people will read as the hook ... that's not a hook, a hook really should
|
||||
// have audio and video stimulation". The first word later than LEAD_ERROR into the cut, with nothing loud under the
|
||||
// opening either, is an error; later than LEAD_WARN, a warning. Sound alone (a hit, a song's first beat) under a
|
||||
// wordless opening is a warning, to be decided, not an error.
|
||||
// airgaps: the silences between words. "Measuring and cutting air gaps ... especially in a hook ... for social media
|
||||
// content or ads, especially if it is at all trying to look organic." In the hook's first HOOK seconds a gap over
|
||||
// HOOK_ERROR is an error and over HOOK_WARN a warning; later, one over BODY_WARN is a warning. The fix is raea's
|
||||
// tighten() (@raea/video airgaps), which cuts only between words and never into one.
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { airGaps } from "../../../video/src/airgaps.ts"
|
||||
|
||||
/** the first word this late (s): an error with a quiet opening, a warning */
|
||||
export const LEAD_ERROR = 1.0
|
||||
export const LEAD_WARN = 0.5
|
||||
/** the opening counts as carrying sound when its loud end is within this of the speech's (dB) */
|
||||
const OPENING_LOUD = 10
|
||||
/** the hook's seconds, and the gaps held in them (s) */
|
||||
export const HOOK = 3
|
||||
export const HOOK_ERROR = 0.5
|
||||
export const HOOK_WARN = 0.3
|
||||
/** a gap this long after the hook (s): a warning */
|
||||
export const BODY_WARN = 0.8
|
||||
|
||||
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))]
|
||||
}
|
||||
|
||||
export type HookFinding = { level: "error" | "warn"; at: number; says: string }
|
||||
|
||||
/** the opening and the gaps, from the words heard and the levels every 10 ms */
|
||||
export function hookAndGaps(words: { text: string; start: number; end: number }[], db: number[]): { hook: HookFinding[]; gaps: HookFinding[] } {
|
||||
const hook: HookFinding[] = []
|
||||
const gaps: HookFinding[] = []
|
||||
if (words.length < 3) return { hook, gaps }
|
||||
const first = words[0].start
|
||||
const speech = pct(words.flatMap((w) => db.slice(Math.floor(w.start * 100), Math.ceil(w.end * 100))), 0.8)
|
||||
const opening = pct(db.slice(0, Math.max(1, Math.floor(first * 100))), 0.8)
|
||||
const loud = opening > speech - OPENING_LOUD
|
||||
if (first > LEAD_WARN + 0.005) {
|
||||
const level = first > LEAD_ERROR && !loud ? "error" : "warn"
|
||||
hook.push({
|
||||
level,
|
||||
at: 0,
|
||||
says: loud
|
||||
? `the first word comes ${first.toFixed(1)} s in, over sound alone (${opening.toFixed(0)} dB against the speech's ${speech.toFixed(0)}): a hook has words and picture together from the first frame, so open on the first line unless the sound is the hook`
|
||||
: `${first.toFixed(1)} s of dead air before the first word ("${words[0].text}"), the opening ${(speech - opening).toFixed(0)} dB under the speech: a hook has sound and picture working together from the first frame. Open on the first line (cut the silent lead-in, or have the line land over the opening shot); a sign or a board people are meant to read is not a hook`,
|
||||
})
|
||||
}
|
||||
for (const g of airGaps(words.map((w) => ({ text: w.text, start: w.start, end: w.end })), HOOK)) {
|
||||
if (g.from === 0) continue // the lead-in is the hook pack's
|
||||
const inHook = g.from < HOOK
|
||||
const over = (x: number) => g.seconds > x + 0.005 // a transcript's times land on 10 ms steps
|
||||
const level = inHook ? (over(HOOK_ERROR) ? "error" : over(HOOK_WARN) ? "warn" : null) : over(BODY_WARN) ? "warn" : null
|
||||
if (!level) continue
|
||||
gaps.push({ level, at: g.from, says: `${g.seconds.toFixed(2)} s of air between "${g.after}" and "${g.before}" at ${g.from.toFixed(1)} s${inHook ? " in the hook" : ""}: tighten it to about ${inHook ? 0.15 : 0.25} s with tighten() (raea's air-gap cut: between words only, never into one), unless the pause is the beat` })
|
||||
}
|
||||
return { hook, gaps }
|
||||
}
|
||||
|
||||
export const hookPack = check<FileFacts>(
|
||||
{ id: "hook", text: "the hook opens on words and picture together, no dead air", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
for (const x of hookAndGaps(heard, f.levels().db).hook) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
|
||||
export const airgapsPack = check<FileFacts>(
|
||||
{ id: "airgaps", text: "no air between words: tight in the hook, no long pause after", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
for (const x of hookAndGaps(heard, f.levels().db).gaps) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
// raea's packs by name (contract.ts PACKS says what each holds a job to).
|
||||
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 frames from "./frames.ts"
|
||||
import montage from "./montage.ts"
|
||||
import { runPack } from "./goal.ts"
|
||||
import { deliverablesPack } from "./job.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"
|
||||
|
||||
/** each pack's checks (say holds each cut, and the phrases one cut is enough for across them) */
|
||||
export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
words: [words],
|
||||
captions: [captions],
|
||||
voice: [voice],
|
||||
reading: [reading],
|
||||
hook: [hookPack],
|
||||
airgaps: [airgapsPack],
|
||||
sound: [sound],
|
||||
frames: [frames],
|
||||
montage: [montage],
|
||||
place: [place],
|
||||
naming: [naming],
|
||||
sizes: [sizes, allSizes],
|
||||
quotes: [quotesPack],
|
||||
count: [countPack],
|
||||
open: [openPack],
|
||||
say: [sayPack, sayOncePack],
|
||||
never: [neverPack],
|
||||
cta: [ctaPack],
|
||||
shape: [shapePack],
|
||||
run: [runPack],
|
||||
deliverables: [deliverablesPack],
|
||||
floor: [floorPack],
|
||||
playable: [playablePack],
|
||||
render: [render],
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 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"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { deliverables as cutFiles } from "./cut.ts"
|
||||
import { deliverables as playableFiles } from "./playable.ts"
|
||||
|
||||
/** 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 */
|
||||
export function deliverablesOf(m: Contract | null): string[] {
|
||||
if (!m) return []
|
||||
const files = (m.rules ?? []).flatMap((r) => (r.file ? [r.file] : []))
|
||||
return [...new Set([...(m.deliverables?.length ? m.deliverables : byKind(m)), ...files])]
|
||||
}
|
||||
|
||||
function byKind(m: Contract): string[] {
|
||||
switch (m.kind) {
|
||||
case "scene":
|
||||
return ["out/stills/"]
|
||||
case "kit":
|
||||
return [...(m.objects ?? []).flatMap((o) => [`out/kit/${o.id}/${o.id}.glb`, `out/kit/${o.id}/${o.id}_lod1.glb`, `out/kit/thumbs/${o.id}.png`]), "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"]
|
||||
case "shot":
|
||||
return (m.shots ?? []).map((s) => `out/shots/${s.name}.png|out/shots/${s.name}.mp4`)
|
||||
case "cut":
|
||||
return m.cut ? cutFiles(m.cut) : []
|
||||
case "playable":
|
||||
return m.playable ? playableFiles(m.playable) : []
|
||||
case "rules":
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const PICTURE = /\.(png|jpe?g|exr)$/i
|
||||
/** one deliverable: a file, `a|b` (either), or `dir/` (three or more pictures in it); the files that answer it, or why not */
|
||||
export function answered(root: string, want: string): string[] | string {
|
||||
if (want.endsWith("/")) {
|
||||
const d = path.join(root, want)
|
||||
const pics = existsSync(d) ? readdirSync(d).filter((n) => PICTURE.test(n)).map((n) => path.join(want, n)) : []
|
||||
return pics.length >= 3 ? pics : `${want} holds ${pics.length} picture${pics.length === 1 ? "" : "s"}; three or more`
|
||||
}
|
||||
const got = want.split("|").filter((w) => existsSync(path.join(root, w)) && statSync(path.join(root, w)).isFile())
|
||||
return got.length ? got : want.replace(/\|/g, " or ")
|
||||
}
|
||||
|
||||
export const deliverablesPack = check<Job>({ id: "deliverables", text: "every deliverable exists", over: "job", at: ["done"] }, async (j) => {
|
||||
for (const want of j.deliverables) {
|
||||
const a = answered(j.root, want)
|
||||
if (typeof a === "string") found({ says: `missing: ${a}`, about: [want] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,297 @@
|
||||
// The montage pack (docs/goal.feature MK48-MK51): each delivered cut read as an editor reads it, cut by cut (Shane,
|
||||
// 11-29, on Kuleshov, Eisenstein's methods of montage and Murch's Rule of Six). Murch weighs a cut's reasons: emotion
|
||||
// 51%, story 23%, rhythm 10%, eye trace 7%, the screen's plane 5%, its 3D space 4%, and gives them up from the bottom:
|
||||
// never story for rhythm, rhythm for eye trace. Emotion and story are the beats' `says` rules, judged by a fresh critic
|
||||
// on the cut in sequence (contract.ts saysOf); this pack measures the rest, from the file's own frames:
|
||||
// pace each beat's shots average within a third of its `asl`, and move as its `tempo` says (build: shorter as it
|
||||
// goes; release: longer; hold: even). Eisenstein's metric montage: tempo set by shot length. An error, as
|
||||
// the plan is a decision
|
||||
// eye the focal point on either side of a cut (the largest face the scene reader finds, else where the frame's
|
||||
// contrast gathers) within 0.4 of the frame's diagonal: the eye shouldn't hunt for what to look at
|
||||
// plane the picture's sideways motion on both sides of a cut not reversed (screen direction)
|
||||
// tone no jump in brightness (0.25) or warmth (0.08) across a cut a beat doesn't start at (tonal montage)
|
||||
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
|
||||
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { type Faces, Unmet } from "../media.ts"
|
||||
import { cutOf } from "./cut.ts"
|
||||
|
||||
/** Murch's weights (In the Blink of an Eye), named in each finding so the order of giving up is plain */
|
||||
export const MURCH = { emotion: 51, story: 23, rhythm: 10, eye: 7, plane: 5, space: 4 } as const
|
||||
/** the width frames are read at (the height by the picture's shape) */
|
||||
export const READ_W = 48
|
||||
export const EYE_JUMP = 0.4
|
||||
export const LUMA_JUMP = 0.25
|
||||
export const WARMTH_JUMP = 0.08
|
||||
/** sideways motion, in widths a second, below which a side counts as still */
|
||||
export const MOVING = 0.15
|
||||
/** a share of a beat's asl the shots may average off by */
|
||||
export const ASL_SLACK = 1 / 3
|
||||
/** a habit: one measure broken at more than this share of a file's cuts */
|
||||
export const HABIT = 0.5
|
||||
|
||||
/** a frame read small: its grey (0..1) and its mean luma and warmth */
|
||||
export type Frame = { grey: Float32Array; luma: number; warmth: number }
|
||||
export type Read = { fps: number; w: number; h: number; frames: Frame[] }
|
||||
export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye" | "plane" | "tone"; at: number | null; until?: number; says: string }
|
||||
|
||||
/** a video's frames, READ_W wide, from one ffmpeg pass */
|
||||
export function read(file: string, fps: number, width: number, height: number): Read {
|
||||
const w = READ_W
|
||||
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
|
||||
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
|
||||
// 4.6 s into a file (12-01)
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
|
||||
let buf: Buffer
|
||||
try {
|
||||
const raw = path.join(dir, "frames.raw")
|
||||
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
|
||||
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
|
||||
buf = readFileSync(raw)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
const size = w * h * 3
|
||||
const frames: Frame[] = []
|
||||
for (let o = 0; o + size <= buf.length; o += size) {
|
||||
const grey = new Float32Array(w * h)
|
||||
let ls = 0
|
||||
let warm = 0
|
||||
for (let i = 0; i < w * h; i++) {
|
||||
const R = buf[o + i * 3] / 255
|
||||
const G = buf[o + i * 3 + 1] / 255
|
||||
const B = buf[o + i * 3 + 2] / 255
|
||||
const y = 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
grey[i] = y
|
||||
ls += y
|
||||
const sum = R + G + B
|
||||
if (sum > 0.05) warm += (R - B) / sum
|
||||
}
|
||||
frames.push({ grey, luma: ls / (w * h), warmth: warm / (w * h) })
|
||||
}
|
||||
return { fps, w, h, frames }
|
||||
}
|
||||
|
||||
const diff = (a: Frame, b: Frame) => {
|
||||
let s = 0
|
||||
for (let i = 0; i < a.grey.length; i++) s += Math.abs(a.grey[i] - b.grey[i])
|
||||
return s / a.grey.length
|
||||
}
|
||||
const median = (xs: number[]) => {
|
||||
const s = [...xs].sort((a, b) => a - b)
|
||||
return s.length ? s[Math.floor(s.length / 2)] : 0
|
||||
}
|
||||
|
||||
/** the frames that start a new shot: a picture change well above its neighbours' (hard cuts; a dissolve isn't one) */
|
||||
export function cutsOf(r: Read): number[] {
|
||||
const d = r.frames.map((f, i) => (i ? diff(r.frames[i - 1], f) : 0))
|
||||
const out: number[] = []
|
||||
for (let i = 1; i < d.length; i++) {
|
||||
const near = d.slice(Math.max(1, i - 6), i).concat(d.slice(i + 1, i + 7))
|
||||
if (d[i] > 0.1 && d[i] > 3 * median(near) + 0.02 && (!out.length || i - out[out.length - 1] >= 4)) out.push(i)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** where a frame's contrast gathers (0..1 from the top left): each pixel's difference from its neighbourhood, squared */
|
||||
export function focal(f: Frame, w: number, h: number): [number, number] {
|
||||
let sx = 0
|
||||
let sy = 0
|
||||
let sw = 0
|
||||
const R = 3
|
||||
for (let y = 0; y < h; y++)
|
||||
for (let x = 0; x < w; x++) {
|
||||
let m = 0
|
||||
let n = 0
|
||||
for (let yy = Math.max(0, y - R); yy <= Math.min(h - 1, y + R); yy++)
|
||||
for (let xx = Math.max(0, x - R); xx <= Math.min(w - 1, x + R); xx++) {
|
||||
m += f.grey[yy * w + xx]
|
||||
n++
|
||||
}
|
||||
const c = (f.grey[y * w + x] - m / n) ** 2
|
||||
sx += c * (x + 0.5)
|
||||
sy += c * (y + 0.5)
|
||||
sw += c
|
||||
}
|
||||
return sw > 1e-6 ? [sx / sw / w, sy / sw / h] : [0.5, 0.5]
|
||||
}
|
||||
|
||||
/** the largest face's centre in the scene reader's frame nearest `t` (RATE a second), when it's in the same shot */
|
||||
export function faceAt(faces: Faces[], rate: number, t: number, from: number, to: number): [number, number] | null {
|
||||
if (!rate) return null
|
||||
const i = Math.round(t * rate)
|
||||
const ts = i / rate
|
||||
if (ts < from || ts >= to) return null
|
||||
const fr = faces[i]
|
||||
if (!fr?.faces.length) return null
|
||||
const [x, y, w, h] = [...fr.faces].sort((a, b) => b[2] * b[3] - a[2] * a[3])[0]
|
||||
return [(x + w / 2) / fr.w, (y + h / 2) / fr.h]
|
||||
}
|
||||
|
||||
/** sideways motion between two frames, in widths a second: the shift that best lines up their column profiles */
|
||||
export function sideways(a: Frame, b: Frame, w: number, h: number, seconds: number): number {
|
||||
const col = (f: Frame) => Array.from({ length: w }, (_, x) => {
|
||||
let s = 0
|
||||
for (let y = 0; y < h; y++) s += f.grey[y * w + x]
|
||||
return s / h
|
||||
})
|
||||
const pa = col(a)
|
||||
const pb = col(b)
|
||||
const max = Math.floor(w / 6)
|
||||
let best = 0
|
||||
let bestErr = Infinity
|
||||
for (let s = -max; s <= max; s++) {
|
||||
let e = 0
|
||||
let n = 0
|
||||
for (let x = Math.max(0, -s); x < Math.min(w, w - s); x++) {
|
||||
e += Math.abs(pa[x] - pb[x + s])
|
||||
n++
|
||||
}
|
||||
// a small pull to no shift, so a flat or still picture reads as still
|
||||
const err = e / n + Math.abs(s) * 1e-4
|
||||
if (err < bestErr) {
|
||||
bestErr = err
|
||||
best = s
|
||||
}
|
||||
}
|
||||
return best / w / seconds
|
||||
}
|
||||
|
||||
/** Kendall's tau of shot lengths against their order: below 0 they shorten, above they lengthen */
|
||||
export function tau(xs: number[]): number {
|
||||
let c = 0
|
||||
let n = 0
|
||||
for (let i = 0; i < xs.length; i++)
|
||||
for (let j = i + 1; j < xs.length; j++) {
|
||||
c += Math.sign(xs[j] - xs[i])
|
||||
n++
|
||||
}
|
||||
return n ? c / n : 0
|
||||
}
|
||||
|
||||
const s2 = (x: number) => `${x.toFixed(1)} s`
|
||||
|
||||
/** a beat's pace against its plan: the shots inside [from, to) from the cut frames */
|
||||
export function pace(beats: Beat[], cuts: number[], fps: number, end: number): Finding[] {
|
||||
const out: Finding[] = []
|
||||
const starts = [0, ...cuts.map((c) => c / fps)]
|
||||
beats.forEach((b, i) => {
|
||||
const from = b.at
|
||||
const to = Math.min(end, beats[i + 1]?.at ?? end)
|
||||
if (to - from <= 0) return
|
||||
const inside = starts.filter((s) => s > from + 1e-6 && s < to - 1e-6)
|
||||
const asl = (to - from) / (inside.length + 1)
|
||||
if (b.asl && Math.abs(asl / b.asl - 1) > ASL_SLACK)
|
||||
out.push({ level: "error", kind: "pace", at: from, until: to, says: `beat ${i + 1} (${b.feel}): its shots average ${s2(asl)}, its asl is ${s2(b.asl)} (${asl > b.asl ? "too slow: cut it into more shots" : "too fast: hold its shots longer"}; rhythm, Murch ${MURCH.rhythm}%)` })
|
||||
if (b.tempo && b.tempo !== "hold") {
|
||||
const edges = [from, ...inside, to]
|
||||
const lens = edges.slice(1).map((e, k) => e - edges[k])
|
||||
if (lens.length < 3) out.push({ level: "error", kind: "tempo", at: from, until: to, says: `beat ${i + 1} (${b.feel}) should ${b.tempo === "build" ? "build" : "release"}, but it has ${lens.length} shot${lens.length === 1 ? "" : "s"}: a tempo needs three or more` })
|
||||
else {
|
||||
const t = tau(lens)
|
||||
if (b.tempo === "build" ? t > -0.2 : t < 0.2) out.push({ level: "error", kind: "tempo", at: from, until: to, says: `beat ${i + 1} (${b.feel}) should ${b.tempo === "build" ? "build: shots shorter as it goes" : "release: shots longer as it goes"}, but its shot lengths go ${lens.map((l) => l.toFixed(1)).join(", ")} s (rhythm, Murch ${MURCH.rhythm}%)` })
|
||||
}
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/** what each cut keeps or breaks: eye trace, screen direction and tone, in Murch's order */
|
||||
export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?: number; beatsAt?: number[] } = {}): Finding[] {
|
||||
const out: Finding[] = []
|
||||
const bounds = [0, ...cuts, r.frames.length]
|
||||
const tally = { eye: 0, plane: 0, tone: 0 }
|
||||
cuts.forEach((c, k) => {
|
||||
const t = c / r.fps
|
||||
const from = bounds[k]
|
||||
const to = bounds[k + 2]
|
||||
const A = r.frames[c - 1]
|
||||
const B = r.frames[c]
|
||||
const at = (f: Frame, frame: number, lo: number, hi: number) => (o.faces && faceAt(o.faces, o.rate ?? 0, frame / r.fps, lo / r.fps, hi / r.fps)) ?? focal(f, r.w, r.h)
|
||||
const fa = at(A, c - 1, from, c)
|
||||
const fb = at(B, c, c, to)
|
||||
const aspect = r.h / r.w
|
||||
const jump = Math.hypot(fa[0] - fb[0], (fa[1] - fb[1]) * aspect) / Math.hypot(1, aspect)
|
||||
if (jump > EYE_JUMP) {
|
||||
tally.eye++
|
||||
out.push({ level: "warn", kind: "eye", at: t, says: `the cut at ${s2(t)} moves the eye ${Math.round(jump * 100)}% of the frame (${where(fa)} to ${where(fb)}): put what matters after the cut near where the eye was (eye trace, Murch ${MURCH.eye}%)` })
|
||||
}
|
||||
const span = Math.min(3, c - from - 1, to - c - 1)
|
||||
if (span >= 2) {
|
||||
const va = sideways(r.frames[c - 1 - span], A, r.w, r.h, span / r.fps)
|
||||
const vb = sideways(B, r.frames[c + span], r.w, r.h, span / r.fps)
|
||||
if (Math.abs(va) > MOVING && Math.abs(vb) > MOVING && Math.sign(va) !== Math.sign(vb)) {
|
||||
tally.plane++
|
||||
out.push({ level: "warn", kind: "plane", at: t, says: `the cut at ${s2(t)} reverses screen direction (moving ${va > 0 ? "right" : "left"}, then ${vb > 0 ? "right" : "left"}): flip or reframe one side, or cut on a neutral move (the screen's plane, Murch ${MURCH.plane}%)` })
|
||||
}
|
||||
}
|
||||
const meant = (o.beatsAt ?? []).some((b) => Math.abs(b - t) < 0.25)
|
||||
const dl = B.luma - A.luma
|
||||
const dw = B.warmth - A.warmth
|
||||
if (!meant && (Math.abs(dl) > LUMA_JUMP || Math.abs(dw) > WARMTH_JUMP)) {
|
||||
tally.tone++
|
||||
const what = Math.abs(dl) > LUMA_JUMP ? `${dl > 0 ? "brighter" : "darker"} by ${Math.round(Math.abs(dl) * 100)}%` : `${dw > 0 ? "warmer" : "cooler"} by ${dw.toFixed(2)}`
|
||||
out.push({ level: "warn", kind: "tone", at: t, says: `the cut at ${s2(t)} jumps ${what} inside a beat: match the two shots' light, or start a beat there (tonal montage)` })
|
||||
}
|
||||
})
|
||||
if (cuts.length >= 2)
|
||||
for (const kind of ["eye", "plane", "tone"] as const)
|
||||
if (tally[kind] / cuts.length > HABIT)
|
||||
out.push({ level: "error", kind, at: null, says: `${tally[kind]} of ${cuts.length} cuts break ${kind === "eye" ? "eye trace" : kind === "plane" ? "screen direction" : "tone"}: a habit of the cut, not a choice` })
|
||||
return out
|
||||
}
|
||||
|
||||
/** a video's montage findings, kept beside it */
|
||||
export const MONTAGE_EXT = "montage.json"
|
||||
|
||||
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
|
||||
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
|
||||
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
|
||||
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
|
||||
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
|
||||
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
|
||||
} catch {}
|
||||
const findings = measure()
|
||||
try {
|
||||
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
|
||||
} catch {}
|
||||
return findings
|
||||
}
|
||||
|
||||
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "montage", text: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts", over: "file", at: ["render", "publish", "done"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video" || !f.width || !f.height) return
|
||||
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
|
||||
const plan = c ? cutOf(c, f.path) : null
|
||||
const beats = plan?.plan.beats ?? []
|
||||
let faces: Faces[] | undefined
|
||||
let rate = 0
|
||||
try {
|
||||
const sc = await f.scene()
|
||||
faces = sc.faces
|
||||
rate = sc.rate
|
||||
} catch (e) {
|
||||
// no scene reader here: the frame's contrast stands in for faces
|
||||
if (!(e instanceof Unmet)) throw e
|
||||
}
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
|
||||
const r = read(f.abs, f.fps, f.width!, f.height!)
|
||||
if (r.frames.length < 2) return []
|
||||
const cuts = cutsOf(r)
|
||||
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
|
||||
}))
|
||||
say(x)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
// The naming pack (from raea cloud's naming check, #112/#115, now here alone): every video and still made is named
|
||||
// client_concept_variant_v#_size (`dutch_grandma_hook2_v1_9x16.mp4`), so a person and the review read what's delivered
|
||||
// from the names alone: an ad is a name without its version and size, its versions and sizes live inside it, its
|
||||
// concept is the part its ads share (11-28, Shane: "it didn't create or use any naming conventions for the files").
|
||||
// A higher-quality export of the same cut adds `_master`. What was handed over (media/) and what the job writes about
|
||||
// itself (review/, previews/) aren't held to it.
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
|
||||
const VERSION = /^v\d{1,3}$/i
|
||||
const SIZE = /^\d{1,4}x\d{1,4}$/i
|
||||
const EXTRA = /^(master|final|hq|lq|proxy|export)$/i
|
||||
|
||||
/** what's wrong with a picture's name, or "" when it's by the convention */
|
||||
export function nameProblem(name: string): string {
|
||||
const base = path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "")
|
||||
if (/\s/.test(base)) return "has spaces"
|
||||
if (base !== base.toLowerCase()) return "isn't lower case"
|
||||
const parts = base.split("_").filter(Boolean)
|
||||
if (parts.length < 2) return "isn't client_concept_variant_v#_size"
|
||||
const words = parts.filter((p) => !VERSION.test(p) && !SIZE.test(p) && !EXTRA.test(p))
|
||||
if (!parts.some((p) => VERSION.test(p))) return "has no version (_v1)"
|
||||
if (!parts.some((p) => SIZE.test(p))) return "has no size (_9x16)"
|
||||
if (words.length < 2) return "needs the client and the concept before the version"
|
||||
return ""
|
||||
}
|
||||
|
||||
/** the size a name says (`9x16`), or null */
|
||||
export const sizeOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "").split("_").find((p) => SIZE.test(p))?.toLowerCase() ?? null
|
||||
/** the ad a name is: the name without its version, size and extras */
|
||||
export const adOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "").split("_").filter((p) => !VERSION.test(p) && !SIZE.test(p) && !EXTRA.test(p)).join("_")
|
||||
|
||||
/** the job's own writing about itself: review rounds, previews, sheets */
|
||||
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|second|check)\.[a-z]+$/i.test(rel) || /\.looks\//.test(rel)
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "naming", text: "files named client_concept_variant_v#_size", over: "file", at: ["edit", "render", "publish", "done"] },
|
||||
async (f) => {
|
||||
if (!f.made || bookkeeping(f.path) || (f.kind !== "video" && f.kind !== "image")) return
|
||||
const p = nameProblem(f.path)
|
||||
if (p) found({ says: `${path.basename(f.path)} ${p}: name it client_concept_variant_v#_size, like dutch_grandma_hook2_v1_9x16.mp4`, fix: "rename it, and keep the convention for every file in the project" })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
// 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(" ")
|
||||
@@ -0,0 +1,307 @@
|
||||
// Where text can go in a shot, and text laid where it hides what the shot is about (11-29, Shane on Dutch: "text being
|
||||
// weirdly placed over footage where it blocks a person or place, dont we have methods of correctly guessing where text
|
||||
// needs to go based on the scene? ... the rule of thirds, and placement of things over the scene").
|
||||
//
|
||||
// A frame's scene (the farm's POST /v1/scene: a person mask as a grid, faces, and the things a shot is about, a dog, a
|
||||
// phone, a cup) becomes a cost for each grid cell: a face most, then a thing, then a person in the shot (the body
|
||||
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
|
||||
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
|
||||
// a person, and a place of the same size costs much less; that place is what's said.
|
||||
// Over a face or a thing it's an error; over a person's body alone, a warning.
|
||||
//
|
||||
// raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
|
||||
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
|
||||
// the clearest places for a box WxH (in a 1080-wide frame; a caption, 840x110, by default), best first, as its
|
||||
// top-left in pixels and in shares of the frame, and what each covers.
|
||||
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) */
|
||||
export type TextLine = [number, number, number, number, string, number]
|
||||
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[]; texts?: TextLine[] } | null
|
||||
/** [x, y, w, h, label, score] */
|
||||
export type Thing = [number, number, number, number, string, number]
|
||||
/** a box in shares of the frame: x, y, w, h */
|
||||
export type Box = [number, number, number, number]
|
||||
|
||||
/** what each covered cell costs */
|
||||
const COST = { face: 10, thing: 6, body: 4, subject: 2, crowd: 0.5, edge: 5 }
|
||||
/** a person whose box is this share of the frame's height or more is in the shot; smaller ones are passers-by */
|
||||
const SUBJECT_MIN = 0.25
|
||||
/** a face this share of the frame's height or more is someone in the shot (frames.ts FACE_MIN); smaller, a passer-by */
|
||||
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
|
||||
/** 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
|
||||
|
||||
/** the edges a phone's own interface covers on a tall frame (Reels and TikTok: the header, the buttons on the right,
|
||||
* the caption and the bar at the bottom), in shares; a wide or square frame keeps a 5% margin all round */
|
||||
export function safe(w: number, h: number): { top: number; bottom: number; left: number; right: number } {
|
||||
return h / w > 1.5 ? { top: 0.07, bottom: 0.2, left: 0.04, right: 0.12 } : { top: 0.05, bottom: 0.05, left: 0.05, right: 0.05 }
|
||||
}
|
||||
|
||||
export type Cost = { cols: number; rows: number; cost: Float32Array; why: Uint8Array }
|
||||
/** why a cell costs what it does: 0 open, 1 crowd, 2 a person's box, 3 a body, 4 a thing, 5 a face, 6 the edge */
|
||||
export const WHY = ["open ground", "passers-by", "a person in the shot", "a person in the shot", "", "a face", "the phone's own interface", "other text on screen"]
|
||||
|
||||
/** a box (shares) overlapping another by this share of the smaller one is the same place */
|
||||
const overlaps = (a: Box, b: Box, share: number) => {
|
||||
const ix = Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]))
|
||||
const iy = Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]))
|
||||
return ix * iy > share * Math.min(a[2] * a[3], b[2] * b[3])
|
||||
}
|
||||
const shareOf = (s: NonNullable<Scene>, t: Thing): Box => [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
|
||||
|
||||
/** a scene as a cost per grid cell, and what each cell holds. `ours`: the render's own texts on this frame (the words
|
||||
* the farm read there are ours, not the shot's); `others`: the ones a place must also stay off */
|
||||
export function costs(s: NonNullable<Scene>, ours: Box[] = [], others: Box[] = []): Cost {
|
||||
const { cols, rows, people } = s.grid
|
||||
const cost = new Float32Array(cols * rows)
|
||||
const why = new Uint8Array(cols * rows)
|
||||
const set = (c: number, r: number, v: number, k: number) => {
|
||||
if (c < 0 || r < 0 || c >= cols || r >= rows) return
|
||||
const i = r * cols + c
|
||||
if (v > cost[i]) {
|
||||
cost[i] = v
|
||||
why[i] = k
|
||||
}
|
||||
}
|
||||
const cells = (t: Thing, pad = 0, inset = 0) => {
|
||||
const [x, y, w, h] = t
|
||||
const c0 = Math.floor(((x + w * inset) / s.w) * cols) - pad
|
||||
const c1 = Math.ceil(((x + w * (1 - inset)) / s.w) * cols) - 1 + pad
|
||||
const r0 = Math.floor((y / s.h) * rows) - pad
|
||||
const r1 = Math.ceil(((y + h) / s.h) * rows) - 1 + pad
|
||||
const out: [number, number][] = []
|
||||
for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) out.push([c, r])
|
||||
return out
|
||||
}
|
||||
const persons = s.things.filter((t) => t[4] === "person")
|
||||
for (const p of persons) {
|
||||
const inShot = p[3] >= s.h * SUBJECT_MIN
|
||||
// a person's box is loose around the body (the air between arms and legs): its middle costs more than its sides
|
||||
for (const [c, r] of cells(p)) set(c, r, inShot ? COST.subject : COST.crowd, inShot ? 2 : 1)
|
||||
if (inShot) for (const [c, r] of cells(p, 0, 0.15)) set(c, r, COST.subject + 1, 2)
|
||||
}
|
||||
// the body itself, where the mask sees it (a light coat it can miss; a card laid over it hides it, hence the box)
|
||||
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (Number(people[r]?.[c] ?? 0) >= 4) set(c, r, COST.body, 3)
|
||||
for (const t of s.things) {
|
||||
if (t[4] === "person") continue
|
||||
if (t[4] === "text" ? ours.some((o) => overlaps(o, shareOf(s, t), 0.4)) : (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
|
||||
for (const [c, r] of cells(t)) set(c, r, COST.thing, 4)
|
||||
}
|
||||
for (const o of others) for (const [c, r] of cells([o[0] * s.w, o[1] * s.h, o[2] * s.w, o[3] * s.h, "overlay", 1])) set(c, r, COST.thing, 7)
|
||||
// a face and a cell around it: hair, chin, the mic at the mouth
|
||||
for (const f of s.faces) {
|
||||
if (f[3] >= s.h * FACE_IN_SHOT) for (const [c, r] of cells(f, 1)) set(c, r, COST.face, 5)
|
||||
else for (const [c, r] of cells(f)) set(c, r, COST.crowd + 1, 1)
|
||||
}
|
||||
const sf = safe(s.w, s.h)
|
||||
for (let r = 0; r < rows; r++)
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const x = (c + 0.5) / cols
|
||||
const y = (r + 0.5) / rows
|
||||
if (y < sf.top || y > 1 - sf.bottom || x < sf.left || x > 1 - sf.right) set(c, r, COST.edge, 6)
|
||||
}
|
||||
return { cols, rows, cost, why }
|
||||
}
|
||||
|
||||
/** labels of the things that make cells cost, for saying what a text covers */
|
||||
function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[] {
|
||||
const out = new Set<string>()
|
||||
for (const t of [...s.faces, ...s.things]) {
|
||||
if (t[4] === "text" && ours.some((o) => overlaps(o, shareOf(s, t), 0.4))) continue
|
||||
if (t[4] === "person" && t[3] < s.h * SUBJECT_MIN) continue
|
||||
if (t[4] === "face" && t[3] < s.h * FACE_IN_SHOT) continue
|
||||
if (t[4] !== "person" && t[4] !== "face" && (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
|
||||
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])) 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]
|
||||
}
|
||||
|
||||
/** the mean cost of the cells a box covers (each cell weighted by how much of it the box covers) */
|
||||
export function boxCost(k: Cost, b: Box): number {
|
||||
let sum = 0
|
||||
let area = 0
|
||||
const c0 = Math.max(0, Math.floor(b[0] * k.cols))
|
||||
const c1 = Math.min(k.cols - 1, Math.ceil((b[0] + b[2]) * k.cols) - 1)
|
||||
const r0 = Math.max(0, Math.floor(b[1] * k.rows))
|
||||
const r1 = Math.min(k.rows - 1, Math.ceil((b[1] + b[3]) * k.rows) - 1)
|
||||
for (let r = r0; r <= r1; r++)
|
||||
for (let c = c0; c <= c1; c++) {
|
||||
const ox = Math.min(b[0] + b[2], (c + 1) / k.cols) - Math.max(b[0], c / k.cols)
|
||||
const oy = Math.min(b[1] + b[3], (r + 1) / k.rows) - Math.max(b[1], r / k.rows)
|
||||
const a = Math.max(0, ox) * Math.max(0, oy)
|
||||
sum += a * k.cost[r * k.cols + c]
|
||||
area += a
|
||||
}
|
||||
return area ? sum / area : 0
|
||||
}
|
||||
|
||||
/** where a box of this size costs least, over several frames together (a text's whole time on screen): candidates
|
||||
* every 2% down and, for a box narrower than the frame's safe width, across too; a box on a third line (the rule of
|
||||
* thirds) wins a tie */
|
||||
export function places(ks: Cost[], w: number, h: number, size: [number, number], n = 3): { box: Box; cost: number }[] {
|
||||
const sf = safe(w, h)
|
||||
const out: { box: Box; cost: number }[] = []
|
||||
const xs: number[] = []
|
||||
const span = 1 - sf.left - sf.right - size[0]
|
||||
if (span <= 0.02) xs.push(Math.max(0, (1 - size[0]) / 2))
|
||||
else for (let x = sf.left; x <= sf.left + span + 1e-9; x += span / 4) xs.push(x)
|
||||
for (let y = sf.top; y + size[1] <= 1 - sf.bottom + 1e-9; y += 0.02)
|
||||
for (const x of xs) {
|
||||
const b: Box = [x, y, size[0], size[1]]
|
||||
const c = ks.reduce((s, k) => s + boxCost(k, b), 0) / ks.length
|
||||
const mid = y + size[1] / 2
|
||||
const third = Math.min(Math.abs(mid - 1 / 3), Math.abs(mid - 2 / 3))
|
||||
// a wide box (a caption, a card) reads best centred; a narrow one may sit to a side
|
||||
const centre = size[0] > 0.4 ? Math.abs(x + size[0] / 2 - (sf.left + (1 - sf.right)) / 2) * 1.5 : 0
|
||||
out.push({ box: b, cost: c + third * 0.3 + centre })
|
||||
}
|
||||
out.sort((a, b) => a.cost - b.cost)
|
||||
// the best few, apart from each other
|
||||
const picked: { box: Box; cost: number }[] = []
|
||||
for (const o of out) {
|
||||
if (picked.some((p) => Math.abs(p.box[1] - o.box[1]) < size[1] && Math.abs(p.box[0] - o.box[0]) < size[0])) continue
|
||||
picked.push(o)
|
||||
if (picked.length >= n) break
|
||||
}
|
||||
return picked
|
||||
}
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "text-over"; at: number | null; until?: number; says: string }
|
||||
|
||||
const px = (v: number, dim: number) => Math.round(v * dim)
|
||||
|
||||
/** each text the render's manifest shows, against the scenes of the frames it's on (sampled `rate` a second): one
|
||||
* finding a text, when it covers a face, a thing or a person and a clearer place of its size exists */
|
||||
export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[] {
|
||||
const W = Number(manifest?.width) || 1080
|
||||
const H = Number(manifest?.height) || 1920
|
||||
const fps = Number(manifest?.fps) || 30
|
||||
// each text: its box (the ink with a margin, or the laid-out box when that's no bigger than twice the ink: a card's
|
||||
// own box), and the sampled frames it's on
|
||||
type On = { text: string; box: Box; from: number; to: number; frames: number[] }
|
||||
// every text's box on each sampled frame
|
||||
const onFrame = new Map<number, Box[]>()
|
||||
const texts = new Map<string, On>()
|
||||
for (const fr of (manifest?.frames ?? []) as any[]) {
|
||||
const t0 = Number(fr?.frame ?? 0) / fps
|
||||
const i = Math.round(t0 * rate)
|
||||
if (Math.abs(i / rate - t0) > 0.5 / fps) continue
|
||||
for (const t of (fr?.text ?? []) as any[]) {
|
||||
const text = String(t?.text ?? "").trim()
|
||||
if (!text || (t?.opacity ?? 1) <= 0.3) continue
|
||||
const ink = (t?.ink ?? t?.box) as number[] | undefined
|
||||
const lay = t?.box as number[] | undefined
|
||||
if (!ink || ink.length < 4) continue
|
||||
const useBox = lay && lay[2] * lay[3] <= 2 * ink[2] * ink[3]
|
||||
const b = useBox ? lay! : [ink[0] - 12, ink[1] - 8, ink[2] + 24, ink[3] + 16]
|
||||
const box: Box = [b[0] / W, b[1] / H, b[2] / W, b[3] / H]
|
||||
const key = `${text}@${box.map((v) => v.toFixed(2)).join(",")}`
|
||||
onFrame.set(i, [...(onFrame.get(i) ?? []), box])
|
||||
const on = texts.get(key) ?? { text, box, from: t0, to: t0, frames: [] }
|
||||
on.to = t0
|
||||
if (!on.frames.includes(i)) on.frames.push(i)
|
||||
texts.set(key, on)
|
||||
}
|
||||
}
|
||||
// lines stacked into one block (a checklist, a two-line caption, a card's title and its line) move together: texts on
|
||||
// the same frames whose boxes touch or nearly touch, one under the other
|
||||
const all = [...texts.values()].sort((p, q) => p.box[1] - q.box[1])
|
||||
const blocks: (On & { lines: number })[] = []
|
||||
for (const t of all) {
|
||||
const near = blocks.find((b) => {
|
||||
const shared = t.frames.filter((f) => b.frames.includes(f)).length
|
||||
const gap = t.box[1] - (b.box[1] + b.box[3])
|
||||
const ox = Math.min(b.box[0] + b.box[2], t.box[0] + t.box[2]) - Math.max(b.box[0], t.box[0])
|
||||
return shared * 2 >= Math.min(t.frames.length, b.frames.length) && gap < 0.02 && gap > -t.box[3] && ox > 0
|
||||
})
|
||||
if (!near) {
|
||||
blocks.push({ ...t, frames: [...t.frames], lines: 1 })
|
||||
continue
|
||||
}
|
||||
const x0 = Math.min(near.box[0], t.box[0])
|
||||
const y0 = Math.min(near.box[1], t.box[1])
|
||||
const x1 = Math.max(near.box[0] + near.box[2], t.box[0] + t.box[2])
|
||||
const y1 = Math.max(near.box[1] + near.box[3], t.box[1] + t.box[3])
|
||||
near.box = [x0, y0, x1 - x0, y1 - y0]
|
||||
near.from = Math.min(near.from, t.from)
|
||||
near.to = Math.max(near.to, t.to)
|
||||
near.lines++
|
||||
}
|
||||
const out: Finding[] = []
|
||||
for (const on of blocks) {
|
||||
// the scene's cost on each of the block's frames: our own texts there aren't the shot's words, and the other texts
|
||||
// on screen are places it can't go
|
||||
const costAt = (i: number) => {
|
||||
const s = scenes[i]
|
||||
if (!s) return null
|
||||
const ours = onFrame.get(i) ?? []
|
||||
return costs(s, ours, ours.filter((b) => !overlaps(b, on.box, 0.5)))
|
||||
}
|
||||
const ks = on.frames.map(costAt).filter((k): k is Cost => !!k)
|
||||
if (!ks.length) continue
|
||||
const here = ks.reduce((s, k) => s + boxCost(k, on.box), 0) / ks.length
|
||||
if (here < BAD) continue
|
||||
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 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"))
|
||||
out.push({ level: hard ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
|
||||
} else if (under.includes("a face")) {
|
||||
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
|
||||
} else if (here >= BAD + 1.5) {
|
||||
out.push({ level: "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}, and no place of its size is clear in this shot: make it smaller, show it on a shot with room (a wider one, a cutaway), or as a card of its own` })
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
|
||||
}
|
||||
|
||||
/** `raea make place`'s answer for a set of scenes and a box size (in a 1080-wide frame's pixels) */
|
||||
export function placeReport(file: string, scenes: Scene[], size: [number, number]) {
|
||||
const ss = scenes.filter((s): s is NonNullable<Scene> => !!s)
|
||||
if (!ss.length) return { file, places: [] }
|
||||
const w = ss[0].w
|
||||
const h = ss[0].h
|
||||
const scale = 1080 / Math.min(w, h)
|
||||
const W = w * scale
|
||||
const H = h * scale
|
||||
const share: [number, number] = [size[0] / W, size[1] / H]
|
||||
const ks = ss.map((s) => costs(s))
|
||||
const ps = places(ks, w, h, share, 3)
|
||||
return {
|
||||
file: path.basename(file),
|
||||
frame: [Math.round(W), Math.round(H)],
|
||||
box: size,
|
||||
places: ps.map((p) => ({ left: px(p.box[0], W), top: px(p.box[1], H), at: `${Math.round(p.box[1] * 100)}% down`, cost: Math.round(p.cost * 100) / 100, covers: [...new Set(ss.flatMap((s) => thingsUnder(s, p.box)))] })),
|
||||
}
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
|
||||
const { scenes } = await f.scene()
|
||||
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
// The playable pack (docs/playables.feature PA19): a playable goal's export, read from the manifest `raea playable`
|
||||
// writes beside its pages (out/playable/NAME.playable.json). Its pages each under the 5 MB cap, its compositions in the
|
||||
// orientations the goal asks for (both unless it says one), exported since the game last changed, and every network
|
||||
// it ships to written. The deliverables are the core/brief playable.rs list, mirrored here as cut.ts mirrors cut.rs.
|
||||
import { existsSync, readFileSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { PlayableGoal } from "raea/brief.gen"
|
||||
import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
|
||||
export const NETWORKS = ["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff"] as const
|
||||
const ZIPPED = new Set(["google", "mintegral", "tiktok"])
|
||||
export const OUT = "out/playable"
|
||||
/** every network's cap (apps/playable pages.rs CAP) */
|
||||
export const CAP = 5 * 1024 * 1024
|
||||
|
||||
/** what `raea playable` says it wrote (apps/playable lib.rs Manifest) */
|
||||
export interface PlayableManifest {
|
||||
name: string
|
||||
game: string
|
||||
orientation: "both" | "portrait" | "landscape"
|
||||
kinds: string[]
|
||||
compositions: { id: string; width: number; height: number; fps: number; frames: number }[]
|
||||
pages: { network: string; file: string; bytes: number }[]
|
||||
cap: number
|
||||
}
|
||||
|
||||
/** the name its files land as: its own (`raea playable --name`), else the game's file name */
|
||||
export const nameOf = (p: PlayableGoal) => p.name ?? path.basename(p.game, path.extname(p.game))
|
||||
export const networksOf = (p: PlayableGoal): string[] => NETWORKS.filter((n) => !p.networks?.length || p.networks.includes(n))
|
||||
|
||||
export function deliverables(p: PlayableGoal): string[] {
|
||||
const n = nameOf(p)
|
||||
const out = networksOf(p).map((net) => `${OUT}/${n}-${net}.${ZIPPED.has(net) ? "zip" : "html"}`)
|
||||
out.push(`${OUT}/${n}-preview.html`, `${OUT}/${n}.playable.json`)
|
||||
if (p.video === true) out.push(`out/cuts/${n}_9x16.mp4`)
|
||||
return out
|
||||
}
|
||||
|
||||
/** the playable goal of a job's contract, if it's one */
|
||||
export const playableOf = (c: Contract | null): PlayableGoal | null => (c?.kind === "playable" ? (c.playable ?? null) : null)
|
||||
|
||||
export function readManifest(root: string, p: PlayableGoal): PlayableManifest | string {
|
||||
const rel = `${OUT}/${nameOf(p)}.playable.json`
|
||||
const abs = path.join(root, rel)
|
||||
if (!existsSync(abs)) return `${rel} isn't there: export it with raea playable ${p.game} -o ${OUT}${p.name ? ` --name ${p.name}` : ""}${p.orientation && p.orientation !== "both" ? ` --orientation ${p.orientation}` : ""}`
|
||||
try {
|
||||
return JSON.parse(readFileSync(abs, "utf8")) as PlayableManifest
|
||||
} catch (e) {
|
||||
return `${rel} doesn't read: ${e instanceof Error ? e.message : e}`
|
||||
}
|
||||
}
|
||||
|
||||
export const playablePack = check<Job>({ id: "playable", text: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed", over: "job", at: ["publish", "done"] }, async (j) => {
|
||||
const p = playableOf(j.contract)
|
||||
if (!p) return
|
||||
const m = readManifest(j.root, p)
|
||||
if (typeof m === "string") {
|
||||
found({ says: m, about: [p.game] })
|
||||
return
|
||||
}
|
||||
const want = p.orientation ?? "both"
|
||||
const shapes = new Set(m.compositions.map((c) => (c.height > c.width ? "portrait" : "landscape")))
|
||||
const asked: ("portrait" | "landscape")[] = want === "both" ? ["portrait", "landscape"] : [want]
|
||||
const missing = asked.filter((s) => !shapes.has(s))
|
||||
for (const s of missing)
|
||||
found({ says: `${p.game} registers no ${s} composition (it has ${m.compositions.map((c) => `${c.id} ${c.width}x${c.height}`).join(", ") || "none"})`, about: [p.game], fix: want === "both" ? "register a portrait and a landscape composition of the game, the host plays the one nearest the screen; or say orientation in the brief" : undefined })
|
||||
for (const pg of m.pages.filter((x) => x.bytes > CAP)) found({ says: `${pg.file} is ${Math.round(pg.bytes / 1024)} KB, over the ${CAP / 1024} KB cap`, about: [pg.file] })
|
||||
const written = new Set(m.pages.map((x) => x.network))
|
||||
for (const net of [...networksOf(p), "preview"].filter((n) => !written.has(n))) found({ says: `no ${net} page in the last export`, about: [`${OUT}/${nameOf(p)}-${net}`] })
|
||||
// exported since the game last changed: the manifest newer than the game's TSX
|
||||
const game = path.join(j.root, p.game)
|
||||
const manifest = path.join(j.root, OUT, `${nameOf(p)}.playable.json`)
|
||||
if (existsSync(game) && statSync(game).mtimeMs > statSync(manifest).mtimeMs) found({ says: `${p.game} changed after its last export: export it again`, about: [p.game] })
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
// 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.
|
||||
//
|
||||
// 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,
|
||||
// unless it holds GLOSS words or more: a screen, fine print or a dense card can't be read in an ad anyway, so it's
|
||||
// texture, and the finding asks which it is meant to be.
|
||||
// the measure: every finding says words, seconds and words a second, so a CTA's reading load is a number the
|
||||
// editor holds (and the skill's end card rule: few words, held long enough).
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import { captionsOf, fit, type Frame, framesOfManifest, LEAST, letters, type Read, similar } from "./captions.ts"
|
||||
import { quote } from "../text.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 }
|
||||
|
||||
/** seconds to find a block before reading it */
|
||||
export const READ_BASE = 0.5
|
||||
/** words read a second */
|
||||
export const WPS = 3
|
||||
/** under this share of its time to read, an error */
|
||||
export const SHORT = 0.6
|
||||
/** a block of this many words or more is texture unless the editor means it read */
|
||||
export const GLOSS = 25
|
||||
/** fewer words than this is a logo, a label or a button, read at a glance */
|
||||
const FEW = 4
|
||||
|
||||
const wordsIn = (t: string) => t.split(/\s+/).filter((w) => letters(w).length > 0).length
|
||||
/** the time a block of `words` needs on screen */
|
||||
export const need = (words: number) => READ_BASE + words / WPS
|
||||
|
||||
/** a frame with more lines read than this is a screen, a shelf or a page (an app shot whole, a product line-up's
|
||||
* labels): texture by nature, left out */
|
||||
export const SCREEN = 6
|
||||
/** lines whose middles are this close (a share of the frame's height) in consecutive frames are one line */
|
||||
const ROW = 0.03
|
||||
/** lines that come up within this of each other (s), up together, are one block */
|
||||
const TOGETHER = 0.6
|
||||
/** a line that fits what's said around it with at most this share of its letters edited is read with the voice */
|
||||
const SAID = 0.35
|
||||
/** a phone's status bar clock: the block is an app's screen, shown, not read */
|
||||
/** text this small (its lines' median height, a share of the frame's) is an app's screen or fine print, not a
|
||||
* designed line: 1080x1920's 54 px */
|
||||
const SMALL = 0.028
|
||||
const CLOCK = /\d{1,2}:\d{2}/
|
||||
|
||||
/** the frames' blocks of text. Each line that isn't a caption is followed from frame to frame (same row, same text,
|
||||
* its fullest reading kept: text building on, or a frame mid-fade); lines that come up together and overlap are one
|
||||
* block, read as one. Frames that are screens are left out */
|
||||
export function blocksOf(frames: Frame[], rate: number, isCaption: (t: number, key: string) => boolean, heard: Word[] = []): Block[] {
|
||||
type Line = { text: string; key: string; from: number; to: number; y: number; size: number }
|
||||
const lines: Line[] = []
|
||||
frames.forEach((fr, i) => {
|
||||
const t = i / rate
|
||||
const read = fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 2)
|
||||
if (read.length > SCREEN) return
|
||||
for (const [, y, , h, text] of read) {
|
||||
const key = letters(text)
|
||||
if (isCaption(t, key)) continue
|
||||
// words shown as they're said (kinetic type, a caption the captions pack didn't take as one) are read with the voice
|
||||
const said = heard.filter((w) => w.end >= t - 1.5 && w.start <= t + 2.5).map((w) => letters(w.text)).join("")
|
||||
if (key.length >= 4 && fit(key, said).dist / key.length <= SAID) continue
|
||||
const mid = (y + h / 2) / Math.max(1, fr.h)
|
||||
const last = lines.findLast((l) => l.to >= t - 1.01 / rate && Math.abs(l.y - mid) <= ROW && (similar(l.key, key) || l.key.includes(key) || key.includes(l.key)))
|
||||
if (last) {
|
||||
last.to = t + 1 / rate
|
||||
if (key.length > last.key.length) Object.assign(last, { text, key })
|
||||
} else lines.push({ text, key, from: t, to: t + 1 / rate, y: mid, size: h / Math.max(1, fr.h) })
|
||||
}
|
||||
})
|
||||
const blocks: (Block & { parts: Line[] })[] = []
|
||||
for (const l of [...lines].sort((a, b) => a.from - b.from || a.y - b.y)) {
|
||||
const b = blocks.find((x) => Math.abs(x.from - l.from) <= TOGETHER && l.from < x.to)
|
||||
if (b) {
|
||||
b.parts.push(l)
|
||||
b.to = Math.max(b.to, l.to)
|
||||
} else blocks.push({ text: "", words: 0, from: l.from, to: l.to, parts: [l] })
|
||||
}
|
||||
return blocks.map(({ parts, ...b }) => {
|
||||
const text = parts.sort((x, y) => x.y - y.y).map((x) => x.text).join(" ")
|
||||
// a block is read for as long as most of it is up: its lines' median time up
|
||||
const ups = parts.map((x) => x.to - x.from).sort((x, y) => x - y)
|
||||
const sizes = parts.map((x) => x.size).sort((x, y) => x - y)
|
||||
return { ...b, text, words: wordsIn(text), to: b.from + ups[Math.floor(ups.length / 2)], size: sizes[Math.floor(sizes.length / 2)] }
|
||||
})
|
||||
}
|
||||
|
||||
/** blocks up for less time than their words take to read */
|
||||
export function reading(blocks: Block[]): Finding[] {
|
||||
const out: Finding[] = []
|
||||
for (const b of blocks) {
|
||||
if (b.words < FEW) continue
|
||||
const up = b.to - b.from
|
||||
const n = need(b.words)
|
||||
if (up >= n) continue
|
||||
const said = quote(b.text, 67)
|
||||
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` })
|
||||
}
|
||||
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[] }))
|
||||
if (!frames.some((x) => x.lines.length)) return
|
||||
const rate = own ? own.rate : sc!.rate || 2
|
||||
const heard = await f.words()
|
||||
const caps = captionsOf(own ? framesOfManifest(f.manifest)!.frames : 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 })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
// 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 })
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
// The sizes pack (raea cloud's one-size-first method of #112, now a rule): one size first. Every concept, variant and version
|
||||
// is made in one size until a person approves the work in it; then each other size is recut from the approved version
|
||||
// (11-28, Shane: "always does all concepts first in one size or aspect ratio ... and then once approved we can then do
|
||||
// any other resizes ... generally lean toward 9:16 first"). The approval is the brief's `open` item about "sizes",
|
||||
// answered by the person (`by`).
|
||||
// And every size by the end (11-30, Shane: "it will show completed but what about doing all the resizes"): Dutch
|
||||
// finished on its 9:16 masters alone, the brief's 4:5, 1:1 and 16:9 never made. At done, every ad's newest version is
|
||||
// there in every format its brief names (brief.ts cut `formats`), unless a person's answer to the open item about "sizes"
|
||||
// says fewer.
|
||||
import { check, found } from "raea/check"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
|
||||
|
||||
/** The size a made file is in, as a name says one (9x16): its name's, else a video's own shape (1080x1920 is 9x16).
|
||||
* A picture with no size in its name is a still of the work, a sheet or a strip, not a size of an ad. Told by pixels
|
||||
* alone, an ad named _9x16 beside its own 1080x1920 renders and one 540x960 still read as three sizes, and an agent
|
||||
* with one size made couldn't stop for its sign-off (12-01). */
|
||||
export function shapeOf(f: { path: string; kind?: string; width?: number | null; height?: number | null }): string | null {
|
||||
const named = sizeOf(f.path)
|
||||
if (named) return named
|
||||
if (f.kind !== "video" || !f.width || !f.height) return null
|
||||
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
|
||||
const g = gcd(f.width, f.height)
|
||||
return `${f.width / g}x${f.height / g}`
|
||||
}
|
||||
|
||||
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
|
||||
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
|
||||
const sizes = new Map<string, string[]>()
|
||||
for (const f of made) {
|
||||
const s = shapeOf(f)
|
||||
if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path])
|
||||
}
|
||||
if (sizes.size < 2) return
|
||||
const open = j.contract?.kind === "cut" ? (j.contract.cut?.open ?? []) : []
|
||||
const approved = open.find((o) => o.about === "sizes" && o.answer?.trim() && o.by?.trim())
|
||||
if (approved) return
|
||||
const [first, ...rest] = [...sizes.entries()].sort((a, b) => b[1].length - a[1].length)
|
||||
found({
|
||||
says: `made in ${sizes.size} sizes before a person approved the first: ${first[0]} (${first[1].length} files), then ${rest.map(([s, fs]) => `${s} (${fs.length})`).join(", ")}`,
|
||||
fix: `finish and show every ad in ${first[0]} first; recut the other sizes from the approved version once a person answers the brief's open item about "sizes" (with \`by\`)`,
|
||||
})
|
||||
})
|
||||
|
||||
/** a format as a name's size: "9:16" is 9x16 */
|
||||
const asSize = (f: string) => f.replace(":", "x").toLowerCase()
|
||||
/** a version's number in a name (v3), else 0 */
|
||||
const versionOf = (name: string) => Number(/_v(\d+)(?=_|\.|$)/i.exec(name)?.[1] ?? 0)
|
||||
|
||||
export const allSizes = check<Job>({ id: "sizes-all", text: "every size the brief asks for, by the end", over: "job", at: ["done"] }, async (j) => {
|
||||
if (j.contract?.kind !== "cut") return
|
||||
const c = j.contract.cut
|
||||
const want = [...new Set([...(c?.formats ?? []), ...(c?.cuts ?? []).flatMap((p) => p.formats ?? [])].map(asSize))]
|
||||
if (want.length < 2) return
|
||||
const sizesItem = (c?.open ?? []).find((o) => o.about === "sizes" && o.answer?.trim() && o.by?.trim())
|
||||
// a person said which sizes (or that one is enough): only the sizes their answer names
|
||||
const wanted = sizesItem ? want.filter((s) => new RegExp(s.replace("x", "[:x]"), "i").test(sizesItem.answer ?? "")) : want
|
||||
if (wanted.length < 2) return
|
||||
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image") && sizeOf(f.path))
|
||||
// each ad at its newest version, and the sizes that version is in
|
||||
const ads = new Map<string, { v: number; sizes: Set<string> }>()
|
||||
for (const f of made) {
|
||||
const ad = adOf(f.path), v = versionOf(f.path), s = sizeOf(f.path)!
|
||||
const cur = ads.get(ad)
|
||||
if (!cur || v > cur.v) ads.set(ad, { v, sizes: new Set([s]) })
|
||||
else if (v === cur.v) cur.sizes.add(s)
|
||||
}
|
||||
for (const [ad, { v, sizes }] of ads) {
|
||||
const missing = wanted.filter((s) => !sizes.has(s))
|
||||
if (!missing.length) continue
|
||||
found({
|
||||
says: `${ad} v${v} is in ${[...sizes].join(", ")} but the brief asks for ${wanted.join(", ")}: ${missing.join(", ")} not made`,
|
||||
fix: `recut ${ad} v${v} in ${missing.join(", ")} from the approved version (same version, a new size: ${ad}_v${v}_${missing[0]}), check each, and deliver them before you finish; a person's answer to the brief's open item about "sizes" is the only way to deliver fewer`,
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,256 @@
|
||||
// The sound pack (docs/goal.feature MK37; the box's sound check of 11-29): what a cut's sound gets wrong that a listener
|
||||
// hears at once, measured from the edit itself (its render manifest) against each source take's own words and level, so
|
||||
// it can't be passed by editing what the cut is "meant" to say (Shane on Dutch: "a lot of it is audio cuts, fading out
|
||||
// words, putting in audio that is too low to hear but whisper picks up ... i dont really hear any sound effects").
|
||||
//
|
||||
// edit points: each voice clip's in and out against its take's words and level every 10 ms. A clip that starts or ends
|
||||
// inside a word, or on sound (a word's tail, its first consonant), is an error, with the nearest gap to move it to.
|
||||
// levels: each voice clip's speech level (its take's, plus its gainDb) against the cut's other lines: 6 dB or more
|
||||
// apart is an error (a line too quiet to hear that a transcriber still hears), 4 dB a warning; the gainDb that
|
||||
// evens it is said.
|
||||
// effects and music: an effect 10 dB or more under the voice is an error (no one hears it); music more than 26 dB
|
||||
// under the voice, or within 6 dB of it, a warning.
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { Clip, FileFacts } from "../facts.ts"
|
||||
import type { Levels, Word } from "../media.ts"
|
||||
|
||||
|
||||
/** a voice clip's speech level is its take's loud 10 ms frames (the 90th percentile) inside the clip */
|
||||
const SPEECH_Q = 0.9
|
||||
/** at a cut point, sound this close to the speech level (dB) is speech still going: a word's tail or first consonant */
|
||||
const ON_SOUND = 10
|
||||
/** a gap to cut in: 40 ms at least this far under the speech level (dB), or, in a noisy take (a street), within
|
||||
* GAP_FLOOR of its own quietest sound, but never closer than GAP_LEAST to the speech */
|
||||
const GAP = 18
|
||||
const GAP_FLOOR = 6
|
||||
const GAP_LEAST = 8
|
||||
/** a take's floor: its quietest 10 ms frames (the 10th percentile) around the clip */
|
||||
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
|
||||
/** an effect this far under the voice (dB) isn't heard */
|
||||
const SFX_UNDER = 10
|
||||
/** music: further under than this isn't heard, closer than this fights the words */
|
||||
const MUSIC_LOST = 26
|
||||
const MUSIC_FIGHTS = 10
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
|
||||
|
||||
const MUSIC = /music|bed|score/i
|
||||
const SFX = /sfx|fx|effect|foley|sting/i
|
||||
/** a sound with no bus, as raea's default mix routes it (systems/mix default_bus, 11-30): footage and voice files are the
|
||||
* talking, effects stay effects, any other audio file is the music, ducked DEFAULT_DUCK under the talking */
|
||||
const VIDEO_EXT = /\.(mp4|mov|m4v|webm|mkv|avi|mxf)$/i
|
||||
const VOICE_NAME = /voice|narrat|dialog|speech|_vo|vo_|-vo|vo-|interview/i
|
||||
const SFX_NAME = /sfx|foley|whoosh|swoosh|sting|riser|impact|click|_fx|fx_/i
|
||||
export const busOf = (c: Clip): "voice" | "music" | "sfx" => {
|
||||
if (c.bus) return MUSIC.test(c.bus) ? "music" : SFX.test(c.bus) ? "sfx" : "voice"
|
||||
const name = path.basename(c.src)
|
||||
if (VIDEO_EXT.test(name) || VOICE_NAME.test(name)) return "voice"
|
||||
if (SFX_NAME.test(name) || SFX.test(name)) return "sfx"
|
||||
return "music"
|
||||
}
|
||||
/** how far raea's default mix ducks a music file with no bus under the talking (dB, systems/mix DEFAULT_DUCK_DB) */
|
||||
export const DEFAULT_DUCK = -6
|
||||
|
||||
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 at = (l: Levels, t: number) => l.db[Math.round((t - l.start) * 100)] ?? -100
|
||||
/** the loudest 10 ms frame in [a, b] */
|
||||
const peak = (l: Levels, a: number, b: number) => {
|
||||
let m = -100
|
||||
for (let t = a; t <= b + 1e-9; t += 0.01) m = Math.max(m, at(l, t))
|
||||
return m
|
||||
}
|
||||
const secs = (t: number) => `${t.toFixed(2)} s`
|
||||
|
||||
/** the speech level of a clip's stretch of its take: its loud frames, inside its words when it has any */
|
||||
export function speechLevel(l: Levels, a: number, b: number, words: Word[]): number {
|
||||
const inWords = words.filter((w) => w.end > a && w.start < b)
|
||||
const frames: number[] = []
|
||||
for (let t = a; t < b; t += 0.01) if (!inWords.length || inWords.some((w) => t >= w.start && t <= w.end)) frames.push(at(l, t))
|
||||
return pct(frames, SPEECH_Q)
|
||||
}
|
||||
|
||||
/** the nearest time to `t` (within NEAR, never past `limit` on the clip's inside) that is a gap: 40 ms around it at
|
||||
* least GAP dB under the speech level and inside no word */
|
||||
/** the level under which a take is quiet enough to cut in: GAP under the speech, or near the take's own floor */
|
||||
export const quietUnder = (l: Levels, ref: number) => Math.min(ref - GAP_LEAST, Math.max(ref - GAP, pct(l.db, FLOOR_Q) + GAP_FLOOR))
|
||||
|
||||
export function nearestGap(l: Levels, t: number, ref: number, words: Word[], inside: 1 | -1, limit: number): number | null {
|
||||
const under = quietUnder(l, ref)
|
||||
const quiet = (c: number) => (inside === 1 ? c <= limit : c >= limit) && peak(l, c - 0.02, c + 0.02) <= under && !words.some((w) => c > w.start - 0.01 && c < w.end + 0.01)
|
||||
for (let d = 0; d <= NEAR + 1e-9; d += 0.01) {
|
||||
for (const s of d ? [-1, 1] : [1]) {
|
||||
const c = t + s * d
|
||||
if (!quiet(c)) continue
|
||||
// the middle of the gap it's in (a cut at a gap's edge takes a breath or a consonant with it), kept near t
|
||||
let a = c
|
||||
let b = c
|
||||
while (a - 0.01 >= t - NEAR && quiet(a - 0.01)) a -= 0.01
|
||||
while (b + 0.01 <= t + NEAR && quiet(b + 0.01)) b += 0.01
|
||||
return Math.round(((a + b) / 2) * 100) / 100
|
||||
}
|
||||
}
|
||||
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
|
||||
/** boundaries between words with no pause (under 80 ms) between them */
|
||||
export function seams(words: Word[]): { at: number; before: string; after: string }[] {
|
||||
const out: { at: number; before: string; after: string }[] = []
|
||||
for (let i = 1; i < words.length; i++) {
|
||||
const a = words[i - 1]
|
||||
const b = words[i]
|
||||
if (b.start - a.end < 0.08) out.push({ at: Math.round(((a.end + b.start) / 2) * 1000) / 1000, before: a.text, after: b.text })
|
||||
}
|
||||
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[] = []
|
||||
const dur = (c.to - c.from) / fps
|
||||
const tin = c.at
|
||||
const tout = c.at + dur
|
||||
const ref = speechLevel(l, tin, tout, words)
|
||||
const name = path.basename(c.src)
|
||||
for (const [edge, t, cutAt, inside] of [["in", tin, c.from / fps, 1], ["out", tout, c.to / fps, -1]] as const) {
|
||||
const where = `the ${edge === "in" ? "start" : "end"} of the clip at ${secs(cutAt)} (${name} ${secs(t)})`
|
||||
// speech that runs on with no pause still has its boundaries between words: a cut on one is tight, not a cut word
|
||||
const seam = seams(words).find((x) => Math.abs(x.at - t) <= SEAM)
|
||||
if (seam) {
|
||||
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
|
||||
if (here >= ref - ON_SOUND)
|
||||
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 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
|
||||
const move =
|
||||
gap !== null
|
||||
? `move it to ${secs(gap)} in ${name} (${ms(gap)}), the gap ${edge === "in" ? "before" : "after"} the words`
|
||||
: bound
|
||||
? `there's no pause within ${NEAR * 1000} ms; the nearest boundary between words is ${secs(bound.at)} in ${name} (${ms(bound.at)}, between “${bound.before}” and “${bound.after}”): cut there, or at another pause`
|
||||
: `no pause or word boundary within ${NEAR * 1000} ms: cut at another pause, or take another line`
|
||||
if (word) {
|
||||
out.push({ level: "error", kind: "edit-in-word", at: cutAt, says: `${where} cuts “${word.text}” (${secs(word.start)}–${secs(word.end)}) in two: ${move}` })
|
||||
continue
|
||||
}
|
||||
// the 10 ms just inside the cut: a word's onset a frame or two after an in point is a tight cut, not a cut one
|
||||
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)}` })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export type Heard = { clip: Clip; kind: "voice" | "music" | "sfx"; level: number }
|
||||
|
||||
/** each voice line against the cut's others; effects and music against the voice */
|
||||
export function balance(heard: Heard[], fps: number): Finding[] {
|
||||
const out: Finding[] = []
|
||||
const voice = heard.filter((h) => h.kind === "voice" && (h.clip.to - h.clip.from) / fps >= 0.4)
|
||||
if (!voice.length) return out
|
||||
const mid = pct(voice.map((h) => h.level), 0.5)
|
||||
for (const h of voice) {
|
||||
const d = h.level - mid
|
||||
if (Math.abs(d) < LEVEL_WARN) continue
|
||||
const g = (h.clip.gainDb ?? 0) - d
|
||||
out.push({ level: Math.abs(d) >= LEVEL_ERROR ? "error" : "warn", kind: "level", at: h.clip.from / fps, says: `the line at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)} ${secs(h.clip.at)}) is ${Math.abs(d).toFixed(0)} dB ${d < 0 ? "under" : "over"} the cut's other lines${d < 0 ? ": too quiet to hear, though a transcriber still hears it" : ""}. Set its gainDb to ${g.toFixed(1)} (now ${(h.clip.gainDb ?? 0).toFixed(1)})` })
|
||||
}
|
||||
for (const h of heard.filter((x) => x.kind === "sfx")) {
|
||||
const d = h.level - mid
|
||||
if (d <= -SFX_UNDER)
|
||||
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
|
||||
}
|
||||
for (const h of heard.filter((x) => x.kind === "music")) {
|
||||
// a music file on no bus is ducked under the talking by the default mix, so it's heard that much lower
|
||||
const d = h.level - mid + (h.clip.bus ? 0 : DEFAULT_DUCK)
|
||||
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||||
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the take a manifest names, on this box: its own path, or the part after a farm job's work/ under the project */
|
||||
|
||||
/** a cut's sound against its takes: what's wrong, and how many voice clips it has */
|
||||
export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voice: number }> {
|
||||
const m = f.manifest
|
||||
if (!m) return { findings: [], voice: 0 }
|
||||
const fps = m.sounds?.fps ?? m.fps ?? 30
|
||||
const out: Finding[] = []
|
||||
const length = m.length ?? 0
|
||||
const frames = m.frames?.length ?? 0
|
||||
if (length > 1 && frames < length * 0.9)
|
||||
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 m.sounds?.clips ?? []) {
|
||||
const kind = busOf(c)
|
||||
const file = f.take(c.src)
|
||||
if (!file) {
|
||||
// a voice clip, or one named only by a hash (a farm's cache: its kind can't be told), that can't be found here is
|
||||
// an edit point no one checked: an error (12-03: every farm render's takes were "not on this machine" warnings, so
|
||||
// words cut off at clips' ends passed)
|
||||
const hashed = /(?:^|\/)[0-9a-f]{64}$/.test(c.src)
|
||||
out.push(kind === "voice" || hashed ? { level: "error", kind: "manifest", at: c.from / fps, says: `${hashed ? "a take named only by its hash" : c.src} isn't on this machine, so its clip at ${secs(c.from / fps)} has edit points no one checked: render with the project's takes in the project (raea cloud's render names them), then check again` } : { level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this machine: its clip at ${secs(c.from / fps)} isn't checked` })
|
||||
continue
|
||||
}
|
||||
const dur = (c.to - c.from) / fps
|
||||
if (kind === "voice") {
|
||||
voice++
|
||||
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) })
|
||||
} 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)
|
||||
heard.push({ clip: c, kind, level: level + (c.gainDb ?? 0) })
|
||||
}
|
||||
}
|
||||
out.push(...balance(heard, fps))
|
||||
return { findings: out.sort((a, b) => (a.at ?? -1) - (b.at ?? -1)), voice }
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (f.kind !== "video" && f.kind !== "audio") return
|
||||
if (!f.made) return
|
||||
if (!f.manifest) {
|
||||
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
|
||||
return
|
||||
}
|
||||
const { findings } = await soundOf(f)
|
||||
for (const x of findings) found({ level: x.level, says: x.says, seconds: x.at ?? undefined })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,97 @@
|
||||
// The voice pack (11-30, Shane: "we should be checking audio if its too quiet for dialogue or what is supposed to be
|
||||
// primary"): whether the dialogue is on top in the export as it was mixed, measured on the export itself. The sound pack
|
||||
// levels each line from its source take and the edit's gains, before the mix: ducking, the limiter and the loudness pass
|
||||
// all come after it, and a line that's even in the edit can sink in the mix.
|
||||
//
|
||||
// on top: the speech (the words pass's words, every 10 ms inside them) against what's under it in the gaps between
|
||||
// words while people are talking (music, effects, the street): under 6 dB above it is an error (the bed is as loud
|
||||
// as the voice), under 10 dB a warning.
|
||||
// even: each line (words with less than 0.7 s between them) against the export's typical line: 6 dB or more quieter
|
||||
// is an error (a line too quiet to follow that a transcriber still hears), 4 dB a warning.
|
||||
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 }
|
||||
|
||||
/** the speech's level over what's under it (dB): under ON_TOP_ERROR an error, under ON_TOP_WARN a warning */
|
||||
export const ON_TOP_ERROR = 6
|
||||
export const ON_TOP_WARN = 10
|
||||
/** a line this far under the typical line (dB) */
|
||||
export const QUIET_ERROR = 6
|
||||
export const QUIET_WARN = 4
|
||||
/** words this close together are one line (s) */
|
||||
const LINE_GAP = 0.7
|
||||
/** a gap between words counts as the bed from this far after a word to this far before the next (s): the word's tail
|
||||
* and breath are left out */
|
||||
const CLEAR = 0.12
|
||||
/** a gap shorter than this is too short to read the bed in (s) */
|
||||
const GAP_MIN = 0.2
|
||||
/** the bed is judged only on this many gaps between words, this many 10 ms frames of them in all */
|
||||
const BED_GAPS = 3
|
||||
const BED_FRAMES = 100
|
||||
/** the level a span is read at: its loud end (this percentile of its 10 ms frames), so pauses inside words don't count */
|
||||
const Q = 0.8
|
||||
|
||||
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 frames = (db: number[], a: number, b: number) => db.slice(Math.max(0, Math.floor(a * 100)), Math.min(db.length, Math.ceil(b * 100)))
|
||||
|
||||
/** the lines: words with under LINE_GAP between them */
|
||||
export function linesOf(heard: Word[]): Word[][] {
|
||||
const out: Word[][] = []
|
||||
for (const w of heard) {
|
||||
const last = out[out.length - 1]
|
||||
if (last && w.start - last[last.length - 1].end < LINE_GAP) last.push(w)
|
||||
else out.push([w])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the speech against the bed under it, and each line against the typical line */
|
||||
export function voice(db: number[], heard: Word[]): Finding[] {
|
||||
if (heard.length < 4) return []
|
||||
const out: Finding[] = []
|
||||
const speech: number[] = []
|
||||
for (const w of heard) speech.push(...frames(db, w.start, w.end))
|
||||
const bed: number[] = []
|
||||
let gaps = 0
|
||||
const lines = linesOf(heard)
|
||||
// the gaps inside lines and between lines close together: what's under the talking, not the end card's music
|
||||
for (let k = 1; k < heard.length; k++) {
|
||||
const a = heard[k - 1].end + CLEAR
|
||||
const b = heard[k].start - CLEAR
|
||||
if (b - a >= GAP_MIN && b - a < 2.5) { bed.push(...frames(db, a, b)); gaps++ }
|
||||
}
|
||||
const S = pct(speech, Q)
|
||||
// enough of the bed to judge: a tightly cut take has few gaps, and one of them is often still a hum or a breath
|
||||
// (11-30: Body Shop's host hook read 1.5 dB off a single 0.34 s gap between two "Mmm"s)
|
||||
if (gaps >= BED_GAPS && bed.length >= BED_FRAMES) {
|
||||
const B = pct(bed, Q)
|
||||
const over = S - B
|
||||
if (over < ON_TOP_WARN) out.push({ level: over < ON_TOP_ERROR ? "error" : "warn", kind: "buried", at: heard[0].start, says: `the dialogue is only ${over.toFixed(1)} dB above what's under it between words (music, effects, the street): it should be ${ON_TOP_WARN} dB or more on top. Duck the music further under the voice, or lift the voice` })
|
||||
}
|
||||
const lv = lines.map((l) => ({ l, db: pct(frames(db, l[0].start, l[l.length - 1].end), Q) }))
|
||||
const typical = pct(lv.map((x) => x.db), 0.5)
|
||||
for (const { l, db: d } of lv) {
|
||||
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` })
|
||||
}
|
||||
return out.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "voice", text: "the dialogue on top of the mix in the export, every line as loud as the others", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && f.kind !== "audio")) return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
for (const x of voice(f.levels().db, heard)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
// The words pack (docs/goal.feature MK37; the box's words check of 11-25): whether an export says what its cut meant
|
||||
// it to, word by word. raea hears the export (raea words; the farm's Whisper on a box) and holds it to the lines its cut
|
||||
// should say, OUT.lines.txt beside it: a word missing or cut short is an error; a word heard differently, speech fading
|
||||
// under a crossfade, or a word running into the first or last frame is a warning (Shane, 11-25: "cuts where it applies
|
||||
// crossfades on audio that make it so you can't hear it, and cuts where it will cut early over someone speaking").
|
||||
// With no lines beside it, only the fades and the edges are held.
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { stem, type Word } from "../media.ts"
|
||||
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "missing" | "clipped" | "changed" | "faded" | "edge" | "extra"; at: number | null; says: string }
|
||||
|
||||
/** a word as it's compared: lower case, letters and digits only ("$1,000." and "1000" are the same word) */
|
||||
export const norm = (w: string) => w.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
|
||||
|
||||
/** the lines' words and the heard words aligned (longest common subsequence), as pairs: [expected index | -1, heard index | -1] */
|
||||
export function align(want: string[], heard: string[]): [number, number][] {
|
||||
const n = want.length
|
||||
const m = heard.length
|
||||
const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1))
|
||||
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = want[i] === heard[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
|
||||
const out: [number, number][] = []
|
||||
let i = 0
|
||||
let j = 0
|
||||
while (i < n && j < m) {
|
||||
if (want[i] === heard[j]) out.push([i++, j++])
|
||||
// a word for a word costs the alignment nothing: kept side by side, so a word heard cut short reads as one
|
||||
else if (L[i + 1][j + 1] === L[i][j]) out.push([i++, -1], [-1, j++])
|
||||
else if (L[i + 1][j] >= L[i][j + 1]) out.push([i++, -1])
|
||||
else out.push([-1, j++])
|
||||
}
|
||||
while (i < n) out.push([i++, -1])
|
||||
while (j < m) out.push([-1, j++])
|
||||
return out
|
||||
}
|
||||
|
||||
/** one heard word is the other cut short: "test" for "tests", "abl" for "able" (three letters at least) */
|
||||
const cutShort = (want: string, got: string) => got.length >= 2 && got.length < want.length && (want.startsWith(got) || want.endsWith(got))
|
||||
|
||||
/** the expected lines against what was heard */
|
||||
export function compare(lines: string, heard: Word[]): Finding[] {
|
||||
const wantRaw = lines.split(/\s+/).filter((w) => norm(w))
|
||||
const want = wantRaw.map(norm)
|
||||
const got = heard.map((w) => norm(w.text))
|
||||
const pairs = align(want, got)
|
||||
const out: Finding[] = []
|
||||
// a missing word next to an extra one is one word heard differently (or cut short): pair them up
|
||||
for (let k = 0; k < pairs.length; k++) {
|
||||
const [i, j] = pairs[k]
|
||||
if (i >= 0 && j >= 0) continue
|
||||
const next = pairs[k + 1]
|
||||
if (i >= 0 && next && next[0] < 0 && next[1] >= 0) {
|
||||
const h = heard[next[1]]
|
||||
out.push(cutShort(want[i], got[next[1]]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[i]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[i]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if (i < 0 && next && next[0] >= 0 && next[1] < 0) {
|
||||
const h = heard[j]
|
||||
out.push(cutShort(want[next[0]], got[j]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[next[0]]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[next[0]]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if (i >= 0) {
|
||||
// where it should have been: after the last word heard before it
|
||||
const before = pairs.slice(0, k).reverse().find((p) => p[1] >= 0)
|
||||
const at = before ? heard[before[1]].end : 0
|
||||
out.push({ level: "error", kind: "missing", at, says: `"${wantRaw[i]}" isn't heard (expected near ${at.toFixed(2)} s): a cut, a fade or the mix took it` })
|
||||
} else out.push({ level: "note", kind: "extra", at: heard[j].start, says: `"${heard[j].text}" at ${heard[j].start.toFixed(2)} s isn't in the lines` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** speech that fades under a crossfade: inside the heard words, a run of 120 ms or more at least 14 dB under the speech's
|
||||
* own median, that comes back up within the same word or the next (a fade out and in across a cut). And a word running
|
||||
* into the first or last 40 ms of the piece, which is speech cut by the piece's own edge */
|
||||
export function fades(db: number[], heard: Word[], seconds: number): Finding[] {
|
||||
const inside: number[] = []
|
||||
for (const w of heard) for (let f = Math.floor(w.start * 100); f < Math.min(db.length, Math.ceil(w.end * 100)); f++) inside.push(db[f])
|
||||
if (inside.length < 20) return []
|
||||
const median = [...inside].sort((a, b) => a - b)[Math.floor(inside.length / 2)]
|
||||
const out: Finding[] = []
|
||||
const quiet = (f: number) => db[f] < median - 14
|
||||
let lastAt = -9
|
||||
for (let n = 0; n < heard.length; n++) {
|
||||
const w = heard[n]
|
||||
const a = Math.floor(w.start * 100)
|
||||
const b = Math.min(db.length, Math.ceil(w.end * 100))
|
||||
// a dip that comes back up inside the word: a fade out and in across a join. One that runs on to the word's end is
|
||||
// the word trailing off (Whisper's spans take in the quiet after a word), not a fade
|
||||
let run = 0
|
||||
let deepest = 0
|
||||
for (let f = a; f < b; f++) {
|
||||
if (quiet(f)) {
|
||||
run++
|
||||
deepest = Math.max(deepest, median - db[f])
|
||||
continue
|
||||
}
|
||||
if (run >= 12 && db[f] > median - 8 && f / 100 - lastAt > 1) {
|
||||
lastAt = f / 100
|
||||
out.push({ level: "warn", kind: "faded", at: (f - run) / 100, says: `"${w.text}" at ${w.start.toFixed(2)} s dips ${deepest.toFixed(0)} dB under the speech for ${run * 10} ms and comes back: a crossfade or fade over speech? Dialogue joins are hard cuts in the gap between words, with fades of 20 ms at most` })
|
||||
}
|
||||
run = 0
|
||||
deepest = 0
|
||||
}
|
||||
}
|
||||
const first = heard[0]
|
||||
const last = heard[heard.length - 1]
|
||||
// Whisper puts a first word at 0 whether or not it's cut: only a sound already at speech level on the first (or last)
|
||||
// 30 ms is speech the edge cut into
|
||||
const loud = (fs: number[]) => fs.length > 0 && fs.every((f) => db[f] !== undefined && db[f] > median - 8)
|
||||
const n0 = db.length
|
||||
if (first && first.start < 0.04 && loud([0, 1, 2])) out.push({ level: "warn", kind: "edge", at: 0, says: `the first word "${first.text}" starts on the first frame: is its start cut off?` })
|
||||
if (last && seconds - last.end < 0.04 && loud([n0 - 3, n0 - 2, n0 - 1])) out.push({ level: "warn", kind: "edge", at: last.end, says: `the last word "${last.text}" runs to the last frame: is its end cut off?` })
|
||||
return out
|
||||
}
|
||||
|
||||
/** the lines a file's cut should say: OUT.lines.txt beside it */
|
||||
export const linesOf = (abs: string) => [`${stem(abs)}.lines.txt`, `${abs}.lines.txt`].find(existsSync) ?? null
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "words", text: "every word a cut's lines say is heard whole in its export, none faded under a crossfade", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && f.kind !== "audio")) return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
const lines = linesOf(f.abs)
|
||||
const l = f.levels()
|
||||
const out = [...(lines ? compare(readFileSync(lines, "utf8"), heard) : []), ...fades(l.db, heard, f.seconds ?? heard[heard.length - 1].end)]
|
||||
for (const x of out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))) found({ level: x.level, says: x.says, seconds: x.at ?? undefined })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,150 @@
|
||||
// A project as raea runs it (docs/goal.feature MK43): brief.ts is the one registered root, run once, and every raea
|
||||
// SDK file in the folder is reached from it, or from taste.ts. A file is reached through the static imports of a
|
||||
// reached file, or when a value the brief or the taste gives names it as a path ("compositions/shots.tsx", a
|
||||
// deliverable's script, a taste line's check, `bun test tests/` in a goal rule: a folder named reaches every file in
|
||||
// it). A file that imports raea (raea, raea/*, @raea/*) and is reached by nothing is never compiled or run, so it is
|
||||
// a finding at every moment (the `registered` check, packs/job.ts): import it, name it in the brief, or delete it.
|
||||
// Nothing reads a project's TS as text to learn what it says: what the brief says is the value its run gives.
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
const SOURCE = /\.(m?[jt]sx?)$/
|
||||
const SKIP = new Set(["node_modules", "out", "review", "dist", "build", "assets"])
|
||||
/** a static import or re-export, a side-effect import, or import("...") with a literal */
|
||||
const IMPORT = /(?:\bimport\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s*)?|\bexport\s+(?:type\s+)?[^'"`;]*?\sfrom\s*|\bimport\s*\(\s*)(['"])([^'"\n]+)\1/g
|
||||
const RAEA = /^(?:raea|@raea\/[^/]+)(?:\/|$)/
|
||||
/** a path string in a value: ./x.ts, dir/x.tsx, tests/ (a command's words are each tried) */
|
||||
const PATHISH = /^(?:\.{0,2}\/)?[\[email protected]][\w@./-]*$/
|
||||
|
||||
export interface Project {
|
||||
root: string
|
||||
/** brief.ts, absolute; null when the folder has none */
|
||||
brief: string | null
|
||||
/** the brief's run: its default export, as raea and the checks read it */
|
||||
value: Record<string, unknown> | null
|
||||
/** taste.ts's run, when the project has one */
|
||||
taste: unknown
|
||||
/** what went wrong running the brief, with its file and line; nothing is edited while it's set */
|
||||
problem?: string
|
||||
}
|
||||
|
||||
/** brief.ts (and taste.ts) run: their default exports */
|
||||
export async function loadProject(root: string): Promise<Project> {
|
||||
const brief = path.join(root, "brief.ts")
|
||||
const out: Project = { root, brief: existsSync(brief) ? brief : null, value: null, taste: undefined }
|
||||
try {
|
||||
if (out.brief) out.value = ((await import(pathToFileURL(brief).href)) as { default?: Record<string, unknown> }).default ?? null
|
||||
const taste = path.join(root, "taste.ts")
|
||||
if (existsSync(taste)) out.taste = ((await import(pathToFileURL(taste).href)) as { default?: unknown }).default
|
||||
} catch (e) {
|
||||
const err = e as Error
|
||||
const at = /\(?((?:\/|file:\/\/)[^\s():]+):(\d+)(?::\d+)?\)?/.exec(err.stack ?? "")
|
||||
out.problem = `${err.message}${at ? ` (${path.relative(root, at[1].replace(/^file:\/\//, ""))}:${at[2]})` : ""}`
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the specifiers a source imports */
|
||||
export function importsOf(text: string): string[] {
|
||||
const out: string[] = []
|
||||
// comments hold example imports (raea's own headers do): they import nothing
|
||||
const code = text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/[^\n]*/g, "$1")
|
||||
for (const m of code.matchAll(IMPORT)) out.push(m[2])
|
||||
return out
|
||||
}
|
||||
|
||||
const CANDIDATES = ["", ".ts", ".tsx", ".mts", ".js", ".jsx", "/index.ts", "/index.tsx"]
|
||||
function resolveFrom(dir: string, spec: string): string | null {
|
||||
const base = path.resolve(dir, spec)
|
||||
for (const c of CANDIDATES) {
|
||||
const p = base + c
|
||||
if (existsSync(p) && statSync(p).isFile()) return p
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** every path string in a value, resolved against the root: the files and folders it names */
|
||||
function pathsIn(v: unknown, root: string, out: Set<string>, depth = 0) {
|
||||
if (depth > 40 || v == null) return
|
||||
if (typeof v === "string") {
|
||||
for (const word of v.length < 400 ? v.split(/\s+/) : []) {
|
||||
// a path has a slash or an extension: a bare word in prose names nothing
|
||||
if (!word || !PATHISH.test(word) || /^\d/.test(word) || !/\/|\.\w+$/.test(word)) continue
|
||||
const p = path.resolve(root, word)
|
||||
if (p.startsWith(root + path.sep) && existsSync(p)) out.add(p)
|
||||
}
|
||||
} else if (Array.isArray(v)) for (const x of v) pathsIn(x, root, out, depth + 1)
|
||||
else if (typeof v === "object") for (const x of Object.values(v as object)) pathsIn(x, root, out, depth + 1)
|
||||
}
|
||||
|
||||
function walk(dir: string, root: string, out: string[]) {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(dir)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const n of names) {
|
||||
if (n.startsWith(".") || SKIP.has(n)) continue
|
||||
const p = path.join(dir, n)
|
||||
const st = statSync(p)
|
||||
// a folder with its own brief.ts is a project of its own, held by its own run
|
||||
if (st.isDirectory()) {
|
||||
if (dir !== root || !existsSync(path.join(p, "brief.ts"))) walk(p, root, out)
|
||||
} else if (SOURCE.test(n) && !n.endsWith(".d.ts")) out.push(p)
|
||||
}
|
||||
}
|
||||
|
||||
/** every file the brief and the taste reach, absolute */
|
||||
export function reached(p: Project): Set<string> {
|
||||
const seen = new Set<string>()
|
||||
const roots = new Set<string>()
|
||||
if (p.brief) roots.add(p.brief)
|
||||
const taste = path.join(p.root, "taste.ts")
|
||||
if (existsSync(taste)) roots.add(taste)
|
||||
pathsIn(p.value, p.root, roots)
|
||||
pathsIn(p.taste, p.root, roots)
|
||||
const queue = [...roots]
|
||||
while (queue.length) {
|
||||
const f = queue.pop()!
|
||||
if (seen.has(f)) continue
|
||||
seen.add(f)
|
||||
if (statSync(f).isDirectory()) {
|
||||
const inside: string[] = []
|
||||
walk(f, f, inside)
|
||||
queue.push(...inside)
|
||||
continue
|
||||
}
|
||||
if (!SOURCE.test(f) && !/\.(sh|json)$/.test(f)) continue
|
||||
let text: string
|
||||
try {
|
||||
text = readFileSync(f, "utf8")
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (/\.(sh|json)$/.test(f)) {
|
||||
// a script a rule runs names the files it runs
|
||||
const named = new Set<string>()
|
||||
pathsIn(text, p.root, named)
|
||||
queue.push(...named)
|
||||
continue
|
||||
}
|
||||
for (const spec of importsOf(text)) {
|
||||
if (!spec.startsWith(".") && !spec.startsWith("/")) continue
|
||||
const r = resolveFrom(path.dirname(f), spec)
|
||||
if (r && r.startsWith(p.root + path.sep)) queue.push(r)
|
||||
}
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
/** the files that use raea's SDK and that nothing the brief runs reaches, relative to the root */
|
||||
export function unregistered(p: Project, reach = reached(p)): string[] {
|
||||
const files: string[] = []
|
||||
walk(p.root, p.root, files)
|
||||
return files
|
||||
.filter((f) => !reach.has(f) && importsOf(readFileSync(f, "utf8")).some((s) => RAEA.test(s)))
|
||||
.map((f) => path.relative(p.root, f))
|
||||
.sort()
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// `raea check` (docs/check.feature): the one check. Every rule each goal of brief.ts holds at one of four moments, on
|
||||
// raea's own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal
|
||||
// or several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
|
||||
//
|
||||
// raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
|
||||
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
|
||||
// `goal`, and with none, the floor. The files are the ones named, else (publish, done) every deliverable and
|
||||
// every video or still made under out/. Each check whose moments include --at (done by default) runs: a file
|
||||
// check on each file, a job check once. A file's check after its render is kept beside it (FILE.check.json) and
|
||||
// publish and done read it while it's fresh, never running it again. One line a rule a file. Writes
|
||||
// review/goal.json and prints each finding. Exit 1 on an error, 2 when it can't run (brief.ts doesn't load). A
|
||||
// check that needs what this machine hasn't (a transcriber) waits, and says what for; it holds nothing.
|
||||
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
|
||||
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, unknownPacks } from "./contract.ts"
|
||||
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
|
||||
import * as media from "./media.ts"
|
||||
import { loadProject, type Project } from "./project.ts"
|
||||
import { PACK_CHECKS } from "./packs/index.ts"
|
||||
import { deliverablesOf } from "./packs/job.ts"
|
||||
import { bookkeeping } from "./packs/naming.ts"
|
||||
import { placeReport } from "./packs/place.ts"
|
||||
import { tasksMain } from "./tasks.ts"
|
||||
import { wellFormed } from "./text.ts"
|
||||
|
||||
/** the checks every project is held to once, whatever its goals: none in the loop (12-04: `registered`, how brief.ts
|
||||
* imports files, failed every Dutch cut, and the taste check waits on every box; neither is a fault in the work) */
|
||||
const ALWAYS: Check[] = []
|
||||
|
||||
/** the moments a deliverable's own check, run once after its render, stands for: publish and done read it, never run it again */
|
||||
const REUSED: Moment[] = ["publish", "done"]
|
||||
/** a deliverable's check kept beside it (FILE.check.json), while it's no older than the file or its manifest: the
|
||||
* checks it ran and what they found */
|
||||
export function keptCheck(abs: string): { checks: string[]; findings: Said[] } | null {
|
||||
const k = `${media.stem(abs)}.check.json`
|
||||
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
|
||||
if (!existsSync(k) || when(k) < when(abs) || when(k) < when(`${media.stem(abs)}.render.json`)) return null
|
||||
try {
|
||||
const j = JSON.parse(readFileSync(k, "utf8")) as { checks?: string[]; findings?: Said[] }
|
||||
return Array.isArray(j.checks) ? { checks: j.checks, findings: j.findings ?? [] } : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** one line a rule a file (12-04, round 26: 34 of one cut's errors were each caption phrase in the same UI zone; 12-05,
|
||||
* run 5: an ERROR and a WARN of the same check each had a line, and a cut listed 12): of a check's findings at moments
|
||||
* in the file, the most severe first one, and how many more there were; findings with no moment are distinct faults,
|
||||
* said once each */
|
||||
const RANK: Record<Said["level"], number> = { error: 0, warn: 1, note: 2 }
|
||||
export function collapse(xs: Said[]): Said[] {
|
||||
const firsts = new Map<string, { x: Said; same: number; lesser: number; to: number | null }>()
|
||||
for (const x of xs) {
|
||||
// a fault found at many moments (located in time) is one line; distinct faults with no moment each keep theirs
|
||||
const key = `${x.goal ?? ""}\u0000${x.file ?? ""}\u0000${x.check}\u0000${x.seconds ? "" : `${x.level}\u0000${x.says}`}`
|
||||
const had = firsts.get(key)
|
||||
if (!had) firsts.set(key, { x, same: 0, lesser: 0, to: x.seconds?.[1] ?? null })
|
||||
else {
|
||||
if (RANK[x.level] < RANK[had.x.level]) {
|
||||
// a worse one leads the line; what led it is counted under it
|
||||
had.lesser += had.same + 1
|
||||
had.same = 0
|
||||
had.x = x
|
||||
} else if (x.level === had.x.level) had.same++
|
||||
else had.lesser++
|
||||
if (x.seconds && (had.to === null || x.seconds[1] > had.to)) had.to = x.seconds[1]
|
||||
}
|
||||
}
|
||||
return [...firsts.values()].map(({ x, same, lesser }) => {
|
||||
const more = [same ? `${same} more like it${x.seconds ? ", to the same fix" : ""}` : "", lesser ? `${lesser} lesser` : ""].filter(Boolean).join("; ")
|
||||
return more ? { ...x, says: `${x.says} (and ${more})` } : x
|
||||
})
|
||||
}
|
||||
|
||||
/** a finding as `raea check` reports it: its goal, its check, the file it's in, and where in it */
|
||||
export type Said = { goal: string | null; check: string; level: Finding["level"]; file: string | null; seconds: [number, number] | null; says: string; fix: string | null; by: string }
|
||||
/** one goal's verdict at a moment */
|
||||
export type GoalVerdict = { name: string; kind: Contract["kind"] | "floor"; step: string | null; after: string[]; passed: boolean; errors: number; warnings: number; checks: string[]; files: string[] }
|
||||
export type Report = {
|
||||
object: "goal.check"
|
||||
at: Moment
|
||||
/** each goal's verdict, in the order written; the floor alone when the brief has none */
|
||||
goals: GoalVerdict[]
|
||||
root: string
|
||||
/** when it ran (s) */
|
||||
when: number
|
||||
/** every goal passed and no check broken: the work may move past this moment */
|
||||
passed: boolean
|
||||
errors: number
|
||||
warnings: number
|
||||
files: string[]
|
||||
checks: string[]
|
||||
findings: Said[]
|
||||
/** checks that couldn't run here, and what they wait for */
|
||||
waits: { check: string; file: string | null; says: string }[]
|
||||
/** checks that broke: a fault in the check, which fails the run */
|
||||
broke: { check: string; file: string | null; says: string }[]
|
||||
/** the goals' own problems (doctor), said before anything runs */
|
||||
plan: string[]
|
||||
}
|
||||
|
||||
/** the folder with brief.ts, from `from` upwards */
|
||||
export function rootOf(from: string): string | null {
|
||||
let d = path.resolve(from)
|
||||
for (;;) {
|
||||
if (existsSync(path.join(d, "brief.ts"))) return d
|
||||
const up = path.dirname(d)
|
||||
if (up === d) return null
|
||||
d = up
|
||||
}
|
||||
}
|
||||
|
||||
/** the brief run once (project.ts), and its goals, their checks as the functions they are */
|
||||
export async function goalsIn(root: string): Promise<{ goals: Contract[]; brief: string | null; project: Project }> {
|
||||
const project = await loadProject(root)
|
||||
return { goals: goalsOf(project.value?.goal as Goals | undefined), brief: project.brief, project }
|
||||
}
|
||||
|
||||
const PICTURE = /\.(mp4|mov|m4v|webm|png|jpe?g|webp)$/i
|
||||
/** every video and still made under out/ (a bounded walk) */
|
||||
function madeUnder(root: string): string[] {
|
||||
const out: string[] = []
|
||||
const stack = [path.join(root, "out")]
|
||||
while (stack.length && out.length < 2000) {
|
||||
const d = stack.pop()!
|
||||
if (!existsSync(d)) continue
|
||||
for (const n of readdirSync(d)) {
|
||||
const p = path.join(d, n)
|
||||
const st = statSync(p)
|
||||
if (st.isDirectory()) stack.push(p)
|
||||
else if (PICTURE.test(n)) out.push(path.relative(root, p))
|
||||
}
|
||||
}
|
||||
return out.filter((r) => !bookkeeping(r)).sort()
|
||||
}
|
||||
|
||||
/** the checks that hold a goal at a moment: its packs', then its own */
|
||||
export function checksOf(contract: Contract | null, at: Moment, only?: string[]): Check[] {
|
||||
const all = [...packsOf(contract).flatMap((p) => PACK_CHECKS[p]), ...((contract?.checks ?? []) as Check[])]
|
||||
const seen = new Set<string>()
|
||||
return all.filter((c) => {
|
||||
if (!c?.id || seen.has(c.id) || !c.once) return false
|
||||
seen.add(c.id)
|
||||
return momentsOf(c).includes(at) && (!only?.length || only.includes(c.id))
|
||||
})
|
||||
}
|
||||
|
||||
/** what doctor says of the goals before anything runs */
|
||||
function planOf(goals: Contract[]): string[] {
|
||||
// core/brief's doctor, from raea's Rust (it keeps the types): RAEA_GOAL_DOCTOR
|
||||
let doctor: string[] = []
|
||||
try {
|
||||
doctor = JSON.parse(process.env.RAEA_GOAL_DOCTOR ?? "[]")
|
||||
} catch {}
|
||||
const out = [...doctor]
|
||||
for (const c of goals) {
|
||||
const at = goals.length > 1 ? `${nameOf(c)}: ` : ""
|
||||
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea check --json lists them)`))
|
||||
for (const k of (c.checks ?? []) as unknown[]) if (!k || typeof (k as Check).id !== "string") out.push(`${at}checks: each is a check() imported from the project's checks/ folder`)
|
||||
// nothing judges a `says` rule any more (12-04): said, so it isn't taken for checked
|
||||
for (const r of c.rules ?? []) if (r.says && !r.run && !r.file) out.push(`${at}rules.${r.id}: a \`says\` rule isn't checked by anything: make it a command (\`run\`) or a file (\`file\`), or leave it to the person's review`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: string; only?: string[]; cwd?: string; manifest?: string }): Promise<Report> {
|
||||
const at = o.at ?? "done"
|
||||
const cwd = o.cwd ?? process.cwd()
|
||||
const root = rootOf(o.files?.length ? path.dirname(path.resolve(cwd, o.files[0])) : cwd) ?? cwd
|
||||
const { goals: all, brief, project } = await goalsIn(root)
|
||||
if (o.goal && !all.some((g) => nameOf(g) === o.goal)) throw new Error(`no goal is named ${o.goal}: ${all.map(nameOf).join(", ") || "the brief has none"}`)
|
||||
const goals: (Contract | null)[] = all.length ? all.filter((g) => !o.goal || nameOf(g) === o.goal) : [null]
|
||||
const named = (o.files ?? []).map((f) => path.relative(root, path.resolve(cwd, f)))
|
||||
const findings: Said[] = []
|
||||
const waits: Report["waits"] = []
|
||||
const broke: Report["broke"] = []
|
||||
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
|
||||
const fps = file?.fps ?? 30
|
||||
for (const x of r.findings)
|
||||
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
|
||||
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
|
||||
}
|
||||
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
|
||||
// the project's own: once, whatever its goals
|
||||
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
|
||||
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
|
||||
const verdicts: GoalVerdict[] = []
|
||||
const allFiles = new Set<string>()
|
||||
for (const contract of goals) {
|
||||
const name = contract ? nameOf(contract) : "floor"
|
||||
const deliverables = deliverablesOf(contract)
|
||||
const wanted = named.length
|
||||
? named
|
||||
: at === "publish" || at === "done"
|
||||
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
|
||||
: []
|
||||
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
|
||||
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
|
||||
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
|
||||
const checks = checksOf(contract, at, o.only)
|
||||
const before = findings.length
|
||||
const brokeBefore = broke.length
|
||||
const j = job(contract, deliverables, files)
|
||||
const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null]))
|
||||
for (const c of checks) {
|
||||
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }]))
|
||||
else
|
||||
for (const f of files) {
|
||||
const k = kept.get(f.path)
|
||||
// run once, after its render: what it found then stands (its own findings, at this goal)
|
||||
if (k?.checks.includes(c.id)) findings.push(...k.findings.filter((x) => x.check === c.id).map((x) => ({ ...x, goal: contract ? name : null })))
|
||||
else keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
|
||||
}
|
||||
}
|
||||
const mine = findings.slice(before)
|
||||
const errors = mine.filter((x) => x.level === "error").length
|
||||
for (const f of files) allFiles.add(f.path)
|
||||
verdicts.push({ name, kind: contract?.kind ?? "floor", step: contract?.step ?? null, after: contract?.after ?? [], passed: errors === 0 && broke.length === brokeBefore, errors, warnings: mine.filter((x) => x.level === "warn").length, checks: checks.map((c) => c.id), files: files.map((f) => f.path) })
|
||||
}
|
||||
findings.sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.seconds?.[0] ?? -1) - (b.seconds?.[0] ?? -1))
|
||||
// printed and saved whole: no finding holds half a character (12-05, Dutch run 9: one broke the check as it printed)
|
||||
findings.splice(0, findings.length, ...collapse(findings).map((x) => ({ ...x, says: wellFormed(x.says), fix: x.fix && wellFormed(x.fix) })))
|
||||
const errors = findings.filter((x) => x.level === "error").length
|
||||
return {
|
||||
object: "goal.check",
|
||||
at,
|
||||
goals: verdicts,
|
||||
root,
|
||||
when: Math.floor(Date.now() / 1000),
|
||||
passed: errors === 0 && broke.length === 0,
|
||||
errors,
|
||||
warnings: findings.filter((x) => x.level === "warn").length,
|
||||
files: [...allFiles].sort(),
|
||||
checks: [...new Set([...once.map((c) => c.id), ...verdicts.flatMap((v) => v.checks)])],
|
||||
findings,
|
||||
waits,
|
||||
broke,
|
||||
plan: planOf(all),
|
||||
}
|
||||
}
|
||||
|
||||
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
|
||||
* each file named */
|
||||
export function writeReport(r: Report, named: string[]) {
|
||||
const dir = path.join(r.root, "review")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
|
||||
for (const f of named) {
|
||||
const mine = r.findings.filter((x) => x.file === f)
|
||||
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), checks: r.checks, findings: mine }, null, 1)}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
|
||||
/** the report as a person or an agent reads it */
|
||||
export function text(r: Report): string {
|
||||
const t: string[] = []
|
||||
for (const p of r.plan) t.push(`PLAN ${p}`)
|
||||
for (const x of r.findings) {
|
||||
if (x.level === "note" && r.at === "edit") continue
|
||||
t.push(`${x.level === "error" ? "ERROR" : x.level === "warn" ? "WARN " : "NOTE "} ${r.goals.length > 1 && x.goal ? `${x.goal}/` : ""}${x.check}${x.file ? ` ${x.file}` : ""} ${secs(x.seconds)}${x.says}${x.fix ? `\n fix: ${x.fix}` : ""}`)
|
||||
}
|
||||
for (const w of r.waits) t.push(`WAITS ${w.check}${w.file ? ` ${w.file}` : ""} ${w.says}`)
|
||||
for (const b of r.broke) t.push(`BROKE ${b.check}${b.file ? ` ${b.file}` : ""} ${b.says}`)
|
||||
if (r.goals.length > 1) for (const g of r.goals) t.push(`${g.passed ? "ok " : "open"} goal ${g.name} (${g.kind}${g.step ? `, step ${g.step}` : ""}${g.after.length ? `, after ${g.after.join(", ")}` : ""}): ${g.errors} errors, ${g.warnings} warnings`)
|
||||
const kinds = r.goals.map((g) => (r.goals.length > 1 ? g.name : g.kind)).join(", ")
|
||||
t.push(`${r.passed ? "PASSED" : "FAILED"} raea check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
|
||||
return t.join("\n")
|
||||
}
|
||||
|
||||
function flag(a: string[], name: string): string | undefined {
|
||||
const i = a.indexOf(name)
|
||||
return i >= 0 ? a[i + 1] : undefined
|
||||
}
|
||||
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
|
||||
|
||||
const USAGE = `raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
|
||||
raea make place FILE [--at S[,S...]] [--box WxH]`
|
||||
|
||||
export async function main(argv: string[]): Promise<number> {
|
||||
const [verb, ...a] = argv
|
||||
if (verb === "check") {
|
||||
const at = (flag(a, "--at") ?? "done") as Moment
|
||||
if (!MOMENTS.includes(at)) {
|
||||
console.error(`raea check: --at is one of ${MOMENTS.join(", ")}`)
|
||||
return 2
|
||||
}
|
||||
const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
|
||||
let r: Report
|
||||
try {
|
||||
r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") })
|
||||
} catch (e) {
|
||||
console.error(`raea check: ${(e as Error).message}`)
|
||||
return 2
|
||||
}
|
||||
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
|
||||
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
|
||||
return r.passed ? 0 : 1
|
||||
}
|
||||
if (verb === "tasks") return tasksMain(a)
|
||||
if (verb === "place") {
|
||||
const file = positional(a, ["--at", "--box", "-o"])[0]
|
||||
if (!file || !existsSync(file)) return usage()
|
||||
const box = (flag(a, "--box") ?? "840x110").split("x").map(Number) as [number, number]
|
||||
if (box.length !== 2 || !box.every((v) => v > 0)) {
|
||||
console.error("raea make place: --box is WxH in a 1080-wide frame's pixels, like 840x110")
|
||||
return 2
|
||||
}
|
||||
let at = flag(a, "--at")?.split(",").map(Number).filter(Number.isFinite)
|
||||
if (!at?.length && kindOf(file) === "video") {
|
||||
const len = media.seconds(file) ?? 1
|
||||
const n = Math.min(12, Math.max(1, Math.floor(len)))
|
||||
at = Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * len * 100) / n) / 100)
|
||||
}
|
||||
const { scenes } = await media.scene(path.resolve(file), at)
|
||||
const rep = placeReport(file, scenes, box)
|
||||
console.log(`${path.basename(file)}${at?.length ? ` at ${at.join(", ")} s` : ""}: the clearest places for a ${box[0]}x${box[1]} box in a ${rep.frame?.join("x")} frame, best first`)
|
||||
for (const p of rep.places) console.log(` left ${p.left} px, top ${p.top} px (${p.at}) cost ${p.cost}${p.covers.length ? ` covers ${p.covers.join(", ")}` : " clear"}`)
|
||||
const o = flag(a, "-o")
|
||||
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
|
||||
return 0
|
||||
}
|
||||
return usage()
|
||||
}
|
||||
|
||||
function usage(): number {
|
||||
console.error(USAGE)
|
||||
return 2
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main(process.argv.slice(2)).then(
|
||||
(c) => process.exit(c),
|
||||
(e) => {
|
||||
console.error(`raea goal: ${e instanceof media.Unmet ? "" : "broke: "}${(e as Error).message}`)
|
||||
process.exit(e instanceof media.Unmet ? 1 : 2)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// `raea goal tasks` (docs/goal.feature MK43, docs/plan.feature PL2): the brief's plan as tasks, and edits written back
|
||||
// where each task is written. The one path every reader takes: the raea app's feed host, an agent's plan tools and
|
||||
// raea cloud's box all run this, so nothing reads a plan another way.
|
||||
//
|
||||
// raea goal tasks [DIR] [--json] the plan the brief's run gives: open tasks by id, or all as JSON
|
||||
// raea goal tasks [DIR] --apply EDITS.json|- edits by task id (sdk/task PlanEdit[]), applied to that value and
|
||||
// written into the files the brief reaches; a project with no plan
|
||||
// gets plan.ts, imported by brief.ts. A task made by code is refused,
|
||||
// naming its file and line; nothing is written then.
|
||||
// raea goal tasks [DIR] --put FILE|- {plan, base}: the whole plan written back where it's written, only
|
||||
// while the brief's plan is still `base` (the raea app's Undo); else
|
||||
// nothing, and {put: false} with the plan as it is
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { applyEdits, type PlanEdit, type PlanFile, planDigest, readPlan, registerPlan, writeBack } from "raea/task"
|
||||
import { loadProject, reached } from "./project.ts"
|
||||
|
||||
const SOURCE = /\.(m?[jt]sx?)$/
|
||||
|
||||
/** the folder with brief.ts, from `from` upwards */
|
||||
function rootOf(from: string): string | null {
|
||||
for (let d = path.resolve(from); ; d = path.dirname(d)) {
|
||||
if (existsSync(path.join(d, "brief.ts"))) return d
|
||||
if (path.dirname(d) === d) return null
|
||||
}
|
||||
}
|
||||
|
||||
/** the plan the brief gives, and the files it reached (each a place a task may be written) */
|
||||
export async function tasksOf(root: string): Promise<{ plan: PlanFile | undefined; problem?: string; sources: { file: string; text: string }[] }> {
|
||||
const p = await loadProject(root)
|
||||
if (p.problem) return { plan: undefined, problem: p.problem, sources: [] }
|
||||
const sources = [...reached(p)].filter((f) => SOURCE.test(f)).map((f) => ({ file: path.relative(root, f), text: readFileSync(f, "utf8") }))
|
||||
return { plan: (p.value?.plan as PlanFile | undefined) ?? undefined, sources }
|
||||
}
|
||||
|
||||
/** the edits applied and written back; the files written, relative to the root */
|
||||
export async function applyTasks(root: string, edits: PlanEdit[], o: { now?: Date; who?: string } = {}): Promise<{ written: string[]; refs: string[] }> {
|
||||
const t = await tasksOf(root)
|
||||
if (t.problem) throw new Error(`brief.ts doesn't run, so nothing was written: ${t.problem}`)
|
||||
const r = applyEdits(t.plan, edits, { now: o.now })
|
||||
return { written: writeTo(root, t, r.file), refs: r.refs }
|
||||
}
|
||||
|
||||
const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
|
||||
|
||||
/** `plan` written back whole, only while the brief's plan is `base` (null: it has none); else nothing */
|
||||
export async function putTasks(root: string, plan: PlanFile, base: PlanFile | null): Promise<{ put: boolean; written: string[]; plan: PlanFile | null }> {
|
||||
const t = await tasksOf(root)
|
||||
if (t.problem) throw new Error(`brief.ts doesn't run, so nothing was written: ${t.problem}`)
|
||||
if (!same(t.plan, base)) return { put: false, written: [], plan: t.plan ?? null }
|
||||
return { put: true, written: writeTo(root, t, plan), plan }
|
||||
}
|
||||
|
||||
/** `after` written where the brief's plan is written (or a new plan.ts, registered in brief.ts); the files written */
|
||||
function writeTo(root: string, t: Awaited<ReturnType<typeof tasksOf>>, after: PlanFile): string[] {
|
||||
const back = writeBack(t.sources, t.plan, after)
|
||||
const written: string[] = []
|
||||
for (const c of back.changed) {
|
||||
writeFileSync(path.join(root, c.file), c.text)
|
||||
written.push(c.file)
|
||||
}
|
||||
if (back.created) {
|
||||
const brief = path.join(root, "brief.ts")
|
||||
const registered = registerPlan(readFileSync(brief, "utf8"))
|
||||
writeFileSync(path.join(root, back.created.file), back.created.text)
|
||||
writeFileSync(brief, registered)
|
||||
written.push(back.created.file, "brief.ts")
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
export async function tasksMain(a: string[]): Promise<number> {
|
||||
const i = a.indexOf("--apply")
|
||||
const put = a.indexOf("--put")
|
||||
const from = a.find((x, k) => !x.startsWith("-") && a[k - 1] !== "--apply" && a[k - 1] !== "--put") ?? process.cwd()
|
||||
const root = rootOf(from)
|
||||
if (!root) {
|
||||
console.error("raea goal tasks: no brief.ts here or above")
|
||||
return 2
|
||||
}
|
||||
if (put >= 0) {
|
||||
const src = a[put + 1]
|
||||
let body: { plan?: PlanFile; base?: PlanFile | null }
|
||||
try {
|
||||
body = JSON.parse(!src || src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8"))
|
||||
} catch (e) {
|
||||
console.error(`raea goal tasks: --put takes {plan, base} as JSON: ${(e as Error).message}`)
|
||||
return 2
|
||||
}
|
||||
if (!body.plan || typeof body.plan !== "object") {
|
||||
console.error("raea goal tasks: --put takes {plan, base}: the plan to write, and the plan it replaces (null for none)")
|
||||
return 2
|
||||
}
|
||||
try {
|
||||
console.log(JSON.stringify(await putTasks(root, body.plan, body.base ?? null)))
|
||||
return 0
|
||||
} catch (e) {
|
||||
console.error(`raea goal tasks: ${(e as Error).message}`)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
if (i >= 0) {
|
||||
const src = a[i + 1]
|
||||
if (!src) {
|
||||
console.error("raea goal tasks: --apply takes a JSON file of edits, or - for stdin")
|
||||
return 2
|
||||
}
|
||||
let edits: PlanEdit[]
|
||||
try {
|
||||
edits = JSON.parse(src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8")) as PlanEdit[]
|
||||
} catch (e) {
|
||||
console.error(`raea goal tasks: the edits aren't JSON: ${(e as Error).message}`)
|
||||
return 2
|
||||
}
|
||||
try {
|
||||
const r = await applyTasks(root, Array.isArray(edits) ? edits : [edits])
|
||||
console.log(a.includes("--json") ? JSON.stringify(r) : r.written.length ? `written: ${r.written.join(", ")}` : "nothing changed")
|
||||
return 0
|
||||
} catch (e) {
|
||||
console.error(`raea goal tasks: ${(e as Error).message}`)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
const t = await tasksOf(root)
|
||||
if (t.problem) {
|
||||
console.error(`raea goal tasks: brief.ts doesn't run: ${t.problem}`)
|
||||
return 2
|
||||
}
|
||||
const plan = readPlan(t.plan)
|
||||
console.log(a.includes("--json") ? JSON.stringify({ plan: t.plan ?? null, problem: plan.problem ?? null }) : planDigest(plan))
|
||||
return plan.problem ? 1 : 0
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Words as a brief's rules compare them (from core/brief cut.rs and Rust's cut gates, now here alone).
|
||||
|
||||
/** lower case, apostrophes dropped ("it's" one word, "its" another), every other run of non-letters one space */
|
||||
export function norm(s: string): string {
|
||||
return s
|
||||
.toLowerCase()
|
||||
.replace(/['’]/g, "")
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** `phrase` in `text` as whole words (both normed) */
|
||||
export const has = (text: string, phrase: string) => phrase !== "" && ` ${text} `.includes(` ${phrase} `)
|
||||
|
||||
/** `got`'s words with each compound the brief writes as one word joined back ("wish list" heard, "Wishlist" written),
|
||||
* each with the index of its first word in `got` */
|
||||
export function joined(got: string[], want: string[]): [string, number][] {
|
||||
const out: [string, number][] = []
|
||||
for (let i = 0; i < got.length; ) {
|
||||
const k = [3, 2].find((k) => i + k <= got.length && want.includes(got.slice(i, i + k).join(""))) ?? 1
|
||||
out.push([got.slice(i, i + k).join(""), i])
|
||||
i += k
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** how far apart a `say` phrase's words may be heard */
|
||||
export const SAY_GAP = 2
|
||||
|
||||
/** where `phrase` (normed) is first said in `got`: the index of its first word. Its words in order, compounds joined,
|
||||
* each at most `gap` words after the one before (1: word for word; "it's free, it's fun, and it's easy" says "free,
|
||||
* fun, and easy" at a gap of 2, and a reordered "fun, free, and easy" doesn't) */
|
||||
export function saidAt(got: string[], phrase: string, gap: number): number | null {
|
||||
const want = phrase.split(" ").filter(Boolean)
|
||||
if (!want.length) return null
|
||||
const g = joined(got, want)
|
||||
for (let s = 0; s < g.length; s++) {
|
||||
if (g[s][0] !== want[0]) continue
|
||||
let at = s
|
||||
const all = want.slice(1).every((w) => {
|
||||
for (let j = at + 1; j < Math.min(at + 1 + gap, g.length); j++)
|
||||
if (g[j][0] === w) {
|
||||
at = j
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
if (all) return g[s][1]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** the share of `want`'s words that `got` has in order (longest common subsequence): a CTA with a word misheard lands */
|
||||
export function inOrder(want: string[], got: string[]): number {
|
||||
if (!want.length) return 1
|
||||
const row = new Array(got.length + 1).fill(0)
|
||||
for (const w of want) {
|
||||
let prev = 0
|
||||
for (let j = 0; j < got.length; j++) {
|
||||
const keep = row[j + 1]
|
||||
row[j + 1] = w === got[j] ? prev + 1 : Math.max(row[j + 1], row[j])
|
||||
prev = keep
|
||||
}
|
||||
}
|
||||
return row[got.length] / want.length
|
||||
}
|
||||
|
||||
// A finding's quoted text, safe to print. 12-05, Dutch run 9: a caption's text cut at 40 UTF-16 units split an emoji, the
|
||||
// report held half of it, and printing it broke the check ("Conversion from string failed: invalid utf-8 sequence").
|
||||
|
||||
/** a lone half of a surrogate pair: no character, and nothing UTF-8 can hold */
|
||||
const LONE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
|
||||
|
||||
/** `s` with any half character replaced by U+FFFD */
|
||||
export const wellFormed = (s: string): string => s.replace(LONE, "�")
|
||||
|
||||
/** `s` cut to at most `n` characters (whole code points, never half an emoji), with "..." when it was longer */
|
||||
export function quote(s: string, n: number): string {
|
||||
const cs = Array.from(s)
|
||||
return cs.length > n ? `${cs.slice(0, n).join("")}...` : s
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
# How raea's agents decide what to make
|
||||
|
||||
You make videos, motion pieces, 3D scenes and games. Bring a director's point of view to each one, chosen for this
|
||||
project and the people it's for, and finish the work. These guides don't hand you a look to copy. They are ways to
|
||||
decide, and the decisions you make go into the project's brief.
|
||||
|
||||
Two rules come before everything else:
|
||||
|
||||
- **The person wins.** What the person asked for, what their taste file says and what the brief commits to beat your
|
||||
own taste and every guide's default. Steering a clear brief toward your own preferences is a failure.
|
||||
- **A change keeps; a redesign replaces.** A note ("quieter music", "the hook is slow") changes what it names and
|
||||
keeps everything else. A redesign keeps the facts and the footage and treats the old look as evidence, not law.
|
||||
Never polish a look you are about to throw away.
|
||||
|
||||
## Start from the context
|
||||
|
||||
Run `raea context PROJECT` before anything else and read all of it. It prints, in order:
|
||||
|
||||
1. **Taste** (`~/.raea/taste/taste.ts`, then the workspace's `taste.ts`): the person's standing corrections, across
|
||||
every project. A line there beats any guide.
|
||||
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
|
||||
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
|
||||
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
|
||||
`raea guide brief` has its types, a cut goal's contract and an example.
|
||||
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
|
||||
4. **The floor**: what breaks a piece, read again right before every edit.
|
||||
5. **One guide per mode**: what that kind of piece has to do.
|
||||
|
||||
If it says the brief isn't shaped (no `believe`, no `mode`), shape it before making anything. Ask two or three
|
||||
questions, each with your best guess, or write your guess and add its field to the brief's `assumed` list, and go on. The person
|
||||
confirms assumed facts later.
|
||||
|
||||
## Modes
|
||||
|
||||
The mode says what success looks like for the people the piece is for. Pick it from what is being made and where it
|
||||
runs, not from the product: an app's ad is `pitch`, and the same app's walkthrough is `explain`.
|
||||
|
||||
| Mode | It works when they... | Guide |
|
||||
|---|---|---|
|
||||
| pitch | stop, believe one thing, and act | `raea guide pitch` |
|
||||
| explain | can do or explain one thing afterwards | `raea guide explain` |
|
||||
| story | feel it, and want to see the rest | `raea guide story` |
|
||||
| play | want another go | `raea guide play` |
|
||||
| tool | get their task done without thinking about the screen | `raea guide tool` |
|
||||
|
||||
Modes mix: a trailer can be `story, pitch`. Read each one's guide. Where two disagree, the first mode in the brief
|
||||
leads. raea will add modes as its work grows; `raea context` says when a brief names a mode with no guide yet.
|
||||
|
||||
## The order of work
|
||||
|
||||
1. **Context:** `raea context`.
|
||||
2. **Shape:** a confirmed brief (who, the belief, the mode, the voice).
|
||||
3. **Plan:** for a pitch, an explain or a story, a storyboard file (scene · on screen · narration · payoff), a
|
||||
camera map and its cuts as a chain of hooks on the thirds (`raea guide match-cuts`: where each shot takes the eye
|
||||
in and leaves it), approved by the person before anything renders.
|
||||
4. **Direction:** when the look or the structure is open, offer real options made with raea, and write the chosen
|
||||
one into the deliverable's brief as a section headed "Direction".
|
||||
5. **The floor:** read it right before you edit.
|
||||
6. **Make it, as components:** list the components the piece needs, look in `raea make component list` and the
|
||||
workspace's `shared/components/` first, add what exists, and write what's missing with a fixture that renders it
|
||||
alone (`raea guide components`). The composition places them and owns the camera, the look and the mix.
|
||||
7. **Evidence:** run `raea check`, look at the frames, critique against the mode's guide, fix, and look again.
|
||||
A line the work must keep every round is a rule, not a reminder: a line `{ text, check, values }` in the project's
|
||||
taste.ts, whose check is one of raea's by name (`text-above`, `loudness`) or a `.ts` check you write with
|
||||
`raea/check` (`check({ id, text }, (world, frame, values) => ...)` and `found(...)`). `raea check
|
||||
PROJECT` runs every rule on every composition and says what waits for a render.
|
||||
|
||||
A quick edit (one value, one word, one cut) skips to the floor and makes the change. "This isn't working" means a
|
||||
redesign: go back to shaping.
|
||||
|
||||
## Notes
|
||||
|
||||
People write notes in their own words, and one note can hold several asks. Before anything in the work changes:
|
||||
|
||||
1. `raea notes take` writes each note the person sent from the raea app, or said to you, to `notes/ROUND/ID.ts` in
|
||||
the project, their words as written.
|
||||
2. Restate each note in its file (`note({...})` from `raea/note`) as its asks: one for each separate thing it asks
|
||||
for; the medium where the words name one (2D means 2D: a 3D scene doesn't make a title 3D); what it is about; and
|
||||
what it doesn't ask for (`not`), so a change keeps the rest. A redesign's asks say what is kept.
|
||||
3. `raea notes ls` says what each restatement still owes. Change nothing until it owes nothing.
|
||||
4. `raea notes post` shows the asks on the person's comments in the raea app. A correction they make there comes back
|
||||
with the next `raea notes take` as a new line of the note: restate that ask again before you go on.
|
||||
5. Give each ask a check that measures it, or a clip the person signs where it can't be measured. A check is a
|
||||
`raea/check` system, as a rule's is: copy the worked one that fits from this skill's `craft/checks` (a part that
|
||||
rides a seat, flat type with the subject in front, a part facing what it serves, nothing of one kind on another,
|
||||
a shot held N seconds, no part of a kind) into the project's `checks/`, and name it in the ask with its `values`
|
||||
and the composition it's about (`of`). A clip is `proof: { shot, sign: true }`.
|
||||
6. `raea notes check` must show each check failing on the work as it stands. A check that passes first is refused: it
|
||||
isn't measuring the ask, so fix the check, not the work. Only then change the work, one move per ask, and run
|
||||
`raea notes check` again until each passes; it also cuts each clip to sign from the newest render, so render first.
|
||||
`raea notes post` again shows where each ask stands. A note closes when the person retires it, never when you mark
|
||||
it done.
|
||||
|
||||
Each ask is one of a small set of moves: name it as the ask's `verb`, and do that move to the part or moment it
|
||||
names. A note with three asks is three moves, not one:
|
||||
|
||||
- **quieter:** less of something (glow, motion, music, colour);
|
||||
- **bolder:** more conviction where a beat already exists;
|
||||
- **distill:** fewer ideas, lines or parts;
|
||||
- **clarify:** the words and the narration;
|
||||
- **retime:** pacing and hold lengths;
|
||||
- **recut:** the order and the cuts;
|
||||
- **regrade:** colour and light;
|
||||
- **remix:** the sound;
|
||||
- **harden:** a game's edge cases;
|
||||
- **layout:** where things sit and how much room each gets;
|
||||
- **typeset:** the type on screen;
|
||||
- **animate:** motion added to what holds still;
|
||||
- **delight:** one small detail that rewards attention;
|
||||
- **adapt:** another size, length or platform;
|
||||
- **optimize:** smaller files, faster renders, smooth play;
|
||||
- **extract:** a brand kit read from finished work;
|
||||
- **generate:** variants of one element to pick from;
|
||||
- **polish:** close out the latest critique;
|
||||
- **critique:** when the person asks "is it good?": an honest look at the piece as it rendered.
|
||||
|
||||
Each move has a short guide: `raea guide quieter` (and the rest). Read the one an ask calls for before you act on
|
||||
it. Never show these words to the person. Answer the note in their terms.
|
||||
|
||||
raea has no colorize, onboard, overdrive or audit move. Colour is **regrade**; more of everything is **bolder** on
|
||||
the one beat that earns it, never on all of them; an audit is `raea check` and then **critique**; a game's first
|
||||
seconds are part of its mode (`raea guide play`), not a note.
|
||||
|
||||
A note reaches you with a move already named when the feed can tell (`{verb, part or moment, words}`). The person's
|
||||
words still come first: if they say more than the verb, each more is another ask.
|
||||
|
||||
## Other guides
|
||||
|
||||
`raea guide` lists the rest: `components` (building anything as components, and where each kind is made), `motion` (writing compositions: timing, words, layout, music, sound, 3D, games) and the
|
||||
3D guides. Read a guide when the work reaches its topic, not all at once.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Kits: props in one style, at real size, made and checked as a set
|
||||
|
||||
A kit is a set of objects that belong together (a 1970s flight desk's phone, clock, ashtray and lamp) and land as
|
||||
components any project can import. It holds together because every reference comes from the same style images and
|
||||
paragraph, every model is picked on clay from two generators, and the whole set is checked on one sheet before
|
||||
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea check` holds you to it
|
||||
and the Stop hook won't let you end before it says done.
|
||||
|
||||
## What to do
|
||||
|
||||
1. **The plan.** `goal: kit({ references: ["media/style.png"], style, objects, dials })` on brief.ts (`raea/brief`).
|
||||
- `style` is one paragraph every reference carries: era, palette, materials, wear, and one fictional maker
|
||||
("Aurora Instruments"). Never a real brand.
|
||||
- Each object: `id` (snake_case), `label`, one size (`h` metres tall, `dims` [w, d, h] for boxy things, `max` for
|
||||
things lying flat), `prompt` (one object, its condition and materials), `hero: true` for the ones seen close.
|
||||
- `raea spec brief.ts --as make` prints the plan and what it still lacks.
|
||||
2. **References, then the reference sheet.** `raea make refs --dry` quotes it; `raea make refs` makes each object's
|
||||
reference from the style images, in the style paragraph, with the scan template (one object, whole, plain grey
|
||||
ground, even light), then writes `review/refs.png` (style images first, then every reference with its size).
|
||||
- Look at the sheet as a set. One that's off (another era, another palette, two objects, a logo) is regenerated
|
||||
now: `raea make refs --only ID`. Ask it: the command the sheet step prints (`make.refs.*`).
|
||||
3. **Both generators.** `raea make gen --dry` quotes it; `raea make gen` sends each reference to Tripo H3.1 (150k
|
||||
faces for a hero, 60k for a prop) and Meshy on fal, into `out/kit/gen/ID/`.
|
||||
4. **Pick on clay.** `raea make pick-sheet` writes `review/picks.png`: the reference, then each model fitted to its
|
||||
real size, in colour and in clay. Judge on the clay: fused parts, blobs where there should be edges, and fidelity
|
||||
to the reference's shape. `raea make pick ID tripo|meshy "why"` records the pick and its reason.
|
||||
5. **Prep.** `raea make prep` fits each pick to its real size (front toward +z, bottom-centred, metres) with
|
||||
`raea gen check`, makes a quarter-triangle `_lod1` beside it (`blender/decimate.py`), and writes a `.glb.json`
|
||||
sidecar for each saying how it was made (generator, why, prompt, reference, style).
|
||||
6. **Land it.** `raea make kit --name KIT` puts the kit in the workspace's `shared/components/KIT/` (else the
|
||||
project's `components/KIT/`): one component per object (`RotaryPhone.tsx`, importing its model and LOD from
|
||||
beside it, `lod` for when it's small on screen), `lineup.tsx` (every piece at its real size beside a 1 m bar),
|
||||
`cover.png`, `thumbs/` and `kit.json`. Import it as `@shared/components/KIT/RotaryPhone`.
|
||||
7. **Review.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, and look at every tile yourself:
|
||||
the pieces belong together, match their references and the brief, hold their form in clay, and stand at their real
|
||||
size. Fix every ERROR the render's check names; keep a list of what you'd still change.
|
||||
|
||||
Cost: a six-piece kit is about $8-10 (references about $0.25 each, Tripo H3.1 and Meshy about $0.60-0.80 each).
|
||||
`--dry` on refs and gen says the price first; ask before going over $10.
|
||||
|
||||
## Why
|
||||
|
||||
- One style paragraph and the same style images in every reference is what keeps a kit of one world. References
|
||||
made one at a time from text alone drift in era and palette, and an outlier caught on the sheet costs a picture,
|
||||
not a model.
|
||||
- Generators fail differently: Tripo fuses a handset to its cradle, Meshy softens numerals. Two models and a pick on
|
||||
clay beat any one, and the reason written down is what the next kit learns from.
|
||||
- Fitting to real size on the way in is what makes a kit drop into a scene without nudging.
|
||||
|
||||
## Common mistakes
|
||||
|
||||
- Picking on the colour render: texture hides a blob. Pick on the clay.
|
||||
- A real brand in a prompt or the style ("Bakelite by Western Electric"). Name the one fictional maker.
|
||||
- Skipping the reference sheet because each reference looks fine alone: judge them together.
|
||||
- Landing a kit before `raea make prep`: `raea make kit` names what isn't prepped rather than landing half.
|
||||
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user