Compare commits

...
10 Commits
Author SHA1 Message Date
shinyobjectz a5f0f43407 A cloud render pass is quicker: warm transcribers, words and scene at once, every named take sent, timed farm steps
12-06, the one-check proof's traces: a pass of four StreetTalk cuts took 6.5 min, and two of Body Shop's failed.
- raea-words (words.py) stays up 15 minutes and runs 8 at once: at 60 s each cut's check paid Parakeet's and the
  aligner's cold start (33-91 s a cut).
- a cut's check asks the farm for its words and its scene together (sdk/goal run.ts; the box image lays it over
  0.1.17's): they came one after the other, 66 s then up to 23 s.
- a take whose name the source builds from pieces (A2 + "Broll3") goes to the farm: it stayed on the box, and the
  farm's render of it failed twice (server/media.ts unusedMedia).
- the farm's CPU containers stay up 300 s, past the four minutes between an agent's passes.
- the farm's log says how long the steps before the drawing took, and how long the drawing took beside its slowest run.
2026-12-06 10:17:38 -08:00
shaneandshinyobjectz f5b6fe118c A font Google Fonts hasn't got draws in its free stand-in: Inter Display in Inter, Helvetica Neue in Arimo (#369)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 09:13:28 -08:00
shaneandshinyobjectz 0948898e53 The farm's renders fetch every font family a cut names from Google Fonts (#368)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 09:11:44 -08:00
shaneandshinyobjectz 15b828ee9f The CTA check reads a heard word as the brief's words: Dutch.com is two, $60 is two (#367)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 08:36:36 -08:00
shaneandshinyobjectz 9c704e92fb A cut's titles draw white on their dark plate, never in the brand's text colour (#366)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 07:41:46 -08:00
shaneandshinyobjectz 1b20fff4d0 A part never stands on what it holds: a mug isn't sunk into its coffee (#365)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 07:23:27 -08:00
shaneandshinyobjectz c2e6e259d1 Skills pin: the skill regenerated from main for 0.1.17's next candidate (raea-skills #166) (#364)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 06:13:05 -08:00
shaneandshinyobjectz 7f2585e8ec A goal without the floor pack keeps the render's own safe-area line (#363)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 03:57:28 -08:00
shaneandshinyobjectz 8052626f20 Skills pin: no check --taste or --things, no montage pack, no rule_check (raea-skills #163-#165) (#362)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 02:48:19 -08:00
shaneandshinyobjectz 6a058856ed The manifest records the colours a line's words are drawn in, and contrast measures each (#361)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 02:24:06 -08:00
24 changed files with 863 additions and 44 deletions

No files matched your search

+6 -4
View File
@@ -223,13 +223,15 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue; continue;
} }
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2) // the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let color = r.middle_color(); // each colour its words are drawn in (an accent word's beside the line's), held to the lowest
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 measure = |color: &str| 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 }; let worst = r.middle_inks().into_iter().filter_map(|c| measure(c).map(|v| (v, c))).min_by(|a, b| a.0.total_cmp(&b.0));
let Some((ratio, color)) = worst else { continue };
let word = if color == r.middle_color() { String::new() } else { format!(" (its words in {color})") };
measured += 1; measured += 1;
if ratio < 3.0 { if ratio < 3.0 {
low += 1; low += 1;
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) }); issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{}{word} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
} }
} }
if measured > 0 && low == 0 { if measured > 0 && low == 0 {
+5 -5
View File
@@ -71,8 +71,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-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() }, Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]); ]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 }; let 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![], inks: 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 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![], inks: vec![], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]); let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed); 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(); let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -268,7 +268,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test] #[test]
fn a_caption_is_timed_from_the_first_word_it_shows() { fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 }; let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: 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 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![]); 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 // on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -336,7 +336,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test] #[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() { fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 }; let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: 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 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 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![]); let (mut issues, mut passed) = (vec![], vec![]);
@@ -426,7 +426,7 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test] #[test]
fn a_moving_text_is_read_where_it_is() { 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 ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 }; let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: vec![], color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0); let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0); assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}"); assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
+34 -1
View File
@@ -46,6 +46,9 @@ pub struct Run {
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step /// 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 /// 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>, pub colors: Vec<String>,
/// the colours its words are drawn in on each of those frames, beside `colors`, when any differs from the line's (the
/// manifest's `inks`: a caption's accent word); empty when every word is in the line's colour
pub inks: Vec<Vec<String>>,
/// its colour on its last frame /// its colour on its last frame
pub color: String, pub color: String,
pub size: f64, pub size: f64,
@@ -70,6 +73,20 @@ impl Run {
_ => &self.color, _ => &self.color,
} }
} }
/// Every colour its words are drawn in on that frame: the line's, and an accent span's beside it (12-06: a line
/// recorded only by its own colour hid a dark word on a dark plate)
pub fn middle_inks(&self) -> Vec<&str> {
let n = self.boxes.len();
let mut all = vec![self.middle_color()];
let at = if n > 1 && self.inks.len() == n { self.inks.get(n / 2) } else { self.inks.last() };
for i in at.into_iter().flatten() {
if !all.contains(&i.as_str()) {
all.push(i);
}
}
all
}
} }
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds /// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
@@ -129,18 +146,21 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
}); });
let mut r = match found { let mut r = match found {
Some(i) => open.remove(i), Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 }, None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), inks: Vec::new(), color: String::new(), size: 0.0 },
}; };
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string(); let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
let inks: Vec<String> = x["inks"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
if text.len() > r.text.len() { if text.len() > r.text.len() {
r.boxes.clear(); r.boxes.clear();
r.colors.clear(); r.colors.clear();
r.inks.clear();
} }
if text.len() >= r.text.len() { if text.len() >= r.text.len() {
r.text = text; r.text = text;
r.box_ = b; r.box_ = b;
r.boxes.push(ink.unwrap_or(b)); r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone()); r.colors.push(color.clone());
r.inks.push(inks);
} }
r.to = t + 1.0 / fps; r.to = t + 1.0 / fps;
r.color = color; r.color = color;
@@ -348,4 +368,17 @@ mod tests {
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour"); 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"); assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
} }
#[test]
fn a_line_with_an_accent_word_is_measured_in_both_colours() {
// a white caption with one word in dark red: the manifest's line colour alone hid the red word
let m = json!({"fps": 10.0, "frames": (0..4).map(|f| json!({"frame": f, "text": [
{"text": "Stay out longer.", "box": [100, 1400, 880, 90], "size": 84, "color": "rgb(255, 255, 255)", "inks": ["rgb(255, 255, 255)", "rgb(120, 0, 0)"]}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs[0].middle_inks(), vec!["rgb(255, 255, 255)", "rgb(120, 0, 0)"]);
// a line drawn in its own colour only has no inks, and is measured in that colour alone
let plain = json!({"fps": 10.0, "frames": [{"frame": 0, "text": [{"text": "raea", "box": [0, 0, 10, 10], "size": 40, "color": "rgb(1, 2, 3)"}]}]});
assert_eq!(text_runs(&plain)[0].middle_inks(), vec!["rgb(1, 2, 3)"]);
}
} }
+2 -2
View File
@@ -37,8 +37,8 @@ A whole video made from the same inputs as an earlier one is copied from the exp
and the command says so. and the command says so.
Every render writes its manifest beside its output: `OUT.render.json` (`DIR/NAME.render.json` for a folder of Every render writes its manifest beside its output: `OUT.render.json` (`DIR/NAME.render.json` for a folder of
frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour and frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour, the
size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check` colours its words are drawn in when one differs, such as a caption's accent word, and size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks. reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks.
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
+29 -9
View File
@@ -19,7 +19,8 @@ impl BlitzPage {
let alpha = |n: blitz_dom::NodeId| alpha(doc, n); let alpha = |n: blitz_dom::NodeId| alpha(doc, n);
let stamps = |n: blitz_dom::NodeId, entry: &mut serde_json::Value| stamps(doc, n, entry); let stamps = |n: blitz_dom::NodeId, entry: &mut serde_json::Value| stamps(doc, n, entry);
let (mut videos, mut text, mut pictures) = (Vec::new(), Vec::new(), Vec::new()); let (mut videos, mut text, mut pictures) = (Vec::new(), Vec::new(), Vec::new());
let mut owned: Vec<(blitz_dom::NodeId, Vec<String>)> = Vec::new(); // each owner's words, and the colour each is drawn in (its text node's parent's: a caption's accent span)
let mut owned: Vec<(blitz_dom::NodeId, Vec<String>, Vec<String>)> = Vec::new();
// the whole document: a composition's sequences and screens are pages of their own under the root's // the whole document: a composition's sequences and screens are pages of their own under the root's
let mut stack = vec![doc.root_node().id]; let mut stack = vec![doc.root_node().id];
while let Some(n) = stack.pop() { while let Some(n) = stack.pop() {
@@ -121,19 +122,20 @@ impl BlitzPage {
if node.parent.is_none_or(|p| alpha(p) <= 0.01) { if node.parent.is_none_or(|p| alpha(p) <= 0.01) {
continue; continue;
} }
match owned.iter_mut().find(|(o, _)| *o == owner) { let ink = node.parent.and_then(|p| doc.get_node(p)).and_then(|x| x.primary_styles()).filter(|_| !words.trim().is_empty()).map(|s| css(s.clone_color()));
Some((_, ws)) => ws.push(words.to_string()), match owned.iter_mut().find(|(o, _, _)| *o == owner) {
None => owned.push((owner, vec![words.to_string()])), Some((_, ws, inks)) => {
ws.push(words.to_string());
inks.extend(ink);
}
None => owned.push((owner, vec![words.to_string()], ink.into_iter().collect())),
} }
} }
for (owner, words) in owned { for (owner, words, inks) in owned {
let Some(words) = run_text(&words) else { continue }; let Some(words) = run_text(&words) else { continue };
let (Some(b), Some(node)) = (rect(owner), doc.get_node(owner)) else { continue }; let (Some(b), Some(node)) = (rect(owner), doc.get_node(owner)) else { continue };
let Some(s) = node.primary_styles() else { continue }; let Some(s) = node.primary_styles() else { continue };
let c = s.clone_color().to_color_space(style::color::ColorSpace::Srgb); let color = css(s.clone_color());
let [cr, cg, cb] = [c.components.0, c.components.1, c.components.2].map(|v| (v.clamp(0.0, 1.0) * 255.0).round());
let ca = c.alpha;
let color = if ca >= 1.0 { format!("rgb({cr}, {cg}, {cb})") } else { format!("rgba({cr}, {cg}, {cb}, {})", (ca * 1000.0).round() / 1000.0) };
let font = s.get_font(); let font = s.get_font();
let align = match s.clone_text_align() { let align = match s.clone_text_align() {
TextAlignKeyword::Center | TextAlignKeyword::MozCenter => "center", TextAlignKeyword::Center | TextAlignKeyword::MozCenter => "center",
@@ -153,6 +155,17 @@ impl BlitzPage {
} }
let mut t = json!({"text": words, "box": [r(b.x), r(b.y), r(w), r(h)], "opacity": (alpha(owner) * 100.0).round() / 100.0, let mut t = json!({"text": words, "box": [r(b.x), r(b.y), r(w), r(h)], "opacity": (alpha(owner) * 100.0).round() / 100.0,
"color": color, "size": font.font_size.computed_size().px() as f64, "weight": font.font_weight.value() as f64, "align": align}); "color": color, "size": font.font_size.computed_size().px() as f64, "weight": font.font_weight.value() as f64, "align": align});
// the colours its words are drawn in, when any differs from the line's (an accent span, a word lit as it's
// said): contrast measures each, so a dark word on a dark plate is found though the line's colour is light
let mut drawn: Vec<String> = Vec::new();
for i in inks {
if !drawn.contains(&i) {
drawn.push(i);
}
}
if drawn.iter().any(|i| *i != color) {
t["inks"] = json!(drawn);
}
// where the letters are across the lines (each line's offset is its alignment's), as a box of its own: a // where the letters are across the lines (each line's offset is its alignment's), as a box of its own: a
// centred line in a full-width box is tested by this, not the box (raea check's safe-area rule, #89) // centred line in a full-width box is tested by this, not the box (raea check's safe-area rule, #89)
if let Some(l) = node.element_data().and_then(|e| e.inline_layout_data.as_ref()) { if let Some(l) = node.element_data().and_then(|e| e.inline_layout_data.as_ref()) {
@@ -406,6 +419,13 @@ fn svg_runs(g: &usvg::Group, a: f64) -> Vec<(String, usvg::Rect, f64)> {
out out
} }
/// A computed colour as CSS (`rgb(…)`, or `rgba(…)` when it isn't opaque), as the manifest writes text colours
fn css(c: style::color::AbsoluteColor) -> String {
let c = c.to_color_space(style::color::ColorSpace::Srgb);
let [cr, cg, cb] = [c.components.0, c.components.1, c.components.2].map(|v| (v.clamp(0.0, 1.0) * 255.0).round());
if c.alpha >= 1.0 { format!("rgb({cr}, {cg}, {cb})") } else { format!("rgba({cr}, {cg}, {cb}, {})", (c.alpha * 1000.0).round() / 1000.0) }
}
/// A run's words from its text nodes, in order: joined by a space, as caption words set one a span are; or, when every /// A run's words from its text nodes, in order: joined by a space, as caption words set one a span are; or, when every
/// one is a single letter (a word revealed letter by letter, its spaces spans of their own), as the letters read /// one is a single letter (a word revealed letter by letter, its spaces spans of their own), as the letters read
/// ("49 BC", not "4 9 B C"). None when the run is only white space. /// ("49 BC", not "4 9 B C"). None when the run is only white space.
+8
View File
@@ -60,6 +60,14 @@ RUN curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/open
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329) # 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; \ 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 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
# 12-06: 0.1.17-rc5's CTA check read "Dutch.com" and "$60" heard as one word each against the brief's two, so a CTA said
# whole was an ERROR (raea #367)
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/cut.ts; \
if grep -q 'const spoken = words.map((w) => norm(w.text)).filter(Boolean)' "$f"; then cp image/sdk-overlay/goal/src/packs/cut.ts "$f" && echo "overlay: cut.ts"; fi
# 12-06: 0.1.17's check asked the farm for a cut's words (66 s, a cold transcriber), then for its scene, one after the
# other; they're asked together now
RUN f=/opt/raea/share/raea/sdk/goal/src/run.ts; \
if ! grep -q 'asked of the farm together' "$f"; then cp image/sdk-overlay/goal/src/run.ts "$f" && echo "overlay: run.ts"; fi
COPY deploy/git deploy/git COPY deploy/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh 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 # readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
+7 -1
View File
@@ -136,6 +136,11 @@ image = (
# RAEA_GOAL_RENDER 0: a render here ends without raea goal check's render moment, which the box that sent it runs # RAEA_GOAL_RENDER 0: a render here ends without raea goal check's render moment, which the box that sent it runs
# on the export it gets back (server/offload.ts), beside the project's brief.ts # on the export it gets back (server/offload.ts), beside the project's brief.ts
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1", "RAEA_GOAL_RENDER": "0", .env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1", "RAEA_GOAL_RENDER": "0",
# every font family a cut names, fetched from Google Fonts by name the first time and cached (raea-sys-fonts
# google.rs), not only those a composition loadFont()s: a box's cuts name the brand kit's families (Inter,
# Nunito, Roboto Slab), which drew in DejaVu Sans with font-missing on every cut (12-06, Shane: "can't it
# download fonts as needed")
"RAEA_PAGE_GOOGLE_FONTS": "1",
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library", "RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
# a render's sound pass, for a sound its project's store doesn't have yet: TokenSynth as # a render's sound pass, for a sound its project's store doesn't have yet: TokenSynth as
# deploy/modal/tokensynth.py installs it, its notes on the GPU (CR25); a model the volume doesn't have fails # deploy/modal/tokensynth.py installs it, its notes on the GPU (CR25); a model the volume doesn't have fails
@@ -268,7 +273,8 @@ SCALEDOWN = 2
# 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 # 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 # 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") # those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
CPU_SCALEDOWN = 180 # 300 since 12-06: an agent's passes over its cuts came about four minutes apart, so each pass started its containers cold
CPU_SCALEDOWN = 300
def on(gpus, job): def on(gpus, job):
+9
View File
@@ -369,6 +369,9 @@ def timed(r, n):
def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None, cpu_render=None): def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None, cpu_render=None):
bill = bill or Bill() bill = bill or Bill()
id = opts["id"] id = opts["id"]
# when the job began here, so the log says how long the steps before the drawing took (12-06: a 29 s cut's job took
# 188 s, of which its containers drew for at most 55 s, and nothing said where the rest went)
began = time.time()
rest, out = split_out(args) rest, out = split_out(args)
# the render's own --manifest is written here once it's done (from frame 0's): left in, the probe's run had two and # the render's own --manifest is written here once it's done (from frame 0's): left in, the probe's run had two and
# wrote its own where the render's went, so it said no length and the job stopped unexplained (11-25: StreetTalk's # wrote its own where the render's went, so it said no length and the job stopped unexplained (11-25: StreetTalk's
@@ -477,7 +480,13 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
got = [r0] if r0 else [] 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 [] 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 again = [] if flat else None
if calls:
log(f"raea farm: drawing starts {time.time() - began:.1f} s into the job (its keys read in {keys_s:.1f} s)")
drew = time.time()
code = (hedged if quick else 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 calls:
slowest = max([r.get("s") or 0 for r in got if r is not r0] or [0])
log(f"raea farm: {len(calls)} runs drawn in {time.time() - drew:.1f} s, the slowest raea run {slowest:.1f} s of it (the rest is containers starting and the volume)")
if again: if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it 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)") log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
+6 -2
View File
@@ -41,7 +41,11 @@ ALIGNS = {"en": "English", "zh": "Chinese", "yue": "Cantonese", "fr": "French",
# 12-05, run 8: three projects' 8-at-once transcriptions queued on 2 of each, and Elfster's 51 takes took 6.5 minutes # 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, # (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 # 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) # kept up 15 minutes after a call, and up to 8 at once (12-06): a cut's check asks for its words as its render ends, and
# at 60 s every check paid a cold start (Parakeet and the aligner loading, 33-91 s a cut; a full pass of four cuts
# waited on them one after another past 4 at once)
WARM_S = 900
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=6, scaledown_window=WARM_S)
class Align: class Align:
@modal.enter() @modal.enter()
def load(self): def load(self):
@@ -83,7 +87,7 @@ def aligned(heard: list, got: list) -> "list | None":
FULL_S = 180 FULL_S = 180
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=4, scaledown_window=60) @app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=8, scaledown_window=WARM_S)
class Hear: class Hear:
@modal.enter() @modal.enter()
def load(self): def load(self):
+3 -1
View File
@@ -83,7 +83,9 @@ export default function Title({ children, region = "top", size = 64, style, face
fontWeight: 800, fontWeight: 800,
fontSize: size, fontSize: size,
lineHeight: 1.1, lineHeight: 1.1,
color: "var(--brand-text, #fff)", // white on its own dark plate, as raea's captions are (brand.ts CAPTION): never the website's text colour, which
// is dark for a light page (12-06, Dutch on rc5: every hook black on the plate, 1.3:1, five floor errors)
color: "#fff",
// a dark plate, as raea's captions have: a hook over a beige coat or a sky read under 3:1 with a shadow alone // a dark plate, as raea's captions have: a hook over a beige coat or a sky read under 3:1 with a shadow alone
background: "rgba(0,0,0,0.6)", background: "rgba(0,0,0,0.6)",
padding: `${Math.round(px * 0.08)}px ${Math.round(px * 0.3)}px`, padding: `${Math.round(px * 0.08)}px ${Math.round(px * 0.3)}px`,
@@ -0,0 +1,240 @@
// The cut packs (docs/goal.feature MK25-MK27, MK38; Rust's cut gates until 11-29, now here alone): a client's brief as rules
// (`goal: cut({ cut: {...} })`), held from what's on disk and heard, never from what the agent says.
// quotes every rule's `from` is in the brief's text, word for word
// count as many cuts as the brief asks for, or an `open` item about "count" a person answered
// open each open item answered, with who answered it
// shape each delivered cut in its format and length
// say every phrase each cut must say, heard or shown; `every: false` phrases once across the cuts
// never no banned phrase heard or shown
// cta each cut ends on the CTA (in its last `within` seconds, 8 by default), heard or shown
import { existsSync, readdirSync, readFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { CutGoal, CutPlan } from "raea/brief.gen"
import type { FileFacts, Job, Manifest } from "../facts.ts"
import { has, inOrder, joined, norm, SAY_GAP, saidAt } from "../text.ts"
import { quote } from "../text.ts"
import { asDigits } from "./numbers.ts"
export const CTA_WITHIN = 8
/** how much of the CTA a run of words must have, in order */
export const CTA_SHARE = 0.85
export const ratio = (f: string): [number, number] | null => {
const [w, h] = f.split(":").map((x) => Number(x.trim()))
return w > 0 && h > 0 ? [w, h] : null
}
export const formatsOf = (c: CutGoal, p: CutPlan) => (p.formats?.length ? p.formats : (c.formats ?? []))
export const secondsOf = (c: CutGoal, p: CutPlan) => p.seconds ?? c.seconds ?? null
/** where a cut lands: out/cuts/ID_WxH.mp4 */
export const fileOf = (p: CutPlan, format: string) => `out/cuts/${p.id}_${format.replace(":", "x")}.mp4`
export const deliverables = (c: CutGoal) => (c.cuts ?? []).flatMap((p) => formatsOf(c, p).map((f) => fileOf(p, f)))
/** every rule and the brief's words it quotes */
export function quotes(c: CutGoal): [string, string][] {
const q: [string, string][] = []
if (c.count) q.push(["count", c.count.from])
for (const [what, list] of [["say", c.say ?? []], ["never", c.never ?? []]] as const) for (const p of list) q.push([`${what} "${p.text}"`, p.from])
if (c.cta) {
q.push(["cta", c.cta.from])
for (const line of c.cta.also ?? []) q.push([`cta "${line}"`, line])
}
for (const o of c.open ?? []) q.push([`open "${o.question}"`, o.from])
return q
}
/** the cut a delivered file is, and its format, when it's one of the brief's */
export function cutOf(c: CutGoal, rel: string): { plan: CutPlan; format: string } | null {
for (const p of c.cuts ?? []) for (const format of formatsOf(c, p)) if (fileOf(p, format) === rel) return { plan: p, format }
return null
}
/** what a file shows: each text of its render manifest, normed, and the second it's first on screen */
export function shown(m: Manifest | null): [string, number][] {
if (!m) return []
const fps = m.fps && m.fps > 0 ? m.fps : 30
const out: [string, number][] = []
for (const fr of m.frames ?? [])
for (const t of fr.text ?? []) {
const s = norm(t.text ?? "")
if (s && (t.opacity ?? 1) > 0.05 && !out.some(([o]) => o === s)) out.push([s, fr.frame / fps])
}
return out
}
/** what each frame from `from` (s) on shows, its texts read together in the order drawn: an end card draws its CTA as
* lines (12-04, Elfster run 4: "Make your Wishlist and organize your Gift Exchange on Elfster." over "It's free.", each
* alone under the CTA's share, and a cut ending on its CTA was failed for none) */
export function shownTogether(m: Manifest | null, from: number): string[] {
if (!m) return []
const fps = m.fps && m.fps > 0 ? m.fps : 30
const out = new Set<string>()
for (const fr of m.frames ?? []) {
if (fr.frame / fps < from) continue
const s = (fr.text ?? []).filter((t) => (t.opacity ?? 1) > 0.05).map((t) => norm(t.text ?? "")).filter(Boolean).join(" ")
if (s) out.add(s)
}
return [...out]
}
const cutJob = (j: Job) => (j.contract?.kind === "cut" ? (j.contract.cut ?? null) : null)
const cutFile = (f: FileFacts) => {
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
const at = c ? cutOf(c, f.path) : null
return c && at ? { c, ...at } : null
}
/** what a cut says and shows */
async function heardOf(f: FileFacts) {
// numbers said in words as the brief writes them ("pets sixty" is PETS60, "sixty dollars" $60): 12-05, Dutch run 10
// one word heard can be two as the brief writes it, and the brief's line is split on its spaces: "Dutch.com" is "dutch
// com", "$60" is "60 dollars" (12-06, Dutch: the whole CTA said, read as 73% of it, so every such cut was an ERROR)
const words = asDigits(await f.words()).flatMap((w) => norm(w.text).split(" ").filter(Boolean).map((text) => ({ ...w, text })))
return { spoken: words.map((w) => w.text), times: words, screen: shown(f.manifest) }
}
const onScreen = (s: string, p: string, gap: number) => saidAt(s.split(" "), p, gap) !== null
export const quotesPack = check<Job>({ id: "quotes", text: "every rule quotes the brief's own words", over: "job", at: ["edit", "done"] }, async (j) => {
const c = cutJob(j)
if (!c) return
const file = path.resolve(j.root, c.brief)
if (!existsSync(file)) return found({ says: `no brief text at ${c.brief}: pdftotext -layout BRIEF.pdf ${c.brief}`, fix: `pdftotext -layout BRIEF.pdf ${c.brief}` })
const text = norm(readFileSync(file, "utf8"))
const unfound = quotes(c).filter(([, from]) => !has(text, norm(from)))
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${quote(from, 60)}")`).join("; ")}` })
})
export const countPack = check<Job>({ id: "count", text: "as many cuts as the brief asks for, or a person's answer saying why not", over: "job", at: ["edit", "done"] }, async (j) => {
const c = cutJob(j)
if (!c?.count) return
const have = c.cuts?.length ?? 0
if (have >= c.count.value) return
// answered: it holds nothing here, but it's said, so raea cloud can show a person a brief made smaller by an answer
// the agent may have written itself (the brief is gospel: only a person lowers its numbers)
const answer = (c.open ?? []).find((o) => o.about === "count" && o.answer?.trim())
if (answer) return found({ level: "note", says: `${have} of the brief's ${c.count.value} cuts, as answered: ${answer.answer}${answer.by ? ` (${answer.by})` : ""}` })
found({ says: `${have} cuts planned; the brief asks for ${c.count.value} ("${c.count.from}"): plan them, or add an \`open\` item about "count" and have a person answer it` })
})
export const openPack = check<Job>({ id: "open", text: "every open item answered by a person", over: "job", at: ["publish", "done"] }, async (j) => {
for (const o of cutJob(j)?.open ?? []) if (!o.answer?.trim()) found({ says: `unanswered: ${o.question} (brief: "${o.from}"): ask at the review, then write the answer and who gave it`, about: o.about ? [o.about] : [] })
})
export const shapePack = check<FileFacts>({ id: "shape", text: "each cut in its format and length", over: "file", at: ["render", "publish", "done"] }, async (f) => {
const at = cutFile(f)
if (!at) return
const want = ratio(at.format)
if (!f.width || !f.height) return found({ says: "not an MP4 or MOV with a video track" })
const wrong: string[] = []
if (want && Math.abs(f.width / f.height / (want[0] / want[1]) - 1) > 0.02) wrong.push(`${f.width}x${f.height} isn't ${at.format}`)
const len = secondsOf(at.c, at.plan)
if (len && f.seconds !== null && (f.seconds + 0.05 < len[0] || f.seconds > len[1] + 0.05)) wrong.push(`${f.seconds.toFixed(1)} s isn't ${len[0]}-${len[1]} s`)
if (wrong.length) found({ says: wrong.join("; ") })
})
export const sayPack = check<FileFacts>({ id: "say", text: "every phrase the brief says each cut says, heard or shown", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
const at = cutFile(f)
if (!at?.c.say?.length) return
const { spoken } = await heardOf(f)
const together = shownTogether(f.manifest, 0)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || together.some((s) => onScreen(s, p, SAY_GAP))
const missing = at.c.say.filter((p) => p.every !== false && !on(norm(p.text)))
if (missing.length) found({ says: `never says or shows: ${missing.map((m) => `"${m.text}"`).join(", ")}` })
})
export const neverPack = check<FileFacts>({ id: "never", text: "no banned phrase heard or shown", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
const at = cutFile(f)
if (!at?.c.never?.length) return
const { spoken, times, screen } = await heardOf(f)
for (const p of at.c.never) {
const n = norm(p.text)
const i = saidAt(spoken, n, 1)
if (i !== null) {
found({ says: `"${p.text}" heard at ${times[i].start.toFixed(1)} s (brief: ${p.from})`, seconds: times[i].start })
continue
}
const s = screen.find(([s]) => onScreen(s, n, 1))
if (s) found({ says: `"${p.text}" on screen at ${s[1].toFixed(1)} s (brief: ${p.from})`, seconds: s[1] })
}
})
export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the CTA", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
const at = cutFile(f)
const cta = at?.c.cta
if (!cta) return
const { times } = await heardOf(f)
const within = cta.within ?? CTA_WITHIN
const end = f.seconds ?? times[times.length - 1]?.end ?? 0
const last = times.filter((w) => w.end >= end - within).map((w) => norm(w.text))
const share = (line: string, got: string[]) => {
const want = norm(line).split(" ")
return inOrder(want, joined(got, want).map(([w]) => w))
}
const lines = [cta.text, ...(cta.also ?? [])]
const heard = lines.map((l) => share(l, last))
const best = Math.max(0, ...heard)
const line = best > 0 ? lines[heard.indexOf(best)] : cta.text
// said and shown together: 12-05, Dutch run 10, the host said "use code PETS60 for sixty dollars off your first" as the
// end card showed "Code PETS60: $60 off your first year", and neither alone was 85% of the line
const late = shownTogether(f.manifest, end - within)
const shownLate = late.some((s) => lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE || share(l, [...last, ...s.split(" ")]) >= CTA_SHARE || share(l, [...s.split(" "), ...last]) >= CTA_SHARE))
if (best < CTA_SHARE && !shownLate) {
// the takes that say it, so the fix is one `raea cut` away (12-05, a street interview run: every cut ended on a host take
// that says "download the app", while two other takes say the brief's "Go to the site" line word for word)
const takes = takesSaying(f.root, lines)
const where = takes.length ? `; said in ${takes.map((t) => `${t.take} at ${t.at.toFixed(1)} s`).join(", ")}: cut it from there` : "; no take says it: show it on the end card"
found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"${where}`, seconds: [Math.max(0, end - within), end] })
}
})
/** the takes in footage/ whose words say one of `lines` (CTA_SHARE of its words in order, inside a window a little longer
* than it), the closest first, three at most */
export function takesSaying(root: string, lines: string[]): { take: string; at: number; share: number }[] {
const dir = path.join(root, "footage")
if (!existsSync(dir)) return []
const out: { take: string; at: number; share: number }[] = []
let names: string[] = []
try {
names = readdirSync(dir).filter((n) => n.endsWith(".words.json"))
} catch {
return []
}
const wants = lines.map((l) => norm(l).split(" ").filter(Boolean)).filter((w) => w.length)
for (const n of names) {
let ws: { text: string; start_ms: number; end_ms?: number }[] = []
try {
ws = JSON.parse(readFileSync(path.join(dir, n), "utf8"))
} catch {
continue
}
if (!Array.isArray(ws)) continue
const heard = asDigits(ws.map((w) => ({ text: String(w.text ?? ""), start: w.start_ms / 1000, end: (w.end_ms ?? w.start_ms) / 1000 })))
// one token per word of norm's (it makes "acme.com" two), each at its word's time
const flat = heard.flatMap((w) => norm(w.text).split(" ").filter(Boolean).map((t) => ({ t, start: w.start })))
const toks = flat.map((x) => x.t)
let best: { at: number; share: number } | null = null
for (const want of wants)
for (let i = 0; i < toks.length; i++) {
if (!want.includes(toks[i])) continue
const win = toks.slice(i, i + want.length + 3)
const sh = inOrder(want, joined(win, want).map(([w]) => w))
if (sh >= CTA_SHARE && (!best || sh > best.share)) best = { at: flat[i].start, share: sh }
}
if (best) out.push({ take: n.replace(/\.words\.json$/, ""), ...best })
}
return out.sort((a, b) => b.share - a.share).slice(0, 3)
}
/** a phrase one cut is enough for (`every: false`): some delivered cut says or shows it */
export const sayOncePack = check<Job>({ id: "say-once", text: "each phrase one cut is enough for, said or shown by one", over: "job", at: ["publish", "done"], needs: "words" }, async (j) => {
const c = cutJob(j)
const once = (c?.say ?? []).filter((p) => p.every === false)
if (!c || !once.length) return
const cuts = j.files.filter((f) => cutOf(c, f.path))
const heard = await Promise.all(cuts.map(async (f) => ({ ...(await heardOf(f)), together: shownTogether(f.manifest, 0) })))
for (const p of once) {
const n = norm(p.text)
const by = heard.some(({ spoken, together }) => saidAt(spoken, n, SAY_GAP) !== null || together.some((s) => onScreen(s, n, SAY_GAP)))
if (!by) found({ says: `no cut says or shows "${p.text}" (brief: "${p.from}")` })
}
})
+355
View File
@@ -0,0 +1,355 @@
// `raea check` (docs/check.feature): the one check. Every rule each goal of brief.ts holds at one of four moments, on
// raea's own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal
// or several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
// `goal`, and with none, the floor. The files are the ones named, else (publish, done) every deliverable and
// every video or still made under out/. Each check whose moments include --at (done by default) runs: a file
// check on each file, a job check once. A file's check after its render is kept beside it (FILE.check.json) and
// publish and done read it while it's fresh, never running it again. One line a rule a file. Writes
// review/goal.json and prints each finding. Exit 1 on an error, 2 when it can't run (brief.ts doesn't load). A
// check that needs what this machine hasn't (a transcriber) waits, and says what for; it holds nothing.
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, unknownPacks } from "./contract.ts"
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import * as media from "./media.ts"
import { loadProject, type Project } from "./project.ts"
import { PACK_CHECKS } from "./packs/index.ts"
import { renderAlone } from "./packs/render.ts"
import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts"
import { tasksMain } from "./tasks.ts"
import { wellFormed } from "./text.ts"
/** packs a brief may still name that raea took out, with why: skipped, and said so (a brief never crashes the check) */
const GONE_PACKS: Record<string, string> = {
montage: "gone (12-06): a cut's beats are the agent's own plan, and a plan graded against itself catches no fault; the montage guide is how to cut one",
}
/** the checks every project is held to once, whatever its goals: none in the loop (12-04: `registered`, how brief.ts
* imports files, failed every Dutch cut, and the taste check waits on every box; neither is a fault in the work) */
const ALWAYS: Check[] = []
/** the moments a deliverable's own check, run once after its render, stands for: publish and done read it, never run it again */
const REUSED: Moment[] = ["publish", "done"]
/** a deliverable's check kept beside it (FILE.check.json), while it's no older than the file or its manifest: the
* checks it ran and what they found */
export function keptCheck(abs: string): { checks: string[]; findings: Said[] } | null {
const k = `${media.stem(abs)}.check.json`
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
if (!existsSync(k) || when(k) < when(abs) || when(k) < when(`${media.stem(abs)}.render.json`)) return null
try {
const j = JSON.parse(readFileSync(k, "utf8")) as { checks?: string[]; findings?: Said[] }
return Array.isArray(j.checks) ? { checks: j.checks, findings: j.findings ?? [] } : null
} catch {
return null
}
}
/** one line a rule a file (12-04, round 26: 34 of one cut's errors were each caption phrase in the same UI zone; 12-05,
* run 5: an ERROR and a WARN of the same check each had a line, and a cut listed 12): of a check's findings at moments
* in the file, the most severe first one, and how many more there were; findings with no moment are distinct faults,
* said once each */
const RANK: Record<Said["level"], number> = { error: 0, warn: 1, note: 2 }
export function collapse(xs: Said[]): Said[] {
const firsts = new Map<string, { x: Said; same: number; lesser: number; to: number | null }>()
for (const x of xs) {
// a fault found at many moments (located in time) is one line; distinct faults with no moment each keep theirs
const key = `${x.goal ?? ""}\u0000${x.file ?? ""}\u0000${x.check}\u0000${x.seconds ? "" : `${x.level}\u0000${x.says}`}`
const had = firsts.get(key)
if (!had) firsts.set(key, { x, same: 0, lesser: 0, to: x.seconds?.[1] ?? null })
else {
if (RANK[x.level] < RANK[had.x.level]) {
// a worse one leads the line; what led it is counted under it
had.lesser += had.same + 1
had.same = 0
had.x = x
} else if (x.level === had.x.level) had.same++
else had.lesser++
if (x.seconds && (had.to === null || x.seconds[1] > had.to)) had.to = x.seconds[1]
}
}
return [...firsts.values()].map(({ x, same, lesser }) => {
const more = [same ? `${same} more like it${x.seconds ? ", to the same fix" : ""}` : "", lesser ? `${lesser} lesser` : ""].filter(Boolean).join("; ")
return more ? { ...x, says: `${x.says} (and ${more})` } : x
})
}
/** a finding as `raea check` reports it: its goal, its check, the file it's in, and where in it */
export type Said = { goal: string | null; check: string; level: Finding["level"]; file: string | null; seconds: [number, number] | null; says: string; fix: string | null; by: string }
/** one goal's verdict at a moment */
export type GoalVerdict = { name: string; kind: Contract["kind"] | "floor"; step: string | null; after: string[]; passed: boolean; errors: number; warnings: number; checks: string[]; files: string[] }
export type Report = {
object: "goal.check"
at: Moment
/** each goal's verdict, in the order written; the floor alone when the brief has none */
goals: GoalVerdict[]
root: string
/** when it ran (s) */
when: number
/** every goal passed and no check broken: the work may move past this moment */
passed: boolean
errors: number
warnings: number
files: string[]
checks: string[]
findings: Said[]
/** checks that couldn't run here, and what they wait for */
waits: { check: string; file: string | null; says: string }[]
/** checks that broke: a fault in the check, which fails the run */
broke: { check: string; file: string | null; says: string }[]
/** the goals' own problems (doctor), said before anything runs */
plan: string[]
}
/** the folder with brief.ts, from `from` upwards */
export function rootOf(from: string): string | null {
let d = path.resolve(from)
for (;;) {
if (existsSync(path.join(d, "brief.ts"))) return d
const up = path.dirname(d)
if (up === d) return null
d = up
}
}
/** the brief run once (project.ts), and its goals, their checks as the functions they are */
export async function goalsIn(root: string): Promise<{ goals: Contract[]; brief: string | null; project: Project }> {
const project = await loadProject(root)
return { goals: goalsOf(project.value?.goal as Goals | undefined), brief: project.brief, project }
}
const PICTURE = /\.(mp4|mov|m4v|webm|png|jpe?g|webp)$/i
/** every video and still made under out/ (a bounded walk) */
function madeUnder(root: string): string[] {
const out: string[] = []
const stack = [path.join(root, "out")]
while (stack.length && out.length < 2000) {
const d = stack.pop()!
if (!existsSync(d)) continue
for (const n of readdirSync(d)) {
const p = path.join(d, n)
const st = statSync(p)
if (st.isDirectory()) stack.push(p)
else if (PICTURE.test(n)) out.push(path.relative(root, p))
}
}
return out.filter((r) => !bookkeeping(r)).sort()
}
/** the checks that hold a goal at a moment: its packs', then its own */
export function checksOf(contract: Contract | null, at: Moment, only?: string[]): Check[] {
const packs = packsOf(contract)
// the render's own UI-zone lines are the floor pack's to measure when it runs, else the render pack keeps them
const of = (p: (typeof packs)[number]) => (p === "render" && !packs.includes("floor") ? [renderAlone as Check] : PACK_CHECKS[p])
const all = [...packs.flatMap(of), ...((contract?.checks ?? []) as Check[])]
const seen = new Set<string>()
return all.filter((c) => {
if (!c?.id || seen.has(c.id) || !c.once) return false
seen.add(c.id)
return momentsOf(c).includes(at) && (!only?.length || only.includes(c.id))
})
}
/** what doctor says of the goals before anything runs */
function planOf(goals: Contract[]): string[] {
// core/brief's doctor, from raea's Rust (it keeps the types): RAEA_GOAL_DOCTOR
let doctor: string[] = []
try {
doctor = JSON.parse(process.env.RAEA_GOAL_DOCTOR ?? "[]")
} catch {}
const out = [...doctor]
for (const c of goals) {
const at = goals.length > 1 ? `${nameOf(c)}: ` : ""
out.push(...unknownPacks(c).map((k) => GONE_PACKS[k] ? `${at}packs.${k}: ${GONE_PACKS[k]}` : `${at}packs.${k}: raea has no pack of that name (raea check --json lists them)`))
for (const k of (c.checks ?? []) as unknown[]) if (!k || typeof (k as Check).id !== "string") out.push(`${at}checks: each is a check() imported from the project's checks/ folder`)
// nothing judges a `says` rule any more (12-04): said, so it isn't taken for checked
for (const r of c.rules ?? []) if (r.says && !r.run && !r.file) out.push(`${at}rules.${r.id}: a \`says\` rule isn't checked by anything: make it a command (\`run\`) or a file (\`file\`), or leave it to the person's review`)
}
return out
}
export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: string; only?: string[]; cwd?: string; manifest?: string }): Promise<Report> {
const at = o.at ?? "done"
const cwd = o.cwd ?? process.cwd()
const root = rootOf(o.files?.length ? path.dirname(path.resolve(cwd, o.files[0])) : cwd) ?? cwd
const { goals: all, brief, project } = await goalsIn(root)
if (o.goal && !all.some((g) => nameOf(g) === o.goal)) throw new Error(`no goal is named ${o.goal}: ${all.map(nameOf).join(", ") || "the brief has none"}`)
const goals: (Contract | null)[] = all.length ? all.filter((g) => !o.goal || nameOf(g) === o.goal) : [null]
const named = (o.files ?? []).map((f) => path.relative(root, path.resolve(cwd, f)))
const findings: Said[] = []
const waits: Report["waits"] = []
const broke: Report["broke"] = []
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
const fps = file?.fps ?? 30
for (const x of r.findings)
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
}
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
// the project's own: once, whatever its goals
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
const verdicts: GoalVerdict[] = []
const allFiles = new Set<string>()
for (const contract of goals) {
const name = contract ? nameOf(contract) : "floor"
const deliverables = deliverablesOf(contract)
const wanted = named.length
? named
: at === "publish" || at === "done"
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
: []
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
const checks = checksOf(contract, at, o.only)
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null]))
// a cut's words and its scene asked of the farm together, before its checks run one by one (12-06: a cut's check
// waited 66 s for its words, then asked for its scene; both are kept on the file's facts, so each check reads them)
if (contract?.kind === "cut") for (const f of files) if (f.kind === "video" && !kept.get(f.path)) for (const p of [f.words(), f.scene()]) p.catch(() => {})
for (const c of checks) {
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }]))
else
for (const f of files) {
const k = kept.get(f.path)
// run once, after its render: what it found then stands (its own findings, at this goal)
if (k?.checks.includes(c.id)) findings.push(...k.findings.filter((x) => x.check === c.id).map((x) => ({ ...x, goal: contract ? name : null })))
else keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
}
}
const mine = findings.slice(before)
const errors = mine.filter((x) => x.level === "error").length
for (const f of files) allFiles.add(f.path)
verdicts.push({ name, kind: contract?.kind ?? "floor", step: contract?.step ?? null, after: contract?.after ?? [], passed: errors === 0 && broke.length === brokeBefore, errors, warnings: mine.filter((x) => x.level === "warn").length, checks: checks.map((c) => c.id), files: files.map((f) => f.path) })
}
findings.sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.seconds?.[0] ?? -1) - (b.seconds?.[0] ?? -1))
// printed and saved whole: no finding holds half a character (12-05, Dutch run 9: one broke the check as it printed)
findings.splice(0, findings.length, ...collapse(findings).map((x) => ({ ...x, says: wellFormed(x.says), fix: x.fix && wellFormed(x.fix) })))
const errors = findings.filter((x) => x.level === "error").length
return {
object: "goal.check",
at,
goals: verdicts,
root,
when: Math.floor(Date.now() / 1000),
passed: errors === 0 && broke.length === 0,
errors,
warnings: findings.filter((x) => x.level === "warn").length,
files: [...allFiles].sort(),
checks: [...new Set([...once.map((c) => c.id), ...verdicts.flatMap((v) => v.checks)])],
findings,
waits,
broke,
plan: planOf(all),
}
}
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
* each file named */
export function writeReport(r: Report, named: string[]) {
const dir = path.join(r.root, "review")
mkdirSync(dir, { recursive: true })
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
const mine = r.findings.filter((x) => x.file === f)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), checks: r.checks, findings: mine }, null, 1)}\n`)
}
}
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
/** the report as a person or an agent reads it */
export function text(r: Report): string {
const t: string[] = []
for (const p of r.plan) t.push(`PLAN ${p}`)
for (const x of r.findings) {
if (x.level === "note" && r.at === "edit") continue
t.push(`${x.level === "error" ? "ERROR" : x.level === "warn" ? "WARN " : "NOTE "} ${r.goals.length > 1 && x.goal ? `${x.goal}/` : ""}${x.check}${x.file ? ` ${x.file}` : ""} ${secs(x.seconds)}${x.says}${x.fix ? `\n fix: ${x.fix}` : ""}`)
}
for (const w of r.waits) t.push(`WAITS ${w.check}${w.file ? ` ${w.file}` : ""} ${w.says}`)
for (const b of r.broke) t.push(`BROKE ${b.check}${b.file ? ` ${b.file}` : ""} ${b.says}`)
if (r.goals.length > 1) for (const g of r.goals) t.push(`${g.passed ? "ok " : "open"} goal ${g.name} (${g.kind}${g.step ? `, step ${g.step}` : ""}${g.after.length ? `, after ${g.after.join(", ")}` : ""}): ${g.errors} errors, ${g.warnings} warnings`)
const kinds = r.goals.map((g) => (r.goals.length > 1 ? g.name : g.kind)).join(", ")
t.push(`${r.passed ? "PASSED" : "FAILED"} raea check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
return t.join("\n")
}
function flag(a: string[], name: string): string | undefined {
const i = a.indexOf(name)
return i >= 0 ? a[i + 1] : undefined
}
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
const USAGE = `raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> {
const [verb, ...a] = argv
if (verb === "check") {
const at = (flag(a, "--at") ?? "done") as Moment
if (!MOMENTS.includes(at)) {
console.error(`raea check: --at is one of ${MOMENTS.join(", ")}`)
return 2
}
const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
let r: Report
try {
r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") })
} catch (e) {
console.error(`raea check: ${(e as Error).message}`)
return 2
}
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
return r.passed ? 0 : 1
}
if (verb === "tasks") return tasksMain(a)
if (verb === "place") {
const file = positional(a, ["--at", "--box", "-o"])[0]
if (!file || !existsSync(file)) return usage()
const box = (flag(a, "--box") ?? "840x110").split("x").map(Number) as [number, number]
if (box.length !== 2 || !box.every((v) => v > 0)) {
console.error("raea make place: --box is WxH in a 1080-wide frame's pixels, like 840x110")
return 2
}
let at = flag(a, "--at")?.split(",").map(Number).filter(Number.isFinite)
if (!at?.length && kindOf(file) === "video") {
const len = media.seconds(file) ?? 1
const n = Math.min(12, Math.max(1, Math.floor(len)))
at = Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * len * 100) / n) / 100)
}
const { scenes } = await media.scene(path.resolve(file), at)
const rep = placeReport(file, scenes, box)
console.log(`${path.basename(file)}${at?.length ? ` at ${at.join(", ")} s` : ""}: the clearest places for a ${box[0]}x${box[1]} box in a ${rep.frame?.join("x")} frame, best first`)
for (const p of rep.places) console.log(` left ${p.left} px, top ${p.top} px (${p.at}) cost ${p.cost}${p.covers.length ? ` covers ${p.covers.join(", ")}` : " clear"}`)
const o = flag(a, "-o")
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
return usage()
}
function usage(): number {
console.error(USAGE)
return 2
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main(process.argv.slice(2)).then(
(c) => process.exit(c),
(e) => {
console.error(`raea goal: ${e instanceof media.Unmet ? "" : "broke: "}${(e as Error).message}`)
process.exit(e instanceof media.Unmet ? 1 : 2)
},
)
}
+7 -1
View File
@@ -271,11 +271,17 @@ export function unusedMedia(root: string, skip: (p: string) => boolean = () => f
} }
} }
walk(root, true) walk(root, true)
// the source's string pieces: a name built from them (12-06, Body Shop: `A2 + "Broll3"` with A2 "TheBodyShop_Angle2_")
// names no file whole, so its b-roll stayed here and the farm's render of it failed, twice
const pieces = new Set<string>()
for (const m of text.matchAll(/(["'`])((?:(?!\1)[^\\\n]|\\.){2,200})\1/g)) for (const p of m[2].split(/\$\{[^}]*\}/)) if (p.length >= 2) pieces.add(p)
const built = (stem: string, depth = 0): boolean =>
pieces.has(stem) || (depth < 2 && [...pieces].some((p) => p.length < stem.length && stem.startsWith(p) && built(stem.slice(p.length), depth + 1)))
const named = (rel: string) => { const named = (rel: string) => {
const name = rel.split("/").pop()! const name = rel.split("/").pop()!
const stem = name.replace(/\.[^.]+$/, "") const stem = name.replace(/\.[^.]+$/, "")
const folder = rel.includes("/") ? rel.split("/").slice(-2, -1)[0] + "/" : "" const folder = rel.includes("/") ? rel.split("/").slice(-2, -1)[0] + "/" : ""
return text.includes(rel) || text.includes(name) || (stem.length >= 3 && text.includes(stem) && (!folder || text.includes(folder))) return text.includes(rel) || text.includes(name) || ((!folder || text.includes(folder)) && stem.length >= 3 && (text.includes(stem) || built(stem)))
} }
const used = av.filter(named) const used = av.filter(named)
// footage/originals/ (the full-size takes, gigabytes) goes only when a source names it, even when none names anything // footage/originals/ (the full-size takes, gigabytes) goes only when a source names it, even when none names anything
+31
View File
@@ -376,3 +376,34 @@ exit 0
assert.equal(otherRaea("0.1.16", "reading", false), undefined) assert.equal(otherRaea("0.1.16", "reading", false), undefined)
console.log("ok a box refuses a worker on another raea") console.log("ok a box refuses a worker on another raea")
} }
// a cut's titles and captions draw white on raea's dark plate, never in a brand's own text colour, which is dark for a
// light website (12-06, Dutch on 0.1.17-rc5: every hook black on the plate at 1.3:1, five floor errors)
{
const title = readFileSync(new URL("../image/Title.tsx", import.meta.url), "utf8")
const colour = title.match(/^\s*color: (.+),$/m)?.[1]
assert.equal(colour, '"#fff"', `Title's words are ${colour}`)
assert.match(title, /background: "rgba\(0,0,0,0\.6\)"/)
const brand = readFileSync(new URL("../image/brand.ts", import.meta.url), "utf8")
assert.match(brand, /export const CAPTION = \{[^}]*color: "#fff"/)
console.log("ok titles and captions draw white on their dark plate")
}
// each file the box image lays over the release's SDK (image/sdk-overlay, deploy/fly/Dockerfile) is the repo's own, so an
// overlay never carries an older copy of a fix (12-06: the CTA check's cut.ts, raea #367)
{
for (const f of ["goal/src/packs/cut.ts", "goal/src/run.ts"]) {
const over = readFileSync(new URL(`../image/sdk-overlay/${f}`, import.meta.url), "utf8")
const repo = readFileSync(new URL(`../../${f}`, import.meta.url), "utf8")
assert.equal(over, repo, `image/sdk-overlay/${f} isn't sdk/${f}`)
}
console.log("ok the box image's SDK overlays are the repo's files")
}
// the farm's renders fetch every font family a cut names from Google Fonts, so a brand kit's family is drawn, not DejaVu
// Sans (12-06)
{
const farm = readFileSync(new URL("../deploy/modal/farm.py", import.meta.url), "utf8")
assert.match(farm, /"RAEA_PAGE_GOOGLE_FONTS": "1"/)
console.log("ok the farm's renders fetch the fonts a cut names")
}
+3
View File
@@ -38,4 +38,7 @@ same(unusedMedia(project({ ...takes, "cut_a.tsx": "const src = (id: string) => `
// nothing names any media: all of it is used, as before, but footage/originals/ (gigabytes; each original goes in its // nothing names any media: all of it is used, as before, but footage/originals/ (gigabytes; each original goes in its
// light copy's place when it goes at all: originals.ts) // light copy's place when it goes at all: originals.ts)
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), ["footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "no source names any") same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), ["footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "no source names any")
// a name built from the source's pieces (12-06, Body Shop: `A2 + "Broll3"`): the take goes, the others stay
same(unusedMedia(project({ ...takes, "cut_a.tsx": `const A1 = "Angle1-"; const clips = [c(A1 + "Take2", 1, 2)]; <Video src={\`footage/\${clip}.mp4\`} />` })),
["footage/Angle1-Take1.mp4", "footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov", "media/music/bed.mp3"], "a name built from pieces")
console.log("ok") console.log("ok")
+4 -4
View File
@@ -87,10 +87,10 @@ const cutFile = (f: FileFacts) => {
/** what a cut says and shows */ /** what a cut says and shows */
async function heardOf(f: FileFacts) { async function heardOf(f: FileFacts) {
// numbers said in words as the brief writes them ("pets sixty" is PETS60, "sixty dollars" $60): 12-05, Dutch run 10 // numbers said in words as the brief writes them ("pets sixty" is PETS60, "sixty dollars" $60): 12-05, Dutch run 10
const words = asDigits(await f.words()) // one word heard can be two as the brief writes it, and the brief's line is split on its spaces: "Dutch.com" is "dutch
const spoken = words.map((w) => norm(w.text)).filter(Boolean) // com", "$60" is "60 dollars" (12-06, Dutch: the whole CTA said, read as 73% of it, so every such cut was an ERROR)
const times = words.filter((w) => norm(w.text)).map((w) => w) const words = asDigits(await f.words()).flatMap((w) => norm(w.text).split(" ").filter(Boolean).map((text) => ({ ...w, text })))
return { spoken, times, screen: shown(f.manifest) } return { spoken: words.map((w) => w.text), times: words, screen: shown(f.manifest) }
} }
const onScreen = (s: string, p: string, gap: number) => saidAt(s.split(" "), p, gap) !== null const onScreen = (s: string, p: string, gap: number) => saidAt(s.split(" "), p, gap) !== null
+16 -8
View File
@@ -9,16 +9,18 @@ import { bookkeeping } from "./naming.ts"
type Said = { check?: string; level?: string; says?: string; fix?: string | null; frames?: [number, number] | null } type Said = { check?: string; level?: string; says?: string; fix?: string | null; frames?: [number, number] | null }
/** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice */ /** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice, when the floor
* pack runs; a goal without it (rules, a scene, a playable) keeps the render's own line (12-06: a desktop title card's
* render found SUNMELT in the right-hand button zone, and its kept check said nothing) */
const MEASURED_AGAIN = new Set(["safe-area"]) const MEASURED_AGAIN = new Set(["safe-area"])
/** the manifest's findings, one a kind: the first of each (by check and level), with how many more there were */ /** the manifest's findings, one a kind: the first of each (by check and level), with how many more there were */
export function renderFindings(manifest: unknown): Said[] { export function renderFindings(manifest: unknown, floorRuns = true): Said[] {
const all = ((manifest as { findings?: Said[] } | null)?.findings ?? []).filter((x) => x && (x.level === "error" || x.level === "warn")) const all = ((manifest as { findings?: Said[] } | null)?.findings ?? []).filter((x) => x && (x.level === "error" || x.level === "warn"))
const firsts = new Map<string, Said & { more: number }>() const firsts = new Map<string, Said & { more: number }>()
for (const x of all) { for (const x of all) {
const k = x.check ?? "render" const k = x.check ?? "render"
if (MEASURED_AGAIN.has(k)) continue if (floorRuns && MEASURED_AGAIN.has(k)) continue
const key = `${k} ${x.level}` const key = `${k} ${x.level}`
const had = firsts.get(key) const had = firsts.get(key)
if (had) had.more++ if (had) had.more++
@@ -27,8 +29,14 @@ export function renderFindings(manifest: unknown): Said[] {
return [...firsts.values()].map((x) => ({ ...x, says: `${x.check ?? "render"}: ${x.says ?? ""}${x.more ? ` (and ${x.more} more like it)` : ""}` })) return [...firsts.values()].map((x) => ({ ...x, says: `${x.check ?? "render"}: ${x.says ?? ""}${x.more ? ` (and ${x.more} more like it)` : ""}` }))
} }
export default check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => { const renderPack = (floorRuns: boolean) =>
if (!f.made || bookkeeping(f.path) || !f.manifest) return check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => {
for (const x of renderFindings(f.manifest)) if (!f.made || bookkeeping(f.path) || !f.manifest) return
found({ level: x.level as "error" | "warn", says: x.says ?? "", fix: x.fix ?? undefined, frames: x.frames ?? undefined }) for (const x of renderFindings(f.manifest, floorRuns))
}) found({ level: x.level as "error" | "warn", says: x.says ?? "", fix: x.fix ?? undefined, frames: x.frames ?? undefined })
})
/** beside the floor pack, which measures the app's UI zones on the video itself */
export default renderPack(true)
/** with no floor pack to measure them: the render's own UI-zone lines kept */
export const renderAlone = renderPack(false)
+8 -1
View File
@@ -20,6 +20,7 @@ import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import * as media from "./media.ts" import * as media from "./media.ts"
import { loadProject, type Project } from "./project.ts" import { loadProject, type Project } from "./project.ts"
import { PACK_CHECKS } from "./packs/index.ts" import { PACK_CHECKS } from "./packs/index.ts"
import { renderAlone } from "./packs/render.ts"
import { deliverablesOf } from "./packs/job.ts" import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts" import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts" import { placeReport } from "./packs/place.ts"
@@ -144,7 +145,10 @@ function madeUnder(root: string): string[] {
/** the checks that hold a goal at a moment: its packs', then its own */ /** the checks that hold a goal at a moment: its packs', then its own */
export function checksOf(contract: Contract | null, at: Moment, only?: string[]): Check[] { export function checksOf(contract: Contract | null, at: Moment, only?: string[]): Check[] {
const all = [...packsOf(contract).flatMap((p) => PACK_CHECKS[p]), ...((contract?.checks ?? []) as Check[])] const packs = packsOf(contract)
// the render's own UI-zone lines are the floor pack's to measure when it runs, else the render pack keeps them
const of = (p: (typeof packs)[number]) => (p === "render" && !packs.includes("floor") ? [renderAlone as Check] : PACK_CHECKS[p])
const all = [...packs.flatMap(of), ...((contract?.checks ?? []) as Check[])]
const seen = new Set<string>() const seen = new Set<string>()
return all.filter((c) => { return all.filter((c) => {
if (!c?.id || seen.has(c.id) || !c.once) return false if (!c?.id || seen.has(c.id) || !c.once) return false
@@ -210,6 +214,9 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const brokeBefore = broke.length const brokeBefore = broke.length
const j = job(contract, deliverables, files) const j = job(contract, deliverables, files)
const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null])) const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null]))
// a cut's words and its scene asked of the farm together, before its checks run one by one (12-06: a cut's check
// waited 66 s for its words, then asked for its scene; both are kept on the file's facts, so each check reads them)
if (contract?.kind === "cut") for (const f of files) if (f.kind === "video" && !kept.get(f.path)) for (const p of [f.words(), f.scene()]) p.catch(() => {})
for (const c of checks) { for (const c of checks) {
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }])) if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }]))
else else
+12 -2
View File
@@ -3,8 +3,8 @@ import { expect, test } from "bun:test"
import { mkdtempSync, utimesSync, writeFileSync } from "node:fs" import { mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import { renderFindings } from "../src/packs/render.ts" import { renderAlone, renderFindings } from "../src/packs/render.ts"
import { collapse, keptCheck } from "../src/run.ts" import { checksOf, collapse, keptCheck } from "../src/run.ts"
const at = (s: number, says = "a caption under the app's buttons") => ({ goal: null, check: "floor", file: "a.mp4", level: "error" as const, says, seconds: [s, s + 1] as [number, number] }) const at = (s: number, says = "a caption under the app's buttons") => ({ goal: null, check: "floor", file: "a.mp4", level: "error" as const, says, seconds: [s, s + 1] as [number, number] })
@@ -38,6 +38,16 @@ test("CK2: the render's own findings, one line a kind; safe-area is measured on
expect(said[0].says).toBe("font-missing: Inter isn't installed (and 1 more like it)") expect(said[0].says).toBe("font-missing: Inter isn't installed (and 1 more like it)")
}) })
test("CK2b: with no floor pack to measure the app's buttons, the render's own safe-area line is kept (12-06)", () => {
const m = { findings: [{ check: "safe-area", level: "warn", says: "SUNMELT sits in the app's UI zone at the right" }] }
expect(renderFindings(m, false).map((x) => x.says)).toEqual(["safe-area: SUNMELT sits in the app's UI zone at the right"])
// a title card's goal (rules) holds no floor pack, so its render pack keeps the line; a cut's holds both, and drops it
const ids = (c: any) => checksOf(c, "render").filter((k) => k.id === "render" || k.id === "floor").map((k) => k.id)
expect(ids({ kind: "rules", rules: [] })).toEqual(["render"])
expect(checksOf({ kind: "rules", rules: [] } as any, "render").find((k) => k.id === "render")).toBe(renderAlone as any)
expect(checksOf({ kind: "cut" } as any, "render").find((k) => k.id === "render")).not.toBe(renderAlone as any)
})
test("CK3: one line a rule a file across levels: the worst leads, the rest counted under it (12-05, run 5)", () => { test("CK3: one line a rule a file across levels: the worst leads, the rest counted under it (12-05, run 5)", () => {
const f = (level: string, check: string, s: number, says: string) => ({ goal: "g", check, file: "out/cuts/a.mp4", level, says, seconds: [s, s + 1], fix: null, by: "raea" }) const f = (level: string, check: string, s: number, says: string) => ({ goal: "g", check, file: "out/cuts/a.mp4", level, says, seconds: [s, s + 1], fix: null, by: "raea" })
const xs = collapse([f("warn", "place", 3.5, "text covers a person"), f("error", "place", 0, "text covers a dog"), f("warn", "frames", 4, "face cut by the bottom edge"), f("error", "frames", 3, "face cut by the right edge"), f("warn", "sound", 8.8, "a tight cut"), f("error", "sound", 14.1, "cuts a word")] as never) const xs = collapse([f("warn", "place", 3.5, "text covers a person"), f("error", "place", 0, "text covers a dog"), f("warn", "frames", 4, "face cut by the bottom edge"), f("error", "frames", 3, "face cut by the right edge"), f("warn", "sound", 8.8, "a tight cut"), f("error", "sound", 14.1, "cuts a word")] as never)
+10
View File
@@ -158,6 +158,16 @@ test("a CTA said in part and shown in part lands, numbers said in words included
expect(of(await run(d), "cta")).toHaveLength(1) expect(of(await run(d), "cta")).toHaveLength(1)
}) })
test("a CTA heard whole lands when a heard word is two of the brief's: Dutch.com, $60 (12-06, Dutch)", async () => {
const cta = { text: "Go to Dutch.com today and use code PETS60 for $60 off your first year.", from: "Go to Dutch.com today and use code PETS60 for $60 off your first year." }
const d = project(contract({ cta, cuts: [{ id: "a1_s1" }] }))
put(d, "media/brief.txt", `${BRIEF}"Go to Dutch.com today and use code PETS60 for $60 off your first year."\n`)
// as the box's transcript wrote it: the site one word, the money in digits, the code misheard
deliver(d, S1, "go to Dutch.com today and use code PET60 for $60 off for your first year")
put(d, S1.replace(/\.mp4$/, ".render.json"), JSON.stringify({ fps: 30, frames: [{ frame: 0, text: [{ text: "Dutch", opacity: 1 }] }] }))
expect(of(await run(d), "cta")).toEqual([])
})
test("a CTA no cut ends on is found in the takes that say it, so the fix is one raea cut away (12-05)", async () => { test("a CTA no cut ends on is found in the takes that say it, so the fix is one raea cut away (12-05)", async () => {
const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs") const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs")
const { tmpdir } = await import("node:os") const { tmpdir } = await import("node:os")
+1 -1
Submodule skills updated: d8a0dc738e...7f083c16ac.
+9 -1
View File
@@ -132,6 +132,12 @@ fn insets(parts: &[Part]) -> Vec<Option<usize>> {
.collect() .collect()
} }
/// Whether `inner` lies wholly in `outer`'s box (within a millimetre): what `outer` holds, never what it stands on.
fn holds(outer: &Part, inner: &Part) -> bool {
let e = Vec3::splat(0.001);
inner.lo.cmpge(outer.lo - e).all() && inner.hi.cmple(outer.hi + e).all()
}
fn rest_of(parts: &[Part], grid: &Grid, insets: &[Option<usize>], i: usize) -> Rest { fn rest_of(parts: &[Part], grid: &Grid, insets: &[Option<usize>], i: usize) -> Rest {
let p = &parts[i]; let p = &parts[i];
let height = p.hi.y - p.lo.y; let height = p.hi.y - p.lo.y;
@@ -147,7 +153,9 @@ fn rest_of(parts: &[Part], grid: &Grid, insets: &[Option<usize>], i: usize) -> R
let mut col = grid.column(parts, f.x, f.z, i); let mut col = grid.column(parts, f.x, f.z, i);
// a part and the wall it's set into don't stand on each other, nor do a wall's pieces (a corner, the wall over // a part and the wall it's set into don't stand on each other, nor do a wall's pieces (a corner, the wall over
// a window) // a window)
col.retain(|&(y, j, _)| y <= f.y + up && insets[i] != Some(j) && insets[j] != Some(i) && !(wall(p) && wall(&parts[j]))); // nor does a part stand on what it holds: coffee in its mug, soil in its pot, a box's contents (12-06, the 3D
// proof: "mug is sunk 12.0 mm into coffee", the coffee's top a floor's thickness above the mug's foot)
col.retain(|&(y, j, _)| y <= f.y + up && insets[i] != Some(j) && insets[j] != Some(i) && !(wall(p) && wall(&parts[j])) && !holds(p, &parts[j]));
let Some(&(y, j, k)) = col.iter().max_by(|a, b| a.0.total_cmp(&b.0)) else { continue }; let Some(&(y, j, k)) = col.iter().max_by(|a, b| a.0.total_cmp(&b.0)) else { continue };
let gap = f.y - y; let gap = f.y - y;
tested += 1; tested += 1;
+16
View File
@@ -170,3 +170,19 @@ fn a_thing_left_in_the_air_is_an_error_unless_it_glows_or_is_floating() {
let (_, level, _, errors) = air(json!({}), json!({"emissive": {"red": 2200.0, "green": 120.0, "blue": 80.0, "alpha": 1.0}})); let (_, level, _, errors) = air(json!({}), json!({"emissive": {"red": 2200.0, "green": 120.0, "blue": 80.0, "alpha": 1.0}}));
assert_eq!((level.as_str(), errors), ("note", 0)); assert_eq!((level.as_str(), errors), ("note", 0));
} }
#[test]
fn a_mug_stands_on_the_table_not_on_its_coffee() {
let floor = part("floor", Vec3::new(0.0, -0.05, 0.0), Vec3::new(4.0, 0.1, 4.0));
let mug = part("mug", Vec3::new(0.3, 0.05, 0.2), Vec3::new(0.08, 0.1, 0.08));
// the coffee in it: its top 12 mm above the mug's foot, wholly inside the mug's box
let coffee = part("coffee", Vec3::new(0.3, 0.007, 0.2), Vec3::new(0.06, 0.01, 0.06));
let parts = [floor, mug, coffee];
match rest(&parts, 1) {
Rest::On { under, gap, .. } => {
assert_eq!(parts[under].label, "floor");
assert!(gap.abs() <= TOUCH, "{gap}");
}
r => panic!("the mug should rest on the floor: {r:?}"),
}
}
+42 -1
View File
@@ -122,8 +122,36 @@ pub fn load_now(family: &str) -> usize {
faces.len() faces.len()
} }
/// A family's Latin faces from Google Fonts, or none /// A family's Latin faces from Google Fonts; for a family Google doesn't have, its free stand-in's (`stand_in`); or none
fn fetch(family: &str) -> Vec<(Bytes, f32, bool)> { fn fetch(family: &str) -> Vec<(Bytes, f32, bool)> {
let faces = fetch_google(family);
if !faces.is_empty() {
return faces;
}
match stand_in(family) {
Some(s) => {
bevy::log::info!("raea-page: {family:?} isn't on Google Fonts: drawn in {s:?}, its closest free family");
fetch_google(s)
}
None => faces,
}
}
/// The free family a page's font is drawn in where Google Fonts hasn't got it and the machine hasn't either (12-06: box
/// cuts named "Inter Display" and "Helvetica Neue", and drew in DejaVu Sans on the farm): a size of a Google family by
/// its own name, or a licensed face's closest free one on its metrics (Arimo is Arial's and Helvetica's)
pub fn stand_in(family: &str) -> Option<&'static str> {
let f = family.trim().trim_matches(|c| c == '"' || c == '\'').to_ascii_lowercase();
match f.as_str() {
"inter display" | "inter var" | "inter variable" => Some("Inter"),
"helvetica neue" | "helvetica" | "arial" | "helveticaneue" => Some("Arimo"),
"sf pro" | "sf pro display" | "sf pro text" => Some("Inter"),
_ => None,
}
}
/// A family's Latin faces from Google Fonts, or none
fn fetch_google(family: &str) -> Vec<(Bytes, f32, bool)> {
let url = format!("https://fonts.googleapis.com/css?family={}:{WEIGHTS}", family.replace(' ', "+")); let url = format!("https://fonts.googleapis.com/css?family={}:{WEIGHTS}", family.replace(' ', "+"));
let css = match raea_io_net::cache::read(&url).and_then(|b| String::from_utf8(b).map_err(|e| e.to_string())) { let css = match raea_io_net::cache::read(&url).and_then(|b| String::from_utf8(b).map_err(|e| e.to_string())) {
Ok(css) => css, Ok(css) => css,
@@ -165,3 +193,16 @@ pub fn face_now(family: &str, url: &str) -> usize {
LOADED.lock().unwrap().push(key); LOADED.lock().unwrap().push(key);
1 1
} }
#[cfg(test)]
mod tests {
use super::stand_in;
#[test]
fn a_family_google_has_not_got_draws_in_its_free_stand_in() {
assert_eq!(stand_in("Inter Display"), Some("Inter"));
assert_eq!(stand_in("\"Helvetica Neue\""), Some("Arimo"));
assert_eq!(stand_in("Arial"), Some("Arimo"));
assert_eq!(stand_in("Roboto Slab"), None);
}
}