mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37e33d624c |
No files matched your search
@@ -223,15 +223,13 @@ 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)
|
||||
// each colour its words are drawn in (an accent word's beside the line's), held to the lowest
|
||||
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 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})") };
|
||||
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 {
|
||||
low += 1;
|
||||
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) });
|
||||
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) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
|
||||
@@ -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-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![], 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![], inks: 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![], 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();
|
||||
@@ -268,7 +268,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
|
||||
|
||||
#[test]
|
||||
fn a_caption_is_timed_from_the_first_word_it_shows() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: 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
|
||||
@@ -336,7 +336,7 @@ fn safe_area_tests_the_letters_not_the_box() {
|
||||
|
||||
#[test]
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: 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![]);
|
||||
@@ -426,7 +426,7 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
#[test]
|
||||
fn a_moving_text_is_read_where_it_is() {
|
||||
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
|
||||
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: 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![], 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:?}");
|
||||
|
||||
@@ -46,9 +46,6 @@ pub struct Run {
|
||||
/// 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>,
|
||||
/// 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
|
||||
pub color: String,
|
||||
pub size: f64,
|
||||
@@ -73,20 +70,6 @@ impl Run {
|
||||
_ => &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
|
||||
@@ -146,21 +129,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
});
|
||||
let mut r = match found {
|
||||
Some(i) => open.remove(i),
|
||||
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), inks: 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();
|
||||
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() {
|
||||
r.boxes.clear();
|
||||
r.colors.clear();
|
||||
r.inks.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.inks.push(inks);
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = color;
|
||||
@@ -368,17 +348,4 @@ mod tests {
|
||||
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");
|
||||
}
|
||||
|
||||
#[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)"]);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, for a person to look at; --json prints it as 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>;
|
||||
|
||||
@@ -84,7 +84,7 @@ pub struct Goal {
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub previews: Vec<String>,
|
||||
/// raea's packs switched by name over the kind's defaults (`{ voice: true, place: false }`): which of
|
||||
/// raea's packs switched by name over the kind's defaults (`{ montage: true, place: false }`): which of
|
||||
/// raea/goal's rules hold this goal (docs/goal.feature)
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<BTreeMap<String, bool>>", optional)]
|
||||
|
||||
+42
-31
@@ -524,8 +524,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
|
||||
check`, `raea sound check`, `raea frames place`, `--plan`, plan.org, the hook's quick path, runtime/cut-plan and
|
||||
runtime/goal-plan, sdk/cloud/server's check code, raea cloud's make-checks logic, publish gate, naming and count
|
||||
checks, and the method paragraphs (RAEA, SOUND, CRAFT, NAMING, SIZES)
|
||||
And `raea check` stays a top-level instrument (MK45): its VIDEO measures are what the floor pack reads (--quick and
|
||||
--taste are gone, MK47); it never decides done
|
||||
And `raea check` stays a top-level instrument (MK45): its VIDEO and --quick measures are what the floor and stills
|
||||
packs read, and its taste lines are held by the taste pack (MK47); it never decides done
|
||||
And every project's first message carries one paragraph on the loop: write the contract, work, run
|
||||
`raea goal check`, fix what it names, until it says done
|
||||
And `rg` over raea, raea-platform, raea-skills and raea-feed finds none of the gone names outside this file and
|
||||
@@ -600,12 +600,13 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
|
||||
And core/brief's doctor says a name given twice and an `after` naming no goal
|
||||
And core/brief tests and sdk/goal/test/contract.test.ts hold it
|
||||
|
||||
@done
|
||||
Scenario: MK47. No rule a project registers runs inside an agent's loop
|
||||
Given taste lines (the person's, the workspace's, the project's) and a person's signed asks
|
||||
Then none runs inside an agent's loop: the taste pack is gone and `raea check --taste` is refused (engine/cli/goal
|
||||
gone()), so the one check (check.feature) is the only check an agent's work meets
|
||||
And the story SDK's checks are a goal's `checks`, never a file of their own
|
||||
@needs:MK43 @needs:MK45
|
||||
Scenario: MK47. Every rule a project registers runs inside the loop
|
||||
Given taste lines (the person's, the workspace's, the project's) with checks, and a person's signed asks (raea notes)
|
||||
Then the taste pack runs them through `raea check`'s rules at the moments they name, and their findings are the
|
||||
goal check's, so no registered rule runs only when an agent remembers an instrument
|
||||
And the story SDK's checks (raea/story `storyCheck`) are taste-line checks or a goal's `checks`, never a file of
|
||||
their own that nothing runs
|
||||
|
||||
|
||||
Rule: The cut, read as an editor reads it (Shane, 11-29: Kuleshov, Eisenstein's methods of montage, Murch's Rule of Six)
|
||||
@@ -614,30 +615,40 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
|
||||
# in fMRI), Eisenstein's collision of shots, Murch's six reasons for a cut weighed emotion 51%, story 23%, rhythm
|
||||
# 10%, eye trace 7%, the screen's plane 5%, its 3D space 4%, given up from the bottom. Murch's weights are his
|
||||
# judgment, not measurements: raea uses them as an order, never as a score. The story SDK says what a piece is
|
||||
# about; these say what each cut does to it. Status 11-29: built in raea #269. 12-06: the montage pack and the beat
|
||||
# critic are out (check.feature: one check, nothing grades an agent's plan); the craft stays in the guide.
|
||||
# about; these say what each cut does to it. Status 11-29: built in raea #269 (sdk/goal packs/montage.ts,
|
||||
# test/montage.test.ts; core/brief cut.rs Beat).
|
||||
|
||||
@done
|
||||
Scenario: MK48. A cut's beats are the agent's plan, in its notes, never brief.ts
|
||||
Given an agent planning a cut beat by beat (what each part makes the viewer feel and understand, and its pace)
|
||||
Then the plan is in its notes, never in brief.ts, which holds only what the brief asks (check.feature), and the
|
||||
guides say so (craft/story/montage.md, craft/motion/brief.md)
|
||||
And a brief.ts that still has `beats` is read as before (core/brief keeps the field) and nothing grades them
|
||||
Scenario: MK48. A cut plan's beats say what each part must make the viewer feel and understand, before it's cut
|
||||
Given a cut goal's plan (`cut({ cuts: [{ id, beats: [...] }] })`)
|
||||
Then each beat has `at` (seconds from the cut's start, the first at 0, in order) and `feel` in the person's words,
|
||||
and may say `story` (what the viewer understands by its end), `asl` (its average shot length in seconds) and
|
||||
`tempo` ("build": shots shorter as it goes, "release": longer, "hold": even)
|
||||
And core/brief's doctor says a beat out of order, one with no feel, a tempo that isn't one of the three and an asl
|
||||
that isn't above 0
|
||||
And Dutch's cuts fail today: none says what any of its parts should make anyone feel
|
||||
|
||||
@done
|
||||
Scenario: MK49. No critic judges a cut's emotion or story
|
||||
Given a cut
|
||||
Then no model is asked whether it makes the viewer feel its beats: `raea goal judge` is gone (engine/cli/goal
|
||||
gone()), and emotion and story stay the editor's, from the guide, never a score
|
||||
Scenario: MK49. Emotion and story are judged on the cut in sequence, by a fresh critic
|
||||
Given a cut goal whose plans have beats
|
||||
Then each beat is a `says` rule (`beat_<cut>_<n>`, contract.ts saysOf): "in out/cuts/<cut>_<W>x<H>.mp4, from A s
|
||||
to B s, watched in sequence as cut, the viewer feels <feel>, and by its end understands <story>", judged by
|
||||
`raea goal judge` with the goal's own `says` rules and held by the says pack at done
|
||||
And it's asked of the shots as cut, never one by one: what a shot means comes from its neighbours (Kuleshov)
|
||||
And no measure stands in for them: they're Murch's top two, 74% of his weight
|
||||
|
||||
@done
|
||||
Scenario: MK50. No pack measures a cut against the agent's own plan
|
||||
Given a brief.ts that names the montage pack (`packs: { montage: true }`)
|
||||
Then the pack is skipped and the check's doctor says it's gone and why (sdk/goal run.ts GONE_PACKS), never a crash
|
||||
And sdk/goal/test/contract.test.ts holds it
|
||||
Scenario: MK50. Each beat's pace is its plan (Eisenstein's metric montage)
|
||||
Given a delivered cut whose plan's beats say `asl` or `tempo`
|
||||
Then the montage pack finds its hard cuts in its own frames (one ffmpeg pass, 48 pixels wide) and, for each beat,
|
||||
its shots must average within a third of its asl, and a build's shot lengths must shorten (Kendall's tau under
|
||||
-0.2), a release's lengthen (over 0.2), with three shots or more; each miss is an error naming the beat's feel,
|
||||
the lengths it has and which way to go
|
||||
And sdk/goal/test/montage.test.ts holds it
|
||||
|
||||
@done
|
||||
Scenario: MK51. Eye trace, screen direction and tone are the editor's, in Murch's order
|
||||
Given any cut
|
||||
Then the guide gives Murch's order for what to give up first (craft/story/montage.md), and no check measures eye
|
||||
trace, screen direction or tone; a cut on a word stays the one check's (sound)
|
||||
Scenario: MK51. Eye trace, screen direction and tone across every cut, in Murch's order
|
||||
Given any delivered cut (`packs: { montage: false }` switches it off)
|
||||
Then at each cut: the focal point on the two sides (the largest face the scene reader finds, else where the
|
||||
frame's contrast gathers) more than 0.4 of the frame's diagonal apart is an eye-trace warning; sideways motion
|
||||
on both sides (over 0.15 widths a second) in opposite directions is a screen-direction warning; a jump in
|
||||
brightness over 0.25 or warmth over 0.08 where no beat starts is a tonal warning
|
||||
And each finding names its Murch weight, so a fix never gives up a higher reason for a lower one
|
||||
And one of them broken at more than half a file's cuts is an error: a habit of the cut, not a choice
|
||||
And a cut on a word stays the sound pack's (edit-on-sound), so no rule is held twice
|
||||
@@ -13,8 +13,7 @@ only what a file has. A new axis judges from its words until it has been trained
|
||||
you point at. A person can keep several, each saying what it's for, and one can build on another with `--extends`.
|
||||
The app's Fingerprint page shows the same thing: what each one knows, what it's still learning, and what it can't
|
||||
judge yet. `postmortem` looks back on a finished project with at most ten questions, and `things` says where a
|
||||
thing floats or passes through another, the camera lurches or the frame is empty, for a person to look at. It is no
|
||||
check: a render checks its own 3D from its manifest, at its end, and `raea check --things` is gone.
|
||||
thing floats or passes through another, the camera lurches or the frame is empty, for `raea check --things`.
|
||||
`score --ask flags` puts each flag to clef again, through the ask runner (apps/ask), on that moment's window alone. Beside the flag it
|
||||
says "clef agrees (0.96)" or "clef doesn't see it (0.00)". It costs by the flags, never by the piece, and a render
|
||||
asked again costs nothing. Clef's answers are kept as its evidence (`eye:clef`), which trains the axis's head but never
|
||||
@@ -38,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, for a person to look at; --json prints it as 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
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, the
|
||||
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`
|
||||
frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour 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.
|
||||
|
||||
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
|
||||
|
||||
@@ -19,8 +19,7 @@ impl BlitzPage {
|
||||
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 (mut videos, mut text, mut pictures) = (Vec::new(), Vec::new(), 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();
|
||||
let mut owned: Vec<(blitz_dom::NodeId, Vec<String>)> = Vec::new();
|
||||
// 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];
|
||||
while let Some(n) = stack.pop() {
|
||||
@@ -122,20 +121,19 @@ impl BlitzPage {
|
||||
if node.parent.is_none_or(|p| alpha(p) <= 0.01) {
|
||||
continue;
|
||||
}
|
||||
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()));
|
||||
match owned.iter_mut().find(|(o, _, _)| *o == owner) {
|
||||
Some((_, ws, inks)) => {
|
||||
ws.push(words.to_string());
|
||||
inks.extend(ink);
|
||||
}
|
||||
None => owned.push((owner, vec![words.to_string()], ink.into_iter().collect())),
|
||||
match owned.iter_mut().find(|(o, _)| *o == owner) {
|
||||
Some((_, ws)) => ws.push(words.to_string()),
|
||||
None => owned.push((owner, vec![words.to_string()])),
|
||||
}
|
||||
}
|
||||
for (owner, words, inks) in owned {
|
||||
for (owner, words) in owned {
|
||||
let Some(words) = run_text(&words) else { continue };
|
||||
let (Some(b), Some(node)) = (rect(owner), doc.get_node(owner)) else { continue };
|
||||
let Some(s) = node.primary_styles() else { continue };
|
||||
let color = css(s.clone_color());
|
||||
let c = s.clone_color().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());
|
||||
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 align = match s.clone_text_align() {
|
||||
TextAlignKeyword::Center | TextAlignKeyword::MozCenter => "center",
|
||||
@@ -155,17 +153,6 @@ 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,
|
||||
"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
|
||||
// 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()) {
|
||||
@@ -419,13 +406,6 @@ fn svg_runs(g: &usvg::Group, a: f64) -> Vec<(String, usvg::Rect, f64)> {
|
||||
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
|
||||
/// 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.
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
|
||||
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
|
||||
// stop unless all the goals pass").
|
||||
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
||||
import * as cp from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
|
||||
/** where a goal's critic verdict is kept, relative to the brief */
|
||||
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
|
||||
export const TIMEOUT = 300
|
||||
/** folders that aren't the work: what the job writes about itself, and what tools keep */
|
||||
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
|
||||
|
||||
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
|
||||
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
|
||||
* as older than the work (12-01) */
|
||||
const READING = /\.(check|words|scene|floor|montage)\.json$/
|
||||
|
||||
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
|
||||
export function newest(dir: string): number | null {
|
||||
let best: number | null = null
|
||||
const stack = [dir]
|
||||
let seen = 0
|
||||
while (stack.length) {
|
||||
const d = stack.pop()!
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(d)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const name of names) {
|
||||
if (++seen > 20_000) return best
|
||||
const p = path.join(d, name)
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (st.isDirectory()) {
|
||||
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
|
||||
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
|
||||
export function verdict(dir: string, g: Contract): Verdict | null {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const goalOf = (j: Job): Contract | null => j.contract
|
||||
|
||||
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
|
||||
for (const r of goalOf(j)?.rules ?? []) {
|
||||
if (!r.run) continue
|
||||
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
|
||||
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
|
||||
const says = saysOf(goalOf(j) ?? null)
|
||||
if (!says.length) return
|
||||
let v = verdict(j.root, j.contract!)
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
|
||||
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
|
||||
// judges by hand), where this session has a critic to ask
|
||||
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
|
||||
try {
|
||||
v = await judge(j.contract!, j.root)
|
||||
} catch (e) {
|
||||
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
|
||||
return
|
||||
}
|
||||
}
|
||||
const fresh = freshOf(v)
|
||||
for (const r of says) {
|
||||
const one = v?.rules?.[r.id]
|
||||
const fix = NO_CRITIC
|
||||
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
|
||||
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
|
||||
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
|
||||
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
|
||||
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
|
||||
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
|
||||
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
|
||||
}
|
||||
|
||||
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
|
||||
export function lastVerdict(text: string): Verdict | null {
|
||||
const key = text.lastIndexOf('"rules"')
|
||||
if (key < 0) return null
|
||||
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
|
||||
let depth = 0
|
||||
let inStr = false
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const ch = text[i]
|
||||
if (inStr) {
|
||||
if (ch === "\\") i++
|
||||
else if (ch === '"') inStr = false
|
||||
continue
|
||||
}
|
||||
if (ch === '"') inStr = true
|
||||
else if (ch === "{") depth++
|
||||
else if (ch === "}" && --depth === 0) {
|
||||
try {
|
||||
const v = JSON.parse(text.slice(open, i + 1))
|
||||
if (v && typeof v.rules === "object") return v
|
||||
} catch {}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
|
||||
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
|
||||
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
|
||||
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
|
||||
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
|
||||
/** whether every rule here can be judged in this session */
|
||||
export function hasCritic(dir: string, rules: Said[]): boolean {
|
||||
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
|
||||
}
|
||||
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
||||
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
||||
/** the videos under out/, newest first */
|
||||
function made(dir: string): string[] {
|
||||
const out: { f: string; at: number }[] = []
|
||||
const walk = (d: string) => {
|
||||
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
|
||||
const f = path.join(d, e.name)
|
||||
if (e.isDirectory()) walk(f)
|
||||
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
|
||||
}
|
||||
}
|
||||
walk(path.join(dir, "out"))
|
||||
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
|
||||
}
|
||||
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
|
||||
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
|
||||
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
|
||||
const CLEF_PIECES = 12
|
||||
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
|
||||
function piecesOf(r: Said, dir: string): string[] {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
|
||||
}
|
||||
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
|
||||
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
|
||||
export const CLEF_AT_ONCE = 6
|
||||
|
||||
/** `f` on each item, at most `n` at once, the answers in the items' order */
|
||||
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of only) {
|
||||
const files = piecesOf(r, dir)
|
||||
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
|
||||
pieces.set(r.id, files)
|
||||
for (const file of files) {
|
||||
const key = [file, w?.[1], w?.[2]].join("\u001f")
|
||||
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
|
||||
at.rules.push(r)
|
||||
groups.set(key, at)
|
||||
}
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = ask === askClef && !asyncSpawn()
|
||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
||||
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
}
|
||||
const rules: Verdict["rules"] = {}
|
||||
for (const r of only) {
|
||||
const a = got.get(r.id) ?? []
|
||||
const open = a.filter((x) => !x.pass)
|
||||
rules[r.id] = !pieces.get(r.id)?.length
|
||||
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
|
||||
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||
}
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
||||
* its 10.5 minutes) */
|
||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
||||
if (!jobs.length) return []
|
||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
||||
mkdirSync(tmp, { recursive: true })
|
||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
||||
try {
|
||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
||||
return jobs.map((k, i) => {
|
||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
||||
return rows
|
||||
})
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
const args = askArgs(file, says, from, to)
|
||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
||||
if (!asyncSpawn()) {
|
||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
||||
const rows = rowsOf(String(r.stdout ?? ""))
|
||||
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
|
||||
return Promise.resolve(rows)
|
||||
}
|
||||
return new Promise((ok, no) => {
|
||||
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = rowsOf(out)
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
||||
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
|
||||
* it judged counts as changed after) */
|
||||
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
|
||||
const all = saysOf(g)
|
||||
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
||||
const read = all.filter((r) => !watched.includes(r))
|
||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
||||
const [heard, said] = await Promise.all([
|
||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
||||
])
|
||||
const rules: Verdict["rules"] = { ...heard }
|
||||
if (said !== null) {
|
||||
const v = lastVerdict(said)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
||||
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
|
||||
}
|
||||
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
|
||||
}
|
||||
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
|
||||
async function askAgent(cwd: string, p: string): Promise<string> {
|
||||
const url = criticUrl()
|
||||
if (!url) throw new Error(NO_CRITIC)
|
||||
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
|
||||
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
|
||||
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
|
||||
return j.text
|
||||
}
|
||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
||||
const file = path.join(dir, verdictPath(g))
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
||||
return out
|
||||
}
|
||||
|
||||
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
|
||||
@@ -7,7 +7,7 @@
|
||||
// import { brief, cut, rules } from "raea/brief"
|
||||
// import clearOfButtons from "./checks/clear.ts"
|
||||
// export default brief({ title: "Dutch", goal: [
|
||||
// cut({ name: "cut", step: "edit", cut: {...}, packs: { place: false }, checks: [clearOfButtons] }),
|
||||
// cut({ name: "cut", step: "edit", cut: {...}, packs: { montage: true }, checks: [clearOfButtons] }),
|
||||
// rules({ name: "deliver", after: ["cut"], aim: "each size uploaded", rules: [{ id: "sizes", file: "out/dutch_4x5.mp4" }] }),
|
||||
// ] })
|
||||
import type { Check, Moment } from "raea/check"
|
||||
@@ -34,6 +34,7 @@ export const PACKS = {
|
||||
reading: "every block of text that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture",
|
||||
sound: "edit points in the pauses, every line within 6 dB of the others, every effect heard",
|
||||
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
|
||||
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
|
||||
place: "no text over a face, hands or what the shot is about where a clear place of its size exists",
|
||||
naming: "files named client_concept_variant_v#_size",
|
||||
sizes: "one size first: no other size before the first is approved",
|
||||
@@ -55,9 +56,8 @@ export type PackName = keyof typeof PACKS
|
||||
/** each kind's packs, on unless the brief switches them off. Only rules that catch a real fault in that kind of work,
|
||||
* each run once on a deliverable after its render (12-04, Shane: "fix how every agent checks its work"; round 26's
|
||||
* checks gave 183 findings on 10 cuts, about 10 of them real faults, and the agents spent their 20 minutes on the
|
||||
* rest). The others stay a brief's to switch on (`packs: { voice: true }`),
|
||||
* never an agent's loop: voice, reading, hook, airgaps, quotes. Nothing asks a model to judge the work. The montage
|
||||
* pack is gone (12-06): a cut's beats are the agent's own plan, and a plan graded against itself catches no fault. */
|
||||
* rest). The others stay a brief's to switch on (`packs: { montage: true }`),
|
||||
* never an agent's loop: voice, reading, hook, airgaps, montage, quotes. Nothing asks a model to judge the work. */
|
||||
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
|
||||
// a word clipped or missing, a face cut by the frame, text over a face, a sign or the app's buttons, captions over
|
||||
// talking, the brief's must-say, never-say and CTA, the size, length and name, and what the render itself found
|
||||
|
||||
@@ -5,6 +5,7 @@ import captions from "./captions.ts"
|
||||
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
|
||||
import { floorPack } from "./floor.ts"
|
||||
import frames from "./frames.ts"
|
||||
import montage from "./montage.ts"
|
||||
import { runPack } from "./goal.ts"
|
||||
import { deliverablesPack } from "./job.ts"
|
||||
import naming from "./naming.ts"
|
||||
@@ -28,6 +29,7 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
airgaps: [airgapsPack],
|
||||
sound: [sound],
|
||||
frames: [frames],
|
||||
montage: [montage],
|
||||
place: [place],
|
||||
naming: [naming],
|
||||
sizes: [sizes, allSizes],
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
// The montage pack (docs/goal.feature MK48-MK51): each delivered cut read as an editor reads it, cut by cut (Shane,
|
||||
// 11-29, on Kuleshov, Eisenstein's methods of montage and Murch's Rule of Six). Murch weighs a cut's reasons: emotion
|
||||
// 51%, story 23%, rhythm 10%, eye trace 7%, the screen's plane 5%, its 3D space 4%, and gives them up from the bottom:
|
||||
// never story for rhythm, rhythm for eye trace. Emotion and story are the person's, watched in review: nothing grades
|
||||
// them (docs/check.feature CK4). This pack measures the rest, from the file's own frames:
|
||||
// pace each beat's shots average within a third of its `asl`, and move as its `tempo` says (build: shorter as it
|
||||
// goes; release: longer; hold: even). Eisenstein's metric montage: tempo set by shot length. An error, as
|
||||
// the plan is a decision
|
||||
// eye the focal point on either side of a cut (the largest face the scene reader finds, else where the frame's
|
||||
// contrast gathers) within 0.4 of the frame's diagonal: the eye shouldn't hunt for what to look at
|
||||
// plane the picture's sideways motion on both sides of a cut not reversed (screen direction)
|
||||
// tone no jump in brightness (0.25) or warmth (0.08) across a cut a beat doesn't start at (tonal montage)
|
||||
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
|
||||
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { type Faces, Unmet } from "../media.ts"
|
||||
import { cutOf } from "./cut.ts"
|
||||
|
||||
/** Murch's weights (In the Blink of an Eye), named in each finding so the order of giving up is plain */
|
||||
export const MURCH = { emotion: 51, story: 23, rhythm: 10, eye: 7, plane: 5, space: 4 } as const
|
||||
/** the width frames are read at (the height by the picture's shape) */
|
||||
export const READ_W = 48
|
||||
export const EYE_JUMP = 0.4
|
||||
export const LUMA_JUMP = 0.25
|
||||
export const WARMTH_JUMP = 0.08
|
||||
/** sideways motion, in widths a second, below which a side counts as still */
|
||||
export const MOVING = 0.15
|
||||
/** a share of a beat's asl the shots may average off by */
|
||||
export const ASL_SLACK = 1 / 3
|
||||
/** a habit: one measure broken at more than this share of a file's cuts */
|
||||
export const HABIT = 0.5
|
||||
|
||||
/** a frame read small: its grey (0..1) and its mean luma and warmth */
|
||||
export type Frame = { grey: Float32Array; luma: number; warmth: number }
|
||||
export type Read = { fps: number; w: number; h: number; frames: Frame[] }
|
||||
export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye" | "plane" | "tone"; at: number | null; until?: number; says: string }
|
||||
|
||||
/** a video's frames, READ_W wide, from one ffmpeg pass */
|
||||
export function read(file: string, fps: number, width: number, height: number): Read {
|
||||
const w = READ_W
|
||||
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
|
||||
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
|
||||
// 4.6 s into a file (12-01)
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
|
||||
let buf: Buffer
|
||||
try {
|
||||
const raw = path.join(dir, "frames.raw")
|
||||
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
|
||||
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
|
||||
buf = readFileSync(raw)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
const size = w * h * 3
|
||||
const frames: Frame[] = []
|
||||
for (let o = 0; o + size <= buf.length; o += size) {
|
||||
const grey = new Float32Array(w * h)
|
||||
let ls = 0
|
||||
let warm = 0
|
||||
for (let i = 0; i < w * h; i++) {
|
||||
const R = buf[o + i * 3] / 255
|
||||
const G = buf[o + i * 3 + 1] / 255
|
||||
const B = buf[o + i * 3 + 2] / 255
|
||||
const y = 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
grey[i] = y
|
||||
ls += y
|
||||
const sum = R + G + B
|
||||
if (sum > 0.05) warm += (R - B) / sum
|
||||
}
|
||||
frames.push({ grey, luma: ls / (w * h), warmth: warm / (w * h) })
|
||||
}
|
||||
return { fps, w, h, frames }
|
||||
}
|
||||
|
||||
const diff = (a: Frame, b: Frame) => {
|
||||
let s = 0
|
||||
for (let i = 0; i < a.grey.length; i++) s += Math.abs(a.grey[i] - b.grey[i])
|
||||
return s / a.grey.length
|
||||
}
|
||||
const median = (xs: number[]) => {
|
||||
const s = [...xs].sort((a, b) => a - b)
|
||||
return s.length ? s[Math.floor(s.length / 2)] : 0
|
||||
}
|
||||
|
||||
/** the frames that start a new shot: a picture change well above its neighbours' (hard cuts; a dissolve isn't one) */
|
||||
export function cutsOf(r: Read): number[] {
|
||||
const d = r.frames.map((f, i) => (i ? diff(r.frames[i - 1], f) : 0))
|
||||
const out: number[] = []
|
||||
for (let i = 1; i < d.length; i++) {
|
||||
const near = d.slice(Math.max(1, i - 6), i).concat(d.slice(i + 1, i + 7))
|
||||
if (d[i] > 0.1 && d[i] > 3 * median(near) + 0.02 && (!out.length || i - out[out.length - 1] >= 4)) out.push(i)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** where a frame's contrast gathers (0..1 from the top left): each pixel's difference from its neighbourhood, squared */
|
||||
export function focal(f: Frame, w: number, h: number): [number, number] {
|
||||
let sx = 0
|
||||
let sy = 0
|
||||
let sw = 0
|
||||
const R = 3
|
||||
for (let y = 0; y < h; y++)
|
||||
for (let x = 0; x < w; x++) {
|
||||
let m = 0
|
||||
let n = 0
|
||||
for (let yy = Math.max(0, y - R); yy <= Math.min(h - 1, y + R); yy++)
|
||||
for (let xx = Math.max(0, x - R); xx <= Math.min(w - 1, x + R); xx++) {
|
||||
m += f.grey[yy * w + xx]
|
||||
n++
|
||||
}
|
||||
const c = (f.grey[y * w + x] - m / n) ** 2
|
||||
sx += c * (x + 0.5)
|
||||
sy += c * (y + 0.5)
|
||||
sw += c
|
||||
}
|
||||
return sw > 1e-6 ? [sx / sw / w, sy / sw / h] : [0.5, 0.5]
|
||||
}
|
||||
|
||||
/** the largest face's centre in the scene reader's frame nearest `t` (RATE a second), when it's in the same shot */
|
||||
export function faceAt(faces: Faces[], rate: number, t: number, from: number, to: number): [number, number] | null {
|
||||
if (!rate) return null
|
||||
const i = Math.round(t * rate)
|
||||
const ts = i / rate
|
||||
if (ts < from || ts >= to) return null
|
||||
const fr = faces[i]
|
||||
if (!fr?.faces.length) return null
|
||||
const [x, y, w, h] = [...fr.faces].sort((a, b) => b[2] * b[3] - a[2] * a[3])[0]
|
||||
return [(x + w / 2) / fr.w, (y + h / 2) / fr.h]
|
||||
}
|
||||
|
||||
/** sideways motion between two frames, in widths a second: the shift that best lines up their column profiles */
|
||||
export function sideways(a: Frame, b: Frame, w: number, h: number, seconds: number): number {
|
||||
const col = (f: Frame) => Array.from({ length: w }, (_, x) => {
|
||||
let s = 0
|
||||
for (let y = 0; y < h; y++) s += f.grey[y * w + x]
|
||||
return s / h
|
||||
})
|
||||
const pa = col(a)
|
||||
const pb = col(b)
|
||||
const max = Math.floor(w / 6)
|
||||
let best = 0
|
||||
let bestErr = Infinity
|
||||
for (let s = -max; s <= max; s++) {
|
||||
let e = 0
|
||||
let n = 0
|
||||
for (let x = Math.max(0, -s); x < Math.min(w, w - s); x++) {
|
||||
e += Math.abs(pa[x] - pb[x + s])
|
||||
n++
|
||||
}
|
||||
// a small pull to no shift, so a flat or still picture reads as still
|
||||
const err = e / n + Math.abs(s) * 1e-4
|
||||
if (err < bestErr) {
|
||||
bestErr = err
|
||||
best = s
|
||||
}
|
||||
}
|
||||
return best / w / seconds
|
||||
}
|
||||
|
||||
/** Kendall's tau of shot lengths against their order: below 0 they shorten, above they lengthen */
|
||||
export function tau(xs: number[]): number {
|
||||
let c = 0
|
||||
let n = 0
|
||||
for (let i = 0; i < xs.length; i++)
|
||||
for (let j = i + 1; j < xs.length; j++) {
|
||||
c += Math.sign(xs[j] - xs[i])
|
||||
n++
|
||||
}
|
||||
return n ? c / n : 0
|
||||
}
|
||||
|
||||
const s2 = (x: number) => `${x.toFixed(1)} s`
|
||||
|
||||
/** a beat's pace against its plan: the shots inside [from, to) from the cut frames */
|
||||
export function pace(beats: Beat[], cuts: number[], fps: number, end: number): Finding[] {
|
||||
const out: Finding[] = []
|
||||
const starts = [0, ...cuts.map((c) => c / fps)]
|
||||
beats.forEach((b, i) => {
|
||||
const from = b.at
|
||||
const to = Math.min(end, beats[i + 1]?.at ?? end)
|
||||
if (to - from <= 0) return
|
||||
const inside = starts.filter((s) => s > from + 1e-6 && s < to - 1e-6)
|
||||
const asl = (to - from) / (inside.length + 1)
|
||||
if (b.asl && Math.abs(asl / b.asl - 1) > ASL_SLACK)
|
||||
out.push({ level: "error", kind: "pace", at: from, until: to, says: `beat ${i + 1} (${b.feel}): its shots average ${s2(asl)}, its asl is ${s2(b.asl)} (${asl > b.asl ? "too slow: cut it into more shots" : "too fast: hold its shots longer"}; rhythm, Murch ${MURCH.rhythm}%)` })
|
||||
if (b.tempo && b.tempo !== "hold") {
|
||||
const edges = [from, ...inside, to]
|
||||
const lens = edges.slice(1).map((e, k) => e - edges[k])
|
||||
if (lens.length < 3) out.push({ level: "error", kind: "tempo", at: from, until: to, says: `beat ${i + 1} (${b.feel}) should ${b.tempo === "build" ? "build" : "release"}, but it has ${lens.length} shot${lens.length === 1 ? "" : "s"}: a tempo needs three or more` })
|
||||
else {
|
||||
const t = tau(lens)
|
||||
if (b.tempo === "build" ? t > -0.2 : t < 0.2) out.push({ level: "error", kind: "tempo", at: from, until: to, says: `beat ${i + 1} (${b.feel}) should ${b.tempo === "build" ? "build: shots shorter as it goes" : "release: shots longer as it goes"}, but its shot lengths go ${lens.map((l) => l.toFixed(1)).join(", ")} s (rhythm, Murch ${MURCH.rhythm}%)` })
|
||||
}
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/** what each cut keeps or breaks: eye trace, screen direction and tone, in Murch's order */
|
||||
export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?: number; beatsAt?: number[] } = {}): Finding[] {
|
||||
const out: Finding[] = []
|
||||
const bounds = [0, ...cuts, r.frames.length]
|
||||
const tally = { eye: 0, plane: 0, tone: 0 }
|
||||
cuts.forEach((c, k) => {
|
||||
const t = c / r.fps
|
||||
const from = bounds[k]
|
||||
const to = bounds[k + 2]
|
||||
const A = r.frames[c - 1]
|
||||
const B = r.frames[c]
|
||||
const at = (f: Frame, frame: number, lo: number, hi: number) => (o.faces && faceAt(o.faces, o.rate ?? 0, frame / r.fps, lo / r.fps, hi / r.fps)) ?? focal(f, r.w, r.h)
|
||||
const fa = at(A, c - 1, from, c)
|
||||
const fb = at(B, c, c, to)
|
||||
const aspect = r.h / r.w
|
||||
const jump = Math.hypot(fa[0] - fb[0], (fa[1] - fb[1]) * aspect) / Math.hypot(1, aspect)
|
||||
if (jump > EYE_JUMP) {
|
||||
tally.eye++
|
||||
out.push({ level: "warn", kind: "eye", at: t, says: `the cut at ${s2(t)} moves the eye ${Math.round(jump * 100)}% of the frame (${where(fa)} to ${where(fb)}): put what matters after the cut near where the eye was (eye trace, Murch ${MURCH.eye}%)` })
|
||||
}
|
||||
const span = Math.min(3, c - from - 1, to - c - 1)
|
||||
if (span >= 2) {
|
||||
const va = sideways(r.frames[c - 1 - span], A, r.w, r.h, span / r.fps)
|
||||
const vb = sideways(B, r.frames[c + span], r.w, r.h, span / r.fps)
|
||||
if (Math.abs(va) > MOVING && Math.abs(vb) > MOVING && Math.sign(va) !== Math.sign(vb)) {
|
||||
tally.plane++
|
||||
out.push({ level: "warn", kind: "plane", at: t, says: `the cut at ${s2(t)} reverses screen direction (moving ${va > 0 ? "right" : "left"}, then ${vb > 0 ? "right" : "left"}): flip or reframe one side, or cut on a neutral move (the screen's plane, Murch ${MURCH.plane}%)` })
|
||||
}
|
||||
}
|
||||
const meant = (o.beatsAt ?? []).some((b) => Math.abs(b - t) < 0.25)
|
||||
const dl = B.luma - A.luma
|
||||
const dw = B.warmth - A.warmth
|
||||
if (!meant && (Math.abs(dl) > LUMA_JUMP || Math.abs(dw) > WARMTH_JUMP)) {
|
||||
tally.tone++
|
||||
const what = Math.abs(dl) > LUMA_JUMP ? `${dl > 0 ? "brighter" : "darker"} by ${Math.round(Math.abs(dl) * 100)}%` : `${dw > 0 ? "warmer" : "cooler"} by ${dw.toFixed(2)}`
|
||||
out.push({ level: "warn", kind: "tone", at: t, says: `the cut at ${s2(t)} jumps ${what} inside a beat: match the two shots' light, or start a beat there (tonal montage)` })
|
||||
}
|
||||
})
|
||||
if (cuts.length >= 2)
|
||||
for (const kind of ["eye", "plane", "tone"] as const)
|
||||
if (tally[kind] / cuts.length > HABIT)
|
||||
out.push({ level: "error", kind, at: null, says: `${tally[kind]} of ${cuts.length} cuts break ${kind === "eye" ? "eye trace" : kind === "plane" ? "screen direction" : "tone"}: a habit of the cut, not a choice` })
|
||||
return out
|
||||
}
|
||||
|
||||
/** a video's montage findings, kept beside it */
|
||||
export const MONTAGE_EXT = "montage.json"
|
||||
|
||||
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
|
||||
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
|
||||
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
|
||||
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
|
||||
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
|
||||
try {
|
||||
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
|
||||
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
|
||||
} catch {}
|
||||
const findings = measure()
|
||||
try {
|
||||
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
|
||||
} catch {}
|
||||
return findings
|
||||
}
|
||||
|
||||
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "montage", text: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts", over: "file", at: ["render", "publish", "done"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video" || !f.width || !f.height) return
|
||||
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
|
||||
const plan = c ? cutOf(c, f.path) : null
|
||||
const beats = plan?.plan.beats ?? []
|
||||
let faces: Faces[] | undefined
|
||||
let rate = 0
|
||||
try {
|
||||
const sc = await f.scene()
|
||||
faces = sc.faces
|
||||
rate = sc.rate
|
||||
} catch (e) {
|
||||
// no scene reader here: the frame's contrast stands in for faces
|
||||
if (!(e instanceof Unmet)) throw e
|
||||
}
|
||||
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
|
||||
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
|
||||
const r = read(f.abs, f.fps, f.width!, f.height!)
|
||||
if (r.frames.length < 2) return []
|
||||
const cuts = cutsOf(r)
|
||||
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
|
||||
}))
|
||||
say(x)
|
||||
},
|
||||
)
|
||||
@@ -9,18 +9,16 @@ import { bookkeeping } from "./naming.ts"
|
||||
|
||||
type Said = { check?: string; level?: string; says?: string; fix?: string | null; frames?: [number, number] | null }
|
||||
|
||||
/** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice, 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) */
|
||||
/** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice */
|
||||
const MEASURED_AGAIN = new Set(["safe-area"])
|
||||
|
||||
/** the manifest's findings, one a kind: the first of each (by check and level), with how many more there were */
|
||||
export function renderFindings(manifest: unknown, floorRuns = true): Said[] {
|
||||
export function renderFindings(manifest: unknown): Said[] {
|
||||
const all = ((manifest as { findings?: Said[] } | null)?.findings ?? []).filter((x) => x && (x.level === "error" || x.level === "warn"))
|
||||
const firsts = new Map<string, Said & { more: number }>()
|
||||
for (const x of all) {
|
||||
const k = x.check ?? "render"
|
||||
if (floorRuns && MEASURED_AGAIN.has(k)) continue
|
||||
if (MEASURED_AGAIN.has(k)) continue
|
||||
const key = `${k} ${x.level}`
|
||||
const had = firsts.get(key)
|
||||
if (had) had.more++
|
||||
@@ -29,14 +27,8 @@ export function renderFindings(manifest: unknown, floorRuns = true): Said[] {
|
||||
return [...firsts.values()].map((x) => ({ ...x, says: `${x.check ?? "render"}: ${x.says ?? ""}${x.more ? ` (and ${x.more} more like it)` : ""}` }))
|
||||
}
|
||||
|
||||
const renderPack = (floorRuns: boolean) =>
|
||||
check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
if (!f.made || bookkeeping(f.path) || !f.manifest) return
|
||||
for (const x of renderFindings(f.manifest, 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)
|
||||
export default check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => {
|
||||
if (!f.made || bookkeeping(f.path) || !f.manifest) return
|
||||
for (const x of renderFindings(f.manifest))
|
||||
found({ level: x.level as "error" | "warn", says: x.says ?? "", fix: x.fix ?? undefined, frames: x.frames ?? undefined })
|
||||
})
|
||||
+2
-11
@@ -20,18 +20,12 @@ 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[] = []
|
||||
@@ -145,10 +139,7 @@ function madeUnder(root: string): string[] {
|
||||
|
||||
/** 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 all = [...packsOf(contract).flatMap((p) => PACK_CHECKS[p]), ...((contract?.checks ?? []) as Check[])]
|
||||
const seen = new Set<string>()
|
||||
return all.filter((c) => {
|
||||
if (!c?.id || seen.has(c.id) || !c.once) return false
|
||||
@@ -167,7 +158,7 @@ function planOf(goals: Contract[]): string[] {
|
||||
const out = [...doctor]
|
||||
for (const c of goals) {
|
||||
const at = goals.length > 1 ? `${nameOf(c)}: ` : ""
|
||||
out.push(...unknownPacks(c).map((k) => GONE_PACKS[k] ? `${at}packs.${k}: ${GONE_PACKS[k]}` : `${at}packs.${k}: raea has no pack of that name (raea check --json lists them)`))
|
||||
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea 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`)
|
||||
|
||||
@@ -3,8 +3,8 @@ import { expect, test } from "bun:test"
|
||||
import { mkdtempSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { renderAlone, renderFindings } from "../src/packs/render.ts"
|
||||
import { checksOf, collapse, keptCheck } from "../src/run.ts"
|
||||
import { renderFindings } from "../src/packs/render.ts"
|
||||
import { collapse, keptCheck } from "../src/run.ts"
|
||||
|
||||
const at = (s: number, says = "a caption under the app's buttons") => ({ goal: null, check: "floor", file: "a.mp4", level: "error" as const, says, seconds: [s, s + 1] as [number, number] })
|
||||
|
||||
@@ -38,16 +38,6 @@ 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)")
|
||||
})
|
||||
|
||||
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)", () => {
|
||||
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)
|
||||
|
||||
@@ -10,10 +10,8 @@ import { project } from "./project.ts"
|
||||
test("a cut holds only the rules that catch real faults (docs/check.feature CK2)", () => {
|
||||
const on = packsOf(cut({ cut: { brief: "b.txt" } }))
|
||||
for (const p of ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"] as const) expect(on).toContain(p)
|
||||
for (const p of ["voice", "reading", "hook", "airgaps", "quotes"] as const) expect(on).not.toContain(p)
|
||||
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { voice: true, place: false } }))).toContain("voice")
|
||||
// a pack raea took out is skipped, never a crash (12-06: montage)
|
||||
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { montage: true } })) as string[]).not.toContain("montage")
|
||||
for (const p of ["voice", "reading", "hook", "airgaps", "montage", "quotes"] as const) expect(on).not.toContain(p)
|
||||
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { montage: true, place: false } }))).toContain("montage")
|
||||
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { place: false } }))).not.toContain("place")
|
||||
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "render"])
|
||||
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "render", "run"])
|
||||
|
||||
@@ -4,6 +4,7 @@ import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { faultsOf, floorOf, type Measured } from "../src/packs/floor.ts"
|
||||
import { keptOr } from "../src/packs/montage.ts"
|
||||
|
||||
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
|
||||
@@ -33,6 +34,23 @@ test("a floor report is kept: measured once, again when the video is newer, and
|
||||
rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
|
||||
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
|
||||
const v = path.join(d, "a.mp4")
|
||||
writeFileSync(v, "x")
|
||||
let runs = 0
|
||||
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
|
||||
keptOr(v, "a", by)
|
||||
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
|
||||
expect(runs).toBe(1)
|
||||
keptOr(v, "b", by)
|
||||
expect(runs).toBe(2)
|
||||
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
|
||||
keptOr(v, "b", by)
|
||||
expect(runs).toBe(3)
|
||||
rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("blocky darks are an error only when the encode added them; untraced, a warning; the picture's own, nothing (12-04)", () => {
|
||||
const xs: Measured[] = [
|
||||
{ level: "error", says: "blocky patches in dark areas in 1 of 1 sampled frames (worst 6% of dark blocks stepping): the encode starved the near-blacks, or the footage holds them; render with --quality master" },
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// MK48-MK51: the montage pack on small videos made here with ffmpeg, cut by cut: the cuts found, eye trace, screen
|
||||
// direction and tone across each, a habit made an error, and each beat's pace and tempo against its plan.
|
||||
import { expect, test } from "bun:test"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import type { CutBeat as Beat } from "raea/brief.gen"
|
||||
import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts"
|
||||
|
||||
const W = 96
|
||||
const H = 170
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-"))
|
||||
const ff = (args: string[]) => {
|
||||
const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args])
|
||||
if (r.status !== 0) throw new Error(String(r.stderr))
|
||||
}
|
||||
/** a shot: a box of `box` colour on `bg`, its x moving by `x` (an ffmpeg expression in t), for `d` seconds */
|
||||
function shot(name: string, bg: string, x: string, y: number, d = 1, box = "white"): string {
|
||||
const out = path.join(dir, `${name}.mp4`)
|
||||
ff(["-f", "lavfi", "-i", `color=c=${bg}:s=${W}x${H}:r=30:d=${d}`, "-f", "lavfi", "-i", `color=c=${box}:s=20x40:r=30:d=${d}`, "-filter_complex", `[0][1]overlay=x='${x}':y=${y}:shortest=1,format=yuv420p`, "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", out])
|
||||
return out
|
||||
}
|
||||
function cut(name: string, shots: string[]): string {
|
||||
const out = path.join(dir, `${name}.mp4`)
|
||||
ff([...shots.flatMap((s) => ["-i", s]), "-filter_complex", `${shots.map((_, i) => `[${i}:v]`).join("")}concat=n=${shots.length}:v=1,format=yuv420p`, "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", out])
|
||||
return out
|
||||
}
|
||||
const kinds = (fs: { kind: string }[]) => fs.map((x) => x.kind)
|
||||
|
||||
test("a cut from a box at the top left to one at the bottom right moves the eye; the same place keeps it", () => {
|
||||
const jump = read(cut("jump", [shot("tl", "black", "6", 10), shot("br", "0x101010", "70", 120)]), 30, W, H)
|
||||
const cs = cutsOf(jump)
|
||||
expect(cs).toEqual([30])
|
||||
expect(kinds(acrossCuts(jump, cs))).toContain("eye")
|
||||
const kept = read(cut("kept", [shot("tl2", "black", "6", 10), shot("tl3", "0x101010", "8", 14, 1, "yellow")]), 30, W, H)
|
||||
expect(kinds(acrossCuts(kept, cutsOf(kept)))).not.toContain("eye")
|
||||
})
|
||||
|
||||
test("motion to the right, then to the left, reverses screen direction; right then right keeps it", () => {
|
||||
const flip = read(cut("flip", [shot("r1", "black", "5+t*60", 60), shot("l1", "0x202020", "70-t*60", 60)]), 30, W, H)
|
||||
expect(kinds(acrossCuts(flip, cutsOf(flip)))).toContain("plane")
|
||||
const same = read(cut("same", [shot("r2", "black", "5+t*60", 60), shot("r3", "0x202020", "5+t*60", 60)]), 30, W, H)
|
||||
expect(kinds(acrossCuts(same, cutsOf(same)))).not.toContain("plane")
|
||||
})
|
||||
|
||||
test("a jump from dark to bright inside a beat is a tonal break; where a beat starts, it's meant", () => {
|
||||
const r = read(cut("tone", [shot("dark", "0x101010", "30", 60), shot("bright", "0xd0d0d0", "30", 60, 1, "black")]), 30, W, H)
|
||||
const cs = cutsOf(r)
|
||||
expect(kinds(acrossCuts(r, cs))).toContain("tone")
|
||||
expect(kinds(acrossCuts(r, cs, { beatsAt: [0, 1] }))).not.toContain("tone")
|
||||
})
|
||||
|
||||
test("one measure broken at more than half the cuts is an error: a habit, not a choice", () => {
|
||||
const r = read(cut("habit", [shot("h1", "black", "6", 10), shot("h2", "0x303030", "70", 120), shot("h3", "black", "6", 10), shot("h4", "0x303030", "70", 120)]), 30, W, H)
|
||||
const fs = acrossCuts(r, cutsOf(r))
|
||||
expect(fs.filter((x) => x.kind === "eye" && x.level === "error").length).toBe(1)
|
||||
})
|
||||
|
||||
test("a beat's shots average within a third of its asl; build shortens and release lengthens", () => {
|
||||
const beats: Beat[] = [
|
||||
{ at: 0, feel: "a chore left undone", asl: 2 },
|
||||
{ at: 6, feel: "rising panic", tempo: "build" },
|
||||
{ at: 10, feel: "relief", tempo: "release" },
|
||||
]
|
||||
// shots: 0-2-4-6 (asl 2), then 6-8-9.2-9.8-10 (shortening), then 10-10.4-11.2-12.8 (lengthening)
|
||||
const cuts = [2, 4, 6, 8, 9.2, 9.8, 10, 10.4, 11.2].map((s) => Math.round(s * 30))
|
||||
expect(pace(beats, cuts, 30, 12.8)).toEqual([])
|
||||
const slow = pace([{ at: 0, feel: "a chore left undone", asl: 1 }], [], 30, 6)
|
||||
expect(slow[0]).toMatchObject({ kind: "pace", level: "error" })
|
||||
expect(slow[0].says).toContain("too slow")
|
||||
const flat = pace([{ at: 0, feel: "rising panic", tempo: "build" }], [30, 60, 90], 30, 4)
|
||||
expect(flat[0]).toMatchObject({ kind: "tempo" })
|
||||
expect(tau([3, 2, 1])).toBe(-1)
|
||||
})
|
||||
@@ -10,7 +10,7 @@ beforeAll(() => {
|
||||
process.env.RAEA_REAL = "/usr/bin/false"
|
||||
delete process.env.RAEA_CLOUD_GPU_URL
|
||||
})
|
||||
const off = { words: false, sound: false, frames: false, place: false, floor: false, naming: false, captions: false, voice: false, reading: false, quotes: false, count: false, open: false, say: false, never: false, cta: false, shape: false }
|
||||
const off = { words: false, sound: false, frames: false, place: false, floor: false, naming: false, captions: false, voice: false, reading: false, montage: false, quotes: false, count: false, open: false, say: false, never: false, cta: false, shape: false }
|
||||
const contract = (open: unknown[] = []) => ({ kind: "cut", packs: off, cut: { brief: "media/brief.txt", formats: ["9:16", "4:5", "1:1"], cuts: [{ id: "a1" }], open } })
|
||||
const clip = readFileSync(CLIP)
|
||||
const all = async (open: unknown[] = [], files: string[]) => {
|
||||
|
||||
@@ -61,8 +61,9 @@ A playable is `goal: playable({ aim, playable: { game: "game.tsx", orientation?,
|
||||
orientations and every network unless brief.ts says otherwise, so a brief that asks for one shape writes it:
|
||||
`orientation: "portrait"` for 9:16, `"landscape"` for 16:9. A brief that names its networks lists them in `networks`.
|
||||
|
||||
A cut's beats are yours, never the brief's: plan them in your own notes, never in brief.ts. Nothing grades a plan
|
||||
against itself.
|
||||
A cut's `beats` are optional and yours, never the brief's: plan them in your own notes, not in brief.ts, unless the
|
||||
brief itself sets the cut's pace. When it does, `{ at, asl?, tempo? }[]` (`asl` the beat's average shot length in
|
||||
seconds, `tempo` `"build"`, `"release"` or `"hold"`) is measured by the montage check, which the brief switches on.
|
||||
|
||||
## Rules
|
||||
|
||||
|
||||
@@ -7,16 +7,22 @@ sequence, never alone, and don't assume a shot keeps its meaning when its neighb
|
||||
|
||||
## Decide the beats before cutting
|
||||
|
||||
Plan each cut beat by beat before you cut it: what the viewer feels and understands, and its pace. The plan is yours,
|
||||
in your notes, never in brief.ts (brief.ts holds only what the brief asks) and never a rule the cut is graded on:
|
||||
A cut goal's plan says, beat by beat, what the viewer feels and understands, and its pace:
|
||||
|
||||
```md
|
||||
choreo_itch_a_v1
|
||||
- 0 s: the itch of a chore left undone; shots about 1.5 s
|
||||
- 8 s: panic as the list grows; shots shorter as it goes
|
||||
- 14 s: relief, the app does the reminding; shots longer
|
||||
```ts
|
||||
cut({ aim: "Three TikTok ads for Choreo", cut: { brief: "brief.md", formats: ["9:16"], seconds: [15, 30], cuts: [
|
||||
{ id: "choreo_itch_a_v1", beats: [
|
||||
{ at: 0, feel: "the itch of a chore left undone", asl: 1.5 },
|
||||
{ at: 8, feel: "panic as the list grows", tempo: "build" },
|
||||
{ at: 14, feel: "relief", story: "the app does the reminding", tempo: "release" },
|
||||
] },
|
||||
] } })
|
||||
```
|
||||
|
||||
Each beat's `feel` and `story` are your plan for the cut: what you build it to do, never a rule it's graded on. `asl`
|
||||
(the beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are
|
||||
measured by the montage pack, when the brief switches it on (`packs: { montage: true }`).
|
||||
|
||||
## Murch's order: what to give up first
|
||||
|
||||
Walter Murch (In the Blink of an Eye) weighs a cut's reasons. The weights are his judgment, not measurements, so treat
|
||||
@@ -24,15 +30,16 @@ them as an order, never as a score:
|
||||
|
||||
| Reason | Weight | Who holds it |
|
||||
|---|---|---|
|
||||
| Emotion | 51% | you, from each beat's feel |
|
||||
| Story | 23% | you, from each beat's story |
|
||||
| Rhythm | 10% | you, from each beat's pace; a cut on a word is the check's (sound) |
|
||||
| Eye trace | 7% | you: the eye lands near where the last shot left it |
|
||||
| The screen's plane | 5% | you: sideways motion not reversed across a cut |
|
||||
| Emotion | 51% | you, from each beat's `feel`: no check grades it |
|
||||
| Story | 23% | you, from each beat's `story`: no check grades it |
|
||||
| Rhythm | 10% | the montage pack: each beat's `asl` and `tempo`; a cut on a word is the sound pack's |
|
||||
| Eye trace | 7% | the montage pack: the focal point within 0.4 of the frame across a cut |
|
||||
| The screen's plane | 5% | the montage pack: sideways motion not reversed across a cut |
|
||||
| Its 3D space | 4% | you: where people are, kept across a cut |
|
||||
|
||||
Give up from the bottom: break spatial continuity before screen direction, screen direction before eye trace, eye trace
|
||||
before rhythm, and never story or emotion for anything below them.
|
||||
before rhythm, and never story or emotion for anything below them. A montage warning that keeps a higher reason is
|
||||
fine to leave; say why in the cut's notes. One broken at most of a file's cuts is an error: a habit, not a choice.
|
||||
|
||||
## Eisenstein's methods of montage, as layers
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ playable?: PlayableGoal,
|
||||
*/
|
||||
previews?: Array<string>,
|
||||
/**
|
||||
* raea's packs switched by name over the kind's defaults (`{ voice: true, place: false }`): which of
|
||||
* raea's packs switched by name over the kind's defaults (`{ montage: true, place: false }`): which of
|
||||
* raea/goal's rules hold this goal (docs/goal.feature)
|
||||
*/
|
||||
packs?: { [key in string]: boolean },
|
||||
|
||||
Reference in new issue
Block a user