mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ea66741a0 | ||
|
|
dbee528778 | ||
|
|
bad441493e | ||
|
|
14a10fc2b0 | ||
|
|
02617df030 | ||
|
|
12ad441266 | ||
|
|
8e7c5a13e7 | ||
|
|
a380418ed5 | ||
|
|
6e35267060 | ||
|
|
05f82ef572 | ||
|
|
563f49a978 | ||
|
|
67277ab967 | ||
|
|
4695f03650 | ||
|
|
41fbcfc2ab | ||
|
|
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 | ||
|
|
06a48730d1 | ||
|
|
28d89f8ffd | ||
|
|
7b8317764a | ||
|
|
c69e28fac3 | ||
|
|
83da71b62d | ||
|
|
4d896d2b2f | ||
|
|
d4d13925fa | ||
|
|
a8d7263235 | ||
|
|
d0f09511fe | ||
|
|
1a8a7df53d | ||
|
|
ef8ea7563d | ||
|
|
6716b6b9f0 | ||
|
|
313ac8ab83 | ||
|
|
cdfb043026 | ||
|
|
35267727b8 | ||
|
|
c72717a635 |
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",
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn stop(v: &Value) -> Option<String> {
|
||||
let cwd = PathBuf::from(v["cwd"].as_str()?);
|
||||
let brief = brief_with_job(&cwd)?;
|
||||
let exe = std::env::current_exe().ok()?;
|
||||
let out = std::process::Command::new(exe).args(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
|
||||
let home = raea_io_home::user_home()?;
|
||||
let session = v["session_id"].as_str().unwrap_or("");
|
||||
@@ -67,7 +67,7 @@ pub fn stop(v: &Value) -> Option<String> {
|
||||
}
|
||||
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
|
||||
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
|
||||
Some(format!("Not done ({open}{}): {items}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
|
||||
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
|
||||
}
|
||||
|
||||
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
|
||||
|
||||
+6
-37
@@ -3,10 +3,10 @@
|
||||
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
|
||||
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
|
||||
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
|
||||
//! file is saved: `raea goal check --at edit` on a composition, or on a file under a brief. As a turn ends: `raea
|
||||
//! goal check --at done` on the brief's goals (apps/check/make). After any tool, and as a turn ends: what the person sent from
|
||||
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit
|
||||
//! moment's findings go back in the shape each one reads.
|
||||
//! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
|
||||
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
|
||||
//! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
|
||||
//! every harness hands its agent; what was sent goes back in the shape each one reads.
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -114,23 +114,6 @@ pub fn steer(files: &[String]) -> String {
|
||||
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
|
||||
}
|
||||
|
||||
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
|
||||
/// adds or updates (Codex).
|
||||
fn saved(v: &Value) -> Vec<String> {
|
||||
let i = &v["tool_input"];
|
||||
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
|
||||
return vec![p.to_string()];
|
||||
}
|
||||
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
|
||||
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
|
||||
}
|
||||
|
||||
/// Whether a saved file is held at the edit moment: a composition (a .tsx that registers a root), or any file under a
|
||||
/// brief.ts
|
||||
fn held_at_edit(p: &Path) -> bool {
|
||||
(p.extension().is_some_and(|e| e == "tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) || p.parent().is_some_and(|d| raea_app_check_make::brief_with_job(d).is_some())
|
||||
}
|
||||
|
||||
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
|
||||
/// plain stdout, Claude Code's and Codex's PostToolUse context.
|
||||
fn after(agent: &str, text: &str) -> String {
|
||||
@@ -178,20 +161,8 @@ pub fn hook(args: &[String]) -> R<String> {
|
||||
}
|
||||
return Ok(String::new());
|
||||
}
|
||||
// the edit moment of the loop (docs/goal.feature MK33): `raea goal check FILE --at edit` on a saved composition, or
|
||||
// on any file under a brief; a save that passes says nothing
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let mut found = Vec::new();
|
||||
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
|
||||
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
|
||||
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
|
||||
if out.status.code() == Some(1) {
|
||||
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
|
||||
}
|
||||
}
|
||||
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
|
||||
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
|
||||
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
|
||||
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
|
||||
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -217,8 +188,6 @@ mod tests {
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
|
||||
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
|
||||
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
|
||||
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
|
||||
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
|
||||
assert_eq!(after("kimi", "x"), "x");
|
||||
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
|
||||
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
|
||||
|
||||
@@ -213,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);
|
||||
}
|
||||
@@ -176,6 +192,10 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
|
||||
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
|
||||
pub const RAIL: f64 = 0.45;
|
||||
|
||||
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
|
||||
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
|
||||
let r = w / h;
|
||||
@@ -208,7 +228,8 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
let q = quote(&r.text);
|
||||
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
|
||||
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
|
||||
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
|
||||
if r.boxes.iter().all(off) {
|
||||
clipped += 1;
|
||||
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
|
||||
@@ -294,3 +315,35 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
|
||||
passed.push(format!("cues: {checked} texts land on their words"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
|
||||
/// down was an error); the same card over the buttons isn't.
|
||||
#[test]
|
||||
fn the_right_zone_starts_where_the_apps_buttons_do() {
|
||||
let right = |y: f64| {
|
||||
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
|
||||
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
|
||||
};
|
||||
assert_eq!(right(682.0), "");
|
||||
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
|
||||
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
|
||||
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
|
||||
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
|
||||
]})).collect::<Vec<_>>()});
|
||||
let runs = text_runs(&m);
|
||||
assert_eq!(runs.len(), 1);
|
||||
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
|
||||
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
|
||||
}
|
||||
}
|
||||
@@ -15,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"]);
|
||||
|
||||
@@ -40,6 +40,29 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
|
||||
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
|
||||
}
|
||||
|
||||
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
|
||||
/// interview: 7 s one after another, 4 s so).
|
||||
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
|
||||
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
|
||||
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
|
||||
let next = AtomicUsize::new(0);
|
||||
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..workers {
|
||||
s.spawn(|| {
|
||||
loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
if i >= n {
|
||||
break;
|
||||
}
|
||||
*out[i].lock().unwrap() = Some(f(i));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
|
||||
}
|
||||
|
||||
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
if files.is_empty() {
|
||||
return Err("raea media sheet FILE... -o OUT: which files?".into());
|
||||
@@ -47,10 +70,9 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
|
||||
let mut tiles = Vec::new();
|
||||
if files.len() == 1 {
|
||||
let p = probe_of(&files[0])?;
|
||||
for i in 0..n.max(1) {
|
||||
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
|
||||
tiles.push((t, frame(&files[0], t)?));
|
||||
}
|
||||
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
|
||||
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
|
||||
tiles.extend(at.into_iter().zip(read));
|
||||
} else {
|
||||
for f in files {
|
||||
let p = probe_of(f)?;
|
||||
|
||||
+69
-62
@@ -1,6 +1,7 @@
|
||||
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
|
||||
|
||||
use super::*;
|
||||
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
|
||||
|
||||
pub(crate) fn round3(x: f64) -> f64 {
|
||||
(x * 1000.0).round() / 1000.0
|
||||
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
|
||||
}
|
||||
i
|
||||
});
|
||||
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
|
||||
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
|
||||
let audio = match audio_track(path) {
|
||||
Some(a) => Some(a),
|
||||
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
|
||||
};
|
||||
if video.is_none() && audio.is_none() {
|
||||
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
|
||||
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
|
||||
@@ -124,74 +129,37 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// The boxes inside `b` (a box's payload): (type, payload).
|
||||
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 8 <= b.len() {
|
||||
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
|
||||
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
|
||||
let mut hdr = 8;
|
||||
if size == 1 && i + 16 <= b.len() {
|
||||
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = b.len() - i;
|
||||
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
|
||||
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
|
||||
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
|
||||
audio_in(&moov_of(path)?)
|
||||
}
|
||||
|
||||
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
let Some(mdia) = child(trak, b"mdia") else { continue };
|
||||
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
|
||||
continue;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
let mdhd = child(mdia, b"mdhd")?;
|
||||
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
|
||||
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
|
||||
// them again as a double at 48 and a count at 56
|
||||
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
|
||||
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
|
||||
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
|
||||
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
|
||||
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
None
|
||||
}
|
||||
|
||||
/// The first video track's timing, for MP4 and QuickTime files.
|
||||
pub fn video_track(path: &Path) -> Option<Track> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
|
||||
let mut at = 0u64;
|
||||
let moov = loop {
|
||||
if at + 8 > len {
|
||||
return None;
|
||||
}
|
||||
let mut h = [0u8; 16];
|
||||
f.seek(SeekFrom::Start(at)).ok()?;
|
||||
f.read_exact(&mut h[..8]).ok()?;
|
||||
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
|
||||
let mut hdr = 8u64;
|
||||
if size == 1 {
|
||||
f.read_exact(&mut h[8..]).ok()?;
|
||||
size = u64::from_be_bytes(h[8..].try_into().ok()?);
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = len - at;
|
||||
}
|
||||
if size < hdr {
|
||||
return None;
|
||||
}
|
||||
if &h[4..8] == b"moov" {
|
||||
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
|
||||
f.read_exact(&mut m).ok()?;
|
||||
break m;
|
||||
}
|
||||
at += size;
|
||||
};
|
||||
let moov = moov_of(path)?;
|
||||
for (k, trak) in boxes(&moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
@@ -295,3 +263,42 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
|
||||
}
|
||||
|
||||
// ---- pictures
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
v.extend_from_slice(kind);
|
||||
v.extend_from_slice(body);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sound_track_is_read_from_the_file_s_own_tables() {
|
||||
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
|
||||
let mut mdhd = vec![0u8; 24];
|
||||
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
|
||||
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
|
||||
let mut hdlr = vec![0u8; 24];
|
||||
hdlr[8..12].copy_from_slice(b"soun");
|
||||
let mut stsd = vec![0u8; 44];
|
||||
stsd[7] = 1;
|
||||
stsd[12..16].copy_from_slice(b"mp4a");
|
||||
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
|
||||
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
|
||||
// a picture track ahead of it is passed over
|
||||
let mut vh = vec![0u8; 24];
|
||||
vh[8..12].copy_from_slice(b"vide");
|
||||
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
|
||||
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
|
||||
// no sound track, or one that states no rate: nothing (the track is decoded instead)
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
|
||||
let mut silent = stsd.clone();
|
||||
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
|
||||
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
|
||||
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
|
||||
}
|
||||
}
|
||||
@@ -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`"))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
Feature: one check (12-04, Shane: "fix how every agent checks its work ... removing ask and judge completely and all
|
||||
that exists is check as the overarching method")
|
||||
|
||||
Round 26's agents met about nine ways to check their work (raea goal check, goal seen, goal judge, raea ask, raea
|
||||
check's taste, the old frames command, a lines.txt words check, raea cloud's stop critic and run eval, and the render and
|
||||
publish tools' own copies), two of them broken on the boxes, and 183 findings on 10 cuts of which about 10 were real
|
||||
faults. Every agent, on raea cloud, in the desktop app or with the raea skill, now has one: `raea check`.
|
||||
|
||||
Rule: every rule lives in one of three places, or nowhere (12-04, Shane)
|
||||
Built in: a component or an SDK default that can't produce the fault (captions from the words file, in the safe area;
|
||||
a Region that keeps text off faces and the app's buttons; raea cut, which cuts only in pauses). Its check is a
|
||||
backstop that shouldn't fire.
|
||||
A check, hard or soft: hard is an error (a fault in the deliverable), soft a warning (a note for the person, never a
|
||||
reason to render again).
|
||||
Context the agent retrieves while it makes the work: craft and taste (how captions read, pacing, a hook, a brand's
|
||||
fingerprint, the person's past notes) live in the skill, the guides and memory. Nothing grades the work against them.
|
||||
A rule that fits none of these isn't a rule: no ritual (the agent saying it looked: `seen`) and no model's opinion
|
||||
of the work (taste, a critic, a judge, an ask).
|
||||
|
||||
Scenario: CK0 one verb
|
||||
Given any project
|
||||
When an agent or a person runs `raea check [FILE...] [--at edit|render|publish|done]`
|
||||
Then it runs every rule the project's goal holds at that moment, and nothing else checks the work
|
||||
And `raea goal check` still runs as `raea check`, for boxes and tools on an older raea
|
||||
And `raea ask`, `raea goal judge`, `raea judge` and `raea goal seen` are gone: raea says so, and names `raea check`
|
||||
|
||||
Scenario: CK1 run once, after the render
|
||||
Given a render that wrote OUT.mp4 (on this machine, or on raea cloud's farm and checked by the box that sent it)
|
||||
When it ends
|
||||
Then `raea check OUT.mp4 --at render` runs once and keeps OUT.check.json beside it
|
||||
And publish and done read OUT.check.json while it's no older than OUT.mp4 or its manifest, and never run its rules again
|
||||
|
||||
Scenario: CK2 only real faults, one line a rule
|
||||
Given a cut
|
||||
Then it is held to: a word clipped or missing (words, sound), a face cut by the frame edge (frames), text over a face,
|
||||
a sign or the app's buttons (place, floor), captions over talking (captions), the brief's must-say, never-say and
|
||||
CTA (say, never, cta), its size, length and name (shape, sizes, naming), the brief's count and open items, and what
|
||||
the render itself found (render)
|
||||
And a 3D scene, kit or shot is held to its deliverables and what its render found: clipping, a part out of place or
|
||||
under its detail, light that jumps
|
||||
And each rule says at most one line a file: its first finding and how many more like it
|
||||
|
||||
Scenario: CK3 our own text from the manifest
|
||||
Given a render manifest beside a video
|
||||
Then captions, placement and size read the texts raea drew from it, never by reading the frames
|
||||
And text in the source footage (a sign, a phone's screen) is never counted as the edit's
|
||||
|
||||
Scenario: CK4 no critic, no ritual in the loop
|
||||
Then no check asks a model to judge the work, and no check waits for the agent to say it looked
|
||||
And a check that can't run on a machine (Mac, Linux, Windows, a raea cloud box) is removed, not left waiting
|
||||
|
||||
Scenario: CK5 a brief that can't break the check
|
||||
Given brief.ts with `goal: [steps, cut({...})]`, `goal: steps` or `goal: cut({...})`
|
||||
Then `raea check` reads every goal in it, and never crashes on what an agent wrote
|
||||
And a cut's beats are the agent's plan, never a rule it is checked against
|
||||
|
||||
Scenario: CK6 one set of instructions
|
||||
Then raea's skill, its guides, `raea help`, the AGENTS.md raea writes, raea cloud's method, workflows and skills, and
|
||||
the desktop app all name `raea check` as the one way to check, and none names ask, judge, seen, frames check or a
|
||||
lines.txt words check
|
||||
@@ -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
|
||||
@@ -110,3 +124,37 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
|
||||
back, a second container handing its render to the first, an ACP turn round-tripped
|
||||
And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file
|
||||
comes back through /v1/files
|
||||
|
||||
Rule: a box edits on light copies, the farm renders from originals (12-05)
|
||||
Scenario: CL17. Nothing on the box takes a light copy's place
|
||||
Given raea cloud brought a run's footage as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt)
|
||||
Then every look the agent takes (a still, a frame, a probe, a check of its words) reads the light copy
|
||||
And no file ever replaces footage/NAME.mp4 on the box, before a render or after one
|
||||
|
||||
Scenario: CL18. A farm render reads each light copy as its original, fetched by the farm
|
||||
Given .raea-cloud/originals.json names a light copy's original: its hash, size and a link that hasn't ended
|
||||
When a render that reads the light copy goes to the farm (server/offload.ts)
|
||||
Then its media manifest names the original under the light copy's path, with its link, and the light copy's own
|
||||
bytes go nowhere
|
||||
And the farm fetches the original from the library into its cache, checks it against its hash, and keeps it for
|
||||
every later render; the box never downloads it, hashes it or sends it
|
||||
And a light copy the render doesn't read is left out, its original included
|
||||
And a size raea cloud doesn't know goes as 0, which the farm takes with a link and never without one
|
||||
|
||||
Scenario: CL19. An original with no link goes from the box
|
||||
Given a light copy whose original has no hash, or whose link ends within 5 minutes
|
||||
When its original is in footage/originals/ under the light copy's name (any extension)
|
||||
Then the render sends that file by its own hash, under the light copy's path
|
||||
And only a farm with its media cache gets an original by its file (by LFS or in the tar it would go as the light
|
||||
copy), and only that farm an original of unknown size: for any other the take is rendered as its light copy
|
||||
And .raea-cloud/proxies/ never goes in a render's tar, and an original no source names stays on the box
|
||||
|
||||
Scenario: CL20. A render that read a light copy says so
|
||||
Given a light copy with no original either way
|
||||
Then the render prints NO ORIGINAL with its name, and is rendered from the light copy
|
||||
And its manifest records {"originals": {"read": [...], "light": [...]}} (a still's in OUT.render.json beside it),
|
||||
checked or not, from which raea cloud marks it a draft that is never shown or published
|
||||
And the farm's media list holds each original by its link in its light copy's place, with everything else that
|
||||
went (12-05 review: the farm-cache path dropped the links while the manifest said they were read)
|
||||
And an original of unknown size over 40 GB is refused as it downloads, before it fills the farm's volume
|
||||
And test/originals.ts and test/farm_media.py check CL17-CL20
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
// pace.ts on made-up words and levels: a short run between two long pauses joins a neighbour; level evening measures
|
||||
// only clips with a second of speech and gives a short clip its own take's gain
|
||||
import { expect, test } from "bun:test";
|
||||
import { evenLevels, linesIn, pace, unsqueezed, type Levels } from "../src/pace";
|
||||
|
||||
/** levels at 10 ms: speech (-20 dB) inside each word, quiet (-70 dB) elsewhere, over `seconds` */
|
||||
function levels(ws: { from: number; to: number }[], seconds: number): Levels {
|
||||
const db = Array.from({ length: Math.round(seconds * 100) }, (_, i) => (ws.some((w) => i / 100 >= w.from && i / 100 < w.to) ? -20 : -70));
|
||||
return { start: 0, db };
|
||||
}
|
||||
|
||||
test("a word alone between two long pauses joins a neighbour instead of flicking by", () => {
|
||||
const ws = [
|
||||
{ text: "Sounds", from: 0.5, to: 0.9 },
|
||||
{ text: "great.", from: 0.95, to: 1.4 },
|
||||
// 0.7 s pause
|
||||
{ text: "Available", from: 2.1, to: 2.55 },
|
||||
// 0.6 s pause
|
||||
{ text: "times", from: 3.15, to: 3.5 },
|
||||
{ text: "the", from: 3.55, to: 3.7 },
|
||||
{ text: "same", from: 3.75, to: 4.0 },
|
||||
{ text: "day.", from: 4.05, to: 4.5 },
|
||||
];
|
||||
const { pieces, trims } = pace(ws, levels(ws, 6), [[0, 6]], { hook: 0 });
|
||||
expect(pieces.length).toBe(2);
|
||||
for (const p of pieces) expect(ws[p.words[1]].to - ws[p.words[0]].from).toBeGreaterThanOrEqual(0.8);
|
||||
// the shorter pause (after "Available") is the one kept; the longer one is still cut
|
||||
expect(pieces[1].words[0]).toBe(2);
|
||||
expect(trims.filter((t) => t.kind === "pause").length).toBe(1);
|
||||
});
|
||||
|
||||
test("a clip too short to measure takes its own take's gain, and gain stays within 9 dB", () => {
|
||||
const clips = [
|
||||
{ take: "A", file: "A.mp4", from: 0, to: 3, line: "a" },
|
||||
{ take: "A", file: "A.mp4", from: 4, to: 4.5, line: "b" },
|
||||
{ take: "B", file: "B.mp4", from: 0, to: 3, line: "c" },
|
||||
{ take: "C", file: "C.mp4", from: 0, to: 3, line: "d" },
|
||||
];
|
||||
const lv: Record<string, { db: number; seconds: number }> = { a: { db: -30, seconds: 2.5 }, b: { db: -45, seconds: 0.4 }, c: { db: -18, seconds: 2.5 }, d: { db: -18, seconds: 2.5 } };
|
||||
const out = evenLevels(clips, (c) => lv[c.line]);
|
||||
expect(out[0].gainDb).toBe(9);
|
||||
expect(out[1].gainDb).toBe(9);
|
||||
expect(out[2].gainDb).toBeUndefined();
|
||||
});
|
||||
|
||||
test("a line stopping mid-sentence with no pause runs on to its sentence's end; a tight seam never crosses a word", () => {
|
||||
const ws = [
|
||||
{ text: "get", from: 0.5, to: 0.66 },
|
||||
{ text: "them", from: 0.66, to: 0.82 },
|
||||
{ text: "delivered", from: 0.82, to: 1.06 },
|
||||
{ text: "for", from: 1.06, to: 1.22 },
|
||||
{ text: "free?", from: 1.22, to: 1.46 },
|
||||
// a pause, then the next sentence
|
||||
{ text: "Uh", from: 2.0, to: 2.3 },
|
||||
{ text: "sounds", from: 2.3, to: 2.6 },
|
||||
];
|
||||
// the sound of "for" starts 60 ms after its transcript time, so halfway between the sounds would be inside it
|
||||
const l = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 1.46 }, { from: 2.0, to: 2.6 }], 3.5);
|
||||
const { pieces } = pace(ws, l, [[0, 2]], { hook: 0 });
|
||||
expect(pieces.length).toBe(1);
|
||||
expect(pieces[0].words).toEqual([0, 4]);
|
||||
expect(pieces[0].to).toBeGreaterThanOrEqual(1.46);
|
||||
// a line ending where the sentence goes on for more than three words is cut at the boundary, not inside the next word
|
||||
const long = [...ws.slice(0, 3), { text: "for", from: 1.06, to: 1.22 }, { text: "all", from: 1.22, to: 1.4 }, { text: "your", from: 1.4, to: 1.55 }, { text: "pets", from: 1.55, to: 1.8 }, { text: "today.", from: 1.8, to: 2.2 }];
|
||||
const l2 = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 2.2 }], 3);
|
||||
const r = pace(long, l2, [[0, 2]], { hook: 0 });
|
||||
expect(r.pieces[0].to).toBeLessThanOrEqual(1.06 + 1 / 30);
|
||||
});
|
||||
|
||||
test("a phrase a transcriber heard twice and squeezed into one instant is dropped, and the line is found where it was said", () => {
|
||||
// 12-05, run 28: "Sign up for the news, sign up for the newsletter", with "up for the news sign" all at 10.32-10.34 s
|
||||
const w = (text: string, a: number, b: number) => ({ text, from: a / 1000, to: b / 1000 });
|
||||
const heard = [w("for", 9280, 9360), w("the", 9360, 9440), w("newsletter.", 9440, 9460), w("Sign", 10080, 10320), w("up", 10320, 10340), w("for", 10320, 10340), w("the", 10320, 10340), w("news", 10320, 10340), w("sign", 10320, 10340), w("up", 10320, 10400), w("for", 10400, 10560), w("the", 10560, 10640), w("newsletter", 10640, 10960)];
|
||||
const ws = unsqueezed(heard);
|
||||
expect(ws.map((x) => x.text).join(" ")).toBe("for the newsletter. Sign up for the newsletter");
|
||||
const { spans } = linesIn(ws, ["sign up for the newsletter"]);
|
||||
expect(ws[spans[0][0]].from).toBe(10.08);
|
||||
// two short words together are speech, kept
|
||||
expect(unsqueezed([w("a", 0, 20), w("cat", 20, 40), w("sat", 300, 500)]).length).toBe(3);
|
||||
});
|
||||
@@ -255,6 +255,44 @@ ${Array.from({ length: 40 }, (_, i) => `.u${i} { margin: ${i}px; }`).join("\n")}
|
||||
}
|
||||
});
|
||||
|
||||
// a take's jump cuts read through the ffmpeg CLI (cutplan.ts ffmpegCuts): where raea media cuts finds them
|
||||
test.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)("raea cut reads a take's jump cuts through ffmpeg, where the engine finds them", async () => {
|
||||
const { ffmpegCuts } = await import("../src/cutplan.ts");
|
||||
const dir = mkdtempSync(join(tmpdir(), "raea-ffcuts-"));
|
||||
try {
|
||||
const color = (c: string) => ["-f", "lavfi", "-i", `color=c=${c}:s=320x180:r=30:d=2`];
|
||||
spawnSync("ffmpeg", ["-v", "error", "-y", ...color("red"), ...color("blue"), ...color("green"), "-filter_complex", "[0][1][2]concat=n=3:v=1:a=0", "-c:v", "libx264", "-pix_fmt", "yuv420p", join(dir, "t.mp4")]);
|
||||
expect(ffmpegCuts(join(dir, "t.mp4"), 0.08)).toEqual([2, 4]);
|
||||
expect(ffmpegCuts(join(dir, "missing.mp4"), 0.08)).toBeNull();
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// raea cloud's footage/faces.json (prep's faces, found on its farm): perception.json takes each clip's face from it,
|
||||
// with no still and no raea-perceive (a box has none). A made clip and made-up faces, never real footage
|
||||
test.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)("raea cut takes each clip's face from footage/faces.json", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "raea-cut-faces-"));
|
||||
const run = (...a: string[]) => spawnSync("bun", [join(here, "src/native.ts"), bin, ...a], { cwd: dir, encoding: "utf8", env: { ...process.env, RAEA_PERCEIVE: "/nonexistent/raea-perceive" } });
|
||||
try {
|
||||
mkdirSync(join(dir, "media"));
|
||||
mkdirSync(join(dir, "footage"));
|
||||
spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x120:r=30:d=4", "-c:v", "libx264", "-pix_fmt", "yuv420p", join(dir, "media/take01.mp4")]);
|
||||
const said: [string, number, number][] = [["Hello", 200, 600], ["there.", 650, 1000], ["This", 1500, 1700], ["is", 1750, 1850], ["the", 1900, 2000], ["second", 2100, 2500], ["line.", 2550, 2900]];
|
||||
writeFileSync(join(dir, "media/take01.words.json"), JSON.stringify(said.map(([text, start_ms, end_ms]) => ({ text, start_ms, end_ms }))));
|
||||
// no face by the first clip's middle (0.6 s, nearest 1 s); two at 2 s, by the second's (2.4 s): the larger is kept
|
||||
const face = [0.25, 0.25, 0.5, 0.5, 0.9];
|
||||
writeFileSync(join(dir, "footage/faces.json"), JSON.stringify({ take01: { w: 160, h: 120, t: [0, 1, 2, 3], s: [[], [], [[0.1, 0.1, 0.1, 0.1, 0.99], face], [face]] } }));
|
||||
const r = run("cut", "take01", "hello there", "the second line");
|
||||
expect(r.stderr).toBe("");
|
||||
const band = { safe: { top: 220, bottom: 1500 } };
|
||||
// 160x120 covering 1080x1920 is 16x, centred: x 0.25*160*16 - 740, y 0.25*120*16, w 0.5*160*16, h 0.5*120*16
|
||||
expect(JSON.parse(readFileSync(join(dir, "perception.json"), "utf8"))).toEqual({ "0": band, "33": { ...band, face: { x: -100, y: 480, w: 1280, h: 960 } } });
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// a stock talking take (fixtures/CREDITS.md): the face branch of frame and perception.json. The footage fixtures are
|
||||
// the maintainers' (tools/public-first/private.paths), so a checkout without them skips this
|
||||
test.skipIf(!existsSync(join(raea, "engine/media/fixtures")))("raea frame and raea cut find the face in a talking take", () => {
|
||||
|
||||
@@ -9,13 +9,27 @@ use std::path::Path;
|
||||
/// `raea goal`'s verbs (docs/goal.feature): the loop's runner, sdk/goal/src/run.ts, run here on raea's JavaScriptCore
|
||||
/// with Node's core. `goal gates` (the record and critic gates the packs read) is apps/make's, and `goal next` this
|
||||
/// binary's own (next()).
|
||||
pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
|
||||
pub const GOAL_TS: &[&str] = &["check", "tasks"];
|
||||
|
||||
/// Verbs that asked a model for its opinion of the work, or the agent to say it looked (docs/check.feature): gone, and
|
||||
/// said so with where their part went, so an old skill or AGENTS.md that names one is set right at once.
|
||||
pub fn gone(args: &[String]) -> Option<String> {
|
||||
let v = |i: usize| args.get(i).map(String::as_str);
|
||||
let what = match (v(0), v(1)) {
|
||||
(Some("ask"), _) => "raea ask",
|
||||
(Some("judge"), _) => "raea judge",
|
||||
(Some("goal"), Some("seen")) => "raea goal seen",
|
||||
(Some("goal"), Some("judge")) => "raea goal judge",
|
||||
(Some("goal"), Some("gates")) => "raea goal gates",
|
||||
(Some("check"), _) if args.iter().any(|a| a == "--taste" || a == "--quick") => "raea check --taste",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!("{what} is gone (docs/check.feature): `raea check` is the one check, and a render checks its own output at its end. How the work should look and sound is the raea skill's and its guides', read while you make it; nothing grades it after."))
|
||||
}
|
||||
|
||||
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
|
||||
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)
|
||||
pub const GOAL_USAGE: &str = "raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (the one check (docs/check.feature): every rule each goal of brief.ts holds at that moment, real faults only, one line a rule a file; with no goal, the floor. A render runs it on its output at its end and keeps OUT.check.json beside it; publish and done read that and never run it again. review/goal.json; exit 1 on an error. `raea goal check` is its old name)
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
|
||||
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
|
||||
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
|
||||
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
|
||||
|
||||
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
|
||||
@@ -42,14 +56,12 @@ pub fn render_moment(args: &[String]) -> i32 {
|
||||
a.extend(["--manifest".into(), m]);
|
||||
}
|
||||
match goal_run(&a) {
|
||||
Ok(1) => {
|
||||
println!("fix every ERROR above, then render again");
|
||||
1
|
||||
}
|
||||
// an ERROR is a fault in the deliverable: fix its cause in the composition before this render is handed over
|
||||
Ok(1) => 1,
|
||||
Ok(_) => 0,
|
||||
// no runner (an install without the SDK): the render stands, and says so
|
||||
Err(e) => {
|
||||
println!("raea goal check: {e}");
|
||||
println!("raea check: {e}");
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
+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 */
|
||||
|
||||
+14
-15
@@ -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") {
|
||||
@@ -204,17 +204,17 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
if args[0] == "spec" {
|
||||
return spec::spec_cli(&args[1..]);
|
||||
}
|
||||
// `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest)
|
||||
if args[0] == "check" && args.iter().any(|a| a == "--quick") {
|
||||
let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?;
|
||||
println!("{report}");
|
||||
std::process::exit(i32::from(bad));
|
||||
}
|
||||
// `hook [AGENT]`: every agent harness's tool hooks (A5d): raea show over Preview, the quick check after a save (SK10)
|
||||
if args[0] == "hook" { return raea_app_check::hook::hook(&args[1..]); }
|
||||
// `check PROJECT|EDIT.tsx`: every rule's check over the compositions' worlds (DR4); a video is the floor alone
|
||||
if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) { std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK)); }
|
||||
if args[0] == "check" { std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?)); }
|
||||
// `check [FILE...] [--at MOMENT]`: the one check (docs/check.feature), sdk/goal/src/run.ts; a model's opinion
|
||||
// (`--taste`, `ask`, `judge`, `goal seen|judge`) is no check, and refused with where its part went
|
||||
if let Some(why) = gone(args) { return Err(why); }
|
||||
// `check EDIT.tsx|NAME.story.ts`: a project's own checks over a composition's frames or a story (DR4), before a
|
||||
// render; the deliverables' check is the runner's
|
||||
if args[0] == "check" && args[1..].iter().find(|a| !a.starts_with('-')).is_some_and(|a| a.ends_with(".tsx") || a.ends_with(".ts")) {
|
||||
std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK));
|
||||
}
|
||||
if args[0] == "check" { return goal_ts(&[&["goal".to_string()], args].concat()); }
|
||||
if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)
|
||||
if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)
|
||||
if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)
|
||||
@@ -280,13 +280,12 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
Some("gen") => return raea_app_tools::generate::generate(args),
|
||||
// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())
|
||||
Some(v) if SHELL.contains(&v) => return shell(args),
|
||||
// `goal check|tasks|seen|judge` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal gates`
|
||||
// apps/make's; `goal next` this binary's
|
||||
// `goal check|tasks` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal check` is `raea
|
||||
// check`'s old name; `goal next` this binary's
|
||||
Some("goal") if args.get(1).is_some_and(|v| GOAL_TS.contains(&v.as_str())) => return goal_ts(args),
|
||||
Some("make") if args.get(1).map(String::as_str) == Some("place") => return goal_ts(&[&["goal".to_string()], &args[1..]].concat()),
|
||||
Some("goal") if args.get(1).map(String::as_str) == Some("gates") => return raea_app_make::cli(args),
|
||||
Some("goal") if args.get(1).map(String::as_str) == Some("next") => return next(&args[2..]),
|
||||
Some("goal") => return Err(format!("raea goal check|tasks|seen|judge|gates|next\n {GOAL_USAGE}")),
|
||||
Some("goal") => return Err(format!("raea goal tasks|next (raea check checks the work)\n {GOAL_USAGE}")),
|
||||
_ => if let Some(r) = raea_app_solid::verb(args) { return r }, // `solid info|view FILE.ts`, `judge DIR`, `ask FILE` (apps/solid)
|
||||
}
|
||||
// `master-gain BUNDLE.js DIR`: the gain and ceiling a composition's render masters its sound with, as JSON (live
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// How raea cut times a take's lines: the take's light copy when raea cloud keeps one, its jump cuts (kept in raea's
|
||||
// cache) and sound level, and pace.ts's timing, kept off the take's own jump cuts. native.ts gives it the engine.
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { basename, dirname } from "node:path";
|
||||
import { levelsOf, linesIn, pace, wavSamples, type Levels, type PaceOptions, type Piece, type Trim, type Word } from "./pace";
|
||||
|
||||
/** what timing needs of the engine: a take's path, raea's commands (text and JSON), and whether a file is sound alone */
|
||||
export type TakeIO = { at: (p: string) => string; engineRun: (a: string[]) => string; engineJson: (a: string[]) => any; isAudio: (f: string) => boolean };
|
||||
|
||||
const ms = (s: number) => Math.round(s * 1000) / 1000;
|
||||
|
||||
/** A take's jump cuts read through the ffmpeg CLI where there is one: its luma at 160x90, every frame, scored as raea
|
||||
* media cuts scores them (ffmpeg's select scene: each frame's mean absolute difference from the last, less the
|
||||
* difference before it, over 100). ffmpeg decodes on every core; the engine's own decoder on a Linux box is openh264 on
|
||||
* one (12-05: 38 s for a 3.5-minute light copy, 66 s for a 6-minute one, against 4 s for ffmpeg), and a box step has
|
||||
* 3 minutes. The small picture leaves a hard cut's score where it was and a frame's grain out. null where ffmpeg
|
||||
* can't read it: the engine reads it then. */
|
||||
export function ffmpegCuts(file: string, threshold: number): number[] | null {
|
||||
const [w, h] = [160, 90];
|
||||
const r = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-an", "-vf", `scale=${w}:${h}:flags=area,format=gray,showinfo`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 });
|
||||
if (r.error || r.status !== 0 || !r.stdout?.length) return null;
|
||||
// each frame's time, from showinfo's lines in order
|
||||
const times = [...String(r.stderr).matchAll(/\bn:\s*\d+\s+pts:\s*-?\d+\s+pts_time:(-?[\d.]+)/g)].map((m) => Number(m[1]));
|
||||
const n = w * h;
|
||||
const frames = Math.floor(r.stdout.length / n);
|
||||
if (!frames || times.length !== frames) return null;
|
||||
const y = r.stdout as Buffer;
|
||||
const out: number[] = [];
|
||||
let prev = 0;
|
||||
for (let f = 1; f < frames; f++) {
|
||||
let sad = 0;
|
||||
for (let i = f * n, j = (f - 1) * n, e = i + n; i < e; i++, j++) sad += Math.abs(y[i] - y[j]);
|
||||
const mafd = sad / n;
|
||||
const score = Math.min(Math.max(Math.min(mafd, Math.abs(mafd - prev)) / 100, 0), 1);
|
||||
prev = mafd;
|
||||
if (score > threshold) out.push(ms(times[f]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** cutPlan and takeLevels over `io`, each take's levels kept for the run */
|
||||
export function timing({ at, engineRun, engineJson, isAudio }: TakeIO) {
|
||||
/** The take to read for timing: its light copy when raea cloud keeps one (.raea-cloud/proxies/NAME.mp4 in the project,
|
||||
* where the light copy goes once a render brings the original into footage/). Its words, pauses, level and jump cuts
|
||||
* are the original's, read in a fraction of the time (12-05: a 4K original's jump cuts took over 10 minutes of a box's
|
||||
* CPU, and a fix pass's `raea cut` ran out of time). */
|
||||
function lightOf(file: string): string {
|
||||
const name = basename(file).replace(/\.[^.]+$/, "");
|
||||
const kept = `${process.cwd()}/.raea-cloud/proxies/${name}.mp4`;
|
||||
return existsSync(kept) ? kept : file;
|
||||
}
|
||||
|
||||
/** A take's own jump cuts (raea media cuts, every frame decoded: 43 s for a 4-minute take on a box), found once per take
|
||||
* and kept by its path, size and time in raea's cache, so the second `raea cut` on a take doesn't decode it again
|
||||
* (12-04: three cuts on one take in a step ran past a box step's 3 minutes, and the run stopped with nothing made) */
|
||||
function jumpCuts(take: string): number[] {
|
||||
const file = lightOf(at(take));
|
||||
let kept = "";
|
||||
try {
|
||||
const s = statSync(file);
|
||||
const dir = `${process.env.XDG_CACHE_HOME || `${homedir()}/.cache`}/raea/cuts`;
|
||||
kept = `${dir}/${createHash("sha1").update(`${realpathSync(file)}|${s.size}|${s.mtimeMs}|0.08`).digest("hex")}.json`;
|
||||
if (existsSync(kept)) return JSON.parse(readFileSync(kept, "utf8")) as number[];
|
||||
} catch {
|
||||
kept = "";
|
||||
}
|
||||
const cuts = ffmpegCuts(file, 0.08) ?? (engineJson(["media", "cuts", file, "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
|
||||
if (kept)
|
||||
try {
|
||||
mkdirSync(dirname(kept), { recursive: true });
|
||||
writeFileSync(kept, JSON.stringify(cuts));
|
||||
} catch {
|
||||
// a cache that can't be written costs the next cut the decode, nothing else
|
||||
}
|
||||
return cuts;
|
||||
}
|
||||
|
||||
/** A take's sound level every 10 ms (raea media audio, 16 kHz mono), kept for this run */
|
||||
const heardLevels = new Map<string, Levels>();
|
||||
function takeLevels(take: string): Levels {
|
||||
const had = heardLevels.get(take);
|
||||
if (had) return had;
|
||||
const dir = mkdtempSync(`${tmpdir()}/raea-levels-`);
|
||||
try {
|
||||
const wav = `${dir}/take.wav`;
|
||||
engineRun(["media", "audio", lightOf(at(take)), "--rate", "16000", "--mono", "-o", wav]);
|
||||
const { pcm, rate } = wavSamples(readFileSync(wav));
|
||||
const l = { start: 0, db: levelsOf(pcm, rate) };
|
||||
heardLevels.set(take, l);
|
||||
return l;
|
||||
} catch {
|
||||
// a take with no sound to read is cut on its words alone
|
||||
return { start: 0, db: [] };
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Where to cut a take for each line (linesIn), timed by pace.ts in the quiet around each line's sound, a breath kept,
|
||||
* long pauses, fillers and false starts taken out (unless `keep`), then off the take's own jump cuts. Pieces in the
|
||||
* take's seconds, on the edit's frame grid. */
|
||||
function cutPlan(take: string, ws: Word[], lines: string[], o: PaceOptions, start: number): { pieces: Piece[]; trims: Trim[]; notes: string[] } {
|
||||
const { spans, notes } = linesIn(ws, lines);
|
||||
// a sound-only take has no jump cuts to keep off
|
||||
const cuts = isAudio(take) ? [] : jumpCuts(take);
|
||||
const { pieces, trims } = pace(ws, takeLevels(take), spans, o, start);
|
||||
const sf = 1 / (o.fps ?? 30);
|
||||
for (const p of pieces) {
|
||||
const [i, j] = p.words;
|
||||
// a jump cut in the take near a join: start one frame after it (or end one before), never on it, or the other
|
||||
// shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - p.from) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined && ca + sf > p.from) p.from = ms(Math.ceil((ca + sf) / sf) * sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - p.to) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined && cb - sf < p.to) p.to = ms(Math.floor((cb - sf) / sf) * sf);
|
||||
}
|
||||
return { pieces, trims, notes };
|
||||
}
|
||||
|
||||
return { cutPlan, takeLevels };
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// A take's faces from raea cloud's footage/faces.json, for raea cut's perception.json (native.ts perception)
|
||||
import { readFileSync } from "node:fs";
|
||||
import { basename, extname } from "node:path";
|
||||
|
||||
type Box = { x: number; y: number; w: number; h: number };
|
||||
|
||||
/** footage/faces.json in the project (raea cloud's prep: each take's faces about once a second, found on its farm, as
|
||||
* shares of the take's picture, [x, y, w, h, score] each), read once. A box has no raea-perceive, so a still per clip
|
||||
* found no face there and cost each `raea cut --append` every earlier clip's lookup again (12-05: a step of 13 cuts ran
|
||||
* past a box's 3 minutes, and no cut on a box had a face in its perception.json) */
|
||||
let facesKept: Record<string, { w?: number; h?: number; t?: number[]; s?: number[][][] }> | null | undefined;
|
||||
function facesFile() {
|
||||
if (facesKept === undefined)
|
||||
try {
|
||||
facesKept = JSON.parse(readFileSync(`${process.cwd()}/footage/faces.json`, "utf8"));
|
||||
} catch {
|
||||
facesKept = null;
|
||||
}
|
||||
return facesKept;
|
||||
}
|
||||
|
||||
/** The largest face at the sample of faces.json nearest `t` (never one more than 1.5 s away), with the take's size: a
|
||||
* face, none there (face undefined), or null when faces.json doesn't hold the take */
|
||||
export function faceKept(file: string, t: number): { face?: Box; sw: number; sh: number } | null {
|
||||
const take = facesFile()?.[basename(file, extname(file))];
|
||||
const ts = take?.t, ss = take?.s;
|
||||
if (!take || !Array.isArray(ts) || !Array.isArray(ss) || !ts.length || !take.w || !take.h) return null;
|
||||
let k = 0;
|
||||
ts.forEach((x, i) => {
|
||||
if (Math.abs(x - t) < Math.abs(ts[k] - t)) k = i;
|
||||
});
|
||||
if (Math.abs(ts[k] - t) > 1.5) return null;
|
||||
const faces = (ss[k] ?? []).filter((f) => Array.isArray(f) && f.length >= 4);
|
||||
if (!faces.length) return { sw: take.w, sh: take.h };
|
||||
const [x, y, w, h] = faces.reduce((a, b) => (b[2] * b[3] > a[2] * a[3] ? b : a));
|
||||
return { face: { x, y, w, h }, sw: take.w, sh: take.h };
|
||||
}
|
||||
+84
-40
@@ -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";
|
||||
|
||||
@@ -49,26 +49,54 @@ export interface Cut {
|
||||
line: string;
|
||||
/** a sound-only take's clip plays as <Audio> (#89); absent means video */
|
||||
kind?: "video" | "audio";
|
||||
/** what brings its speech to the cut's other lines (dB): raea cut evens them */
|
||||
gainDb?: number;
|
||||
/** it follows a clip of the same take with time skipped (a jump cut): the edit reframes it (punchIn(i)) */
|
||||
jump?: boolean;
|
||||
}
|
||||
|
||||
/** A cutaway: a picture laid over the join after clip `after`, `l` seconds over that clip's end (an L cut: its sound runs
|
||||
* on under the cutaway) and `j` over the next one's start (a J cut: that line's sound starts under it). */
|
||||
export interface Cutaway extends Cut {
|
||||
after: number;
|
||||
l: number;
|
||||
j: number;
|
||||
}
|
||||
|
||||
/** cuts.ts from the clips: data the edit imports (each take's file as a module, so the bundler finds the media). */
|
||||
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }): string {
|
||||
const files = [...new Set(clips.map((c) => c.file))];
|
||||
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }, cutaways: Cutaway[] = []): string {
|
||||
const files = [...new Set([...clips, ...cutaways].map((c) => c.file))];
|
||||
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.
|
||||
const more = (c: Cut) => `${c.gainDb ? `, gainDb: ${c.gainDb}` : ""}${c.jump ? ", jump: true" : ""}`;
|
||||
const row = (c: Cut) => `{ take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")}${more(c)} }`;
|
||||
const len = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
|
||||
// a cutaway's first frame in the edit: the end of the clip it lies over, less its L part
|
||||
const startOf = (x: Cutaway) => Math.max(0, clips.slice(0, x.after + 1).reduce((n, c) => n + len(c), 0) - Math.round(x.l * edit.fps));
|
||||
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds, timed by their sound (a breath at each join,
|
||||
// long pauses, fillers and false starts out), each one's gainDb evening its level with the others, and a jump cut (the
|
||||
// same take with time skipped) marked jump. Re-run raea cut to change them, or edit by hand (the edit reads only this
|
||||
// file). cuts.json beside it is the same list for raea's checks.
|
||||
${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 type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
export const cuts: Cut[] = [
|
||||
${rows.join("\n")}
|
||||
${clips.map((c) => ` ${row(c)},`).join("\n")}
|
||||
];
|
||||
/** pictures laid over a join, muted (the clips' sound runs under them): \`start\` is the edit's frame each begins at */
|
||||
export const cutaways: (Cut & { start: number })[] = [
|
||||
${cutaways.map((x) => ` { ...${row(x)}, start: ${startOf(x)} },`).join("\n")}
|
||||
];
|
||||
/** a clip's length in the edit's frames */
|
||||
export const frames = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
|
||||
/** the cuts end to end, in frames */
|
||||
export const total = cuts.reduce((n, c) => n + frames(c), 0);
|
||||
/** how far clip i is punched in: a jump cut alternates 1 and 1.15 along a run of them, so the picture reframes at each */
|
||||
export const punchIn = (i: number) => {
|
||||
let k = 0;
|
||||
for (let n = i; n > 0 && cuts[n]?.jump; n--) k++;
|
||||
return k % 2 ? 1.15 : 1;
|
||||
};
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -78,20 +106,17 @@ 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 the brand's site). edit.tsx loads them with the project's
|
||||
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and
|
||||
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg),
|
||||
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where
|
||||
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables
|
||||
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout
|
||||
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes
|
||||
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are
|
||||
a start, not a limit.
|
||||
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
|
||||
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
|
||||
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
|
||||
\`raea help\` lists the rest.
|
||||
by hand, or captions and checks lose their timing). It times each clip by its sound: a breath at each join, long
|
||||
pauses, fillers and false starts out, each clip's gainDb evening the voices, a jump cut marked for punchIn(i). components/: components you added (\`raea make component add\`), yours to change.
|
||||
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from its site), loaded with the project's
|
||||
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
|
||||
(text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
|
||||
font-brand-body) or --brand-* variables; never a colour from outside it. Size, weight, layout and motion are yours,
|
||||
chosen against the brand's own best work.
|
||||
- \`raea render edit.tsx -o final.mp4 --manifest render.json\` renders, then checks the export once as it ends
|
||||
(\`raea check\`: real faults only, each ERROR with its fix, kept as final.check.json; nothing runs it again). Fix the
|
||||
ERRORs; a warning is a note for the person. \`raea render edit.tsx --at 105 -o review/stills/\` gives frame 105 to
|
||||
look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); \`raea help\` lists the rest.
|
||||
|
||||
## raea (everything there is; import from "raea")
|
||||
|
||||
@@ -99,19 +124,21 @@ Time: useCurrentFrame() (frames, from 0 inside the nearest Sequence), useVideoCo
|
||||
durationInFrames}, interpolate(frame, [in...], [out...], {extrapolateLeft, extrapolateRight: "clamp", easing}),
|
||||
spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...).
|
||||
Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequence durationInFrames>, <Loop>, <Freeze>.
|
||||
Media: <Video src startFrom endAt volume playbackRate muted framing="face" punchIn style> (framing="face" keeps the
|
||||
eyes 38% down as the speaker moves; an objectPosition or transform turns it off), <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
||||
Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
|
||||
through components/Framed.tsx when the project has it (<Framed src startFrom endAt at? punchIn?>: the crop on the
|
||||
person's face, from footage/faces.json; at picks a face), else an objectPosition you
|
||||
measured on the take, never a guess. A cut of footage is composed whole with components/Cut.tsx when the project
|
||||
has it: <Cut moments={fromCuts(cuts, edit.fps, punchIn)} said={words.json} keys? hook? bed? />, each moment's show
|
||||
(speaker, two, product, broll, screen, wide, end) and who, asset or cta set by you; it frames, splits, places the
|
||||
product clear of faces, captions every word, lays the music bed under the voices at the level the check wants, and ends on the brand's card. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
||||
<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, score, effects); music,
|
||||
where there is some, in Tone.js (import * as Tone from "raea/tone"), composed for the cut (a motif, chords that move,
|
||||
a part with rhythm, ending on a cut; never a pad or drone by default): instruments in a Tone.Sampler playing Parts and
|
||||
Sequences, the notes from a sample library (\`raea make sounds\`, \`raea guide sources\`) or, for a timbre no library has,
|
||||
Tone.tokensynth("a bowed saw, close", ["C3", "C4", "C5"]); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
|
||||
is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
|
||||
"./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: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and
|
||||
the platforms' buttons; useRegion() gives its box.
|
||||
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.
|
||||
`;
|
||||
@@ -199,8 +226,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");
|
||||
@@ -276,12 +313,19 @@ export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
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");
|
||||
const num = (name: string) => {
|
||||
const v = flag(args, name);
|
||||
return v === undefined || !Number.isFinite(Number(v)) ? undefined : Number(v);
|
||||
};
|
||||
const [take, ...lines] = clean(args.slice(1), "--at", "--j", "--breath");
|
||||
const cutaway = args.includes("--cutaway");
|
||||
if (!take || (!lines.length && !spans.length) || (cutaway && !spans.length))
|
||||
return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append] [--cutaway [--j S]] [--breath S] [--keep-pauses] [--no-gain]\n`);
|
||||
// a cutaway lies over the cut there is: it always appends
|
||||
const saved: { cuts?: Cut[]; cutaways?: Cutaway[] } = (args.includes("--append") || cutaway) && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")) : {};
|
||||
const r = ask("cut", { take, lines, spans, keep: saved.cuts ?? [], cutaways: saved.cutaways ?? [], cutaway, j: num("--j"), breath: num("--breath"), keepPauses: args.includes("--keep-pauses"), gain: !args.includes("--no-gain") }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; cutaways: Cutaway[]; words: unknown[]; perception?: unknown; said: string };
|
||||
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit, r.cutaways));
|
||||
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts, ...(r.cutaways.length ? { cutaways: r.cutaways } : {}) }, null, 2) + "\n");
|
||||
await c.fs.writeFile(p("words.json"), JSON.stringify(r.words) + "\n");
|
||||
// where the face and the safe band are in the edit, for <Region> and the checks (a host may not see faces)
|
||||
if (r.perception) await c.fs.writeFile(p("perception.json"), JSON.stringify(r.perception) + "\n");
|
||||
|
||||
@@ -37,9 +37,8 @@ pub fn main() -> i32 {
|
||||
}
|
||||
};
|
||||
match args.first().map(String::as_str) {
|
||||
// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3
|
||||
// (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: `check` here)
|
||||
Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") && raea_app_direction::check::of_video(&args[1..]) => raea_app_check::cli_with(&args[1..], Vec::new()),
|
||||
// `floor VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3, as raea check's floor pack reads them
|
||||
Some("floor") => raea_app_check::cli_with(&args[1..], Vec::new()),
|
||||
// `ci …`: the gates' sound measurements and lightspeed's process measurements
|
||||
Some("ci") => raea_app_ci::cli(&args[1..]),
|
||||
_ => {
|
||||
|
||||
+90
-83
@@ -10,6 +10,9 @@ import { basename, delimiter, dirname, extname } from "node:path";
|
||||
import { brandKit, pixelsOf } from "./brand";
|
||||
import { readSite, stylesOf } from "./scrape";
|
||||
import { wordsOf } from "./heard";
|
||||
import { evenLevels, unsqueezed, linesIn, markJumps, speechOf, toSound, type PaceOptions } from "./pace";
|
||||
import { timing } from "./cutplan";
|
||||
import { faceKept } from "./faces";
|
||||
import { harness, library, show, task } from "./app";
|
||||
import { fromCwd } from "./show";
|
||||
import { clothesHost } from "./wardrobe";
|
||||
@@ -43,17 +46,21 @@ 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 */
|
||||
/** Every take under media/ and footage/ (not footage/originals/, which the render reads in its light copies' place): its
|
||||
* path from the project's root */
|
||||
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);
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "footage/originals") walk(p);
|
||||
} else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
|
||||
}
|
||||
};
|
||||
// media/ is a project's own; footage/ is what raea cloud fetched (its light copies: originals/ follow on their own)
|
||||
walk("media");
|
||||
walk("footage");
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
@@ -63,7 +70,7 @@ function takeOf(name: string): string {
|
||||
const all = takes();
|
||||
const bare = (p: string) => p.slice(0, p.length - extname(p).length);
|
||||
const found = all.find((p) => p === t || bare(p) === t) ?? all.find((p) => basename(p) === t || basename(bare(p)) === t || p.endsWith(`/${t}`) || p.includes(`${t}/`));
|
||||
if (!found) throw new Error(`no take "${name}" under media/ (${all.join(", ") || "none"})`);
|
||||
if (!found) throw new Error(`no take "${name}" under media/ or footage/ (${all.join(", ") || "none"})`);
|
||||
return found;
|
||||
}
|
||||
|
||||
@@ -84,9 +91,11 @@ function words(take: string, hear = false): Word[] {
|
||||
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 }));
|
||||
return unsqueezed(
|
||||
(JSON.parse(readFileSync(file, "utf8")) as { text: string; start_ms: number; end_ms: number }[])
|
||||
.filter((w) => w.text?.trim())
|
||||
.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 })),
|
||||
);
|
||||
}
|
||||
|
||||
/** A tool a clean Mac lacks, found or installed once by raea's tools/ensure.sh (docs/app.feature AP6), which sits in
|
||||
@@ -118,107 +127,103 @@ function hearTake(take: string, out: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Where to cut a take for each line: found word for word in its transcript, in order (a line that follows the last one
|
||||
* in the take joins its clip), else where 70% of its words are said in a window its length (and a note says so); each
|
||||
* cut inside the pauses around it, off the take's own jump cuts, on the take's frame grid. [from, to, said] in the
|
||||
* take's seconds. */
|
||||
function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, number, string][]; notes: string[] } {
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "");
|
||||
const toks = ws.map((w) => norm(w.text).trim());
|
||||
// a sound-only take has no jump cuts to keep off, and its grid is the edit's usual 30 (a probe has no video fps)
|
||||
const cuts = isAudio(take) ? [] : (engineJson(["media", "cuts", at(take), "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
|
||||
const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
|
||||
let from = 0;
|
||||
const spans: [number, number][] = [];
|
||||
const notes: string[] = [];
|
||||
lines.forEach((line, k) => {
|
||||
const want = norm(line).split(/\s+/).filter(Boolean);
|
||||
if (!want.length) throw new Error(`line ${k + 1} is empty`);
|
||||
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
|
||||
const close = () => {
|
||||
const n = want.length;
|
||||
if (n < 3 || toks.length < n) return undefined;
|
||||
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
|
||||
let best = 0;
|
||||
for (let i = 1; i <= toks.length - n; i++) {
|
||||
const [s, b] = [score(i), score(best)];
|
||||
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
|
||||
}
|
||||
return score(best) * 10 >= n * 7 ? best : undefined;
|
||||
};
|
||||
let exact: number | undefined;
|
||||
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
const i = exact ?? close();
|
||||
if (i === undefined) {
|
||||
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(n, n + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
|
||||
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
}
|
||||
const j = Math.min(i + want.length - 1, toks.length - 1);
|
||||
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(i, j + 1).map((w) => w.text).join(" ")}"`);
|
||||
from = j + 1;
|
||||
const last = spans[spans.length - 1];
|
||||
if (last && last[1] + 1 === i) last[1] = j;
|
||||
else spans.push([i, j]);
|
||||
});
|
||||
const sf = 1 / fps;
|
||||
const plan = spans.map(([i, j], k): [number, number, string] => {
|
||||
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
|
||||
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
|
||||
// transcript word ends run early: a generous tail (more on the last line), a short lead-in, both inside the pause
|
||||
let a = ws[i].from - Math.min(before * 0.6, 0.12);
|
||||
let b = ws[j].to + Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22);
|
||||
// a jump cut in the take near a join: start one take frame after it (or end one before), never on it, or the
|
||||
// other shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - a) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined) a = Math.max(a, ca + sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - b) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined) b = Math.min(b, cb - sf);
|
||||
return [Math.ceil(Math.max(a, 0) * fps) / fps, Math.floor(b * fps) / fps, ws.slice(i, j + 1).map((w) => w.text).join(" ")];
|
||||
});
|
||||
return { plan, notes };
|
||||
}
|
||||
// how each line is timed (cutplan.ts): the light copy, the take's jump cuts and sound level, pace.ts
|
||||
const { cutPlan, takeLevels } = timing({ at, engineRun, engineJson, isAudio });
|
||||
|
||||
/** 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" };
|
||||
type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
/** a cutaway: a picture laid over the join after clip `after` (its index in the cut), `l` seconds over that clip's end
|
||||
* (its sound runs on under it: an L cut) and `j` over the next one's start (whose sound starts under it: a J cut) */
|
||||
type Cutaway = Clip & { after: number; l: number; j: number };
|
||||
|
||||
/** `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[] }) {
|
||||
/** how `raea cut` is asked to cut */
|
||||
type CutAsk = { take: string; lines: string[]; spans: number[][]; keep: Clip[]; cutaways?: Cutaway[]; cutaway?: boolean; j?: number; breath?: number; keepPauses?: boolean; gain?: boolean };
|
||||
|
||||
/** A take's words with their edges on their sound (pace.ts toSound): for the timeline's words, and a clip's level */
|
||||
function heardWords(file: string): Word[] {
|
||||
return toSound(words(file), takeLevels(file));
|
||||
}
|
||||
|
||||
/** `raea cut`'s host step: the clips for the lines (or --at spans) paced (pace.ts), their levels evened and jump cuts
|
||||
* marked, the words in the edit's frames, and what was cut */
|
||||
function cut(a: CutAsk) {
|
||||
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[] = [];
|
||||
let clips: Clip[] = [...a.keep];
|
||||
const cutaways: Cutaway[] = [...(a.cutaways ?? [])];
|
||||
const seconds = (cs: Clip[]) => cs.reduce((n, c) => n + framesOf(c.from, c.to, edit.fps), 0) / edit.fps;
|
||||
// the breath kept at a join: 40% before a line's first sound, 60% after its last
|
||||
const b = a.breath;
|
||||
const o: PaceOptions = { fps: edit.fps, keepPauses: a.keepPauses, ...(b !== undefined ? { lead: b * 0.4, tail: b * 0.6, sentence: b * 0.6 + 0.08 } : {}) };
|
||||
const notes: string[] = [];
|
||||
let trims: Trim[] = [];
|
||||
let before = 0;
|
||||
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 r = cutPlan(file, words(file, true), a.lines, o, seconds(clips));
|
||||
notes.push(...r.notes);
|
||||
trims = r.trims;
|
||||
// what the lines would have run to cut as said, from each one's first word to its last
|
||||
const ws = heardWords(file);
|
||||
before = linesIn(ws, a.lines).spans.reduce((n, [i, j]) => n + ws[j].to - ws[i].from + 0.4, 0);
|
||||
for (const p of r.pieces) {
|
||||
clips.push({ take: stem, file, from: ms(p.from), to: ms(p.to), line: p.line, kind });
|
||||
if (p.tight) notes.push(`"${p.line.slice(0, 40)}" has no pause at one end (its words run on): that end is cut between two words; look at it`);
|
||||
}
|
||||
}
|
||||
const { 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(" ");
|
||||
if (a.cutaway) {
|
||||
const k = clips.length - 1;
|
||||
if (k < 0) throw new Error("a cutaway is laid over the cut's clips: cut a line first, then the cutaway with --append");
|
||||
const j = Math.min(Math.max(a.j ?? 0, 0), to - from);
|
||||
const l = ms(to - from - j);
|
||||
if (l > clips[k].to - clips[k].from) throw new Error(`the cutaway runs ${l.toFixed(2)} s over the last clip's end, and it's ${(clips[k].to - clips[k].from).toFixed(2)} s long: give it less, or --j to put some over the next line`);
|
||||
cutaways.push({ take: stem, file, from: ms(from), to: ms(to), line: "", kind: "video", after: k, l, j: ms(j) });
|
||||
continue;
|
||||
}
|
||||
const line = heardWords(file).filter((w) => w.from >= from - 0.02 && w.to <= to + 0.08).map((w) => w.text).join(" ");
|
||||
clips.push({ take: stem, file, from: ms(from), to: ms(to), line, kind });
|
||||
}
|
||||
// the words in the edit's frames, for captions (useWords())
|
||||
// a jump cut is hidden by a cutaway over its join; the rest are marked for the edit to reframe
|
||||
clips = markJumps(clips, edit.fps).map((c, k) => (c.jump && cutaways.some((x) => x.after === k - 1) ? (({ jump: _, ...r }) => r)(c) : c));
|
||||
if (a.gain !== false)
|
||||
clips = evenLevels(clips, (c) => {
|
||||
const inside = heardWords(c.file).filter((w) => w.to > c.from && w.from < c.to).map((w) => ({ ...w, from: Math.max(w.from, c.from), to: Math.min(w.to, c.to) }));
|
||||
return inside.length ? { db: speechOf(takeLevels(c.file), inside), seconds: inside.reduce((n, w) => n + w.to - w.from, 0) } : null;
|
||||
});
|
||||
// the words in the edit's frames, for captions (useWords()): each word that sounds inside its clip
|
||||
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}"`);
|
||||
for (const w of heardWords(c.file)) if ((w.from + w.to) / 2 >= c.from && (w.from + w.to) / 2 <= c.to) timeline.push({ text: w.text, from: Math.max(f(w.from), t), to: Math.max(Math.min(f(w.to), t + n), Math.max(f(w.from), t) + 1) });
|
||||
const marks = [c.jump ? "jump" : "", c.gainDb ? `${c.gainDb > 0 ? "+" : ""}${c.gainDb} dB` : ""].filter(Boolean).join(", ");
|
||||
said.push(`${String(k + 1).padStart(2)} ${(t / edit.fps).toFixed(2).padStart(5)}-${((t + n) / edit.fps).toFixed(2).padStart(5)} s ${c.take} "${c.line}"${marks ? ` (${marks})` : ""}`);
|
||||
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") };
|
||||
for (const x of cutaways) said.push(` cutaway ${x.take} ${x.from.toFixed(2)}-${x.to.toFixed(2)} s over the join after clip ${x.after + 1}: ${x.l.toFixed(2)} s before it${x.j ? `, ${x.j.toFixed(2)} s after` : ""}`);
|
||||
const cutOut = trims.filter((x) => x.kind !== "pause");
|
||||
const pauses = trims.filter((x) => x.kind === "pause");
|
||||
const paced = [
|
||||
pauses.length ? `${pauses.length} long pause${pauses.length === 1 ? "" : "s"} cut to a breath (${pauses.reduce((n, x) => n + x.seconds, 0).toFixed(1)} s out)` : "",
|
||||
...cutOut.map((x) => `${x.kind} "${x.said}" at ${x.at.toFixed(2)} s out`),
|
||||
].filter(Boolean);
|
||||
const head = `cuts.ts: ${clips.length} clips, ${(t / edit.fps).toFixed(1)} s (${t} frames at ${edit.fps} fps)${before ? `; the lines as said ran ${before.toFixed(1)} s` : ""}; words.json for captions`;
|
||||
const tail = [
|
||||
...(paced.length ? [`paced: ${paced.join("; ")} (--keep-pauses keeps them)`] : []),
|
||||
...(clips.some((c) => c.jump) ? ["jump: a clip marked jump follows the same take with its time skipped: reframe it (punchIn(i) in cuts.ts), or lay a cutaway over the join"] : []),
|
||||
];
|
||||
return { edit, cuts: clips, cutaways, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...tail, ...notes.map((n) => `note: ${n}`)].join("\n") };
|
||||
}
|
||||
|
||||
/** raea-perceive, as `raea song` finds it (raea-io-assets perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
|
||||
@@ -273,8 +278,10 @@ function perception(edit: { width: number; height: number; fps: number }, clips:
|
||||
if (!seen.has(key)) {
|
||||
let face: Box | undefined;
|
||||
try {
|
||||
const f = faceAt(c.file, mid);
|
||||
const { sw, sh } = probeOf(c.file);
|
||||
// faces.json's when it holds the take, else a still of it read here
|
||||
const kept = faceKept(c.file, mid);
|
||||
const f = kept ? kept.face : faceAt(c.file, mid);
|
||||
const { sw, sh } = kept ?? probeOf(c.file);
|
||||
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];
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
// The timing of `raea cut` (12-05, Shane: "when we assemble the clips or video footage we should be hyper focused on
|
||||
// framing and timing. both seem to go wayside or not even done ... it could be done procedurally"). The agent chooses
|
||||
// the lines and their order; this times them, from the take's words and its sound level every 10 ms, as a short-form
|
||||
// editor would (auto-editor's dead-space pass, a breath kept at each join, loudness matched per line):
|
||||
//
|
||||
// toSound each word's edges moved onto its sound: a transcriber's word times run into the pauses around it
|
||||
// (parakeet's 80 ms frames: "question?" timed 2.88-4.16 s and said 2.63-3.18 s), so a cut on them keeps
|
||||
// dead air, and captions show a word after it's said
|
||||
// joins every cut point sits in quiet by the sound check's own measure (sdk/goal packs/sound.ts: 18 dB under the
|
||||
// line's speech, or within 6 dB of a street's floor), a breath kept: ~0.06 s before a line's first sound,
|
||||
// ~0.10 s after its last (0.18 s after a sentence's end), so the join between two lines is ~0.16-0.24 s
|
||||
// pauses a pause inside a line longer than 0.45 s (0.3 s in the cut's first 3 s, the hook) is cut down to a breath
|
||||
// fillers "um", "uh" and a false start ("I I think": the first "I") come out, only with quiet on both sides
|
||||
// level each clip's gainDb brings its speech to the cut's median (the sound check errs at 6 dB apart)
|
||||
// jump a clip that follows one of the same take with its time skipped is marked jump: the edit reframes it
|
||||
//
|
||||
// Pure: native.ts reads the words and levels and writes cuts.ts.
|
||||
|
||||
/** a word in its take's seconds */
|
||||
export type Word = { text: string; from: number; to: number };
|
||||
|
||||
/** A transcript's words less the runs it squeezed: three or more words each SQUEEZED s long or less, all starting within
|
||||
* 50 ms of the first. No one says three words in 50 ms; a transcriber writes them when it hears a phrase twice and
|
||||
* times the copy at one instant (12-05, run 28: Body Shop's "Sign up for the news, sign up for the newsletter" came
|
||||
* as "Sign up for the news sign up for the newsletter" with "up for the news sign" all at 10.32-10.34 s, raea cut took
|
||||
* the line from that "sign", and the CTA clip started inside "up") */
|
||||
export const SQUEEZED = 0.03;
|
||||
export function unsqueezed<W extends Word>(ws: W[]): W[] {
|
||||
const out: W[] = [];
|
||||
for (let i = 0; i < ws.length; ) {
|
||||
let j = i;
|
||||
while (j < ws.length && ws[j].to - ws[j].from <= SQUEEZED && ws[j].from - ws[i].from <= 0.05) j++;
|
||||
if (j - i >= 3) i = j;
|
||||
else out.push(ws[i++]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/** a take's sound level every 10 ms (dB), from `start` seconds */
|
||||
export type Levels = { start: number; db: number[] };
|
||||
/** a stretch of quiet in a take: from its first quiet 10 ms to the first sound after it (s) */
|
||||
export type Gap = { from: number; to: number };
|
||||
|
||||
export interface PaceOptions {
|
||||
/** the edit's frame rate: every cut point lands on its grid (30) */
|
||||
fps?: number;
|
||||
/** what's kept before a line's first sound (s): 0.06 */
|
||||
lead?: number;
|
||||
/** what's kept after a line's last sound (s): 0.10, so a join keeps ~0.16 s of breath */
|
||||
tail?: number;
|
||||
/** after a sentence's end (. ? !): 0.18 */
|
||||
sentence?: number;
|
||||
/** a pause inside a line longer than this is cut down to a breath (s): 0.45 */
|
||||
pause?: number;
|
||||
/** in the cut's first `hook` seconds: 0.3 */
|
||||
hookPause?: number;
|
||||
hook?: number;
|
||||
/** pauses inside lines, fillers and false starts left as they are */
|
||||
keepPauses?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULTS = { fps: 30, lead: 0.06, tail: 0.1, sentence: 0.18, pause: 0.45, hookPause: 0.3, hook: 3, keepPauses: false };
|
||||
|
||||
/** as the sound check measures (packs/sound.ts): speech is its loud 10 ms frames (90th percentile), a take's floor its
|
||||
* quietest (10th), and quiet is 18 dB under the speech, or within 6 dB of the floor, never closer than 8 to the speech */
|
||||
const SPEECH_Q = 0.9;
|
||||
const FLOOR_Q = 0.1;
|
||||
export const quietUnder = (floor: number, ref: number) => Math.min(ref - 8, Math.max(ref - 18, floor + 6));
|
||||
/** the fewest quiet frames that make a gap: a cut point needs 20 ms of quiet either side (the check's 40 ms peak) */
|
||||
const LEAST = 5;
|
||||
/** a word's edge is moved onto its sound past this much quiet (s): a shorter quiet is a stop inside the word */
|
||||
const TRIM = 0.12;
|
||||
/** the least speech a clip cut out of a line holds (s): shorter, it joins its neighbour and keeps the pause */
|
||||
const MIN_RUN = 0.8;
|
||||
/** the least quiet after a word that is a pause a line can end in (s): shorter is a breath inside a sentence */
|
||||
const PAUSE_MIN = 0.15;
|
||||
/** the least speech a clip's level is measured on (s), and the most gain evening gives (dB) */
|
||||
const MEASURE = 1;
|
||||
const MOST_GAIN = 9;
|
||||
|
||||
export const pct = (xs: number[], q: number) => {
|
||||
if (!xs.length) return -100;
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s[Math.min(s.length - 1, Math.floor(q * s.length))];
|
||||
};
|
||||
const idx = (l: Levels, t: number) => Math.round((t - l.start) * 100);
|
||||
const dbAt = (l: Levels, i: number) => l.db[i] ?? -100;
|
||||
const span = (l: Levels, a: number, b: number) => l.db.slice(Math.max(0, idx(l, a)), Math.max(0, idx(l, b)));
|
||||
|
||||
/** speech's level over words: their loud frames */
|
||||
export function speechOf(l: Levels, ws: Word[]): number {
|
||||
return pct(ws.flatMap((w) => span(l, w.from, w.to)), SPEECH_Q);
|
||||
}
|
||||
|
||||
/** the level under which a stretch around [a, b] is quiet, for speech at `ref` */
|
||||
export function underAt(l: Levels, a: number, b: number, ref: number): number {
|
||||
return quietUnder(pct(span(l, a - 0.5, b + 0.5), FLOOR_Q), ref);
|
||||
}
|
||||
|
||||
/** the quiet stretches of LEAST frames or more in [a, b] */
|
||||
export function gapsIn(l: Levels, under: number, a: number, b: number): Gap[] {
|
||||
const out: Gap[] = [];
|
||||
let run = -1;
|
||||
const i0 = Math.max(0, idx(l, a));
|
||||
const i1 = Math.min(l.db.length, idx(l, b));
|
||||
for (let i = i0; i <= i1; i++) {
|
||||
const quiet = i < i1 && dbAt(l, i) <= under;
|
||||
if (quiet && run < 0) run = i;
|
||||
if (!quiet && run >= 0) {
|
||||
if (i - run >= LEAST) out.push({ from: l.start + run / 100, to: l.start + i / 100 });
|
||||
run = -1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const r3 = (t: number) => Math.round(t * 1000) / 1000;
|
||||
|
||||
/** words with their edges moved onto their sound: a word's start later past quiet it was timed into, its end earlier;
|
||||
* never shorter than 80 ms (a word the levels don't hear keeps its times). Speech is each word's neighbourhood's. */
|
||||
export function toSound(ws: Word[], l: Levels): Word[] {
|
||||
if (!l.db.length) return ws.map((w) => ({ ...w }));
|
||||
return ws.map((w) => {
|
||||
const ref = pct(span(l, w.from - 1, w.to + 1), SPEECH_Q);
|
||||
const under = underAt(l, w.from, w.to, ref);
|
||||
const loud = (i: number) => dbAt(l, i) > under;
|
||||
let a = idx(l, w.from);
|
||||
let b = idx(l, w.to) - 1;
|
||||
let a1 = a;
|
||||
while (a1 <= b && !loud(a1)) a1++;
|
||||
let b1 = b;
|
||||
while (b1 >= a1 && !loud(b1)) b1--;
|
||||
const at = (i: number, k: number) => ({ text: w.text, from: r3(l.start + i / 100), to: r3(l.start + k / 100) });
|
||||
// under 80 ms of sound: a word timed past its sound (parakeet put "that?" at 23.68-24.40 s, said by 23.68), so it
|
||||
// sits on the sound it has, or the sound it touches; a word with neither keeps its times (whispered, or masked)
|
||||
if (b1 - a1 < 7) {
|
||||
if (b1 >= a1) return at(Math.max(a, a1 - 2), Math.min(b + 1, Math.max(b1 + 3, a1 + 8)));
|
||||
if (loud(a - 1)) return at(a, Math.min(b + 1, a + 8));
|
||||
if (loud(b + 1)) return at(Math.max(a, b - 7), b + 1);
|
||||
return { ...w };
|
||||
}
|
||||
// a stretch of quiet shorter than TRIM at an edge is the word's own (a stop, a soft consonant): kept
|
||||
if ((a1 - a) / 100 >= TRIM) a = a1 - 2;
|
||||
if ((b - b1) / 100 >= TRIM) b = b1 + 2;
|
||||
return { text: w.text, from: r3(l.start + a / 100), to: r3(l.start + (b + 1) / 100) };
|
||||
});
|
||||
}
|
||||
|
||||
const FILLERS = new Set(["um", "umm", "uh", "uhm", "uhh", "erm", "er", "ah", "hmm", "mm", "mhm"]);
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "");
|
||||
const endsSentence = (s: string) => /[.?!]["')\]]*$/.test(s.trim());
|
||||
|
||||
/** a stretch of a take a cut keeps: its words [first, last] (indexes into the take's words) and its in and out (s) */
|
||||
export type Piece = { words: [number, number]; from: number; to: number; line: string; jump?: boolean; gainDb?: number; tight?: boolean };
|
||||
|
||||
/** What's cut out of a line, said: a filler or a false start, or a pause made shorter. */
|
||||
export type Trim = { kind: "filler" | "false start" | "pause"; at: number; seconds: number; said: string };
|
||||
|
||||
/** The pieces a run of lines keeps, in order, each line given as its words [first, last] in the take, timed as above;
|
||||
* `start` is where the first of them lands in the edit (s), for the hook's tighter pauses. */
|
||||
export function pace(ws0: Word[], l: Levels, lines: [number, number][], o: PaceOptions = {}, start = 0): { pieces: Piece[]; trims: Trim[] } {
|
||||
const p = { ...DEFAULTS, ...o };
|
||||
const ws = toSound(ws0, l);
|
||||
const n = ws.length;
|
||||
const trims: Trim[] = [];
|
||||
const pieces: Piece[] = [];
|
||||
let t = start;
|
||||
const grid = (x: number, lo: number, hi: number) => {
|
||||
// the edit's frame nearest x that keeps inside [lo, hi], else the nearest frame
|
||||
const f = x * p.fps;
|
||||
const c = [Math.round(f), Math.floor(f), Math.ceil(f)].map((k) => k / p.fps).filter((v) => v >= lo - 1e-6 && v <= hi + 1e-6);
|
||||
return r3(c.length ? c[0] : Math.round(f) / p.fps);
|
||||
};
|
||||
for (const [i, j0] of lines) {
|
||||
const ref = speechOf(l, ws.slice(i, j0 + 1));
|
||||
const under = underAt(l, ws[i].from, ws[j0].to, ref);
|
||||
const mid = (w: Word) => Math.min(0.1, (w.to - w.from) / 2);
|
||||
/** the quiet between word k and k + 1 (k = -1: before the first; k = n - 1: after the last): the longest stretch */
|
||||
const gapAfter = (k: number): Gap | null => {
|
||||
const a = k < 0 ? Math.max(0, ws[0].from - 1) : ws[k].to - mid(ws[k]);
|
||||
const b = k + 1 >= n ? ws[n - 1].to + 1 : ws[k + 1].from + mid(ws[k + 1]);
|
||||
const gs = gapsIn(l, under, a, b);
|
||||
if (!gs.length) return null;
|
||||
if (k < 0) return gs[gs.length - 1];
|
||||
if (k + 1 >= n) return gs[0];
|
||||
return gs.reduce((x, y) => (y.to - y.from > x.to - x.from ? y : x));
|
||||
};
|
||||
// a cut between two words with no quiet between: halfway between their sounds, never past the transcript's own
|
||||
// boundary (12-05: "delivered" and "for" touched at 99.12 s, the halfway of their sounds was 99.20 s, and the clip
|
||||
// ended inside "for")
|
||||
const seam = (k: number) => {
|
||||
if (k < 0) return r3(Math.max(0, ws[0].from - 0.02));
|
||||
if (k + 1 >= n) return r3(ws[n - 1].to + 0.02);
|
||||
const mid = (ws[k].to + ws[k + 1].from) / 2;
|
||||
const [lo, hi] = [ws0[k].to, ws0[k + 1].from];
|
||||
if (lo > hi) return r3(hi);
|
||||
// the quietest 10 ms between them, the nearest the middle on a tie: two words with no pause between still dip
|
||||
// somewhere, and a cut halfway can land on the first one's tail (12-05: "platform." ran on to "Yeah" with no
|
||||
// quiet, and the cut halfway was 5 dB under the speech, the word's tail cut)
|
||||
let best = Math.min(hi, Math.max(lo, mid));
|
||||
let low = Infinity;
|
||||
for (let i = idx(l, lo); i <= idx(l, hi); i++) {
|
||||
const t = l.start + i / 100;
|
||||
const d = dbAt(l, i);
|
||||
if (d < low - 0.5 || (Math.abs(d - low) <= 0.5 && Math.abs(t - mid) < Math.abs(best - mid))) {
|
||||
if (d < low - 0.5) low = d;
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
return r3(Math.min(hi, Math.max(lo, best)));
|
||||
};
|
||||
// a line that stops mid-sentence with no quiet after it ends where its sentence does, when that's three words or
|
||||
// fewer and 0.8 s away (12-05: "...and get them delivered" ran straight into "for free?")
|
||||
const pausesAfter = (k: number) => {
|
||||
const g = gapAfter(k);
|
||||
return !!g && g.to - g.from >= PAUSE_MIN;
|
||||
};
|
||||
let j = j0;
|
||||
if (!endsSentence(ws[j].text) && !pausesAfter(j))
|
||||
for (let e = j + 1; e < n && e <= j + 3 && ws[e].to - ws[j].to <= 0.8; e++)
|
||||
if (endsSentence(ws[e].text) && pausesAfter(e)) {
|
||||
j = e;
|
||||
break;
|
||||
}
|
||||
// where to cut in before word k, and out after word k: in the quiet beside it, a breath from its sound
|
||||
// never into the transcript's neighbour word, on the frame grid: the check reads the transcript's word times, so a
|
||||
// cut in a short quiet its words don't have lands inside a word for it (12-05: "for" at 99.12 s, the cut at 99.20 s)
|
||||
// and holding its own word whole by the transcript too (12-05: "Available" 171.84-172.24 s by its words, its sound
|
||||
// over by 172.0 s, the cut at 172.03 s: inside the word for the check)
|
||||
const fl = (t: number) => Math.floor(t * p.fps + 1e-6) / p.fps;
|
||||
const ce = (t: number) => Math.ceil(t * p.fps - 1e-6) / p.fps;
|
||||
const notBefore = (k: number, at: number) => r3(Math.max(Math.min(at, fl(ws0[k].from)), k > 0 ? ce(ws0[k - 1].to) : 0));
|
||||
const notAfter = (k: number, at: number) => r3(Math.min(Math.max(at, ce(ws0[k].to)), k + 1 < n ? fl(ws0[k + 1].from) : Infinity));
|
||||
const cutIn = (k: number) => {
|
||||
const g = gapAfter(k - 1);
|
||||
if (!g) return { at: notBefore(k, grid(seam(k - 1), 0, Infinity)), tight: true };
|
||||
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
|
||||
return { at: notBefore(k, grid(Math.min(hi, Math.max(lo, g.to - p.lead)), lo, hi)), tight: false };
|
||||
};
|
||||
const cutOut = (k: number) => {
|
||||
const g = gapAfter(k);
|
||||
if (!g) return { at: notAfter(k, grid(seam(k), 0, Infinity)), tight: true };
|
||||
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
|
||||
const keep = endsSentence(ws[k].text) ? p.sentence : p.tail;
|
||||
return { at: notAfter(k, grid(Math.min(hi, Math.max(lo, g.from + keep)), lo, hi)), tight: false };
|
||||
};
|
||||
// the words kept: fillers and false starts with quiet both sides come out
|
||||
const keep = new Array<boolean>(j - i + 1).fill(true);
|
||||
const quietBoth = (a: number, b: number) => (a === i || gapAfter(a - 1) !== null) && (b === j || gapAfter(b) !== null);
|
||||
if (!p.keepPauses) {
|
||||
for (let k = i; k <= j; k++) {
|
||||
if (FILLERS.has(norm(ws[k].text)) && j > i && quietBoth(k, k)) {
|
||||
keep[k - i] = false;
|
||||
trims.push({ kind: "filler", at: ws[k].from, seconds: r3(ws[k].to - ws[k].from), said: ws[k].text });
|
||||
}
|
||||
}
|
||||
for (let k = i; k <= j; k++)
|
||||
for (let m = 1; m <= 3 && k + 2 * m - 1 <= j; m++) {
|
||||
const same = Array.from({ length: m }, (_, q) => norm(ws[k + q].text) === norm(ws[k + m + q].text) && norm(ws[k + q].text) !== "").every(Boolean);
|
||||
if (same && keep[k - i] && quietBoth(k, k + m - 1)) {
|
||||
for (let q = 0; q < m; q++) keep[k + q - i] = false;
|
||||
trims.push({ kind: "false start", at: ws[k].from, seconds: r3(ws[k + m - 1].to - ws[k].from), said: ws.slice(k, k + m).map((w) => w.text).join(" ") });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// runs of kept words, split again at a long pause (shorter in the hook: the cut's first seconds)
|
||||
const runs: [number, number][] = [];
|
||||
const paused = new Map<number, Trim>(); // the pause after word k, cut down
|
||||
for (let k = i; k <= j; k++) {
|
||||
if (!keep[k - i]) continue;
|
||||
const last = runs[runs.length - 1];
|
||||
const cut = last && last[1] === k - 1 && !p.keepPauses ? long(k - 1, t + ws[k - 1].to - ws[i].from) : null;
|
||||
if (last && last[1] === k - 1 && !cut) last[1] = k;
|
||||
else {
|
||||
if (cut) paused.set(k - 1, cut);
|
||||
runs.push([k, k]);
|
||||
}
|
||||
}
|
||||
// a run under MIN_RUN of speech would flick by as a clip of its own (12-05: "Available", 0.47 s between two cut
|
||||
// pauses): it keeps a pause and joins its neighbour across the shorter one
|
||||
for (let r = 0; r < runs.length && runs.length > 1; r++) {
|
||||
const [a, b] = runs[r];
|
||||
if (ws[b].to - ws[a].from >= MIN_RUN) continue;
|
||||
const left = r > 0 && runs[r - 1][1] === a - 1 ? paused.get(a - 1) : undefined;
|
||||
const right = r + 1 < runs.length && runs[r + 1][0] === b + 1 ? paused.get(b) : undefined;
|
||||
if (!left && !right) continue;
|
||||
if (left && (!right || left.seconds <= right.seconds)) {
|
||||
runs[r - 1][1] = b;
|
||||
runs.splice(r, 1);
|
||||
paused.delete(a - 1);
|
||||
r = Math.max(-1, r - 2);
|
||||
} else {
|
||||
runs[r][1] = runs[r + 1][1];
|
||||
runs.splice(r + 1, 1);
|
||||
paused.delete(b);
|
||||
r -= 1;
|
||||
}
|
||||
}
|
||||
trims.push(...paused.values());
|
||||
for (const [a, b] of runs) {
|
||||
const ci = cutIn(a);
|
||||
const co = cutOut(b);
|
||||
if (co.at <= ci.at) continue;
|
||||
pieces.push({ words: [a, b], from: ci.at, to: co.at, line: ws0.slice(a, b + 1).map((w) => w.text).join(" "), ...(ci.tight || co.tight ? { tight: true } : {}) });
|
||||
t += co.at - ci.at;
|
||||
}
|
||||
/** the pause after word k is longer than the cut keeps there (`at`: where it falls in the edit) */
|
||||
function long(k: number, at: number): Trim | null {
|
||||
const g = gapAfter(k);
|
||||
if (!g || g.to - g.from <= (at < p.hook ? p.hookPause : p.pause)) return null;
|
||||
return { kind: "pause", at: r3(g.from), seconds: r3(g.to - g.from), said: `${ws[k].text} | ${ws[k + 1].text}` };
|
||||
}
|
||||
}
|
||||
// two lines that follow each other in the take with a short pause between are one clip: no cut where none is needed
|
||||
// (two cut points in a pause shorter than the breath they keep would play its middle twice)
|
||||
for (let k = pieces.length - 1; k > 0; k--) {
|
||||
const [a, b] = [pieces[k - 1], pieces[k]];
|
||||
const between = b.from - a.to;
|
||||
const inHook = pieces.slice(0, k).reduce((s, x) => s + x.to - x.from, start) < p.hook;
|
||||
if (b.words[0] === a.words[1] + 1 && between <= (inHook ? p.hookPause : p.pause) - p.lead - p.tail) {
|
||||
pieces.splice(k - 1, 2, { ...a, words: [a.words[0], b.words[1]], to: b.to, line: `${a.line} ${b.line}`, ...(a.tight || b.tight ? { tight: true } : {}) });
|
||||
}
|
||||
}
|
||||
// a pause made shorter: what was taken out of it is the pause less what the two cuts keep
|
||||
for (const x of trims) if (x.kind === "pause") x.seconds = r3(Math.max(0, x.seconds - p.lead - p.tail));
|
||||
return { pieces, trims };
|
||||
}
|
||||
|
||||
/** Which words of a take each line is: found word for word in its transcript, in order, else where 70% of its words
|
||||
* are said in a window its length (and a note says so), that window's ends trimmed of words the line doesn't have (a
|
||||
* filler before it, the next line's first word after it). Words are compared as letters and digits, a word's digits
|
||||
* apart from its letters ("about$1,200." is "about 1200"). [first, last] word of each line, in the take's words. */
|
||||
export function linesIn(ws: { text: string }[], lines: string[]): { spans: [number, number][]; notes: string[] } {
|
||||
const parts = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "").replace(/(\p{L})(\p{N})|(\p{N})(\p{L})/gu, "$1$3 $2$4").split(/\s+/).filter(Boolean);
|
||||
// the take's words as tokens, each with the word it's part of
|
||||
const toks: string[] = [];
|
||||
const owner: number[] = [];
|
||||
ws.forEach((w, k) => parts(w.text).forEach((t) => (toks.push(t), owner.push(k))));
|
||||
let from = 0;
|
||||
const spans: [number, number][] = [];
|
||||
const notes: string[] = [];
|
||||
lines.forEach((line, k) => {
|
||||
const want = parts(line);
|
||||
if (!want.length) throw new Error(`line ${k + 1} is empty`);
|
||||
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
|
||||
const close = () => {
|
||||
const n = want.length;
|
||||
if (n < 3 || toks.length < n) return undefined;
|
||||
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
|
||||
let best = 0;
|
||||
for (let i = 1; i <= toks.length - n; i++) {
|
||||
const [s, b] = [score(i), score(best)];
|
||||
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
|
||||
}
|
||||
return score(best) * 10 >= n * 7 ? best : undefined;
|
||||
};
|
||||
let exact: number | undefined;
|
||||
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
let i = exact ?? close();
|
||||
if (i === undefined) {
|
||||
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(owner[n], owner[n] + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
|
||||
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
}
|
||||
let j = Math.min(i + want.length - 1, toks.length - 1);
|
||||
if (exact === undefined) {
|
||||
while (i < j && !want.includes(toks[i])) i++;
|
||||
while (j > i && !want.includes(toks[j])) j--;
|
||||
}
|
||||
const [a, b] = [owner[i], owner[j]];
|
||||
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(a, b + 1).map((w) => w.text).join(" ")}"`);
|
||||
from = j + 1;
|
||||
spans.push([a, b]);
|
||||
});
|
||||
return { spans, notes };
|
||||
}
|
||||
|
||||
/** a clip as cuts.ts holds it */
|
||||
export type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
|
||||
/** each clip that follows another of the same take with its time skipped (forward or back): jump, so the edit reframes it
|
||||
* (a punch-in, every other one, or a cutaway over the join); the rest lose the mark */
|
||||
export function markJumps<C extends Clip>(clips: C[], fps = 30): C[] {
|
||||
return clips.map((c, k) => {
|
||||
const prev = clips[k - 1];
|
||||
const { jump: _, ...rest } = c;
|
||||
const jump = !!prev && prev.file === c.file && Math.abs(c.from - prev.to) > 1.5 / fps;
|
||||
return (jump ? { ...rest, jump: true } : rest) as C;
|
||||
});
|
||||
}
|
||||
|
||||
/** the gainDb that brings each voice clip's speech to the clips' median, 1 dB or more off it, within +-MOST_GAIN dB.
|
||||
* A level is measured only on MEASURE s of speech or more (one word's level is mostly its edges); a shorter clip takes
|
||||
* the gain of the nearest measured clip of its own take, so one take never jumps in level at a join (12-05: a 0.47 s
|
||||
* "Available" was given +12 dB between two clips at 0). `levelOf` gives a clip's speech level and its seconds of words. */
|
||||
export function evenLevels<C extends Clip>(clips: C[], levelOf: (c: C) => { db: number; seconds: number } | null): C[] {
|
||||
const lv = clips.map((c) => {
|
||||
const x = c.to - c.from >= 0.4 ? levelOf(c) : null;
|
||||
return x && x.db > -90 && x.seconds >= MEASURE ? x.db : null;
|
||||
});
|
||||
const known = lv.filter((x): x is number => x !== null);
|
||||
if (known.length < 2) return clips;
|
||||
const mid = pct(known, 0.5);
|
||||
const gain = (k: number) => Math.max(-MOST_GAIN, Math.min(MOST_GAIN, Math.round((mid - (lv[k] as number)) * 2) / 2));
|
||||
return clips.map((c, k) => {
|
||||
const { gainDb: _, ...rest } = c;
|
||||
let g: number | null = lv[k] !== null ? gain(k) : null;
|
||||
if (g === null) {
|
||||
// the nearest measured clip of the same take, either side
|
||||
for (let d = 1; d < clips.length && g === null; d++)
|
||||
for (const q of [k - d, k + d]) if (q >= 0 && q < clips.length && lv[q] !== null && clips[q].file === c.file && g === null) g = gain(q);
|
||||
}
|
||||
if (g === null) return c;
|
||||
return (Math.abs(g) >= 1 ? { ...rest, gainDb: g } : rest) as C;
|
||||
});
|
||||
}
|
||||
|
||||
/** the level every 10 ms of 16-bit PCM samples */
|
||||
export function levelsOf(pcm: Int16Array, rate = 16000): number[] {
|
||||
const hop = Math.round(rate / 100);
|
||||
const out: number[] = [];
|
||||
for (let s = 0; s + hop <= pcm.length; s += hop) {
|
||||
let e = 0;
|
||||
for (let k = s; k < s + hop; k++) e += (pcm[k] / 32768) ** 2;
|
||||
out.push(Math.round(10 * Math.log10(e / hop + 1e-10) * 10) / 10);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** a mono 16-bit WAV's samples and rate (`raea media audio --mono` writes one) */
|
||||
export function wavSamples(buf: Uint8Array): { pcm: Int16Array; rate: number } {
|
||||
const v = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
const tag = (o: number) => String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]);
|
||||
if (tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error("not a WAV file");
|
||||
let rate = 16000;
|
||||
for (let o = 12; o + 8 <= buf.length; ) {
|
||||
const id = tag(o);
|
||||
const size = v.getUint32(o + 4, true);
|
||||
if (id === "fmt ") {
|
||||
if (v.getUint16(o + 10, true) !== 1 || v.getUint16(o + 22, true) !== 16) throw new Error("not mono 16-bit PCM");
|
||||
rate = v.getUint32(o + 12, true);
|
||||
}
|
||||
if (id === "data") {
|
||||
const n = Math.floor(Math.min(size, buf.length - o - 8) / 2);
|
||||
const copy = buf.slice(o + 8, o + 8 + n * 2);
|
||||
return { pcm: new Int16Array(copy.buffer, copy.byteOffset, n), rate };
|
||||
}
|
||||
o += 8 + size + (size % 2);
|
||||
}
|
||||
throw new Error("a WAV with no data");
|
||||
}
|
||||
@@ -22,6 +22,6 @@ export const REGISTRY: Record<string, Record<string, string>> = {
|
||||
}
|
||||
};
|
||||
export const TEMPLATE: Record<string, string> = {
|
||||
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from \"raea\";\nimport { cuts, edit, frames, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />\n ) : (\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
|
||||
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from \"raea\";\nimport { cutaways, cuts, edit, frames, punchIn, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />\n ) : (\n // a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\", transform: `scale(${punchIn(i)})` }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n {/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}\n {cutaways.map((c, i) => (\n <Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>\n <Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n </Sequence>\n ))}\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
|
||||
"theme.css": "/* The Tailwind theme every raea project compiles with: class names (text-brand-accent, bg-brand-surface, font-brand,\n text-caption, rounded-brand) mapped onto the brand kit's variables (brand/brand.css, the --brand-* format).\n Nothing here is a colour, a font or a size of its own: change the brand, and every component follows. The kit's\n sizes are the website's, so on a 1080x1920 video they're scaled up (the kit's own note: about 2.5x). */\n@theme inline {\n --color-brand-accent: var(--brand-accent);\n --color-brand-bg: var(--brand-background);\n --color-brand-surface: var(--brand-background);\n --color-brand-on-surface: var(--brand-text);\n --color-brand-ink: var(--brand-background);\n --color-brand-on-accent: var(--brand-background);\n --color-brand-1: var(--brand-color-1);\n --color-brand-2: var(--brand-color-2);\n --color-brand-3: var(--brand-color-3);\n --font-brand: var(--brand-font-heading);\n --font-brand-body: var(--brand-font);\n --text-display: calc(var(--brand-h1-size) * 3);\n --text-title: calc(var(--brand-h2-size) * 2.5);\n --text-caption: calc(var(--brand-h2-size) * 2.5);\n --text-body: calc(var(--brand-p-size) * 2.5);\n --text-label: calc(var(--brand-h4-size) * 2.2);\n --radius-brand: var(--brand-radius);\n}\n"
|
||||
};
|
||||
+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.`,
|
||||
"",
|
||||
|
||||
@@ -83,11 +83,6 @@ pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `--taste`'s .ts files, each checked as Taste.
|
||||
pub fn tastes_ts(args: &[String]) -> R<Vec<schema::Taste>> {
|
||||
raea_app_direction::check::taste_files(args).iter().map(|f| read_spec(f)).collect()
|
||||
}
|
||||
|
||||
/// `raea spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:
|
||||
/// brief, script, taste or parts in it; anything else is checked as Taste, the files in
|
||||
/// ~/.raea/taste being named for their kind).
|
||||
|
||||
@@ -84,6 +84,9 @@ fn a_verb_refuses_what_it_doesnt_take() {
|
||||
let why = stray(&help, &a(&["render", "e.tsx", "f.tsx", "-o", "o.mp4"])).unwrap();
|
||||
assert!(why.contains("\"f.tsx\": it takes 1 argument besides its flags"), "{why}");
|
||||
assert!(stray(&help, &a(&["play", "g.tsx", "--full"])).unwrap().starts_with("raea play doesn't take \"--full\""));
|
||||
// `goal check`, check's old name, takes check's flags (CK0)
|
||||
assert_eq!(stray(&help, &a(&["goal", "check", "out/cuts/a_9x16.mp4", "--at", "render", "--manifest", "out/cuts/a_9x16.render.json"])), None);
|
||||
assert!(stray(&help, &a(&["goal", "check", "--frobnicate"])).unwrap().starts_with("raea check doesn't take \"--frobnicate\""));
|
||||
assert!(stray(&help, &a(&["track", "c.mp4", "--setup"])).is_some());
|
||||
assert!(stray(&help, &a(&["splat", "train", "v.mp4", "-o", "o.ply", "--steps", "100"])).is_none());
|
||||
}
|
||||
|
||||
@@ -143,6 +143,11 @@ use raea_cli_goal::verb_at;
|
||||
/// the ones it takes. None when it is, or when the help doesn't give the verb's usage.
|
||||
pub fn stray(help: &str, args: &[String]) -> Option<String> {
|
||||
let verb = args.first()?;
|
||||
// `goal check` is `check`'s old name (docs/check.feature CK0): its flags are check's, which the help lists under
|
||||
// check alone (12-04: `raea goal check OUT --at render`, raea cloud's render tool, was refused for --at)
|
||||
if verb == "goal" && args.get(1).is_some_and(|v| v == "check") {
|
||||
return stray(help, &args[1..]);
|
||||
}
|
||||
// physics hands its subverb's arguments to the bake, the goo or the part, which check them; gen to raea-io-gen's own
|
||||
if verb == "physics" || verb == "gen" {
|
||||
return None;
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn mezz(args: &[String]) -> R<String> {
|
||||
|
||||
|
||||
|
||||
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, goal_ts, render_moment};
|
||||
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, gone, goal_ts, render_moment};
|
||||
|
||||
/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)
|
||||
pub const SHELL: &[&str] = &["init", "cut", "words", "frame", "component", "brand", "library", "show", "clothes", "bug"];
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),
|
||||
// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.
|
||||
// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.
|
||||
import { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from "raea";
|
||||
import { cuts, edit, frames, total } from "./cuts";
|
||||
import { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from "raea";
|
||||
import { cutaways, cuts, edit, frames, punchIn, total } from "./cuts";
|
||||
import { css } from "./styles.gen";
|
||||
|
||||
// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's
|
||||
@@ -29,13 +29,20 @@ function Edit() {
|
||||
{/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with
|
||||
sound alone (a voice recording) plays under whatever you put in its place */}
|
||||
{c.kind === "audio" ? (
|
||||
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />
|
||||
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />
|
||||
) : (
|
||||
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
// a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15
|
||||
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${punchIn(i)})` }} />
|
||||
)}
|
||||
</Series.Sequence>
|
||||
))}
|
||||
</Series>
|
||||
{/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}
|
||||
{cutaways.map((c, i) => (
|
||||
<Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>
|
||||
<Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
</Sequence>
|
||||
))}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,11 +30,11 @@ const EXTS: &[&str] = &["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json
|
||||
/// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names
|
||||
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
|
||||
let raw = spec.strip_prefix("file://").unwrap_or(spec);
|
||||
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
|
||||
let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
|
||||
// (a path whole on Windows too, `D:\..`: the React raea ships, found, was asked for again by its path and read as a package's name, #278)
|
||||
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." || Path::new(raw).is_absolute() {
|
||||
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
|
||||
return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display()));
|
||||
}
|
||||
// a package: its name (a scope takes two parts) and the subpath after it
|
||||
let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/');
|
||||
let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() };
|
||||
let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into());
|
||||
@@ -53,9 +53,9 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
|
||||
return Ok(f);
|
||||
}
|
||||
}
|
||||
// raea's own file (sdk/app, under `raea goal check`) importing a package raea ships: a release has those in the React runtime's node_modules alone (#278)
|
||||
let (home, own) = (raea_io_home::home(), raea_io_home::home().join("sdk/react/js/node_modules").join(&name));
|
||||
if dir.starts_with(&home) && own.is_dir() {
|
||||
// a package raea ships, imported by a file with no node_modules of its own: raea's (sdk/app), or a project's brief.ts or scene (#278)
|
||||
let own = raea_io_home::home().join("sdk/react/js/node_modules").join(&name);
|
||||
if own.is_dir() {
|
||||
return package_entry(&own, &sub, esm).ok_or_else(|| format!("Cannot find module '{spec}': {} has no {sub}", own.display()));
|
||||
}
|
||||
Err(format!("Cannot find package '{name}' imported from {}", dir.display()))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A file of raea's own importing a package raea ships finds it in the React runtime's node_modules (#278): a release has
|
||||
//! A file importing a package raea ships (raea's own, or a project's with no node_modules) finds it in the React runtime's node_modules (#278): a release has
|
||||
//! no node_modules above sdk/app, so `raea goal check` ended every render "Cannot find package 'react'". Its own test
|
||||
//! binary: raea's home is read once a process.
|
||||
#![cfg(feature = "modules")]
|
||||
@@ -16,7 +16,21 @@ fn raeas_own_file_finds_the_react_raea_ships() {
|
||||
// SAFETY: the one test here, before anything reads the environment
|
||||
unsafe { std::env::set_var("RAEA_HOME", &home) };
|
||||
assert_eq!(raea_native::node::resolve_file("react", &own, true).unwrap(), pkg.join("index.js"));
|
||||
// a project's own file never reaches into raea's packages
|
||||
assert!(raea_native::node::resolve_file("react", &theirs, true).unwrap_err().contains("Cannot find package 'react'"));
|
||||
// a project's file with no node_modules of its own gets the same React (brief.ts, a scene it registers): a release's
|
||||
// render was applied and then failed its checks on "Cannot find package 'react'"
|
||||
fs::create_dir_all(&theirs).unwrap();
|
||||
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), pkg.join("index.js"));
|
||||
// its own copy, when it has one, wins
|
||||
let mine = theirs.join("node_modules/react");
|
||||
fs::create_dir_all(&mine).unwrap();
|
||||
fs::write(mine.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
|
||||
fs::write(mine.join("index.js"), "module.exports = {}").unwrap();
|
||||
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), mine.join("index.js"));
|
||||
// a file asked for by its whole path is that file, on Windows too (`D:\..` was read as a package's name)
|
||||
let whole = pkg.join("index.js");
|
||||
assert_eq!(raea_native::node::resolve_file(whole.to_str().unwrap(), &theirs, true).unwrap(), whole);
|
||||
// and a package raea doesn't ship is still not found
|
||||
assert!(raea_native::node::resolve_file("left-pad", &own, true).unwrap_err().contains("Cannot find package 'left-pad'"));
|
||||
fs::remove_dir_all(&theirs).ok();
|
||||
fs::remove_dir_all(&home).ok();
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod mezz;
|
||||
pub mod mp4box;
|
||||
#[cfg(feature = "mux")]
|
||||
pub mod remux;
|
||||
pub mod samples;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! An MP4 or QuickTime file's boxes, read directly: what `media probe` and the ffmpeg backend take a track's own facts
|
||||
//! from (its frame times, its sound's rate) without reading the gigabytes of pictures beside them.
|
||||
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::Path;
|
||||
|
||||
/// The boxes inside `b` (a box's payload): (type, payload).
|
||||
pub fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 8 <= b.len() {
|
||||
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
|
||||
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
|
||||
let mut hdr = 8;
|
||||
if size == 1 && i + 16 <= b.len() {
|
||||
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = b.len() - i;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
pub fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub fn be64(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The file's moov box, read alone (mdat can be gigabytes).
|
||||
pub fn moov_of(path: &Path) -> Option<Vec<u8>> {
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
let mut at = 0u64;
|
||||
loop {
|
||||
if at + 8 > len {
|
||||
return None;
|
||||
}
|
||||
let mut h = [0u8; 16];
|
||||
f.seek(SeekFrom::Start(at)).ok()?;
|
||||
f.read_exact(&mut h[..8]).ok()?;
|
||||
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
|
||||
let mut hdr = 8u64;
|
||||
if size == 1 {
|
||||
f.read_exact(&mut h[8..]).ok()?;
|
||||
size = u64::from_be_bytes(h[8..].try_into().ok()?);
|
||||
hdr = 16;
|
||||
} else if size == 0 {
|
||||
size = len - at;
|
||||
}
|
||||
if size < hdr {
|
||||
return None;
|
||||
}
|
||||
if &h[4..8] == b"moov" {
|
||||
let mut m = vec![0u8; usize::try_from(size - hdr).ok().filter(|n| *n <= 256 << 20)?];
|
||||
f.read_exact(&mut m).ok()?;
|
||||
return Some(m);
|
||||
}
|
||||
at += size;
|
||||
}
|
||||
}
|
||||
+52
-31
@@ -9,6 +9,8 @@ use raea_io_codec::{
|
||||
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
|
||||
};
|
||||
|
||||
mod mov;
|
||||
|
||||
pub struct Ffmpeg;
|
||||
|
||||
/// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`)
|
||||
@@ -50,14 +52,40 @@ fn says(option: &str) -> String {
|
||||
/// phone): libx264 where ffmpeg was built with it (Homebrew's, Linux distributions'), else the system's own (Windows'
|
||||
/// Media Foundation, h264_mf, in the LGPL build raea ships there; macOS's VideoToolbox) at 8 Mb/s; None without one.
|
||||
pub fn h264() -> Option<Vec<&'static str>> {
|
||||
static ENCODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
let have = ENCODERS.get_or_init(|| says("-encoders"));
|
||||
let has = |c: &str| have.split_whitespace().any(|w| w == c);
|
||||
let enc = ["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| has(c))?;
|
||||
let enc = listed()?;
|
||||
let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] };
|
||||
Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].concat())
|
||||
}
|
||||
|
||||
/// The first of libx264, Media Foundation's and VideoToolbox's H.264 encoders this machine's ffmpeg lists
|
||||
fn listed() -> Option<&'static str> {
|
||||
["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| lists("-encoders", c))
|
||||
}
|
||||
|
||||
/// `codec` is among what this machine's ffmpeg prints for `option` (-encoders, -decoders), each asked once
|
||||
fn lists(option: &'static str, codec: &str) -> bool {
|
||||
static PRINTED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<&'static str, String>>> = std::sync::OnceLock::new();
|
||||
let mut printed = PRINTED.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
|
||||
printed.entry(option).or_insert_with(|| says(option)).split_whitespace().any(|w| w == codec)
|
||||
}
|
||||
|
||||
/// A render's encoder and its rate, as ffmpeg's arguments: NVENC and libx264 at a constant quality when one is asked
|
||||
/// (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate. The system's own encoders (h264_mf, h264_videotoolbox)
|
||||
/// have no CRF, so they take the bitrate either way: the LGPL ffmpeg raea ships on Windows has no libx264, and
|
||||
/// RAEA_MEDIA=ffmpeg failed there on `-c:v libx264` (#279)
|
||||
fn video_args(enc: &str, o: &EncodeOpts) -> Vec<String> {
|
||||
let rate = || vec!["-b:v".to_string(), format!("{}k", o.kbps), "-maxrate".to_string(), format!("{}k", o.kbps * 3 / 2), "-bufsize".to_string(), format!("{}k", o.kbps * 2)];
|
||||
let q = |q: f32| format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0));
|
||||
let (nvenc, x264) = (NVENC.map(String::from).to_vec(), ["-c:v", "libx264", "-preset", "medium"].map(String::from).to_vec());
|
||||
match (enc, o.quality) {
|
||||
("h264_nvenc", Some(v)) => [nvenc, vec!["-rc".into(), "constqp".into(), "-qp".into(), q(v)]].concat(),
|
||||
("h264_nvenc", None) => [nvenc, rate()].concat(),
|
||||
("libx264", Some(v)) => [x264, vec!["-crf".into(), q(v)]].concat(),
|
||||
("libx264", None) => [x264, rate()].concat(),
|
||||
_ => [vec!["-c:v".into(), enc.to_string()], rate()].concat(),
|
||||
}
|
||||
}
|
||||
|
||||
/// RAEA_NV=1 (the render farm sets it on a GPU's runs of a piece with 3D in it, docs/cloud-render.feature CR34): NVIDIA's
|
||||
/// encoder (`enc`, NVENC) or decoder (NVDEC, through CUDA) in place of libx264 and ffmpeg's own, each only once a
|
||||
/// one-frame try of it worked on this machine (a GPU without the driver's video libraries keeps libx264, said once).
|
||||
@@ -98,6 +126,12 @@ const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
|
||||
/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
|
||||
/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
|
||||
fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
probe_with(path, mov::frame_times(path))
|
||||
}
|
||||
|
||||
/// `tabled`: the frame times the file's own tables state (mov.rs). Without them ffprobe is asked for every packet's
|
||||
/// time, which reads the whole file.
|
||||
fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
let out = cli("ffprobe", named_video(path))?
|
||||
.args([
|
||||
"-v",
|
||||
@@ -106,11 +140,9 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
|
||||
"-show_entries",
|
||||
"packet=pts_time",
|
||||
"-of",
|
||||
"json",
|
||||
])
|
||||
.args(if tabled.is_none() { &["-show_entries", "packet=pts_time"][..] } else { &[] })
|
||||
.args(["-of", "json"])
|
||||
.arg(path)
|
||||
.output()
|
||||
.map_err(|e| format!("ffprobe: {e}"))?;
|
||||
@@ -133,12 +165,15 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
.and_then(|r| r.split_once('/'))
|
||||
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
|
||||
.unwrap_or(30.0);
|
||||
let mut pts: Vec<f64> = j["packets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
|
||||
.collect();
|
||||
let mut pts: Vec<f64> = match tabled {
|
||||
Some(t) => t,
|
||||
None => j["packets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
|
||||
.collect(),
|
||||
};
|
||||
pts.sort_by(f64::total_cmp);
|
||||
let duration = j["format"]["duration"]
|
||||
.as_str()
|
||||
@@ -154,9 +189,7 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
_ => None,
|
||||
};
|
||||
// an ffmpeg built without libvpx decodes the picture alone, as before
|
||||
static DECODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
let have = DECODERS.get_or_init(|| says("-decoders"));
|
||||
let alpha = alpha.filter(|c| have.split_whitespace().any(|w| w == *c));
|
||||
let alpha = alpha.filter(|c| lists("-decoders", c));
|
||||
Ok((
|
||||
Info {
|
||||
codec: s["codec_name"].as_str().unwrap_or("?").into(),
|
||||
@@ -400,6 +433,7 @@ impl Backend for Ffmpeg {
|
||||
}
|
||||
fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {
|
||||
let video = out.with_extension("video.mp4");
|
||||
let enc = if nv(true) { "h264_nvenc" } else { listed().ok_or("this machine's ffmpeg has no H.264 encoder (libx264, h264_mf or h264_videotoolbox)")? };
|
||||
let child = cli("ffmpeg", false)?
|
||||
.args([
|
||||
"-v",
|
||||
@@ -416,20 +450,7 @@ impl Backend for Ffmpeg {
|
||||
"-i",
|
||||
"-",
|
||||
])
|
||||
.args(if nv(true) { &NVENC[..] } else { &["-c:v", "libx264", "-preset", "medium"][..] })
|
||||
// constant quality as CRF (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate
|
||||
.args(match o.quality {
|
||||
Some(q) if nv(true) => vec!["-rc".to_string(), "constqp".to_string(), "-qp".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
|
||||
Some(q) => vec!["-crf".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
|
||||
None => vec![
|
||||
"-b:v".to_string(),
|
||||
format!("{}k", o.kbps),
|
||||
"-maxrate".to_string(),
|
||||
format!("{}k", o.kbps * 3 / 2),
|
||||
"-bufsize".to_string(),
|
||||
format!("{}k", o.kbps * 2),
|
||||
],
|
||||
})
|
||||
.args(video_args(enc, o))
|
||||
.args([
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! An MP4 or QuickTime file's frame times from its own sample tables. Opening a video asked ffprobe for every packet's
|
||||
//! time, and for these files ffprobe reads every packet to say it: each open of a 1 GB interview read 1 GB (two
|
||||
//! minutes on a cloud Sprite's disk, 12-01), and a contact sheet opened its file once a frame.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use raea_io_codec::mp4box::{be32, be64, boxes, child, moov_of};
|
||||
|
||||
/// Every frame's presentation time in seconds, sorted, as ffprobe's packets give them up to one shift of them all
|
||||
/// (the decoder uses them from the first on). None for a file that isn't MP4 or QuickTime, one in fragments (mvex), and one
|
||||
/// whose edit list does more than set where the track starts: those are asked of ffprobe as before.
|
||||
pub(crate) fn frame_times(path: &Path) -> Option<Vec<f64>> {
|
||||
let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
|
||||
if !["mp4", "mov", "m4v"].contains(&ext.as_str()) {
|
||||
return None;
|
||||
}
|
||||
times_in(&moov_of(path)?)
|
||||
}
|
||||
|
||||
fn times_in(moov: &[u8]) -> Option<Vec<f64>> {
|
||||
if child(moov, b"mvex").is_some() {
|
||||
return None;
|
||||
}
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
let Some(mdia) = child(trak, b"mdia") else { continue };
|
||||
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"vide"[..]) {
|
||||
continue;
|
||||
}
|
||||
// an edit list that plays the track from one place on is a shift of every time; one with a gap ahead of it,
|
||||
// or more than one piece, moves frames apart
|
||||
if let Some(elst) = child(trak, b"edts").and_then(|e| child(e, b"elst")) {
|
||||
if be32(elst, 4)? != 1 {
|
||||
return None;
|
||||
}
|
||||
let from = if elst.first() == Some(&1) { be64(elst, 16)? as i64 } else { be32(elst, 12)? as i32 as i64 };
|
||||
if from < 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mdhd = child(mdia, b"mdhd")?;
|
||||
let scale = if mdhd.first() == Some(&1) { be32(mdhd, 20)? } else { be32(mdhd, 12)? } as f64;
|
||||
if scale <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let stbl = child(child(mdia, b"minf")?, b"stbl")?;
|
||||
let stts = child(stbl, b"stts")?;
|
||||
let mut times: Vec<i64> = Vec::new();
|
||||
let mut dts = 0i64;
|
||||
for e in 0..be32(stts, 4)? as usize {
|
||||
let (n, d) = (be32(stts, 8 + e * 8)?, be32(stts, 12 + e * 8)? as i64);
|
||||
// a table that claims more frames than a day of 240 a second isn't one to trust
|
||||
if times.len() + n as usize > 20_736_000 {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..n {
|
||||
times.push(dts);
|
||||
dts += d;
|
||||
}
|
||||
}
|
||||
if let Some(ctts) = child(stbl, b"ctts") {
|
||||
let mut i = 0usize;
|
||||
for e in 0..be32(ctts, 4)? as usize {
|
||||
// signed whatever the version says: QuickTime writes negative offsets in version 0 boxes
|
||||
let (n, off) = (be32(ctts, 8 + e * 8)? as usize, be32(ctts, 12 + e * 8)? as i32 as i64);
|
||||
for t in times.iter_mut().skip(i).take(n) {
|
||||
*t += off;
|
||||
}
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
if times.is_empty() {
|
||||
return None;
|
||||
}
|
||||
times.sort_unstable();
|
||||
return Some(times.into_iter().map(|t| t as f64 / scale).collect());
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -47,3 +47,57 @@ fn nv_falls_back_where_nvidia_isnt() {
|
||||
assert!(!nv(true) && !nv(false), "off without RAEA_NV=1");
|
||||
}
|
||||
}
|
||||
|
||||
/// libx264's arguments are what they were, and the system's encoder (macOS's here, Windows' Media Foundation the same
|
||||
/// way) takes a bitrate even when a quality is asked, and encodes with them (#279)
|
||||
#[test]
|
||||
fn a_system_encoder_takes_the_bitrate() {
|
||||
let o = |quality| EncodeOpts { width: 256, height: 256, fps: 30.0, kbps: 900, quality, nv12: false, realtime: false };
|
||||
assert_eq!(video_args("libx264", &o(Some(0.85))), ["-c:v", "libx264", "-preset", "medium", "-crf", "13"]);
|
||||
assert_eq!(video_args("libx264", &o(None)), ["-c:v", "libx264", "-preset", "medium", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
|
||||
let args = video_args("h264_videotoolbox", &o(Some(0.85)));
|
||||
assert_eq!(args, ["-c:v", "h264_videotoolbox", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
|
||||
if !lists("-encoders", "h264_videotoolbox") {
|
||||
return eprintln!("skipped the encode: no h264_videotoolbox in this ffmpeg");
|
||||
}
|
||||
let out = std::env::temp_dir().join(format!("raea-ffmpeg-system-{}.mp4", std::process::id()));
|
||||
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=256x256:d=0.3"]).args(&args).args(["-pix_fmt", "yuv420p"]).arg(&out).status().is_ok_and(|s| s.success());
|
||||
assert!(ok && std::fs::metadata(&out).is_ok_and(|m| m.len() > 500), "ffmpeg encodes with the system encoder's arguments");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
}
|
||||
|
||||
/// An MP4's and a QuickTime file's frame times, read from their own tables, are the ones ffprobe's packets give (up to
|
||||
/// one shift of them all), with B-frames, at a rate that isn't whole, and the same frames come out either way.
|
||||
#[test]
|
||||
fn a_file_s_own_tables_give_ffprobe_s_frame_times() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-ffmpeg-tables-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let make = |name: &str, args: &[&str]| {
|
||||
let p = dir.join(name);
|
||||
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=128x72:r=30000/1001:d=2", "-pix_fmt", "yuv420p"]).args(args).arg(&p).status().is_ok_and(|s| s.success());
|
||||
ok.then_some(p)
|
||||
};
|
||||
let files = [make("b.mp4", &["-c:v", "libx264", "-bf", "3"]), make("b.mov", &["-c:v", "libx264", "-bf", "2", "-g", "12"]), make("plain.mp4", &["-c:v", "mpeg4"])];
|
||||
let mut seen = 0;
|
||||
for f in files.into_iter().flatten() {
|
||||
let Some(tabled) = mov::frame_times(&f) else { panic!("{}: its tables weren't read", f.display()) };
|
||||
let (_, asked, ..) = probe_with(&f, None).unwrap();
|
||||
assert_eq!(tabled.len(), asked.len(), "{}: as many frames", f.display());
|
||||
for (a, b) in tabled.iter().zip(&asked) {
|
||||
assert!(((a - tabled[0]) - (b - asked[0])).abs() < 2e-4, "{}: {a} against {b}", f.display());
|
||||
}
|
||||
// and the decoder gives the same picture at a time either way
|
||||
let (info, pts, ..) = probe(&f).unwrap();
|
||||
assert_eq!(pts.len(), info.frames);
|
||||
let mut d = Ffmpeg.open_video(&f).unwrap();
|
||||
let at = d.frame_at(1.0).unwrap();
|
||||
assert!((at.pts - 1.0).abs() < 0.04, "{}: the frame at 1 s is at {}", f.display(), at.pts);
|
||||
seen += 1;
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
if seen == 0 {
|
||||
eprintln!("skipped: no ffmpeg here to make a file with");
|
||||
}
|
||||
// a file in fragments, or of another kind, is asked of ffprobe as before
|
||||
assert!(mov::frame_times(Path::new("a.webm")).is_none());
|
||||
}
|
||||
+22
-1
@@ -58,7 +58,23 @@ pub struct Track {
|
||||
|
||||
/// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV).
|
||||
pub fn rotation_of(path: &Path) -> i32 {
|
||||
std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
|
||||
// the moov box alone, as a file of that one box (the whole file was read for it: gigabytes, for a matrix)
|
||||
let Some(moov) = raea_io_codec::mp4box::moov_of(path) else { return 0 };
|
||||
let mut b = ((moov.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
b.extend_from_slice(b"moov");
|
||||
b.extend_from_slice(&moov);
|
||||
mp4_rotation(&b)
|
||||
}
|
||||
|
||||
/// The first video track's sample entry (avc1, hvc1, av01, ...), from the moov box alone.
|
||||
fn video_fourcc(path: &Path) -> Option<[u8; 4]> {
|
||||
use raea_io_codec::mp4box::{boxes, child, moov_of};
|
||||
let moov = moov_of(path)?;
|
||||
boxes(&moov).into_iter().filter(|(k, _)| k == b"trak").find_map(|(_, trak)| {
|
||||
let mdia = child(trak, b"mdia")?;
|
||||
(child(mdia, b"hdlr")?.get(8..12)? == b"vide").then_some(())?;
|
||||
child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?.get(12..16)?.try_into().ok()
|
||||
})
|
||||
}
|
||||
|
||||
/// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d).
|
||||
@@ -107,6 +123,11 @@ fn mp4_rotation(b: &[u8]) -> i32 {
|
||||
}
|
||||
|
||||
pub fn demux(path: &Path, want: &str) -> R<Track> {
|
||||
// another codec's file is refused before it is read: every open of a 4K HEVC interview on Linux read its whole
|
||||
// gigabyte here to learn it wasn't H.264, then went to the backend that reads it (two minutes on a cloud disk)
|
||||
if let Some(is) = video_fourcc(path).filter(|f| want.len() >= 3 && f[..3] != want.as_bytes()[..3]) {
|
||||
return Err(format!("{}: {}, not {want} (this backend reads {want} mezzanines)", path.display(), String::from_utf8_lossy(&is)));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let (_, t) = mp4
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! A file of another codec is refused from its moov box alone, and a rotation is read from it, without the file's
|
||||
//! pictures being read (a 1 GB HEVC interview was read whole on every open to learn it wasn't H.264).
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn made(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
|
||||
let p = dir.join(name);
|
||||
Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).arg(&p).status().is_ok_and(|s| s.success()).then_some(p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_codec_is_refused_by_its_tables_and_a_rotation_read_from_them() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-soft-refuse-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let src = ["-f", "lavfi", "-i", "testsrc2=s=128x72:r=30:d=1", "-pix_fmt", "yuv420p"];
|
||||
let Some(other) = made(&dir, "other.mp4", &[&src[..], &["-c:v", "mpeg4"]].concat()) else { return eprintln!("skipped: no ffmpeg here") };
|
||||
let e = raea_io_soft::demux(&other, "avc1").err().expect("an MPEG-4 file isn't H.264");
|
||||
assert!(e.contains("mp4v, not avc1"), "{e}");
|
||||
// cut short after its moov, the refusal is the same: nothing past the tables was needed
|
||||
if let Some(front) = made(&dir, "front.mp4", &[&src[..], &["-c:v", "mpeg4", "-movflags", "+faststart"]].concat()) {
|
||||
let bytes = std::fs::read(&front).unwrap();
|
||||
let mdat = bytes.windows(4).position(|w| w == b"mdat").unwrap();
|
||||
std::fs::write(&front, &bytes[..mdat + 4]).unwrap();
|
||||
assert!(raea_io_soft::demux(&front, "avc1").err().unwrap().contains("mp4v, not avc1"));
|
||||
assert_eq!(raea_io_soft::rotation_of(&front), 0);
|
||||
}
|
||||
// an H.264 file is read as before, and one turned on its side says so
|
||||
if let Some(h264) = made(&dir, "h264.mp4", &[&src[..], &["-c:v", "libx264"]].concat()) {
|
||||
assert!(raea_io_soft::demux(&h264, "avc1").is_ok());
|
||||
assert_eq!(raea_io_soft::rotation_of(&h264), 0);
|
||||
let h = h264.to_string_lossy().to_string();
|
||||
if let Some(turned) = made(&dir, "turned.mp4", &["-display_rotation:v:0", "90", "-i", &h, "-c", "copy"]) {
|
||||
assert_eq!(raea_io_soft::rotation_of(&turned).rem_euclid(180), 90);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -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,81 @@
|
||||
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
|
||||
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
|
||||
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
|
||||
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
|
||||
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
|
||||
# deploy/fly/box.sh builds it from sdk/cloud:
|
||||
#
|
||||
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
|
||||
FROM ubuntu:26.04
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
|
||||
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
|
||||
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
|
||||
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
|
||||
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
|
||||
xvfb x11vnc xdotool fonts-noto-color-emoji python3-opencv > /dev/null \
|
||||
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
|
||||
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
|
||||
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
|
||||
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG NODE=24.22.0
|
||||
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
|
||||
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
|
||||
|
||||
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
|
||||
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
|
||||
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
|
||||
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
|
||||
&& ln -s /home/raea /home/sprite
|
||||
|
||||
# raea, checked against its release's .sha256
|
||||
ARG RAEA_VERSION
|
||||
ARG RAEA_REPO=shinyobjectz/raea
|
||||
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
|
||||
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
|
||||
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
|
||||
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
|
||||
&& /opt/raea/bin/raea --version
|
||||
|
||||
WORKDIR /opt/raea-cloud
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
|
||||
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
|
||||
COPY server server
|
||||
ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
# OpenCV's YuNet face detector (232 KB, MIT), for image/faces.py: prep finds each take's faces and components/Framed.tsx
|
||||
# crops on them (12-05: agents guessed each 9:16 crop and cut the speaker off at the edge); prep also copies the cut
|
||||
# components beside it (image/Cut.tsx, Shot, crop, Said, EndCard, brand, Title)
|
||||
RUN curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \
|
||||
&& python3 -c "import cv2; cv2.FaceDetectorYN.create('/opt/yunet.onnx', '', (640, 360))" && chmod +x image/faces.py
|
||||
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
||||
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
|
||||
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
|
||||
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
|
||||
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
|
||||
COPY deploy/git deploy/git
|
||||
COPY deploy/fly/start.sh image/fly-start.sh
|
||||
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
|
||||
# the entrypoint 711, and it re-runs itself as raea)
|
||||
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
|
||||
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
|
||||
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
|
||||
&& git lfs install --system --skip-repo > /dev/null
|
||||
|
||||
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
|
||||
ARG COMMIT=unknown
|
||||
ARG DIRTY=false
|
||||
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
|
||||
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
|
||||
|
||||
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
|
||||
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
|
||||
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
|
||||
+242
-64
@@ -4,13 +4,14 @@
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/farm.py
|
||||
#
|
||||
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X] body: the project as a tar. {id}
|
||||
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X][&nv=1|0] body: the project as a tar. {id}
|
||||
# GET /v1/jobs/ID?from=N {log, next, exit?}, held up to 20 s for more
|
||||
# GET /v1/jobs/ID/out?as=zst|gz|tar the files the job made or changed; the job is removed
|
||||
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
|
||||
# left out of /out
|
||||
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
|
||||
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
|
||||
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid],
|
||||
# links: 1} (links: it fetches an original of unknown size)
|
||||
# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
|
||||
# hashes to OID (a box's project not in raea's LFS)
|
||||
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
|
||||
@@ -32,6 +33,7 @@ import re
|
||||
import resource
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
@@ -81,8 +83,10 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
|
||||
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
|
||||
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
|
||||
# workspace limit holds these back as it does GPUs
|
||||
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
|
||||
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
|
||||
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
|
||||
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
|
||||
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
|
||||
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
|
||||
ROOT = "/farm"
|
||||
JOBS = f"{ROOT}/jobs"
|
||||
|
||||
@@ -90,7 +94,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",
|
||||
)
|
||||
@@ -145,8 +149,20 @@ image = (
|
||||
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release
|
||||
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
|
||||
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
|
||||
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
|
||||
)
|
||||
# raea's SDK files the box image overlays on the release (image/sdk-overlay, deploy/fly/Dockerfile), here too: the farm
|
||||
# bundles each composition it's sent with its own SDK, so the box's zone-aware <Region> never reached a render (12-05,
|
||||
# run 17: titles through <Title> still landed at y=154, inside the app's top 220 px). Only while the release lacks them
|
||||
OVERLAY = os.path.join(CLOUD, "image", "sdk-overlay")
|
||||
if os.path.isdir(os.path.join(OVERLAY, "video")):
|
||||
image = image.add_local_dir(OVERLAY, "/opt/sdk-overlay", copy=True).run_commands(
|
||||
"set -e; S=/opt/raea/share/raea/sdk; O=/opt/sdk-overlay; if [ ! -f $S/video/src/zones.ts ]; then "
|
||||
"cp $O/video/src/captions.tsx $O/video/src/index.ts $O/video/src/region.tsx $O/video/src/zones.ts "
|
||||
"$O/video/src/registry.tsx $S/video/src/ && cp $O/video/package.json $S/video/package.json && "
|
||||
"cp $O/raea/src/index.tsx $S/raea/src/index.tsx && echo 'overlay: zones'; fi"
|
||||
)
|
||||
# last: files added without copy (these) can't be followed by a build step
|
||||
image = image.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
|
||||
|
||||
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
|
||||
vol = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
|
||||
@@ -155,19 +171,32 @@ 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"}
|
||||
|
||||
|
||||
# NVIDIA's shader cache and Cycles' kernels on the farm's volume, so a GPU's start reuses what an earlier one compiled
|
||||
CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}/cache/nvidia", "__GL_SHADER_DISK_CACHE_SKIP_CLEANUP": "1",
|
||||
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
|
||||
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg",
|
||||
# but a composition's bundle on this container's own disk (12-05, Dutch run 6: a job's 32 parts each missed the
|
||||
# shared cache at once, wrote the same file and committed it, and parts that read it mid-commit got zeros:
|
||||
# "bundle.js: String contained internal null bytes", up to 23 of a cut's 32 parts sent back to the 10 GPUs)
|
||||
"RAEA_BUNDLE_CACHE": "/tmp/raea-bundles"}
|
||||
|
||||
|
||||
# the scene reader's models, loaded once a container (/v1/scene)
|
||||
SCENE = None
|
||||
# one reading at a time a container: the models aren't safe to run from two threads
|
||||
SCENE_LOCK = threading.Lock()
|
||||
|
||||
# when this container's Python started, for the job's bill (farm_plan.Bill)
|
||||
BOOTED = time.time()
|
||||
@@ -185,7 +214,7 @@ def life():
|
||||
|
||||
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
|
||||
t = time.time()
|
||||
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
|
||||
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"], CACHES["RAEA_BUNDLE_CACHE"]):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
build = os.environ.get("RAEA_FARM_BUILD")
|
||||
if build and cmd[0] == "raea":
|
||||
@@ -199,16 +228,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:
|
||||
@@ -228,6 +262,12 @@ class Log:
|
||||
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
|
||||
# about five times their GPUs' working seconds
|
||||
SCALEDOWN = 2
|
||||
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
|
||||
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
|
||||
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 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):
|
||||
@@ -291,7 +331,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
|
||||
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
|
||||
|
||||
|
||||
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
|
||||
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
|
||||
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
|
||||
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
|
||||
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
|
||||
@@ -315,12 +355,43 @@ def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
|
||||
return {"code": code, "out": out[-1000:], "s": s}
|
||||
|
||||
|
||||
def stills_run(args, frames, first, work, env, seg, man):
|
||||
"""A video run drawn as stills and encoded: the run's frames from `first` (its warm-up ones dropped) at the piece's
|
||||
rate (its manifest's, else 30)"""
|
||||
import farm_plan
|
||||
|
||||
tmp = f"/tmp/{uuid.uuid4().hex}"
|
||||
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp, "--manifest", man], cwd=work, env=env)
|
||||
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
|
||||
if code or len(made) != len(frames):
|
||||
return code or 1, out + f"\n{len(made)} of {len(frames)} stills drawn", s
|
||||
kept = f"{tmp}/kept"
|
||||
os.makedirs(kept)
|
||||
n = 0
|
||||
for i, name in enumerate(made):
|
||||
if frames[i] >= first:
|
||||
os.replace(os.path.join(tmp, name), f"{kept}/frame-{n:05d}.png")
|
||||
n += 1
|
||||
try:
|
||||
fps = float(json.load(open(man)).get("fps") or 30)
|
||||
except Exception:
|
||||
fps = 30.0
|
||||
c, o, _ = farm_plan.encode(kept, seg, fps, None, run, start=0, frames=n)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return c, out + o, s
|
||||
|
||||
|
||||
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
|
||||
vol.reload()
|
||||
work = f"{JOBS}/{id}/work"
|
||||
if probe:
|
||||
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env)
|
||||
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
|
||||
# what frame 0 brought up to date in the work folder (styles.gen.ts, written by raea when it's older than the
|
||||
# code), for the parts after it: uncommitted, every part's container rewrote it on the volume at once, truncating
|
||||
# it under the others, and 14 of a Dutch cut's parts refused with "couldn't bundle edit.tsx: Unterminated
|
||||
# string" (12-05, run 19: the cut was lost)
|
||||
vol.commit()
|
||||
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
|
||||
if frames is None:
|
||||
code, out, s = run(["raea", *args], cwd=work)
|
||||
@@ -335,6 +406,11 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
|
||||
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
|
||||
man = f"/tmp/run-{first:05d}.json"
|
||||
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"})
|
||||
# a piece whose --at draws only stills (a game's, 12-05: "/tmp/run-00024.mp4: The file extension .mp4 was not
|
||||
# recognized as an image format" on every run, and a playable's capture never came back): its frames as stills,
|
||||
# encoded here into the run's H.264 part, as a Blender run's are
|
||||
if code and "not recognized as an image format" in out:
|
||||
code, out, s = stills_run(args, frames, first, work, env, seg, man)
|
||||
if os.path.exists(seg):
|
||||
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
|
||||
vol.commit()
|
||||
@@ -408,7 +484,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)
|
||||
@@ -420,8 +498,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
|
||||
@@ -434,7 +519,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
except Exception as e: # the job's own failure, said in its log; the farm goes on
|
||||
log(f"raea farm: {e!r}", err=True)
|
||||
code = 1
|
||||
t_end = [time.time()]
|
||||
vol.commit()
|
||||
t_end.append(time.time())
|
||||
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
|
||||
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
|
||||
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
|
||||
@@ -448,7 +535,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
|
||||
else:
|
||||
time.sleep(pause)
|
||||
t_end.append(time.time())
|
||||
after = snapshot(work)
|
||||
t_end.append(time.time())
|
||||
changed = [p for p, v in after.items() if before.get(p) != v]
|
||||
if opts.get("media"):
|
||||
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
|
||||
@@ -460,11 +549,67 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
|
||||
f.write("".join(p + "\n" for p in changed))
|
||||
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
|
||||
t_end.append(time.time())
|
||||
vol.commit()
|
||||
t_end.append(time.time())
|
||||
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
|
||||
if t_end[-1] - t_end[0] > 5:
|
||||
d = [b - a for a, b in zip(t_end, t_end[1:])]
|
||||
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
|
||||
log.end(code)
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
|
||||
def seams(g):
|
||||
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
|
||||
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
|
||||
import numpy as np
|
||||
|
||||
found = []
|
||||
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
|
||||
n = d.shape[0]
|
||||
share = (d > 24).mean(axis=1)
|
||||
for i in range(int(n * 0.08), int(n * 0.92)):
|
||||
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
|
||||
found.append([axis, i + 1, round(float(share[i]), 2)])
|
||||
return found
|
||||
|
||||
|
||||
def read_scenes(frames):
|
||||
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
|
||||
import base64
|
||||
import cv2
|
||||
import numpy as np
|
||||
import farm_scene
|
||||
|
||||
global SCENE
|
||||
with SCENE_LOCK:
|
||||
if SCENE is None:
|
||||
SCENE = farm_scene.Scene()
|
||||
out = []
|
||||
for b64 in frames:
|
||||
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
|
||||
if im is None:
|
||||
out.append(None)
|
||||
continue
|
||||
r = SCENE.read(im)
|
||||
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
|
||||
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
|
||||
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
|
||||
SCENE_HERE = 4
|
||||
SCENE_PART = 6
|
||||
|
||||
|
||||
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
|
||||
def scene_run(frames: list[str]) -> list:
|
||||
return read_scenes(frames)
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret, groq_secret], timeout=3600)
|
||||
@modal.concurrent(max_inputs=32)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
@@ -482,15 +627,22 @@ def api():
|
||||
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a
|
||||
# reload waits until none of them is in it.
|
||||
class Gate:
|
||||
# 12-04 (one-check proof, 12 cuts in flight): blob uploads and other requests kept the volume in use without a
|
||||
# break, a reload waited for none of them to be in it, and GET out sat behind it past Modal's 150 s web limit:
|
||||
# 408, and Elfster's finished cut was lost. So a waiting reload holds new users back (it goes next), a reload
|
||||
# that starts after a request asked for one serves that request too, and a wait has a limit (a 503, asked again)
|
||||
def __init__(self):
|
||||
self.users = 0
|
||||
self.reloading = False
|
||||
self.waiting = 0
|
||||
self.begun = 0 # reloads started
|
||||
self.fresh = 0 # the latest reload that worked, by its start
|
||||
self.cond = asyncio.Condition()
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def use(self):
|
||||
async with self.cond:
|
||||
await self.cond.wait_for(lambda: not self.reloading)
|
||||
await self.cond.wait_for(lambda: not self.reloading and not self.waiting)
|
||||
self.users += 1
|
||||
try:
|
||||
yield
|
||||
@@ -499,17 +651,36 @@ def api():
|
||||
self.users -= 1
|
||||
self.cond.notify_all()
|
||||
|
||||
async def reload(self, wait: bool = True) -> bool:
|
||||
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use"""
|
||||
async def reload(self, wait: bool = True, within: "float | None" = None) -> bool:
|
||||
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use,
|
||||
and False when `within` seconds pass first"""
|
||||
async with self.cond:
|
||||
if not wait and (self.users or self.reloading):
|
||||
if not wait and (self.users or self.reloading or self.waiting):
|
||||
return False
|
||||
await self.cond.wait_for(lambda: not self.users and not self.reloading)
|
||||
want = self.begun + 1
|
||||
self.waiting += 1
|
||||
try:
|
||||
ready = lambda: self.fresh >= want or (not self.users and not self.reloading)
|
||||
if within is None:
|
||||
await self.cond.wait_for(ready)
|
||||
else:
|
||||
await asyncio.wait_for(self.cond.wait_for(ready), within)
|
||||
except asyncio.TimeoutError:
|
||||
return False
|
||||
finally:
|
||||
self.waiting -= 1
|
||||
self.cond.notify_all()
|
||||
if self.fresh >= want:
|
||||
return True
|
||||
self.reloading = True
|
||||
self.begun += 1
|
||||
mine = self.begun
|
||||
ok = False
|
||||
try:
|
||||
for pause in (0.5, 1, 2, 4, 0):
|
||||
try:
|
||||
await vol.reload.aio()
|
||||
ok = True
|
||||
return True
|
||||
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
|
||||
if not pause:
|
||||
@@ -520,13 +691,17 @@ def api():
|
||||
finally:
|
||||
async with self.cond:
|
||||
self.reloading = False
|
||||
if ok:
|
||||
self.fresh = mine
|
||||
self.cond.notify_all()
|
||||
|
||||
gate = Gate()
|
||||
# under Modal's 150 s web request limit, past which the request is lost (408) and a box can't ask again
|
||||
RELOAD_WAIT_S = 100
|
||||
|
||||
async def reloaded():
|
||||
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)"""
|
||||
if not await gate.reload():
|
||||
if not await gate.reload(within=RELOAD_WAIT_S):
|
||||
raise HTTPException(503, "the farm's volume is busy: try again")
|
||||
|
||||
def check(req: Request):
|
||||
@@ -544,23 +719,10 @@ 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.
|
||||
def seams(g):
|
||||
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
|
||||
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
|
||||
import numpy as np
|
||||
|
||||
found = []
|
||||
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
|
||||
n = d.shape[0]
|
||||
share = (d > 24).mean(axis=1)
|
||||
for i in range(int(n * 0.08), int(n * 0.92)):
|
||||
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
|
||||
found.append([axis, i + 1, round(float(share[i]), 2)])
|
||||
return found
|
||||
|
||||
@web.post("/v1/scene")
|
||||
async def scene(req: Request):
|
||||
@@ -569,11 +731,6 @@ def api():
|
||||
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
|
||||
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
|
||||
[x, y, w, h, "the text", score], in that frame's pixels"""
|
||||
import base64
|
||||
import cv2
|
||||
import numpy as np
|
||||
import farm_scene
|
||||
|
||||
check(req)
|
||||
body = await req.json()
|
||||
frames = body.get("frames") if isinstance(body, dict) else None
|
||||
@@ -581,18 +738,11 @@ def api():
|
||||
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
|
||||
if len(frames) > 400:
|
||||
raise HTTPException(413, "at most 400 frames a call")
|
||||
global SCENE
|
||||
if SCENE is None:
|
||||
SCENE = farm_scene.Scene()
|
||||
out = []
|
||||
for b64 in frames:
|
||||
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
|
||||
if im is None:
|
||||
out.append(None)
|
||||
continue
|
||||
r = SCENE.read(im)
|
||||
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
|
||||
out.append(r)
|
||||
if len(frames) <= SCENE_HERE:
|
||||
out = await asyncio.to_thread(read_scenes, frames)
|
||||
else:
|
||||
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
|
||||
out = [r async for part in scene_run.map.aio(parts) for r in part]
|
||||
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
|
||||
|
||||
@web.post("/v1/words")
|
||||
@@ -604,8 +754,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")
|
||||
@@ -615,7 +766,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:
|
||||
@@ -623,11 +793,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):
|
||||
@@ -636,7 +814,7 @@ def api():
|
||||
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
|
||||
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
|
||||
q = req.query_params
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "nv": q.get("nv") if q.get("nv") in ("0", "1") else None, "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
id = str(uuid.uuid4())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
async with gate.use():
|
||||
@@ -671,7 +849,7 @@ def api():
|
||||
blob = f"{ROOT}/blobs/{oid}"
|
||||
if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
have.append(oid)
|
||||
return {"have": have}
|
||||
return {"have": have, "links": 1}
|
||||
|
||||
@web.put("/v1/blobs/{oid}")
|
||||
async def blob_put(oid: str, req: Request):
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
|
||||
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
|
||||
|
||||
import uuid
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -43,9 +44,21 @@ def inside(work, rel):
|
||||
return p == os.path.realpath(work) or p.startswith(os.path.realpath(work) + os.sep)
|
||||
|
||||
|
||||
def get(href, header, dest):
|
||||
# the most an original of unknown size may be: a link that answers with more is refused before it fills the volume
|
||||
UNKNOWN_MAX = 40 << 30
|
||||
|
||||
|
||||
def get(href, header, dest, limit=None):
|
||||
req = urllib.request.Request(href, headers={**AGENT, **(header or {})})
|
||||
with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:
|
||||
if limit:
|
||||
n = 0
|
||||
while chunk := r.read(8 << 20):
|
||||
n += len(chunk)
|
||||
if n > limit:
|
||||
raise ValueError(f"media: {href.split('?')[0]} is over {limit >> 30} GB, more than an original of unknown size may be")
|
||||
f.write(chunk)
|
||||
return
|
||||
shutil.copyfileobj(r, f, CHUNK)
|
||||
|
||||
|
||||
@@ -80,38 +93,64 @@ def fetch(work, cache, log=print, download=get, check=probe):
|
||||
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
|
||||
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
|
||||
blob = os.path.join(cache, oid)
|
||||
# size 0: a library original whose size raea cloud doesn't know (it comes with its link); its hash alone says
|
||||
# it's the one. What the box sent (no link) is held only at its own size
|
||||
held = os.path.exists(blob) and (os.path.getsize(blob) == size or (size <= 0 and bool(o.get("href"))))
|
||||
if not o.get("href"):
|
||||
# sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
|
||||
if not (os.path.exists(blob) and os.path.getsize(blob) == size):
|
||||
if not held:
|
||||
raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
|
||||
cached += size
|
||||
elif os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
elif held:
|
||||
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
|
||||
check(o["href"], o.get("header"))
|
||||
cached += size
|
||||
cached += os.path.getsize(blob)
|
||||
else:
|
||||
tmp = f"{blob}.part-{os.getpid()}"
|
||||
download(o["href"], o.get("header"), tmp)
|
||||
tmp = f"{blob}.part-{uuid.uuid4().hex}"
|
||||
try:
|
||||
download(o["href"], o.get("header"), tmp, *([UNKNOWN_MAX] if size <= 0 else []))
|
||||
except Exception:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
raise
|
||||
got = sha256(tmp)
|
||||
if got != oid or os.path.getsize(tmp) != size:
|
||||
if got != oid or (size > 0 and os.path.getsize(tmp) != size):
|
||||
os.remove(tmp)
|
||||
raise ValueError(f"media: {path} came back as {got[:12]}…, not {oid[:12]}…")
|
||||
fetched += os.path.getsize(tmp)
|
||||
os.replace(tmp, blob)
|
||||
fetched += size
|
||||
dest = os.path.join(work, path)
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if os.path.lexists(dest):
|
||||
os.remove(dest)
|
||||
# a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
|
||||
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too
|
||||
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too. It ends at a
|
||||
# file with the take's own name (cache/named/OID/NAME, a hard link to the blob): a bundler follows the link, and
|
||||
# a composition that knows its takes by name (Framed's faces) found only a hash and framed every shot centred
|
||||
try:
|
||||
os.symlink(blob, dest)
|
||||
os.symlink(named(cache, oid, path), dest)
|
||||
except OSError:
|
||||
shutil.copyfile(blob, dest)
|
||||
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
|
||||
return {"objects": len(objects), "fetched": fetched, "cached": cached}
|
||||
|
||||
|
||||
def named(cache, oid, path):
|
||||
"""the blob under the take's own name, cache/named/OID/NAME: a hard link (the same file, no space), else the blob"""
|
||||
blob = os.path.join(cache, oid)
|
||||
out = os.path.join(cache, "named", oid, os.path.basename(path))
|
||||
if os.path.exists(out) and os.path.getsize(out) == os.path.getsize(blob):
|
||||
return out
|
||||
try:
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
tmp = f"{out}.part-{uuid.uuid4().hex}"
|
||||
os.link(blob, tmp)
|
||||
os.replace(tmp, out)
|
||||
return out
|
||||
except OSError:
|
||||
return blob
|
||||
|
||||
|
||||
def is_media(path, size):
|
||||
ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path) else ""
|
||||
return ext in MEDIA or size >= LARGE
|
||||
|
||||
@@ -94,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
|
||||
@@ -277,7 +365,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
|
||||
t.start()
|
||||
video = out.endswith(VIDEO)
|
||||
can_flat = bool(video and cpu_render and not opts.get("gpu"))
|
||||
can_flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1")
|
||||
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys
|
||||
keyed, keys_s = farm_keys.read(rest, work, run, cpu_env, f"/tmp/{id}-keys.json") if video and opts.get("keys") else (None, 0)
|
||||
|
||||
@@ -321,9 +409,14 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
gpu_render, gpu_kind = render, kind
|
||||
# a piece with 3D in it keeps its GPU, and its runs use the GPU's encoder and decoder too (CR34): on a 2D piece NVENC
|
||||
# bought nothing (300 frames: 210 s against libx264's 215 s, 11% more bytes), the page and the clips are the work
|
||||
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)
|
||||
# (opts nv "1" or "0" says so for the job, and "1" keeps it on GPUs: to measure what NVENC and NVDEC buy a cut)
|
||||
nv = opts.get("nv") == "1" or (opts.get("nv") != "0" and bool((p.get("manifest") or {}).get("has3d")))
|
||||
flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1" and (p.get("manifest") or {}).get("has3d") is False)
|
||||
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 +437,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 +463,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)
|
||||
@@ -429,7 +541,10 @@ def joined(probe, parts):
|
||||
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
|
||||
clips = []
|
||||
for c in pieces:
|
||||
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
|
||||
# the same source carried on across a run's seam, whatever its React key: each run numbers its nodes its own
|
||||
# way (12-04, StreetTalk round 22: Body Shop's clips came back keyed n3 and n11 by turns, split at frames 60,
|
||||
# 420, 720 and 807, and the sound check called each seam a cut inside a word)
|
||||
prev = next((p for p in reversed(clips) if p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
|
||||
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
|
||||
prev["to"] = c["to"]
|
||||
if "fadeOut" in c:
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# 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
|
||||
# every proxy says what it is in its comment tag, and ffmpeg carries the tag into what's made from it: a box's renders
|
||||
# and publishes read it (raea-platform harness/light.ts) so nothing made from a proxy is shown to a person as a final
|
||||
LIGHT_TAG = "raea-light-copy"
|
||||
AGENT = {"user-agent": "raea-ingest/1"}
|
||||
|
||||
|
||||
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", "-metadata", f"comment={LIGHT_TAG}", "-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,131 @@
|
||||
# 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"}
|
||||
|
||||
|
||||
# 12-05, run 8: three projects' 8-at-once transcriptions queued on 2 of each, and Elfster's 51 takes took 6.5 minutes
|
||||
# (its wait for them ran past the fetch step's 4). Hear 4 and Align 3 hold 7 of the account's 10 GPUs at a run's start,
|
||||
# before its renders, which draw on CPUs and use the GPUs only for each cut's first frame
|
||||
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=3, scaledown_window=60)
|
||||
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=4, 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
|
||||
@@ -86,7 +86,8 @@ up)
|
||||
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
|
||||
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
|
||||
for i in $(seq 1 90); do
|
||||
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
|
||||
# (a Sprite just made has no server yet: curl's own exit ended this script, 12-01)
|
||||
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null || true" | python3 -c 'import json,sys
|
||||
try: print(json.load(sys.stdin).get("running", "unknown"))
|
||||
except Exception: print("down")')
|
||||
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
|
||||
|
||||
@@ -21,6 +21,17 @@ 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
|
||||
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
|
||||
node -v 2> /dev/null | grep -q '^v24' || {
|
||||
say "node $NODE"
|
||||
curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | sudo tar -xJ -C /opt
|
||||
@@ -103,6 +114,9 @@ cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
|
||||
set -a
|
||||
. ~/.raea-cloud.env
|
||||
set +a
|
||||
# footage is read 16 MB ahead: a Sprite's disk answers each read in about 26 ms, and at its own 256 KB a pass over
|
||||
# a 1 GB interview took two minutes that takes 14 s so (12-01, measured). Set at each start: a Sprite woken keeps none.
|
||||
for b in /sys/class/bdi/*/read_ahead_kb /sys/block/*/queue/read_ahead_kb; do sudo sh -c "echo 16384 > $b" 2> /dev/null || true; done
|
||||
export PORT=8080 RAEA_CLOUD_DEVICE=cpu WGPU_BACKEND=vulkan __EGL_VENDOR_LIBRARY_DIRS=/nonexistent
|
||||
export VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)
|
||||
mkdir -p ~/work
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// components/Cut.tsx: a whole cut composed from its moments. The agent says, per moment, WHAT is on screen (the speaker,
|
||||
// two people, the product, a cutaway, a screen, the wide, the end card) and which take is heard; this lays each one out
|
||||
// with <Shot>, places the product clear of faces, keeps the speaker talking under a cutaway, captions every word in the
|
||||
// brand's style (on the seam of a split, at the bottom otherwise), holds the hook in <Title> at the top, and
|
||||
// ends on the brand's <EndCard>. Every cut of a project then looks the same, and nothing is placed by a typed number.
|
||||
// Put there by the box's prep beside Shot.tsx.
|
||||
//
|
||||
// <Cut said={words} keys={["the product"]} hook="Do you know her this well?" bed={bed} moments={[
|
||||
// { show: "speaker", src: "footage/A.mp4", startFrom: 30, endAt: 120, who: "right" },
|
||||
// { show: "two", src: "footage/A.mp4", startFrom: 400, endAt: 520 },
|
||||
// { show: "broll", src: "footage/A.mp4", startFrom: 520, endAt: 610, asset: "footage/B.mp4", assetFrom: 300 },
|
||||
// { show: "product", src: "footage/A.mp4", startFrom: 900, endAt: 1010, asset: "media/product.png" },
|
||||
// { show: "end", src: "footage/H.mp4", startFrom: 0, endAt: 90, cta: "Get yours today", offer: "20% off" },
|
||||
// ]} />
|
||||
//
|
||||
// A moment lasts its take's span (endAt - startFrom), or `frames` when it has no take. `said` is the cut's words in its
|
||||
// own frames, as `raea cut` gives them for these spans in this order.
|
||||
import { Audio, Sequence, useCurrentFrame } from "raea";
|
||||
import EndCard from "./EndCard";
|
||||
import Said from "./Said";
|
||||
import Shot, { type Layout } from "./Shot";
|
||||
import Title from "./Title";
|
||||
|
||||
type Who = number | string;
|
||||
type Word = { text: string; from: number; to: number };
|
||||
|
||||
export type Moment = {
|
||||
/** what's on screen: the speaker, two people (a split), the product (an insert), a cutaway, a screen (a stack), the
|
||||
* whole wide take, or the end card */
|
||||
show: "speaker" | "two" | "product" | "broll" | "screen" | "wide" | "end";
|
||||
/** the take heard (and seen, but for a cutaway, a screen's top and the end card), and its span in the edit's frames */
|
||||
src?: string;
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** the length when there's no take (an end card alone) */
|
||||
frames?: number;
|
||||
/** who's framed (Shot's `who`), and a split's two (Shot's `pair`) */
|
||||
who?: Who;
|
||||
pair?: [Who, Who];
|
||||
/** the product picture, the cutaway's take or the screen, and where its video starts */
|
||||
asset?: string;
|
||||
assetFrom?: number;
|
||||
/** the product picture's width over its height */
|
||||
aspect?: number;
|
||||
/** the clip's level change in dB (cuts.ts's gainDb) and how far it's punched in (cuts.ts's punchIn(i): a jump cut
|
||||
* reframes) */
|
||||
gainDb?: number;
|
||||
punchIn?: number;
|
||||
/** the end card's CTA (the brief's words) and offer */
|
||||
cta?: string;
|
||||
offer?: string;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
moments: Moment[];
|
||||
/** the cut's words, in its frames; no captions without them */
|
||||
said?: readonly Word[];
|
||||
/** key words the captions light (Said's `keys`) */
|
||||
keys?: string[];
|
||||
/** emoji by word (Said's `emoji`); none unless named */
|
||||
emoji?: Record<string, string>;
|
||||
/** the hook, held in <Title> at the top over the first `hookFrames` (until the first sentence ends, 2 s at most);
|
||||
* the captions run under it at the bottom, so no word goes uncaptioned */
|
||||
hook?: string;
|
||||
hookFrames?: number;
|
||||
/** the music bed under the whole cut (the generate tool's), at BED_DB with fades: never a typed level */
|
||||
bed?: string;
|
||||
};
|
||||
|
||||
/** the bed's level: about 16 dB under the voices once <Mix> masters the cut, inside the check's 12-20 dB (12-05: beds
|
||||
* typed at volume 0.07 or gainDb -21 sat 28-30 dB under, and the check heard no music) */
|
||||
export const BED_DB = -10;
|
||||
|
||||
const LAYOUT: Record<Exclude<Moment["show"], "end">, Layout> = { speaker: "face", two: "split", product: "insert", broll: "broll", screen: "stack", wide: "fit" };
|
||||
|
||||
/** each moment's first frame on the cut and its length */
|
||||
export function spans(ms: Moment[]): { from: number; len: number }[] {
|
||||
let at = 0;
|
||||
return ms.map((m) => {
|
||||
const len = Math.max(1, m.src && m.endAt !== undefined ? m.endAt - (m.startFrom ?? 0) : (m.frames ?? 60));
|
||||
const s = { from: at, len };
|
||||
at += len;
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
/** the cut's words in its frames, from each heard take's words (footage/NAME.words.json, by the take's name): the words
|
||||
* each moment's span says, in the moments' order; a word cut off by a span's edge is left out */
|
||||
export function saidOf(ms: Moment[], words: Record<string, readonly { text: string; start_ms: number; end_ms: number }[]>, fps: number): Word[] {
|
||||
const out: Word[] = [];
|
||||
const sp = spans(ms);
|
||||
ms.forEach((m, i) => {
|
||||
if (!m.src) return;
|
||||
const ws = words[m.src.split("/").pop()!.replace(/\.[^.]+$/, "")] ?? [];
|
||||
const a = (m.startFrom ?? 0) / fps;
|
||||
const b = a + sp[i].len / fps;
|
||||
for (const w of ws) {
|
||||
const s = w.start_ms / 1000;
|
||||
const e = w.end_ms / 1000;
|
||||
if (s >= a - 0.02 && e <= b + 0.05) out.push({ text: w.text, from: sp[i].from + Math.max(0, Math.round((s - a) * fps)), to: sp[i].from + Math.min(sp[i].len, Math.round((e - a) * fps)) });
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** cuts.ts's clips as moments, in order: each one the speaker (or `show` for clip i), its span in the edit's frames as
|
||||
* cuts.ts counts them, its gainDb, and a jump cut punched in every other time (cuts.ts's punchIn). Change a moment's
|
||||
* show, who or asset after; the timing stays raea cut's. */
|
||||
export function fromCuts(
|
||||
cuts: readonly { src: string; from: number; to: number; gainDb?: number; jump?: boolean; kind?: string }[],
|
||||
fps: number,
|
||||
punchIn?: (i: number) => number,
|
||||
show?: (i: number) => Partial<Moment> | undefined,
|
||||
): Moment[] {
|
||||
return cuts.map((c, i) => {
|
||||
const s = Math.round(c.from * fps);
|
||||
const len = Math.max(1, Math.round((c.to - c.from) * fps));
|
||||
const k = punchIn ? punchIn(i) : 1;
|
||||
return { show: "speaker", src: c.src, startFrom: s, endAt: s + len, ...(c.gainDb ? { gainDb: c.gainDb } : {}), ...(k !== 1 ? { punchIn: k } : {}), ...(show?.(i) ?? {}) } as Moment;
|
||||
});
|
||||
}
|
||||
|
||||
/** the captions' band for what's on screen: over a split's or a stack's seam, else at the bottom */
|
||||
const bandOf = (m?: Moment) => (m && (m.show === "two" || m.show === "screen") ? "center" : "bottom");
|
||||
|
||||
export default function Cut({ moments, said, keys, emoji, hook, hookFrames, bed }: Props) {
|
||||
const f = useCurrentFrame();
|
||||
const sp = spans(moments);
|
||||
const now = sp.findIndex((s) => f >= s.from && f < s.from + s.len);
|
||||
// the hook holds until the first sentence is said (2 s at most), unless told
|
||||
const firstEnd = said?.find((w) => /[.?!]$/.test(w.text))?.to;
|
||||
const hookLen = hookFrames ?? Math.min(60, firstEnd ?? 60);
|
||||
const showHook = !!hook && f < hookLen;
|
||||
return (
|
||||
<>
|
||||
{moments.map((m, i) => (
|
||||
<Sequence key={i} from={sp[i].from} durationInFrames={sp[i].len} name={`${m.show} ${i + 1}`}>
|
||||
{m.show === "end" ? (
|
||||
<>
|
||||
<EndCard cta={m.cta ?? ""} offer={m.offer} asset={m.asset} />
|
||||
{m.src ? <Audio src={m.src} startFrom={m.startFrom} endAt={m.endAt} gainDb={m.gainDb} /> : null}
|
||||
</>
|
||||
) : m.src ? (
|
||||
<Shot layout={LAYOUT[m.show]} src={m.src} startFrom={m.startFrom} endAt={m.endAt} who={m.who} pair={m.pair} asset={m.asset} assetFrom={m.assetFrom} aspect={m.aspect} gainDb={m.gainDb} punchIn={m.punchIn} />
|
||||
) : null}
|
||||
</Sequence>
|
||||
))}
|
||||
{bed ? <Audio src={bed} gainDb={BED_DB} fadeIn={0.3} fadeOut={1} /> : null}
|
||||
{showHook ? <Title region="top">{hook}</Title> : null}
|
||||
{said?.length ? <Said said={said} keys={keys} emoji={emoji} region={bandOf(moments[now])} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// components/EndCard.tsx: a cut's last card from the brand template (components/brand.ts): the brand's surface, its logo,
|
||||
// the CTA in the brief's own words and the offer on the brand's button, every part inside the app's zones. Put there by
|
||||
// the box's prep beside Shot.tsx. Change the look freely; never give a part a top or a left.
|
||||
import type React from "react";
|
||||
import { AbsoluteFill, Img, interpolate, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import { COLORS, FONTS, RADIUS, logo as brandLogo, zones } from "./brand";
|
||||
|
||||
type Props = {
|
||||
/** the call to action, word for word from the brief */
|
||||
cta: string;
|
||||
/** the offer (a code, a discount), on the brand's button */
|
||||
offer?: string;
|
||||
/** the logo's file; the brand kit's when unset, none when it has none */
|
||||
logo?: string | null;
|
||||
/** a product picture above the CTA */
|
||||
asset?: string;
|
||||
/** merged over the card's surface */
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
/** the offer's size: 64 px at 1080 wide, less when its line (about 0.6 em a letter in a bold face, and the button's
|
||||
* padding) wouldn't fit `inner`; never under 56 px (the check calls less small print): a longer offer wraps, evenly */
|
||||
export const offerSize = (offer: string, inner: number, s: number) => Math.max(56 * s, Math.min(64 * s, (inner - 96 * s) / (0.6 * Math.max(1, offer.length))));
|
||||
|
||||
export default function EndCard({ cta, offer, logo, asset, style }: Props) {
|
||||
const f = useCurrentFrame();
|
||||
const { width: W, height: H } = useVideoConfig();
|
||||
const z = zones(W, H);
|
||||
const s = W / 1080;
|
||||
const mark = logo === undefined ? brandLogo("dark") : logo;
|
||||
// the card's inner width: inside the app's zones and the card's own margin
|
||||
const inner = W - z.left - Math.max(z.left, z.right) - 80 * s;
|
||||
const rise = (d: number) => ({
|
||||
opacity: interpolate(f, [d, d + 8], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }),
|
||||
transform: `translateY(${interpolate(f, [d, d + 10], [24 * s, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })}px)`,
|
||||
});
|
||||
return (
|
||||
<AbsoluteFill data-shot="end" style={{ background: COLORS.surface, ...style }}>
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: z.left + 40 * s,
|
||||
right: Math.max(z.left, z.right) + 40 * s,
|
||||
top: z.top + 40 * s,
|
||||
bottom: z.bottom + 40 * s,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 56 * s,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
{mark ? <Img src={mark} style={{ maxWidth: 560 * s, maxHeight: 220 * s, objectFit: "contain", ...rise(0) }} /> : null}
|
||||
{asset ? <Img src={asset} style={{ maxWidth: 620 * s, maxHeight: 520 * s, objectFit: "contain", borderRadius: RADIUS * s, ...rise(4) }} /> : null}
|
||||
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: 88 * s, lineHeight: 1.08, color: COLORS.text, ...rise(6) }}>{cta}</div>
|
||||
{offer ? (
|
||||
// the offer on one line when it fits at 56 px or more, else wrapped evenly (12-05: "Code SAVE60 · $60 off" broke
|
||||
// over two with one word alone, and shrunk to fit it was 40 px, small print)
|
||||
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: offerSize(offer, inner, s), lineHeight: 1.1, maxWidth: inner, textWrap: "balance", color: COLORS.buttonText, background: COLORS.button, borderRadius: RADIUS * s * 2, padding: `${28 * s}px ${48 * s}px`, ...rise(12) }}>{offer}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// components/Framed.tsx: a take cropped to the edit's shape around the person in it, from footage/faces.json (the
|
||||
// box's prep finds every take's faces at its keyframes: image/faces.py). 12-05, Shane: "the ai fucks up the composition
|
||||
// of subjects in frame all the time": each crop was a number the agent guessed (objectPosition), and a 9:16 cut showed
|
||||
// a bench while the woman talking was cut off at the edge.
|
||||
//
|
||||
// <Framed src={c.src} startFrom={f0} endAt={f1} /> the clip's largest face, whole, eyes a third down
|
||||
// <Framed ... at={0.7} /> the face nearest 70% across the take (the guest, not the host)
|
||||
// <Framed ... punchIn={1.15} /> tighter, still on the face
|
||||
//
|
||||
// The crop holds still for the clip (an editor's locked-off reframe), and follows only when the face moves further
|
||||
// than one still crop can hold, smoothed over a second. A take with no faces is centred.
|
||||
import type React from "react";
|
||||
import { Video, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import FACES from "../footage/faces.json";
|
||||
|
||||
type Take = { w: number; h: number; t: number[]; s: number[][][] };
|
||||
const TRACKS = FACES as unknown as Record<string, Take>;
|
||||
|
||||
type Props = {
|
||||
src: string;
|
||||
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** which face when several: the one nearest this share across the take (0 left, 1 right); default the largest */
|
||||
at?: number;
|
||||
/** 1 = the whole height of the take; above 1 = tighter, centred on the face */
|
||||
punchIn?: number;
|
||||
volume?: number;
|
||||
/** the clip's level change in dB (cuts.ts gives it, evening the cut's voices) */
|
||||
gainDb?: number;
|
||||
playbackRate?: number;
|
||||
muted?: boolean;
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
const clamp = (x: number, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
||||
const median = (xs: number[]) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s.length ? s[Math.floor(s.length / 2)] : 0.5;
|
||||
};
|
||||
/** the face's room from the crop's edge: a third of its own width either side */
|
||||
const ROOM = 1 / 3;
|
||||
|
||||
/** the take's face at each sample from `a` to `b` seconds: [t, cx, ey, fw], and every other face's span across the
|
||||
* take ([t, left, right]) */
|
||||
function path(take: Take, a: number, b: number, near?: number): { p: [number, number, number, number][]; others: [number, number, number][] } {
|
||||
const out: [number, number, number, number][] = [];
|
||||
const others: [number, number, number][] = [];
|
||||
let last: number | undefined = near;
|
||||
for (let i = 0; i < take.t.length; i++) {
|
||||
const t = take.t[i];
|
||||
if (t < a - 1 || t > b + 1) continue;
|
||||
const fs = take.s[i];
|
||||
if (!fs?.length) continue;
|
||||
// the face asked for (nearest `at`), followed from sample to sample, else the largest; a sample where no face is in
|
||||
// reach of them (a face width and a half, or 8% of the take) doesn't have them, and the crop holds: it never jumps
|
||||
// to someone else (12-05: the host at 0.4 went undetected for a second, the guest at 0.61 was nearest, and the crop
|
||||
// swung to him mid-shot, under the hook)
|
||||
const g = last === undefined ? fs[0] : fs.reduce((p, q) => (Math.abs(q[0] - last!) < Math.abs(p[0] - last!) ? q : p));
|
||||
const f = last === undefined || Math.abs(g[0] - last) <= Math.max(1.5 * g[2], 0.08) ? g : undefined;
|
||||
for (const o of fs) if (o !== f) others.push([t, o[0] - o[2] / 2, o[0] + o[2] / 2]);
|
||||
if (!f) continue;
|
||||
last = f[0];
|
||||
out.push([t, f[0], f[1], f[2]]);
|
||||
}
|
||||
return { p: out, others };
|
||||
}
|
||||
|
||||
/** the crop's left edge nearest `ideal` that keeps the framed face (lo..hi across the take) inside it and cuts no other
|
||||
* face: each other face either whole in the crop or wholly out of it (12-05, a street interview: the crop on the host cut the
|
||||
* man beside her in half at the right edge). `ideal` when no such edge exists */
|
||||
function cleanLeft(ideal: number, vw: number, lo: number, hi: number, others: [number, number][]): number {
|
||||
const most = Math.max(0, 1 - vw);
|
||||
const a = clamp(hi - vw, 0, most);
|
||||
const b = clamp(lo, 0, most);
|
||||
if (a > b || !others.length) return ideal;
|
||||
const cuts = (l: number) => others.some(([x1, x2]) => (l > x1 && l < x2) || (l + vw > x1 && l + vw < x2));
|
||||
const tries = [ideal, ...others.flatMap(([x1, x2]) => [x2 + 0.005, x1 - 0.005, x1 - vw - 0.005, x2 - vw + 0.005])];
|
||||
const ok = tries.filter((l) => l >= a && l <= b && l >= 0 && l <= most && !cuts(l));
|
||||
return ok.length ? ok.reduce((x, y) => (Math.abs(y - ideal) < Math.abs(x - ideal) ? y : x)) : ideal;
|
||||
}
|
||||
|
||||
export default function Framed({ src, startFrom = 0, endAt, at, punchIn = 1, volume, gainDb, playbackRate, muted, style }: Props) {
|
||||
const frame = useCurrentFrame();
|
||||
const { width, height, fps } = useVideoConfig();
|
||||
const name = src.split("/").pop()!.replace(/\.[^.]+$/, "");
|
||||
const take = TRACKS[name];
|
||||
const a = startFrom / fps;
|
||||
const b = endAt !== undefined ? endAt / fps : a + 600;
|
||||
const now = a + (frame / fps) * (playbackRate ?? 1);
|
||||
let pos = "50% 50%";
|
||||
let transform: string | undefined;
|
||||
let origin: string | undefined;
|
||||
if (take) {
|
||||
const k = Math.max(1, punchIn);
|
||||
// the share of the take the box shows across and down (object-fit: cover), before and after the punch-in
|
||||
const box = width / height;
|
||||
const src_ = take.w / take.h;
|
||||
const vw = Math.min(1, box / src_) / k;
|
||||
const vh = Math.min(1, src_ / box) / k;
|
||||
const { p, others } = path(take, a, b, at);
|
||||
if (p.length) {
|
||||
const xs = p.map((s) => s[1]);
|
||||
const fw = Math.max(...p.map((s) => s[3]));
|
||||
// one still crop when every sample's face fits it with room either side; else follow, smoothed over a second
|
||||
const fits = Math.max(...xs) - Math.min(...xs) + fw * (1 + 2 * ROOM) <= vw;
|
||||
const near = p.filter((s) => Math.abs(s[0] - now) <= 0.5);
|
||||
const cx = fits ? median(xs) : median((near.length ? near : p).map((s) => s[1]));
|
||||
const ey = median((fits || !near.length ? p : near).map((s) => s[2]));
|
||||
// the crop's left and top edges, in shares of the take: the face across its middle, the eyes a third down
|
||||
// the framed face's span the crop must hold (every sample's when still, the nearest second's when following),
|
||||
// and the other faces there, which it mustn't cut
|
||||
const held = fits || !near.length ? p : near;
|
||||
const lo = Math.min(...held.map((s) => s[1] - s[3] / 2));
|
||||
const hi = Math.max(...held.map((s) => s[1] + s[3] / 2));
|
||||
const span = (fits ? others : others.filter((o) => Math.abs(o[0] - now) <= 0.5)).map((o) => [o[1], o[2]] as [number, number]);
|
||||
const left = cleanLeft(clamp(cx - vw / 2, 0, 1 - vw), vw, lo, hi, span);
|
||||
const top = clamp(ey - vh / 3, 0, 1 - vh);
|
||||
if (k === 1) {
|
||||
pos = `${vw >= 1 ? 50 : (left / (1 - vw)) * 100}% ${vh >= 1 ? 50 : (top / (1 - vh)) * 100}%`;
|
||||
} else {
|
||||
// cover at 1, then scaled about the point that puts the chosen window in the box
|
||||
const vw1 = vw * k;
|
||||
const vh1 = vh * k;
|
||||
const l1 = cleanLeft(clamp(cx - vw1 / 2, 0, 1 - vw1), vw1, lo, hi, span);
|
||||
const t1 = clamp(ey - vh1 / 3, 0, 1 - vh1);
|
||||
pos = `${vw1 >= 1 ? 50 : (l1 / (1 - vw1)) * 100}% ${vh1 >= 1 ? 50 : (t1 / (1 - vh1)) * 100}%`;
|
||||
// the window's left edge at the box's left: scale about the point o where (o - l1)/vw1 = (o - left)/vw
|
||||
const ox = vw1 === vw ? 0.5 : (left * vw1 - l1 * vw) / (vw1 - vw);
|
||||
const oy = vh1 === vh ? 0.5 : (top * vh1 - t1 * vh) / (vh1 - vh);
|
||||
transform = `scale(${k})`;
|
||||
origin = `${clamp((ox - l1) / vw1) * 100}% ${clamp((oy - t1) / vh1) * 100}%`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Video
|
||||
src={src}
|
||||
startFrom={startFrom}
|
||||
endAt={endAt}
|
||||
volume={volume}
|
||||
gainDb={gainDb}
|
||||
playbackRate={playbackRate}
|
||||
muted={muted}
|
||||
style={{ width: "100%", height: "100%", objectFit: "cover", ...style, objectPosition: pos, ...(transform ? { transform, transformOrigin: origin } : {}) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// components/Said.tsx: a cut's captions in the brand's caption style with its key words lit, through raea's <Captions>
|
||||
// (the cut's own words, in a safe band, marked as captions for the check and the layered export). Put there by the box's
|
||||
// prep beside Shot.tsx. The word being said is lit in the accent; a key word (a number, a price, a percentage, or one of
|
||||
// `keys`: the product's name, the brief's must-say) is lit from the moment it's said. An emoji goes
|
||||
// after a word only where `emoji` names it: never chosen by guess.
|
||||
import { Captions, type RegionName } from "raea";
|
||||
import { CAPTION } from "./brand";
|
||||
|
||||
type Word = { text: string; from: number; to: number };
|
||||
type Props = {
|
||||
/** the cut's words, in its frames (`raea cut` gives them) */
|
||||
said: readonly Word[];
|
||||
/** the key words and phrases to light, case ignored ("the product's name", "96 hours") */
|
||||
keys?: string[];
|
||||
/** an emoji after a word, by the word, case ignored ({ "love": "❤️" }) */
|
||||
emoji?: Record<string, string>;
|
||||
/** the band (Region): "bottom" by default; "center" over a split's or a stack's seam */
|
||||
region?: RegionName;
|
||||
/** the size in px at 1080 wide (the brand's caption size) */
|
||||
size?: number;
|
||||
/** how a misheard word is written, as Captions takes it */
|
||||
fix?: Record<string, string>;
|
||||
};
|
||||
|
||||
const bare = (t: string) => t.toLowerCase().replace(/[^\p{L}\p{N}%$€£']/gu, "");
|
||||
/** a word worth lighting by itself: a number, a price, a percentage */
|
||||
const NUMBER = /\d|%|\$|€|£/;
|
||||
|
||||
/** which of `ws` are key: a number, or part of a run of words that spells one of `keys` */
|
||||
export function keyed(ws: readonly Word[], keys: string[] = []): boolean[] {
|
||||
const out = ws.map((w) => NUMBER.test(w.text));
|
||||
const phrases = keys.map((k) => k.split(/\s+/).map(bare).filter(Boolean)).filter((k) => k.length);
|
||||
for (let i = 0; i < ws.length; i++)
|
||||
for (const k of phrases) if (k.every((p, j) => bare(ws[i + j]?.text ?? "") === p)) for (let j = 0; j < k.length; j++) out[i + j] = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
export default function Said({ said, keys, emoji, region = "bottom", size = CAPTION.size, fix }: Props) {
|
||||
const hot = keyed(said, keys);
|
||||
const at = new Map(said.map((w, i) => [w, i]));
|
||||
const em = Object.fromEntries(Object.entries(emoji ?? {}).map(([k, v]) => [bare(k), v]));
|
||||
return (
|
||||
<Captions said={said as Word[]} region={region} size={size} fix={fix}>
|
||||
{(ws, saying) =>
|
||||
ws.map((w, j) => {
|
||||
// the caption's words are copies (spelled by `fix`): found again among the cut's by their frames
|
||||
const i = at.get(said.find((x) => x.from === w.from && x.to === w.to) as Word) ?? -1;
|
||||
const key = i >= 0 && hot[i];
|
||||
const lit = j === saying || (key && saying >= j);
|
||||
const e = em[bare(w.text)];
|
||||
return (
|
||||
// a key word is lit, never drawn bigger: a bigger word made the line taller than the band Captions keeps it in,
|
||||
// and its letters reached the app's bottom zone (12-05, a composed street cut: 1 px into the 420 px)
|
||||
<span key={j} style={{ color: lit ? CAPTION.accent : undefined }}>
|
||||
{w.text}
|
||||
{e ? ` ${e}` : ""}
|
||||
{j < ws.length - 1 ? " " : ""}
|
||||
</span>
|
||||
);
|
||||
})
|
||||
}
|
||||
</Captions>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// components/Shot.tsx: one moment of a cut, laid out from what the agent says is on screen, every time the same way. Put
|
||||
// there by the box's prep beside Framed.tsx. 12-05, Shane: framing and timing aren't enough, "it's also composition of
|
||||
// footage and assets": agents built each cut's layout by hand and by guess (a split on one face, a product card over the
|
||||
// guest's face, a cutaway with nobody talking under it). The agent picks the moment and the layout; this places it.
|
||||
//
|
||||
// <Shot layout="face" src={take} startFrom={f0} endAt={f1} who={0.7} /> the speaker framed (Framed.tsx)
|
||||
// <Shot layout="split" src={take} ... pair={["left", "right"]} /> two people of one wide take, one a half
|
||||
// <Shot layout="insert" src={take} ... asset="media/product.png" /> the speaker, the product in the clear
|
||||
// <Shot layout="stack" src={take} ... asset="media/screen.mp4" /> the asset on top, the speaker below
|
||||
// <Shot layout="fit" src={take} ... /> the whole take over a dimmed copy
|
||||
// <Shot layout="broll" src={take} ... asset="footage/broll.mp4" /> the cutaway, the take still heard (L-cut)
|
||||
//
|
||||
// Each falls back when the take can't hold it, from the faces prep found (footage/faces.json): a split with fewer than
|
||||
// two people in the moment, or two who can't each be shown whole and alone, is the face of the first; an insert with no
|
||||
// clear place off every face is a stack. Never type a crop, a top or a left: change what's on screen instead.
|
||||
import type React from "react";
|
||||
import { AbsoluteFill, Audio, Img, Video, interpolate, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import FACES from "../footage/faces.json";
|
||||
import Framed from "./Framed";
|
||||
import { RADIUS, zones } from "./brand";
|
||||
import { type Take, type Win, css, holdsAlone, onScreen, people, pick, windowOn } from "./crop";
|
||||
|
||||
export type Layout = "face" | "split" | "stack" | "fit" | "insert" | "broll";
|
||||
type Who = number | string;
|
||||
|
||||
export type ShotProps = {
|
||||
layout: Layout;
|
||||
/** the take this moment is heard from (and shown from, but for a cutaway) */
|
||||
src: string;
|
||||
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** face, insert, stack: who's framed: a share across the take (0 left, 1 right), "left", "right", or the largest */
|
||||
who?: Who;
|
||||
/** split: the two people, top first (the leftmost on top when unset) */
|
||||
pair?: [Who, Who];
|
||||
/** insert: the product or logo picture; stack: what goes on top (a picture or a video); broll: the cutaway's take */
|
||||
asset?: string;
|
||||
/** broll and stack: where the asset's video starts, in the edit's frames */
|
||||
assetFrom?: number;
|
||||
/** insert: the picture's width over its height (1) and its width as a share of the frame's (0.38) */
|
||||
aspect?: number;
|
||||
size?: number;
|
||||
/** insert: px boxes [x, y, w, h] it must keep off besides faces (the caption band is kept by default) */
|
||||
keep?: [number, number, number, number][];
|
||||
/** face: tighter than the take's whole height (Framed's punchIn) */
|
||||
punchIn?: number;
|
||||
volume?: number;
|
||||
/** the clip's level change in dB (cuts.ts's gainDb) */
|
||||
gainDb?: number;
|
||||
muted?: boolean;
|
||||
};
|
||||
|
||||
const TRACKS = FACES as unknown as Record<string, Take>;
|
||||
/** the share of a split's span each of its two must be seen in */
|
||||
const SPLIT_SEEN = 0.85;
|
||||
const nameOf = (src: string) => src.split("/").pop()!.replace(/\.[^.]+$/, "");
|
||||
const isVideo = (src: string) => /\.(mp4|mov|m4v|webm|mkv)$/i.test(src);
|
||||
|
||||
/** a take's window in a panel at x, y, w x h: the Video cropped to it, its box clipped by the panel */
|
||||
function Panel({ src, win, x, y, w, h, startFrom, endAt, volume, gainDb, muted, dim }: { src: string; win: Win; x: number; y: number; w: number; h: number; startFrom?: number; endAt?: number; volume?: number; gainDb?: number; muted?: boolean; dim?: boolean }) {
|
||||
const c = css(win, w, h);
|
||||
return (
|
||||
<div style={{ position: "absolute", left: x, top: y, width: w, height: h, overflow: "hidden", opacity: dim ? 0.45 : 1 }}>
|
||||
<Video
|
||||
src={src}
|
||||
startFrom={startFrom}
|
||||
endAt={endAt}
|
||||
volume={volume}
|
||||
gainDb={gainDb}
|
||||
muted={muted}
|
||||
style={{ position: "absolute", left: c.left, top: c.top, width: c.width, height: c.height, objectFit: "cover", objectPosition: c.objectPosition, ...(dim ? { filter: "blur(40px)" } : {}) }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** the clearest place for a box `bw` x `bh` in a frame `W` x `H`: off every face (with a third of its width round it),
|
||||
* then off `keep`, then off the bodies below the faces, inside the app's zones; null when every place covers a face */
|
||||
export function clearSpot(W: number, H: number, faces: [number, number, number, number][], keep: [number, number, number, number][], bw: number, bh: number): [number, number] | null {
|
||||
const z = zones(W, H);
|
||||
const m = 0.04 * W;
|
||||
const x0 = z.left + m;
|
||||
const x1 = W - Math.max(z.right, z.left) - m - bw;
|
||||
const y0 = z.top + m;
|
||||
const y1 = H - z.bottom - m - bh;
|
||||
if (x1 < x0 || y1 < y0) return null;
|
||||
const over = (ax: number, ay: number, b: [number, number, number, number]) => Math.max(0, Math.min(ax + bw, b[0] + b[2]) - Math.max(ax, b[0])) * Math.max(0, Math.min(ay + bh, b[1] + b[3]) - Math.max(ay, b[1]));
|
||||
const padded = faces.map((f) => [f[0] - f[2] / 3, f[1] - f[3] / 3, f[2] * (5 / 3), f[3] * (5 / 3)] as [number, number, number, number]);
|
||||
const bodies = faces.map((f) => [f[0] - f[2] * 0.9, f[1] + f[3], f[2] * 2.8, H] as [number, number, number, number]);
|
||||
let best: [number, number] | null = null;
|
||||
let cost = Infinity;
|
||||
const step = Math.max(8, Math.round(W / 60));
|
||||
for (let y = y0; y <= y1; y += step)
|
||||
for (let x = x0; x <= x1; x += step) {
|
||||
if (padded.some((f) => over(x, y, f) > 0)) continue;
|
||||
const c = keep.reduce((s, k) => s + over(x, y, k), 0) * 3 + bodies.reduce((s, b) => s + over(x, y, b), 0) * 0.5 + Math.abs(y + bh / 2 - H / 3) * bw * 0.02;
|
||||
if (c < cost) {
|
||||
cost = c;
|
||||
best = [x, y];
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export default function Shot(p: ShotProps) {
|
||||
const { width: W, height: H, fps } = useVideoConfig();
|
||||
const frame = useCurrentFrame();
|
||||
const take = TRACKS[nameOf(p.src)];
|
||||
const a = (p.startFrom ?? 0) / fps;
|
||||
const b = p.endAt !== undefined ? p.endAt / fps : a + 600;
|
||||
const ps = people(take, a, b);
|
||||
const av = { startFrom: p.startFrom, endAt: p.endAt, volume: p.volume, gainDb: p.gainDb, muted: p.muted };
|
||||
|
||||
const face = () => {
|
||||
const at = typeof p.who === "number" ? p.who : p.who === "left" || p.who === "right" ? pick(ps, p.who)?.cx : undefined;
|
||||
// `who` beyond a place across (a person's id, "speaker") goes to Framed as it is: its take graph knows them
|
||||
const extra = typeof p.who === "string" && p.who !== "left" && p.who !== "right" ? ({ who: p.who } as Record<string, unknown>) : {};
|
||||
return (
|
||||
<AbsoluteFill data-shot="face">
|
||||
<Framed src={p.src} {...av} at={at} punchIn={p.punchIn} {...extra} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
};
|
||||
const speakerIn = (x: number, y: number, w: number, h: number, alone = false) => {
|
||||
const on = pick(ps, p.who);
|
||||
const win = take ? windowOn(take, w, h, on, ps.filter((q) => q !== on), alone) : { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
|
||||
return { on, win, el: take ? <Panel src={p.src} win={win} x={x} y={y} w={w} h={h} {...av} /> : <Video src={p.src} {...av} style={{ position: "absolute", left: x, top: y, width: w, height: h, objectFit: "cover" }} /> };
|
||||
};
|
||||
const pic = (src: string, fit: "cover" | "contain", from?: number) =>
|
||||
isVideo(src) ? (
|
||||
<Video src={src} startFrom={from} muted style={{ width: "100%", height: "100%", objectFit: fit }} />
|
||||
) : (
|
||||
<Img src={src} style={{ width: "100%", height: "100%", objectFit: fit }} />
|
||||
);
|
||||
|
||||
switch (p.layout) {
|
||||
case "face":
|
||||
return face();
|
||||
|
||||
case "split": {
|
||||
const half = H / 2;
|
||||
// both people in nearly the whole span: a split with one half empty for a second is the fault the check names
|
||||
// (12-05: the guest's face went at 175 s, a 4 s split showed one face for its last second)
|
||||
const two = ps.filter((q) => q.seen >= SPLIT_SEEN);
|
||||
const [t0, t1] = p.pair ? [pick(two, p.pair[0]), pick(two, p.pair[1])] : [...two.slice(0, 2)].sort((q, r) => q.cx - r.cx);
|
||||
const ok = take && t0 && t1 && t0 !== t1 && holdsAlone(take, W, half, t0, ps.filter((q) => q !== t0)) && holdsAlone(take, W, half, t1, ps.filter((q) => q !== t1));
|
||||
if (!ok) return face();
|
||||
const w0 = windowOn(take!, W, half, t0, ps.filter((q) => q !== t0), true);
|
||||
const w1 = windowOn(take!, W, half, t1, ps.filter((q) => q !== t1), true);
|
||||
return (
|
||||
<AbsoluteFill data-shot="split" style={{ background: "#000" }}>
|
||||
<Panel src={p.src} win={w0} x={0} y={0} w={W} h={half} {...av} />
|
||||
<Panel src={p.src} win={w1} x={0} y={half} w={W} h={half} {...av} muted />
|
||||
<div style={{ position: "absolute", left: 0, top: half - 3, width: W, height: 6, background: "var(--brand-background, #101010)" }} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "insert": {
|
||||
if (!p.asset) return face();
|
||||
const s = speakerIn(0, 0, W, H);
|
||||
const bw = Math.round((p.size ?? 0.38) * W);
|
||||
const bh = Math.round(bw / (p.aspect ?? 1));
|
||||
const z = zones(W, H);
|
||||
const keep = p.keep ?? [[0, H - z.bottom - 0.16 * H, W, 0.16 * H] as [number, number, number, number]];
|
||||
const faces = ps.map((q) => onScreen(q, s.win, 0, 0, W, H));
|
||||
const at = clearSpot(W, H, faces, keep, bw, bh);
|
||||
if (!at) return <Shot {...p} layout="stack" />;
|
||||
const k = interpolate(frame, [0, 6], [0.92, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
const o = interpolate(frame, [0, 4], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill data-shot="insert">
|
||||
{s.el}
|
||||
<div style={{ position: "absolute", left: at[0], top: at[1], width: bw, height: bh, borderRadius: RADIUS * (W / 1080) * 1.4, overflow: "hidden", boxShadow: "0 18px 48px rgba(0,0,0,0.45)", background: "#fff", opacity: o, transform: `scale(${k})` }}>
|
||||
{pic(p.asset, "contain", p.assetFrom)}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "stack": {
|
||||
const half = Math.round(H / 2);
|
||||
const s = speakerIn(0, half, W, H - half);
|
||||
return (
|
||||
<AbsoluteFill data-shot="stack" style={{ background: "var(--brand-background, #101010)" }}>
|
||||
<div style={{ position: "absolute", left: 0, top: 0, width: W, height: half, overflow: "hidden" }}>{p.asset ? pic(p.asset, isVideo(p.asset) ? "cover" : "contain", p.assetFrom) : null}</div>
|
||||
{s.el}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "fit": {
|
||||
const h = Math.round((W * (take?.h ?? 9)) / (take?.w ?? 16));
|
||||
const whole: Win = { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
|
||||
const back = take ? windowOn(take, W, H, undefined, []) : whole;
|
||||
return (
|
||||
<AbsoluteFill data-shot="fit" style={{ background: "#000" }}>
|
||||
<Panel src={p.src} win={back} x={0} y={0} w={W} h={H} startFrom={p.startFrom} endAt={p.endAt} muted dim />
|
||||
<Panel src={p.src} win={whole} x={0} y={Math.round((H - h) / 2)} w={W} h={h} {...av} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "broll": {
|
||||
// the cutaway seen, the take heard: the speaker talks on under it (an L-cut), so a cutaway never plays in silence
|
||||
const src = p.asset ?? p.src;
|
||||
const own = TRACKS[nameOf(src)];
|
||||
const bp = own ? people(own, (p.assetFrom ?? 0) / fps, (p.assetFrom ?? 0) / fps + (b - a)) : [];
|
||||
const win = own ? windowOn(own, W, H, bp[0], bp.slice(1)) : undefined;
|
||||
const push = interpolate(frame, [0, Math.max(1, (b - a) * fps)], [1, 1.06], { extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill data-shot="broll" style={{ background: "#000" }}>
|
||||
{isVideo(src) && win ? (
|
||||
<Panel src={src} win={win} x={0} y={0} w={W} h={H} startFrom={p.assetFrom} muted />
|
||||
) : isVideo(src) ? (
|
||||
<Video src={src} startFrom={p.assetFrom} muted style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
) : (
|
||||
<Img src={src} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${push})` }} />
|
||||
)}
|
||||
{p.asset && !p.muted ? <Audio src={p.src} startFrom={p.startFrom} endAt={p.endAt} volume={p.volume} gainDb={p.gainDb} /> : null}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user