Compare commits

..
Author SHA1 Message Date
shinyobjectz b70c8c868d raea goal check on a plan: only the cut's own exact errors stop it
A plan check's exit 1 stops raea cloud from rendering any cut, so it has to mean "this cut has something to fix".
The review of #332 found three ways it didn't:

- The project's own checks (registered, taste) and the goals' job checks (count, quotes) ran on a plan. A brief
  asking for 10 cuts with the count question still open, which is normal until a person answers it at the first
  stop, failed every plan, so nothing could ever be rendered. A plan now runs only its cut's file checks; the job
  and project checks stay with the render, publish and done moments.
- A farm failure (/v1/scene answering 503 three times) made frames and place break, and a broken check fails the
  run, with no ERROR line to act on. On a plan, a check that throws now waits and says the render's check holds it.
- Place, captions, reading and faces cut by the frame's edge read the source frames without the cut's text over
  them, or hold captions against the takes' words rather than the mix. On round 22's Body Shop each cut had at
  least one such error that the export's check didn't give. On a plan these are warnings now, marked "(on the plan
  a warning: the render's check holds it)". Floor's text rules, text too small and sound's edit points and levels
  stay errors, since a plan knows them exactly as the export does.

Tested: bun test in sdk/goal passes all 72 tests, three of them new in test/plan.test.ts (a brief's unanswered
count doesn't stop a clean plan, while the same project checked without a plan still errs on it; a farm answering
503 leaves a clean plan PASSED with frames waiting; text over a face and talking with no captions are warnings on a
plan). On raea-box-6, the four Body Shop cuts' plans went from 15-31 errors each (captions, frames, place, reading
and sound) to sound errors only (17, 22, 11, 11), which match the export's sound errors one for one.
2026-12-04 11:08:29 -08:00
shinyobjectz 1e559373fc raea goal check --at edit --manifest PLAN EDIT.tsx: a cut checked on its plan before it's drawn
In round 22 every run missed its budget the same way: a full render of every cut, and only then dozens of floor,
sound, place and frames errors, fixed, and everything rendered again. All of those can be known from the composition's
timeline, its takes' words and its sources' frames, before anything is drawn.

With a composition named and --manifest given, goal check now treats the manifest as the plan of one of its cuts (what
`raea render EDIT.tsx --composition ID --plan -o OUT.plan.json` writes: the render manifest of every frame, nothing
drawn). The file it checks is the export the plan is of (OUT.mp4, named by stripping .plan/.render/.manifest), and its
findings are written to OUT.plan.check.json as well as review/goal.json (both written whole, since several cuts' plans
are checked at once). At the edit moment, on a plan:

- floor: apps/check/text's text rules ported to TypeScript (src/plan.ts textRuns, zones, textRules): text in the app's
  UI zones and text clipped off the frame are errors, text up too briefly a warning. Contrast, freezes, flashes,
  loudness and blotching still wait for the export.
- sound: unchanged, now also run at edit; it already works from the manifest's clips against each take's words and level.
- frames and place: what each sampled frame (two a second) shows is read from the source frames its videos show. Each
  video's box, fit, object-position and clip give the part of the source picture the frame shows; that part is cut out
  of the source frame (ffmpeg crop at the scene reader's size, eight at a time), read by the farm's POST /v1/scene, and
  its faces, things, person mask and text are mapped back into the cut's frame. Reading the crop rather than the whole
  source frame gives the reader the same pixels and resolution the export's reader gets, so a face half out of the shot
  is read the way the export reads it. A video's edge inside the frame is a seam; a full-frame opaque fill beyond the
  cut's background count (an end card) hides the videos under it. Each read is kept under review/scenes/ by source,
  second and crop, so a plan checked again only asks for what changed.
- captions and reading: what the cut shows is its own text as laid out (a text on several lines read a line each, as
  the export's reader reads it), and what it says is its voice clips' takes' words where the clips put them.

media.ts's scene() posting is split out as readScenes() so the plan reads go through the same retrying farm client.

Tested: bun test (69 pass, 5 new in test/plan.test.ts: drawing and crops, mapping a crop's scene into the frame,
seams and hiding, the cut's words from its clips, the text rules, and goal check on a plan end to end with a stand-in
farm, including the kept reads). On raea cloud boxes, the changed sdk/goal (with the box image's goal.ts) was run as
`raea goal check --at edit --manifest OUT.plan.json edit.tsx` against the full render manifests of round 22's 14 cuts
(their format is the plan's) in read-only copies of the three projects, and its errors compared with each export's
.check.json from the same render. Over the 10 cuts with a check from the same render: floor 8 of 8 matched (3 more
are blotching and a flash, which only the picture shows), sound 95 of 95 with none extra, frames 4 of 5 with 3 extra,
place 20 of 32 with 8 extra (the misses are mostly captions over a person that the plan says as warnings where the
export's reader found a handbag or a face in the caption's own box), captions 5 of 14, reading 1 of 5 (its misses are
the export's reader reading signs in the footage). A first plan check took 15-41 s a cut on the box (most of it the
farm's reads); checked again with its reads kept, 2-4 s.
2026-12-04 10:25:36 -08:00
28 changed files with 916 additions and 1089 deletions

No files matched your search

+1 -1
View File
@@ -125,7 +125,7 @@ fn labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on
let sent = &groups[0].questions[0];
assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
// new words for the flat question, asked of its labelled clips
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad, by_ref: None }, &mut |_| {}).unwrap();
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad }, &mut |_| {}).unwrap();
let (old, new) = both.unwrap();
assert_eq!(sum.calls, 36);
assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
+27 -119
View File
@@ -5,12 +5,6 @@
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
//! person's own calibration when it has earned one (calibrate.rs).
//!
//! Through an agent key (a pipeline, CI, a raea cloud box), a call about the picture with its sound, at most a minute,
//! names the video kept on raea-api and its window instead of cutting clips here (raea_io_clef::by_reference, 12-04): the
//! video goes up once, raea-api cuts the window, and this machine decodes nothing, so every call goes at once. Where
//! that isn't offered, each file's video windows are cut in one pass over the stretch they cover (`media::videos`),
//! not one decode per window.
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
@@ -18,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits};
use raea_io_clef::{Answered, ByReference, Call, Fail, Media, Source, media};
use raea_io_clef::{Answered, Call, Fail, Media, media};
use serde::Serialize;
use serde_json::{Value, json};
@@ -108,20 +102,11 @@ pub struct Opts {
pub dry: bool,
/// how a call is made: `raea_io_clef::ask` (a test gives its own)
pub ask: fn(&Call) -> Result<Answered, Fail>,
/// how a call by reference is made, when one can be (an agent key is the first route): `raea_io_clef::ask_by_reference`;
/// its `Fail::Next` means the clips are cut here and `ask` is used
pub by_ref: Option<fn(&ByReference) -> Result<Answered, Fail>>,
}
impl Opts {
pub fn new(jobs: usize, dry: bool) -> Opts {
let by_ref = !raea_io_clef::by_reference::off(&raea_io_clef::route::open());
Opts { jobs, dry, ask: raea_io_clef::ask, by_ref: by_ref.then_some(raea_io_clef::ask_by_reference as fn(&ByReference) -> Result<Answered, Fail>) }
}
/// Whether this machine cuts the picture: nothing goes by reference, or raea-api has said it can't take it.
fn cuts_here(&self) -> bool {
self.by_ref.is_none() || raea_io_clef::by_reference::off(&raea_io_clef::route::open())
Opts { jobs, dry, ask: raea_io_clef::ask }
}
}
@@ -181,50 +166,6 @@ pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
/// Clips cut once a run, by what they are.
type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
/// A clip's name among the cuts: what it is, of which file, over which window.
fn cut_key(what: &str, f: &Path, from: f64, to: Option<f64>) -> String {
format!("{what}:{}:{from}:{to:?}", f.display())
}
/// Each file's video windows the run's calls look at, cut in one pass the first time any of them is needed here.
struct Batches {
windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>>,
done: Mutex<HashMap<PathBuf, Arc<Mutex<bool>>>>,
}
impl Batches {
fn plan(groups: &[Group]) -> Batches {
let mut windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>> = HashMap::new();
for g in groups.iter().filter(|g| g.kept.is_none() && g.sees == Sees::Video && g.piece.probe.video) {
let w = windows.entry(g.piece.file.clone()).or_default();
if !w.contains(&(g.from, g.to)) {
w.push((g.from, g.to));
}
}
Batches { windows, done: Mutex::default() }
}
/// Every window of `f` not cut yet, cut in one pass (once a run); a window it fails leaves is cut on its own later.
fn cut(&self, cuts: &Cuts, f: &Path) {
let Some(all) = self.windows.get(f).filter(|w| w.len() > 1) else { return };
let lock = self.done.lock().unwrap().entry(f.to_path_buf()).or_default().clone();
let mut done = lock.lock().unwrap();
if std::mem::replace(&mut *done, true) {
return;
}
let left: Vec<(f64, Option<f64>)> = all.iter().filter(|(from, to)| !cuts.lock().unwrap().contains_key(&cut_key("video", f, *from, *to))).copied().collect();
if left.len() < 2 {
return;
}
if let Ok(clips) = media::videos(f, &left) {
let mut c = cuts.lock().unwrap();
for ((from, to), clip) in left.iter().zip(clips) {
c.insert(cut_key("video", f, *from, *to), Ok(Arc::new(clip)));
}
}
}
}
fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> {
if let Some(r) = cuts.lock().unwrap().get(&key) {
return r.clone();
@@ -235,7 +176,7 @@ fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>)
}
/// A group's media, and its seconds of video and of sound (for the estimate).
fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media, f64, f64), String> {
fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
if let Some(k) = &g.kept {
return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
}
@@ -246,12 +187,9 @@ fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media,
let (mut vs, mut ss) = (0.0, 0.0);
for f in &files {
let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? };
let k = |what: &str| cut_key(what, f, from, to);
let k = |what: &str| format!("{what}:{}:{from}:{to:?}", f.display());
match g.sees {
Sees::Video if p.video => {
if let Some(b) = batches {
b.cut(cuts, f);
}
m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
vs += span(&p).min(limits::VIDEO_SECONDS);
}
@@ -297,34 +235,40 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
out(Event::Answer(a));
}
let cuts: Cuts = Mutex::default();
let batches = Batches::plan(&groups);
let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false));
let spent_why = Mutex::new(String::new());
let (tx, rx) = mpsc::channel::<(usize, Done)>();
std::thread::scope(|s| {
for _ in 0..o.jobs.clamp(1, JOBS_MOST).min(groups.len().max(1)) {
let (tx, groups, cuts, batches, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &batches, &next, &spent, &spent_why);
for _ in 0..o.jobs.clamp(1, 16).min(groups.len().max(1)) {
let (tx, groups, cuts, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &next, &spent, &spent_why);
s.spawn(move || {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some(g) = groups.get(i) else { break };
let spend = |why: String| {
spent.store(true, Ordering::Relaxed);
*spent_why.lock().unwrap() = why.clone();
Done::Waits(why)
};
let done = if spent.load(Ordering::Relaxed) {
Done::Waits(spent_why.lock().unwrap().clone())
} else if let Some(r) = by_reference(g, o) {
// asked by reference; when it can't be, the clips are cut here below
match r {
Ok(a) => Done::Asked(a, vec![], g.piece.state()),
Err(Fail::Spent(why)) => spend(why),
Err(Fail::Stop(why)) => Done::Failed(why),
Err(Fail::Next(_)) => here(g, o, cuts, batches, &spend),
}
} else {
here(g, o, cuts, batches, &spend)
match media_of(g, cuts) {
Err(e) => Done::Failed(e),
Ok((m, vs, ss)) => {
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
let call = Call { state, questions: g.questions.clone(), media: m };
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
if o.dry {
Done::Would(would(g, &call, estimate))
} else {
match (o.ask)(&call) {
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
Err(Fail::Spent(why)) => {
spent.store(true, Ordering::Relaxed);
*spent_why.lock().unwrap() = why.clone();
Done::Waits(why)
}
Err(f) => Done::Failed(f.to_string()),
}
}
}
}
};
if tx.send((i, done)).is_err() {
break;
@@ -341,42 +285,6 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
sum
}
/// Calls at once: by reference each is a request and no work here, so more than a machine has cores.
const JOBS_MOST: usize = 32;
/// A call by reference, when this group can go that way: the picture with its sound (or none), of one file, a minute at
/// most, not clips kept from an earlier call, not a dry run. None: it can't, and its clips are cut here.
fn by_reference(g: &Group, o: &Opts) -> Option<Result<Answered, Fail>> {
let ask = o.by_ref?;
let p = g.piece.probe;
let end = g.to.unwrap_or(p.seconds).min(p.seconds);
if o.dry || g.kept.is_some() || !g.with.is_empty() || g.sees != Sees::Video || !p.video || end <= g.from || end - g.from > limits::VIDEO_SECONDS {
return None;
}
let source = Source { file: g.piece.file.clone(), from: g.from, to: g.to, sound: g.hears && p.sound };
Some(ask(&ByReference { state: g.piece.state(), questions: g.questions.clone(), source }))
}
/// A call with its clips cut here (or kept from an earlier call): asked, or (dry) what would be sent.
fn here(g: &Group, o: &Opts, cuts: &Cuts, batches: &Batches, spend: &dyn Fn(String) -> Done) -> Done {
match media_of(g, cuts, o.cuts_here().then_some(batches)) {
Err(e) => Done::Failed(e),
Ok((m, vs, ss)) => {
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
let call = Call { state, questions: g.questions.clone(), media: m };
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
if o.dry {
return Done::Would(would(g, &call, estimate));
}
match (o.ask)(&call) {
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
Err(Fail::Spent(why)) => spend(why),
Err(f) => Done::Failed(f.to_string()),
}
}
}
}
/// The clips a call sent, kept by hash for `raea ask try`.
fn kept(m: &Media) -> Vec<String> {
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
+1 -1
View File
@@ -124,7 +124,7 @@ fn clip(name: &str) -> PathBuf {
fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) {
setup();
let mut got = Vec::new();
let sum = runner::run(entries, &Opts { jobs, dry: false, ask, by_ref: None }, &mut |e| {
let sum = runner::run(entries, &Opts { jobs, dry: false, ask }, &mut |e| {
if let Event::Answer(a) = e {
got.push(a.clone());
}
-28
View File
@@ -136,34 +136,6 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
pool spent on the third call keeps two calls' answers and sends nothing more. `raea check`, the critique and
the fingerprint move onto the runner in AK5, AK4 and AK8. docs/manual/reference/sdk/ask.md is `raea/ask`'s.
@needs:AK3
Scenario: AK3b. A window asked by reference: the video kept once on raea-api, cut there
Given a raea cloud box judging a project's beats (12-04): about 18 questions a stop, each about its own window of
one of about six cuts (94 MB each, 1080x1920), every `raea ask` decoding its cut, cutting its window and
encoding it (6.4 s and 18 s of CPU an ask on the box's 8 cores, so six at a time was the ceiling)
And raea-api's `POST /v1/clef/media {sha256, size}` (kept, or a URL to PUT it to once) and `POST /v1/clef/ask
{state, questions, source: {sha256, from, to, sound}}`, which cuts the window with Cloudflare's Media
Transformations (480 px wide H.264, the sound in the clip), keeps the clip, and asks clef as any ask
(raea-platform apps/site/api/src/clef.ts)
When a call is asked through an agent key (`RAEA_AGENT_KEY` is the first route) about the picture with its
sound, one file, at most 60 s
Then each video goes up once a run by its SHA-256, or not at all when the account's storage has it already
(Git LFS, an upload), every call names it and its window, and the machine decodes nothing, so `--jobs` can be
as many as the calls (32 at most)
And a raea-api that doesn't offer it (an older one: 404 or 403 for the route, bad_media for the source; one
without Media Transformations: 501) turns it off for the run, and a window it can't cut (too large, not kept,
a failed cut) is cut here for that call alone; the app's route, stills, a sound alone, files set beside it
(`--with`) and windows over 60 s are cut here as before; `RAEA_ASK_BY_REFERENCE=0` turns it off
And where windows are cut here, each file's video windows are cut in one pass over the stretch they cover (one
decode, one scale, a split to each window's encode), and windows more than 2 s apart are separate passes
And `raea goal check` asks all of a stop's windows in one `raea ask --batch` (sdk/goal goal.ts askClefMany), so the
brief and each file are read once and each video goes up once
Status: in review 12-04 (raea PR on goal-spawn-fallback, raea-platform PR clef-by-reference). io/clef tests (a
video goes up once and each window is asked by its hash, a kept one isn't sent, an older raea-api turns it off,
a window too large is cut here alone, a spent pool stops), media.rs's stretches test and raea-platform's
test/clef-source.sh (a fake cutter in place of Media Transformations) are written; the Rust is unbuilt (the
machine had 7 GB free), and Media Transformations on a real cut is unmeasured.
Rule: AK4. On the person's plan
@needs:AK3
-1
View File
@@ -44,7 +44,6 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,
| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) |
| `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) |
| `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers |
| `RAEA_ASK_BY_REFERENCE` | `0`: never ask about a window by naming the video kept on raea-api; cut its clips here (docs/ask.feature AK3b) |
| `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) |
| `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend |
| `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) |
-170
View File
@@ -1,170 +0,0 @@
//! A call that names a video kept on raea-api and a window of it, in place of its clips (docs/ask.feature AK3b; raea-api
//! clef.ts, "Asking by reference"). A raea cloud box judging a project's beats decoded the same cut for every window it
//! asked about (12-04: 6.4 s and 18 s of CPU an ask, so six at a time was its ceiling). Now each video goes up once a
//! run, by its SHA-256 (`POST /v1/clef/media`, then one PUT; nothing at all when it's there already, in the account's
//! storage or Git LFS), and each call names it and a window, which raea-api cuts with Cloudflare's Media
//! Transformations: nothing is decoded here, so every window can be asked at once. Only through an agent key (the route
//! a pipeline, CI or a raea cloud box asks by), and only for the picture with its sound, at most 60 s (runner.rs says
//! which calls); anything else, and every call once raea-api has shown it doesn't offer this, cuts its clips here as
//! before. `RAEA_ASK_BY_REFERENCE=0` turns it off.
use std::collections::{HashMap, HashSet};
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use raea_core_ask::Question;
use raea_io_home::setting;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use crate::cache;
use crate::client::{Answered, Call, Fail, Transport, api_answer, said};
use crate::route::Route;
/// The largest video raea-api cuts (Media Transformations' input limit).
pub const MAX_BYTES: u64 = 100 * 1024 * 1024;
const ROUTE: &str = "your raea plan, with an agent key (cut on raea-api)";
/// A window of a video, to be cut on raea-api: `sound` puts its sound in the clip (clef hears a video's soundtrack with
/// its frames).
#[derive(Debug, Clone)]
pub struct Source {
pub file: PathBuf,
pub from: f64,
pub to: Option<f64>,
pub sound: bool,
}
/// One call by reference: what the piece is, its questions, and the window they're about.
#[derive(Debug, Clone)]
pub struct ByReference {
pub state: String,
pub questions: Vec<Question>,
pub source: Source,
}
/// The raea-apis that have shown they don't offer it this run (an older one, or one that can't cut): every call to them
/// cuts its own clips.
fn refused() -> &'static Mutex<HashSet<String>> {
static OFF: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
OFF.get_or_init(Mutex::default)
}
fn turn_off(api: &str) {
refused().lock().unwrap().insert(api.to_string());
}
/// Whether asking by reference is off for the rest of this run (or wasn't open: no agent key first, or turned off).
pub fn off(routes: &[Route]) -> bool {
api(routes).is_none()
}
/// The agent key's raea-api and key, when a call can go by reference: an agent key is the first route, and neither
/// `RAEA_ASK_BY_REFERENCE=0` nor that raea-api has turned it off.
pub fn api(routes: &[Route]) -> Option<(&str, &str)> {
if setting("RAEA_ASK_BY_REFERENCE").as_deref() == Some("0") {
return None;
}
match routes.first() {
Some(Route::Agent { api, key }) if !refused().lock().unwrap().contains(api.as_str()) => Some((api.as_str(), key.as_str())),
_ => None,
}
}
type Kept = Arc<OnceLock<Result<String, Fail>>>;
/// Each file hashed and kept once a run, by its path, length and time written: every call about it waits for that once.
fn memo(file: &Path) -> Kept {
static FILES: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();
let m = std::fs::metadata(file).ok();
let id = format!("{}\u{1f}{:?}\u{1f}{:?}", file.display(), m.as_ref().map(|m| m.len()), m.and_then(|m| m.modified().ok()));
FILES.get_or_init(Mutex::default).lock().unwrap().entry(id).or_default().clone()
}
/// A file's SHA-256 and length, read once in 1 MiB pieces.
pub fn hashed(file: &Path) -> Result<(String, u64), String> {
let mut f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let (mut h, mut buf, mut n) = (Sha256::new(), vec![0u8; 1 << 20], 0u64);
loop {
let got = f.read(&mut buf).map_err(|e| format!("{}: {e}", file.display()))?;
if got == 0 {
break;
}
h.update(&buf[..got]);
n += got as u64;
}
Ok((h.finalize().iter().map(|b| format!("{b:02x}")).collect(), n))
}
/// The video on raea-api, by its SHA-256: there already, or sent once. A raea-api that doesn't know the route turns
/// asking by reference off for the run.
fn keep(t: &dyn Transport, api: &str, key: &str, file: &Path) -> Result<String, Fail> {
let (sha, size) = hashed(file).map_err(Fail::Next)?;
if size > MAX_BYTES {
return Err(Fail::Next(format!("{} is over {} MB, more than raea-api cuts", file.display(), MAX_BYTES >> 20)));
}
let (code, j) = t.post(&format!("{api}/v1/clef/media"), Some(key), &json!({"sha256": sha, "size": size})).map_err(|e| Fail::Next(format!("keeping {} for asking: {e}", file.display())))?;
match code {
200 if j["kept"] == true => Ok(sha),
200 => {
let url = j["url"].as_str().ok_or_else(|| Fail::Next("raea-api gave no URL to keep the video at".into()))?;
match t.put_file(url, file) {
Ok(200..=299) => Ok(sha),
Ok(c) => Err(Fail::Next(format!("keeping {} for asking: HTTP {c}", file.display()))),
Err(e) => Err(Fail::Next(e)),
}
}
// no plan, a spent pool, a file too large to cut there: this call's clips are cut here, and its ask says why
402 | 413 => Err(Fail::Next(said(&j, code))),
// an older raea-api (404, or 403 for an agent key's route it doesn't know): cut here for the rest of the run
_ => {
turn_off(api);
Err(Fail::Next(format!("raea-api doesn't keep videos for asking: {}", said(&j, code))))
}
}
}
/// The body raea-api takes: the state, the questions, and the video by its hash with the window.
fn body(call: &ByReference, sha: &str) -> Value {
let c = Call { state: call.state.clone(), questions: call.questions.clone(), ..Default::default() };
let s = &call.source;
let mut source = json!({"sha256": sha, "from": s.from, "sound": s.sound});
if let Some(to) = s.to {
source["to"] = json!(to);
}
json!({"state": c.state(), "questions": c.questions(), "source": source})
}
/// One call by reference through the agent key's raea-api. `Fail::Next` means cut the clips here and ask as before.
pub fn ask(t: &dyn Transport, call: &ByReference, routes: &[Route]) -> Result<Answered, Fail> {
let Some((api, key)) = api(routes) else { return Err(Fail::Next("asked by reference only with an agent key".into())) };
let questions = Call { questions: call.questions.clone(), ..Default::default() };
if let Some(p) = questions.question_problem() {
return Err(Fail::Stop(p));
}
let file = &call.source.file;
let sha = memo(file).get_or_init(|| keep(t, api, key, file)).clone()?;
let body = body(call, &sha);
let ckey = cache::key_of(&body);
if let Some(answers) = cache::get(&ckey) {
return Ok(Answered { answers, cost: 0.0, cached: true, route: "asked before (cache)".into(), pool_left: None });
}
let own = routes.iter().any(|r| matches!(r, Route::Own { .. }));
let (code, j) = t.post(&format!("{api}/v1/clef/ask"), Some(key), &body).map_err(|e| Fail::Next(format!("{ROUTE} didn't answer: {e}")))?;
match (code, j["error"].as_str()) {
// an older raea-api (it reads no source), or one that can't cut: cut here for the rest of the run
(400, Some("bad_media")) | (501, _) => {
turn_off(api);
Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code))))
}
// not kept any more, too large to cut there, the cut failed: this call's clips are cut here
(404 | 413 | 502, _) | (400, Some("bad_source")) => Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code)))),
_ => {
let a = api_answer(code, &j, ROUTE, own)?;
cache::put(&ckey, &a.answers);
Ok(a)
}
}
}
+1 -6
View File
@@ -16,13 +16,8 @@ pub fn dir() -> PathBuf {
/// The request's hash.
pub fn key(call: &Call) -> String {
key_of(&call.clef_body())
}
/// The hash of a request's body as sent (an ask by reference names its video by hash and window: by_reference.rs).
pub fn key_of(body: &Value) -> String {
let mut h = Sha256::new();
h.update(body.to_string().as_bytes());
h.update(call.clef_body().to_string().as_bytes());
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
+10 -38
View File
@@ -3,8 +3,6 @@
//! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded
//! answers and never spend.
use std::path::Path;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use raea_core_ask::{Question, limits};
@@ -57,10 +55,6 @@ impl std::fmt::Display for Fail {
/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.
pub trait Transport {
fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>;
/// A file's bytes PUT to a presigned URL (a video kept on raea-api to be asked about by reference): its status.
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
Err(format!("this transport doesn't send files ({url}, {})", file.display()))
}
}
pub struct Http;
@@ -77,25 +71,16 @@ impl Transport for Http {
Err(e) => Err(format!("{url}: {e}")),
}
}
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
let f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let len = f.metadata().map_err(|e| format!("{}: {e}", file.display()))?.len();
// a Content-Length of its own, so the body isn't chunked: R2 and raea-api's own URLs take only a known length
let r = ureq::put(url).timeout(std::time::Duration::from_secs(600)).set("content-length", &len.to_string());
match r.send(f) {
Ok(res) => Ok(res.status()),
Err(ureq::Error::Status(code, _)) => Ok(code),
Err(e) => Err(format!("sending {}: {e}", file.display())),
}
}
}
impl Call {
/// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits.
pub fn problem(&self) -> Option<String> {
let m = &self.media;
if let Some(p) = self.question_problem() {
if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
}
if let Some(p) = self.questions.iter().find_map(limits::check) {
return Some(p);
}
if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() {
@@ -111,19 +96,11 @@ impl Call {
(m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into())
}
/// Why its questions can't be sent, or None: how many, and each one's own limits.
pub(crate) fn question_problem(&self) -> Option<String> {
if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
}
self.questions.iter().find_map(limits::check)
}
pub(crate) fn questions(&self) -> Value {
fn questions(&self) -> Value {
Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect())
}
pub(crate) fn state(&self) -> String {
fn state(&self) -> String {
self.state.chars().take(limits::STATE_CHARS).collect()
}
@@ -151,7 +128,7 @@ impl Call {
}
}
pub(crate) fn said(body: &Value, code: u16) -> String {
fn said(body: &Value, code: u16) -> String {
body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}"))
}
@@ -174,11 +151,6 @@ pub fn workers_ai(t: &dyn Transport, call: &Call, account: &str, token: &str) ->
/// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account.
pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> {
let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?;
api_answer(code, &j, route, own_keys)
}
/// raea-api's answer read: the answers, or why not (a spent pool stops a batch unless the person's own keys can go on).
pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> Result<Answered, Fail> {
match (code, j["error"].as_str()) {
(200..=299, _) => Ok(Answered {
answers: j["answers"].as_object().cloned().unwrap_or_default(),
@@ -187,8 +159,8 @@ pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> R
route: route.into(),
pool_left: j["pool_left_usd"].as_f64(),
}),
(402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(j, code))),
(400 | 413, _) => Err(Fail::Stop(said(j, code))),
_ => Err(Fail::Next(format!("{route}: {}", said(j, code)))),
(402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(&j, code))),
(400 | 413, _) => Err(Fail::Stop(said(&j, code))),
_ => Err(Fail::Next(format!("{route}: {}", said(&j, code)))),
}
}
+1 -10
View File
@@ -1,16 +1,13 @@
//! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers
//! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the
//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it. Through an agent key, a call about
//! a window of a video can name the video kept on raea-api instead of sending its clips (`by_reference`).
//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it.
pub mod by_reference;
pub mod cache;
pub mod client;
pub mod critic;
pub mod media;
pub mod route;
pub use by_reference::{ByReference, Source};
pub use client::{Answered, Call, Fail, Http, Media, Transport};
pub use route::Route;
@@ -19,11 +16,5 @@ pub fn ask(call: &Call) -> Result<Answered, Fail> {
route::ask(&Http, call, &route::open())
}
/// One call by reference (a window of a video kept on raea-api), by the routes open on this computer. `Fail::Next`
/// means it can't go that way: cut the clips here and `ask`.
pub fn ask_by_reference(call: &ByReference) -> Result<Answered, Fail> {
by_reference::ask(&Http, call, &route::open())
}
#[cfg(test)]
mod tests;
-72
View File
@@ -99,68 +99,6 @@ pub fn video(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String>
out.read()
}
/// Windows a pass reads together: those that overlap or sit within this many seconds of each other. Further apart, each
/// stretch is its own pass, so two short windows a minute apart don't decode the minute between them.
const STRETCH_GAP: f64 = 2.0;
/// Each window as seconds from and to, held to 60 s as `video` holds it.
fn spans(windows: &[(f64, Option<f64>)]) -> Vec<(f64, f64)> {
windows.iter().map(|&(from, to)| (from, from + to.map(|t| (t - from).max(0.1)).unwrap_or(limits::VIDEO_SECONDS).min(limits::VIDEO_SECONDS))).collect()
}
/// The windows (by index) gathered into stretches read in one pass each.
fn stretches(spans: &[(f64, f64)]) -> Vec<Vec<usize>> {
let mut order: Vec<usize> = (0..spans.len()).collect();
order.sort_by(|a, b| spans[*a].0.total_cmp(&spans[*b].0));
let mut out: Vec<Vec<usize>> = Vec::new();
let mut end = f64::NEG_INFINITY;
for i in order {
match out.last_mut() {
Some(s) if spans[i].0 <= end + STRETCH_GAP => s.push(i),
_ => out.push(vec![i]),
}
end = if out.last().is_some_and(|s| s.len() > 1) { end.max(spans[i].1) } else { spans[i].1 };
}
out
}
/// Several windows of one file's picture, as `video` cuts each (480 px wide, 10 frames a second, no sound), in the
/// windows' order: each stretch of nearby windows decoded once, scaled once and split to each window's own encode,
/// rather than decoded again for every window (12-04: a raea cloud box asked 18 windows of six cuts, each decoded on its
/// own).
pub fn videos(file: &Path, windows: &[(f64, Option<f64>)]) -> Result<Vec<Vec<u8>>, String> {
let spans = spans(windows);
let mut out: Vec<Option<Vec<u8>>> = vec![None; windows.len()];
for s in stretches(&spans) {
if let &[i] = s.as_slice() {
out[i] = Some(video(file, windows[i].0, windows[i].1)?);
continue;
}
let start = s.iter().map(|&i| spans[i].0).fold(f64::INFINITY, f64::min);
let end = s.iter().map(|&i| spans[i].1).fold(f64::NEG_INFINITY, f64::max);
let outs: Vec<Temp> = s.iter().map(|_| Temp::new("mp4")).collect();
let mut graph = format!("[0:v]scale=480:-2,fps=10,split={}", s.len());
for n in 0..s.len() {
graph += &format!("[s{n}]");
}
for (n, &i) in s.iter().enumerate() {
graph += &format!(";[s{n}]trim=start={:.3}:end={:.3},setpts=PTS-STARTPTS[v{n}]", spans[i].0 - start, spans[i].1 - start);
}
let mut c = tool("ffmpeg", file)?;
c.args(["-nostdin", "-v", "error", "-y", "-ss", &format!("{start:.3}"), "-t", &format!("{:.3}", end - start)]).arg("-i").arg(file);
c.args(["-filter_complex", &graph]);
let enc = small_h264()?;
for (n, t) in outs.iter().enumerate() {
c.args(["-map", &format!("[v{n}]"), "-an"]).args(&enc).args(["-movflags", "+faststart"]).arg(&t.0);
}
run(c, "cutting the pictures")?;
for (&i, t) in s.iter().zip(&outs) {
out[i] = Some(t.read()?);
}
}
Ok(out.into_iter().map(Option::unwrap_or_default).collect())
}
/// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3.
pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {
let out = Temp::new("mp3");
@@ -194,14 +132,4 @@ mod tests {
assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]);
assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000");
}
#[test]
fn nearby_windows_are_read_in_one_pass_and_far_ones_apart() {
// a cut's beats, one after another, and a window to its end; one more a minute later
let w = [(0.0, Some(3.5)), (3.5, Some(7.2)), (7.2, Some(12.0)), (5.0, None), (90.0, Some(94.0))];
let s = spans(&w);
assert_eq!(s[3], (5.0, 65.0), "a window to the end is held to 60 s");
assert_eq!(stretches(&s), [vec![0, 1, 3, 2], vec![4]]);
assert_eq!(stretches(&spans(&[(0.0, Some(1.0)), (2.5, Some(3.0)), (6.0, Some(7.0))])), [vec![0, 1], vec![2]]);
}
}
-108
View File
@@ -106,111 +106,3 @@ fn workers_ai_gets_data_urls_and_raea_api_bare_base64() {
assert_eq!(c.api_body()["audio"][0], "AQ==");
assert_eq!(clef["questions"]["q"]["type"], "noul");
}
// ---- asking by reference (by_reference.rs): a video kept on raea-api once, each window asked by its hash
use crate::by_reference::{self, ByReference, Source};
/// Canned replies by URL ending, every URL asked (a file sent as "PUT url") and every body sent.
struct Api {
replies: Vec<(&'static str, u16, Value)>,
seen: RefCell<Vec<String>>,
bodies: RefCell<Vec<Value>>,
}
impl Api {
fn new(replies: Vec<(&'static str, u16, Value)>) -> Api {
Api { replies, seen: RefCell::default(), bodies: RefCell::default() }
}
}
impl Transport for Api {
fn post(&self, url: &str, _bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String> {
self.seen.borrow_mut().push(url.to_string());
self.bodies.borrow_mut().push(body.clone());
self.replies.iter().find(|(end, ..)| url.ends_with(end)).map(|(_, c, j)| (*c, j.clone())).ok_or_else(|| format!("{url}: connection refused"))
}
fn put_file(&self, url: &str, file: &std::path::Path) -> Result<u16, String> {
self.seen.borrow_mut().push(format!("PUT {url}"));
std::fs::metadata(file).map(|_| 200).map_err(|e| e.to_string())
}
}
/// A "video" unique to its test (the files kept are remembered by path), and an agent key's route to its own raea-api
/// (a raea-api that turns asking by reference off does so for itself alone).
fn video(test: &str) -> (std::path::PathBuf, Vec<Route>) {
setup();
let f = std::env::temp_dir().join(format!("raea-clef-ref-{}-{test}.mp4", std::process::id()));
std::fs::write(&f, format!("not really a video: {test}")).unwrap();
(f, vec![Route::Agent { api: format!("https://{test}.api.test"), key: "k".into() }])
}
fn by_ref(file: &std::path::Path, from: f64, to: Option<f64>) -> ByReference {
let source = Source { file: file.to_path_buf(), from, to, sound: true };
ByReference { state: format!("a test piece: {}", file.display()), questions: vec![Question::plain("q", "Is the product on screen?")], source }
}
const BY_REF: &str = r#"{"answers": {"q": {"noul": 0.4}}, "cost_usd": 0.001, "cached": false, "pool_left_usd": 1.5}"#;
#[test]
fn a_video_goes_up_once_and_each_window_is_asked_by_its_hash() {
let (file, routes) = video("once");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": false, "url": "https://r2.test/put"})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
let a = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
assert_eq!((a.answers["q"]["noul"].as_f64(), a.route.as_str()), (Some(0.4), "your raea plan, with an agent key (cut on raea-api)"));
by_reference::ask(&api, &by_ref(&file, 3.5, None), &routes).unwrap();
let seen = api.seen.borrow();
assert_eq!(seen.iter().map(|u| u.rsplit('/').next().unwrap()).collect::<Vec<_>>(), ["media", "put", "ask", "ask"], "{seen:?}");
let (sha, size) = by_reference::hashed(&file).unwrap();
let bodies = api.bodies.borrow();
assert_eq!(bodies[0], json!({"sha256": sha, "size": size}));
assert_eq!(bodies[1]["source"], json!({"sha256": sha, "from": 1.0, "to": 3.5, "sound": true}));
assert_eq!(bodies[2]["source"], json!({"sha256": sha, "from": 3.5, "sound": true}), "a window to the end names no end");
assert!(bodies[1].get("videos").is_none() && bodies[1]["questions"]["q"]["type"] == "noul");
// the same call again comes from the cache
let again = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
assert!(again.cached && api.seen.borrow().len() == 4);
}
#[test]
fn a_video_already_there_isnt_sent() {
let (file, routes) = video("there");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes).unwrap();
assert!(!api.seen.borrow().iter().any(|u| u.starts_with("PUT")), "{:?}", api.seen.borrow());
}
#[test]
fn an_older_raea_api_turns_it_off_and_the_clips_are_cut_here() {
let (file, routes) = video("older");
let api = Api::new(vec![("/v1/clef/media", 403, json!({"error": "agent_scope", "message": "an agent key reaches ..."}))]);
assert!(by_reference::api(&routes).is_some());
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))));
assert!(by_reference::off(&routes), "the rest of the run cuts its own clips");
// one that keeps videos but reads no source (bad_media) or can't cut (501) does the same
for (test, code, error) in [("no-source", 400, "bad_media"), ("no-cutter", 501, "cut_unavailable")] {
let (file, routes) = video(test);
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", code, json!({"error": error, "message": "no"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))), "{test}");
assert!(by_reference::off(&routes), "{test}");
}
}
#[test]
fn a_window_raea_api_cant_cut_is_cut_here_and_the_rest_still_go_by_reference() {
let (file, routes) = video("too-large");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 413, json!({"error": "media_too_large", "message": "over 16 MB"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(60.0)), &routes), Err(crate::Fail::Next(m)) if m.contains("16 MB")));
assert!(!by_reference::off(&routes));
}
#[test]
fn a_spent_pool_stops_and_only_an_agent_key_asks_by_reference() {
let (file, routes) = video("spent");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 402, json!({"error": "pool_spent", "message": "used up"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Spent(_))));
let app_first = [Route::App("http://127.0.0.1:9".into()), routes[0].clone()];
let none = Api::new(vec![]);
assert!(matches!(by_reference::ask(&none, &by_ref(&file, 0.0, Some(2.0)), &app_first), Err(crate::Fail::Next(_))));
assert!(none.seen.borrow().is_empty(), "the app's route cuts its own clips");
}
-5
View File
@@ -50,11 +50,6 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS
COPY src src
COPY image image
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
COPY deploy/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
@@ -1,312 +0,0 @@
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
// stop unless all the goals pass").
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
// 0.1.17-rc4: no StreetTalk cut could publish)
import * as cp from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
/** where a goal's critic verdict is kept, relative to the brief */
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
export const TIMEOUT = 300
/** folders that aren't the work: what the job writes about itself, and what tools keep */
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null {
let best: number | null = null
const stack = [dir]
let seen = 0
while (stack.length) {
const d = stack.pop()!
let names: string[] = []
try {
names = readdirSync(d)
} catch {
continue
}
for (const name of names) {
if (++seen > 20_000) return best
const p = path.join(d, name)
let st
try {
st = statSync(p)
} catch {
continue
}
if (st.isDirectory()) {
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
}
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
export function verdict(dir: string, g: Contract): Verdict | null {
try {
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
} catch {
return null
}
}
const goalOf = (j: Job): Contract | null => j.contract
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
for (const r of goalOf(j)?.rules ?? []) {
if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
}
})
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
}
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
export function lastVerdict(text: string): Verdict | null {
const key = text.lastIndexOf('"rules"')
if (key < 0) return null
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
let depth = 0
let inStr = false
for (let i = open; i < text.length; i++) {
const ch = text[i]
if (inStr) {
if (ch === "\\") i++
else if (ch === '"') inStr = false
continue
}
if (ch === '"') inStr = true
else if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
try {
const v = JSON.parse(text.slice(open, i + 1))
if (v && typeof v.rules === "object") return v
} catch {}
break
}
}
}
return null
}
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
export const CLEF_AT_ONCE = 6
/** `f` on each item, at most `n` at once, the answers in the items' order */
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length)
let next = 0
const worker = async () => {
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
return out
}
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()]
const heard = ask === askClef && !asyncSpawn()
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
for (const [j, k] of list.entries()) {
const answers = heard[j]
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
* its 10.5 minutes) */
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
if (!jobs.length) return []
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
try {
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
return jobs.map((k, i) => {
const rows = rowsOf(read(`${tmp}/${i}.out`))
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
return rows
})
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
const args = askArgs(file, says, from, to)
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
if (!asyncSpawn()) {
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
const rows = rowsOf(String(r.stdout ?? ""))
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
return Promise.resolve(rows)
}
return new Promise((ok, no) => {
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => {
const rows = rowsOf(out)
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
ok(rows)
})
})
}
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
// what's watched and heard, and what's read, at once: neither waits on the other
const [heard, said] = await Promise.all([
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
])
const rules: Verdict["rules"] = { ...heard }
if (said !== null) {
const v = lastVerdict(said)
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
return out
}
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
+66 -3
View File
@@ -9,14 +9,19 @@ import type { Contract } from "./contract.ts"
import * as media from "./media.ts"
import type { Faces, Levels, Word } from "./media.ts"
import type { Scene } from "./packs/place.ts"
import { outOf, planScene, said } from "./plan.ts"
import type { Project } from "./project.ts"
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
/** a text on a frame, in render pixels: its layout box and its ink */
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number; lines?: number }
/** a video on a frame, in render pixels: its source and the source second it shows, its box (and what of it a box it's
* in leaves showing, `clip`), its object-fit and object-position ([x px, x share of the free space, y px, y share]) */
export type ManifestVideo = { src: string; at: number; box: number[]; clip?: number[]; fit?: string; position?: number[]; opacity?: number }
/** `raea render --manifest`: the frames with their texts and videos, and the sound's clips; `plan`: written by `raea
* render --plan`, which draws nothing (every frame laid out, no picture) */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; plan?: boolean; frames?: { frame: number; text?: ManifestText[]; videos?: ManifestVideo[]; pictures?: { kind?: string; box?: number[]; opacity?: number }[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
@@ -37,6 +42,9 @@ export interface FileFacts {
height: number | null
fps: number
manifest: Manifest | null
/** a cut checked on its plan, before it's drawn (plan.ts): `manifest` is the plan, `path` and `abs` name the export
* it's of (which may not be there yet), and its words and scene are what its takes say and its sources show */
plan: boolean
moment: Moment
contract: Contract | null
/** what it says, word by word */
@@ -125,6 +133,7 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
height: shape?.height ?? manifest?.height ?? null,
fps: manifest?.fps ?? shape?.fps ?? 30,
manifest,
plan: false,
moment,
contract,
words: once(() => media.words(abs)),
@@ -167,3 +176,57 @@ export function runIn(dir: string) {
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
}
}
/** a composition checked on a plan of one of its cuts (`raea goal check --at edit --manifest OUT.plan.json EDIT.tsx`):
* the facts of the export the plan is of (OUT.mp4 beside the plan), known before it's drawn. Its words are its voice
* clips' takes' words where the clips put them, its scene its videos' source frames' (plan.ts); its own level, sheet
* and look wait for the export */
export function planFacts(plan: Manifest, planAbs: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
const abs = `${outOf(planAbs)}.mp4`
const roots = [root, path.dirname(planAbs)]
const fps = Number(plan.fps) || 30
const takeWords = new Map<string, Promise<Word[]>>()
const take = (src: string) => onMachine(src, roots)
const wordsOfTake = (src: string) => {
const f = take(src)
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
return takeWords.get(f)!
}
const st = statSync(planAbs)
return {
path: path.relative(root, abs),
abs,
root,
kind: "other",
made: true,
stamp: `${Math.round(st.mtimeMs)} ${st.size}`,
seconds: (Number(plan.length) || plan.frames?.length || 0) / fps,
width: Number(plan.width) || null,
height: Number(plan.height) || null,
fps,
manifest: plan,
plan: true,
moment,
contract,
words: once(async () => {
const clips = plan.sounds?.clips ?? []
const got = new Map<string, Word[]>()
for (const c of clips) {
if (got.has(c.src)) continue
try {
got.set(c.src, await wordsOfTake(c.src))
} catch {}
}
return said(clips, plan.sounds?.fps ?? fps, (src) => got.get(src) ?? null)
}),
take,
takeWords: wordsOfTake,
levels: (a, b, src) => (src ? media.levels(take(src) ?? src, a, b) : { start: a ?? 0, db: [] }),
scene: once(() => planScene(root, plan, take)),
sheet: () => {
throw new media.Unmet("a plan has no picture to make a sheet of: render it")
},
seen: () => null,
}
}
+31 -18
View File
@@ -233,24 +233,7 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const faces: Faces[] = []
const scenes: Scene[] = []
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
}
const { faces, scenes } = await readScenes(jpgs.map((n) => readFileSync(path.join(dir, n))))
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
@@ -262,6 +245,36 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
}
}
/** frames (JPEGs, a null where there's none) read by the farm's scene reader, 300 a request: each one's faces and seams,
* and its scene (people, faces, things, words in the shot) */
export async function readScenes(jpgs: (Buffer | null)[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!farm()) throw new Unmet("no scene reader on this machine (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)")
const faces: Faces[] = []
const scenes: Scene[] = []
const real = jpgs.flatMap((j, i) => (j ? [i] : []))
const got = new Map<number, Record<string, any> | null>()
for (let i = 0; i < real.length; i += 300) {
const part = real.slice(i, i + 300)
const body = JSON.stringify({ frames: part.map((k) => jpgs[k]!.toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
;(JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames.forEach((g, n) => got.set(part[n], g))
}
for (let i = 0; i < jpgs.length; i++) {
const g = got.get(i)
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
return { faces, scenes }
}
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
export function sheet(file: string): string {
const out = `${stem(file)}.sheet.jpg`
+8 -5
View File
@@ -16,7 +16,8 @@
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.ts"
import type { TextLine } from "./place.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
@@ -235,13 +236,15 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
}
export default check<FileFacts>(
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
if (!f.made || (f.kind !== "video" && !f.plan)) return
const heard = await f.words()
if (!heard.length) return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
// a cut's plan (plan.ts): what it shows is its own text, as laid out, and what it says its takes' words where its
// clips put them; an export's is what the reader reads and hears in it
const sc = f.plan && f.manifest ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const shown = captionsOf(frames, sc.rate || 2, heard)
const rate = sc.rate || 2
+8 -1
View File
@@ -10,6 +10,7 @@ import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { textRules, ZONE_FIX } from "../plan.ts"
import { bookkeeping } from "./naming.ts"
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
@@ -53,7 +54,13 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["edit", "render", "publish", "done"] }, async (f) => {
// a cut's plan (plan.ts): the text rules raea check holds a manifest to, on every frame, before it's drawn; what only
// the picture and the mix show (contrast, freezes, flashing, loudness, blotching) waits for the export
if (f.plan && f.manifest) {
for (const x of textRules(f.manifest)) found({ level: x.level, says: x.says, fix: x.rule === "safe-area" ? ZONE_FIX : undefined, seconds: x.at })
return
}
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of floorOf(f.abs, m, f.root)) say(x)
+8 -3
View File
@@ -13,6 +13,7 @@ import { existsSync, readFileSync } from "node:fs"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE, stem, type Faces } from "../media.ts"
import { PLAN_SOFT } from "../plan.ts"
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
export const FACE_MIN = 0.05
@@ -141,13 +142,17 @@ export const despite = (abs: string) => {
}
export default check<FileFacts>(
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// at edit only a cut's plan (plan.ts): its faces are its sources' frames, mapped into the cut's
if (!f.made || (f.kind !== "video" && !f.plan)) return
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
// the text's sizes are said even where the faces wait for a scene reader
const why = despite(f.abs)
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
// on a plan a face cut by the edge is a warning (plan.ts ON_PLAN_WARNS): its source frames are read without the cut's
// text over them, and the render's check holds it
for (const x of cutFaces((await f.scene()).faces, RATE))
say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : f.plan && x.kind === "face-cut" && x.level === "error" ? { ...x, level: "warn", says: `${x.says}${PLAN_SOFT}` } : x)
},
)
+8 -99
View File
@@ -5,11 +5,8 @@
// 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 { spawn } from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
@@ -170,12 +167,9 @@ 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 calls `raea ask` makes at once: 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); six `raea ask`s at once was a raea cloud box's ceiling,
* each decoding its cut (12-04). Now one `raea ask --batch` asks them all: through an agent key each window is asked by
* reference (the cut sent once, raea-api cuts the window: docs/ask.feature AK3b) and costs the box nothing, so all at
* once; cut on the machine, each cut's windows are cut in one pass */
export const CLEF_AT_ONCE = 24
/** 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[]> {
@@ -204,11 +198,7 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
}
const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()]
const jobs = list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to }))
// raea's own: one `raea ask --batch` for every window; a caller's own `ask` (a test) one job at a time
const heard = ask !== askClef
? await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
: asyncSpawn() ? await askClefManyAsync(dir, jobs) : askClefMany(dir, jobs)
const heard = 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"}` }]))
@@ -225,97 +215,16 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
}
type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
type AskJob = { file: string; says: string[]; from?: string; to?: string }
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"
/** a question's id from its words, as `raea ask` makes it (apps/ask verbs.rs own_id), so a batch's ids are the command
* line's and its cached answers still count */
export const ownId = (words: string) => `own-${words.split(/[^A-Za-z0-9]+/).filter(Boolean).slice(0, 6).map((w) => w.toLowerCase()).join("-")}`.slice(0, 64)
/** one job a batch line (apps/ask verbs.rs from_batch): its file, its window, its rules as true-or-false questions */
const batchLine = (k: AskJob) => JSON.stringify({
file: k.file,
...(k.from || k.to ? { window: { ...(k.from ? { from: Number(k.from) } : {}), ...(k.to ? { to: Number(k.to) } : {}) } } : {}),
questions: k.says.map((s) => ({ id: ownId(s), ask: s, type: "choose", options: ["true", "false"] })),
})
/** the batch's answers back to their jobs, by file, window and question id: each job's in its rules' order */
function answersOf(jobs: AskJob[], out: string, err: string): Answer[][] {
const at = (file: string, from: number, to: number | null) => [file, from, to].join("\u001f")
const want = new Map(jobs.map((k, i) => [at(k.file, Number(k.from ?? 0), k.to ? Number(k.to) : null), i]))
const got: (Answer | undefined)[][] = jobs.map((k) => k.says.map(() => undefined))
const why = new Map<number, string>()
for (const l of out.split("\n")) {
let o: { answer?: string; file?: string; id?: string; from?: number; to?: number | null; not_asked?: string; waits?: string } & Answer
try { o = JSON.parse(l) } catch { continue }
const j = want.get(at(String(o.file), Number(o.from ?? 0), o.to ?? null))
if (j === undefined) continue
if (!o.answer) { if (o.not_asked || o.waits) why.set(j, String(o.not_asked ?? o.waits)); continue }
const i = jobs[j].says.findIndex((s, n) => ownId(s) === o.id && !got[j][n])
if (i >= 0) got[j][i] = o
}
return jobs.map((k, j) => {
const rows = got[j].filter((a): a is Answer => !!a)
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${why.get(j) ?? (err.trim().slice(-300) || out.trim().slice(-300))}`)
return rows
})
}
/** the batch written for `raea ask --batch`, in review/ (gone after) */
function batchFile(dir: string, jobs: AskJob[]): { file: string; args: string[]; done: () => void } {
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const file = path.join(tmp, "batch.jsonl")
writeFileSync(file, jobs.map(batchLine).join("\n") + "\n")
return { file, args: ["ask", "--batch", file, "--json", "--jobs", String(Math.min(CLEF_AT_ONCE, jobs.length))], done: () => rmSync(tmp, { recursive: true, force: true }) }
}
/** every job in one `raea ask --batch` (12-04): the brief and each cut read once, each cut sent to raea-api once when the
* windows are asked by reference, else each cut's windows cut in one pass, CLEF_AT_ONCE calls at once. Where there's
* no async spawn (raea's runtime) it waits here; askClefManyAsync is the same with node's spawn */
export function askClefMany(dir: string, jobs: AskJob[]): Answer[][] {
if (!jobs.length) return []
const b = batchFile(dir, jobs)
try {
const r = cp.spawnSync(RAEA, b.args, { cwd: dir, encoding: "utf8", maxBuffer: 64 << 20 }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
return answersOf(jobs, String(r.stdout ?? ""), String(r.stderr ?? ""))
} finally {
b.done()
}
}
export function askClefManyAsync(dir: string, jobs: AskJob[]): Promise<Answer[][]> {
if (!jobs.length) return Promise.resolve([])
const b = batchFile(dir, jobs)
return new Promise<Answer[][]>((ok, no) => {
const c = cp.spawn(RAEA, b.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", () => {
try { ok(answersOf(jobs, out, err)) } catch (e) { no(e) }
})
}).finally(b.done)
}
/** `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"] })
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { 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)
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
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)
})
+2 -2
View File
@@ -294,9 +294,9 @@ export function placeReport(file: string, scenes: Scene[], size: [number, number
}
export default check<FileFacts>(
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
async (f) => {
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
if (!f.made || (f.kind !== "video" && !f.plan) || !f.manifest?.frames?.length) return
const { scenes } = await f.scene()
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
},
+9 -5
View File
@@ -11,7 +11,8 @@
// editor holds (and the skill's end card rule: few words, held long enough).
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
export type Block = { text: string; words: number; from: number; to: number; size?: number }
@@ -105,11 +106,14 @@ export function reading(blocks: Block[]): Finding[] {
}
export default check<FileFacts>(
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!f.made || (f.kind !== "video" && !f.plan)) return
// a cut's plan (plan.ts): its own text as laid out (a sign in the footage isn't meant to be read); an export's,
// what the reader reads in it
const planned = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : null
const sc = planned ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = planned ?? sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = sc.rate || 2
const heard = await f.words()
+3 -2
View File
@@ -229,9 +229,10 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
}
export default check<FileFacts>(
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (f.kind !== "video" && f.kind !== "audio") return
// at edit only a cut's plan (plan.ts), whose clips are the export's
if (f.kind !== "video" && f.kind !== "audio" && !f.plan) return
if (!f.made) return
if (!f.manifest) {
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
+475
View File
@@ -0,0 +1,475 @@
// A cut checked before it's drawn (12-04, round 22: every run missed its budget the same way, a full render of every cut
// and only then dozens of errors, fixed, and everything rendered again). `raea render EDIT.tsx --composition ID --plan
// -o OUT.plan.json` runs each frame through React and layout and gathers the sound, drawing nothing: its plan is a render
// manifest of every frame. `raea goal check --at edit --manifest OUT.plan.json EDIT.tsx` holds the plan to what can be
// known from it:
//
// floor its text clipped by the frame or in the app's UI zones, and up too briefly (apps/check/text's rules)
// frames text too small, and faces cut by the frame or a split screen's seam
// place text over a face, a person or what the shot is about
// sound clips cut inside a word or on sound, lines and effects at uneven levels (from each take's words and level)
// captions what's said with no caption over it, and a caption that isn't what's said there
// reading text up too briefly to read
//
// What the cut says is its voice clips' takes' words, laid where the clips put them. What its frames show is the scene of
// each SOURCE frame a video shows there (the farm's POST /v1/scene, as for an export), mapped through the video's box,
// fit and object-position into the cut's frame: the picture the render would draw, read without drawing it. Each
// source frame's reading is kept under review/scenes/, so a plan checked again asks only for frames it hasn't read.
// What only the export has (the words heard in the mix, its loudness, contrast, blotching) waits for --at render.
//
// A plan's errors stop the renders (raea cloud renders a batch only when every cut's plan passes), so on a plan an error
// is only what the plan knows as exactly as the export's check: floor's text rules, text too small, sound's edit points
// and levels. Place, captions, reading and faces cut by the edge are read from the source frames without the cut's own
// text over them, or held against the takes' words rather than the mix, and on round 22's Body Shop each cut had one
// such error the export's check didn't give (ON_PLAN_WARNS): on a plan they're warnings, and the render's check holds
// them. The plan holds its own cut alone: the project's checks and the goals' job checks (the count, the brief's quotes)
// don't run on it, and a check that can't run (the farm busy) waits instead of failing it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import type { Clip, Manifest, ManifestVideo } from "./facts.ts"
import * as media from "./media.ts"
import type { Faces, Word } from "./media.ts"
import { busOf } from "./packs/sound.ts"
import type { Scene, Thing } from "./packs/place.ts"
/** a file a plan is checked for: a composition (the plan of one of its compositions) */
export const COMPOSITION = /\.(tsx|jsx|ts|js|mjs)$/i
/** the export a plan is of: OUT.plan.json (or OUT.render.json, OUT.manifest.json) is OUT's */
export const outOf = (plan: string) => media.stem(plan).replace(/\.(plan|render|manifest)$/i, "")
/** checks whose errors are warnings on a plan (frames' faces cut by the edge too, in frames.ts; its text sizes stay
* errors): each is read or heard otherwise than the export's check reads and hears it */
export const ON_PLAN_WARNS = new Set(["place", "captions", "reading"])
/** said after each error a plan tells and doesn't hold */
export const PLAN_SOFT = " (on the plan a warning: the render's check holds it)"
/** the width the scene reader reads a frame at (media.ts SIDE), so sizes are the export's */
const SIDE = 540
/** a grid cell's side, as the farm's scene reader makes them (540x960: 27x48) */
const CELL = 20
/** a video under this opacity is fading: what's under it, or over it, is what's seen */
const SEEN = 0.5
/** a thing or a face with less than this share of it inside its video's visible box is out of the shot */
const VISIBLE = 0.25
/** a thing this much covered by a video drawn over it is hidden */
const HIDDEN = 0.75
type Rect = [number, number, number, number]
/** the times a plan's frames are read at: RATE a second, from 0 to its end */
export function samples(m: Manifest, rate = media.RATE): number[] {
const fps = Number(m.fps) || 30
const len = Number(m.length) || m.frames?.length || 0
const n = Math.max(0, Math.ceil((len / fps) * rate - 1e-9))
return Array.from({ length: n }, (_, i) => i / rate)
}
/** where a picture sw x sh is drawn in a video's box: its fit, then its object-position ([x px, x share of the free
* space, y px, y share], centred when unset); `native`: the picture's own size, for fit none and scale-down */
export function drawn(v: ManifestVideo, sw: number, sh: number, native: [number, number] = [sw, sh]): Rect {
const [bx, by, bw, bh] = v.box
let dw = bw
let dh = bh
const contain = Math.min(bw / sw, bh / sh)
const fit = v.fit ?? "fill"
if (fit === "cover" || fit === "contain" || fit === "scale-down" || fit === "none") {
const s = fit === "cover" ? Math.max(bw / sw, bh / sh) : fit === "contain" ? contain : fit === "none" ? native[0] / sw : Math.min(contain, native[0] / sw)
dw = sw * s
dh = sh * s
}
const p = v.position ?? [0, 0.5, 0, 0.5]
return [bx + p[0] + p[1] * (bw - dw), by + p[2] + p[3] * (bh - dh), dw, dh]
}
const meet = (a: Rect, b: Rect): Rect | null => {
const x0 = Math.max(a[0], b[0])
const y0 = Math.max(a[1], b[1])
const x1 = Math.min(a[0] + a[2], b[0] + b[2])
const y1 = Math.min(a[1] + a[3], b[1] + b[3])
return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null
}
const area = (r: Rect | null) => (r ? r[2] * r[3] : 0)
/** what a video shows in a frame: where its picture (`size`, as decoded: rotation applied) is drawn, what of it is seen
* in the frame (cut px), and that part of the picture as shares of it ([x, y, w, h], the `crop` read for its scene) */
export type Layer = { v: ManifestVideo; size: [number, number]; draw: Rect; seen: Rect; crop: Rect }
/** the videos a frame shows, bottom first: each drawn by its box, fit and position, cut to what its box (and the box
* clipping it) leaves showing in the frame. A fading video (under SEEN) only when nothing else shows */
export function layersOf(videos: ManifestVideo[], W: number, H: number, sizeOf: (v: ManifestVideo) => [number, number] | null): Layer[] {
const frame: Rect = [0, 0, W, H]
const opaque = videos.filter((v) => (v.opacity ?? 1) >= SEEN)
const shown = opaque.length ? opaque : [...videos].sort((a, b) => (b.opacity ?? 1) - (a.opacity ?? 1)).slice(0, 1)
const out: Layer[] = []
for (const v of shown) {
if (!v.box || v.box.length < 4) continue
const size = sizeOf(v)
if (!size) continue
const seen = meet(meet(v.box as Rect, (v.clip as Rect | undefined) ?? frame) ?? [0, 0, 0, 0], frame)
if (!seen) continue
const draw = drawn(v, size[0], size[1], size)
const round = (x: number) => Math.round(x * 1000) / 1000
const x0 = Math.max(0, (seen[0] - draw[0]) / draw[2])
const y0 = Math.max(0, (seen[1] - draw[1]) / draw[3])
const x1 = Math.min(1, (seen[0] + seen[2] - draw[0]) / draw[2])
const y1 = Math.min(1, (seen[1] + seen[3] - draw[1]) / draw[3])
if (x1 <= x0 || y1 <= y0) continue
out.push({ v, size, draw, seen, crop: [round(x0), round(y0), round(x1 - x0), round(y1 - y0)] })
}
return out
}
/** the scene read of the part of a source frame a layer shows (its crop, at the reader's size, as the export's reader
* sees it: a face half out of the shot is read as the export reads it) */
export type Source = { scene: NonNullable<Scene>; faces: NonNullable<Faces> }
/** what a frame of the cut shows, from the scenes of the parts of the source frames its videos show: each one's things,
* faces and person mask mapped through its crop and its drawn box into the cut's frame (SIDE wide), and hidden where a
* video is drawn over it. A video's edge inside the frame is a seam (a split screen, a picture in a picture). Null
* when no video shows there */
export function compose(all: Layer[], W: number, H: number, sourceOf: (l: Layer) => Source | null): { scene: Scene; faces: Faces } {
const k = SIDE / Math.min(W, H)
const w = Math.round(W * k)
const h = Math.round(H * k)
const layers = all.flatMap((l) => {
const src = sourceOf(l)
return src ? [{ ...l, src }] : []
})
if (!layers.length) return { scene: null, faces: null }
type Read = (typeof layers)[number]
// a box in a crop's scene, in the cut's pixels
const toCut = (l: Read, t: readonly unknown[]): Rect => {
const [x, y, bw, bh] = [0, 1, 2, 3].map((i) => Number(t[i]) || 0)
const sx = (v: number) => (l.crop[0] + (v / l.src.scene.w) * l.crop[2]) * l.draw[2]
const sy = (v: number) => (l.crop[1] + (v / l.src.scene.h) * l.crop[3]) * l.draw[3]
return [l.draw[0] + sx(x), l.draw[1] + sy(y), sx(x + bw) - sx(x), sy(y + bh) - sy(y)]
}
const scaled = (r: Rect): [number, number, number, number] => [r[0] * k, r[1] * k, r[2] * k, r[3] * k]
// what of a box is seen: inside its layer's visible box, and not hidden by a layer over it
const seenOf = (i: number, b: readonly unknown[]): Rect | null => {
const l = layers[i]
const r = toCut(l, b)
const vis = meet(r, l.seen)
if (!vis || area(vis) < VISIBLE * area(r)) return null
for (const o of layers.slice(i + 1)) if (area(meet(vis, o.seen)) >= HIDDEN * area(vis)) return null
return vis
}
const things: Thing[] = []
const faces: Thing[] = []
layers.forEach((l, i) => {
for (const t of l.src.scene.things) {
const r = seenOf(i, t)
if (r) things.push([...scaled(r), t[4], t[5]] as Thing)
}
for (const f of l.src.scene.faces) {
const r = seenOf(i, f)
if (r) faces.push([...scaled(r), "face", Number(f[5] ?? f[4]) || 0] as Thing)
}
})
// the person mask: each cell's centre, in the topmost layer that shows there, read from its crop's grid
const cols = Math.round(w / CELL)
const rows = Math.round(h / CELL)
const people: string[] = []
for (let r = 0; r < rows; r++) {
let line = ""
for (let c = 0; c < cols; c++) {
const x = ((c + 0.5) / cols) * W
const y = ((r + 0.5) / rows) * H
const l = layers.findLast((o) => x >= o.seen[0] && x < o.seen[0] + o.seen[2] && y >= o.seen[1] && y < o.seen[1] + o.seen[3])
if (!l) {
line += "0"
continue
}
const g = l.src.scene.grid
const sc = Math.floor((((x - l.draw[0]) / l.draw[2] - l.crop[0]) / l.crop[2]) * g.cols)
const sr = Math.floor((((y - l.draw[1]) / l.draw[3] - l.crop[1]) / l.crop[3]) * g.rows)
line += g.people[sr]?.[sc] ?? "0"
}
people.push(line)
}
// a video's edge inside the frame: a seam, where it shows over a good part of the frame's other side
const seams: media.Seam[] = []
for (const l of layers) {
const [x, y, sw, sh] = l.seen
if (sw >= W * 0.5) for (const e of [y, y + sh]) if (e > H * 0.02 && e < H * 0.98) seams.push(["h", Math.round(e * k), sw / W])
if (sh >= H * 0.5) for (const e of [x, x + sw]) if (e > W * 0.02 && e < W * 0.98) seams.push(["v", Math.round(e * k), sh / H])
}
const texts = layers.flatMap((l, i) => (l.src.scene.texts ?? []).flatMap((t) => {
const r = seenOf(i, t)
return r ? [[...scaled(r), t[4], t[5]] as [number, number, number, number, string, number]] : []
}))
return {
scene: { w, h, grid: { cols, rows, people }, things, faces, texts },
faces: { w, h, faces: faces.map((f) => [f[0], f[1], f[2], f[3], f[5]]), seams },
}
}
/** what a plan's cut says: each voice clip's take's words that fall inside it, laid where the clip puts them (a word
* the clip cuts into is said if most of it is inside; the sound pack holds the cut itself) */
export function said(clips: Clip[], fps: number, wordsOf: (src: string) => Word[] | null): Word[] {
const out: Word[] = []
for (const c of clips) {
if (busOf(c) !== "voice") continue
const ws = wordsOf(c.src)
if (!ws) continue
const a = c.at
const b = c.at + (c.to - c.from) / fps
for (const w of ws) {
const inside = Math.min(b, w.end) - Math.max(a, w.start)
// a word the clip cuts into is heard when much of it is in (a transcriber hears half a word)
if (inside <= 0 || inside < Math.min(0.12, 0.4 * Math.max(0.01, w.end - w.start))) continue
const shift = c.from / fps - a
out.push({ text: w.text, start: Math.max(c.from / fps, w.start + shift), end: Math.min(c.to / fps, w.end + shift) })
}
}
return out.sort((x, y) => x.start - y.start)
}
/** a plan's frames by number */
export function byFrame(m: Manifest): Map<number, NonNullable<Manifest["frames"]>[number]> {
return new Map((m.frames ?? []).map((f) => [Number(f.frame), f]))
}
type Line = [number, number, number, number, string, number]
/** a text laid out on `n` lines, as the reader reads it: a line each, its words shared out by their letters (where
* layout broke it isn't in the manifest, only how many lines it made) */
export function linesOf(text: string, b: number[], n: number): Line[] {
const words = text.split(/\s+/).filter(Boolean)
if (n <= 1 || words.length < 2) return [[b[0], b[1], b[2], b[3], text, 1]]
const k = Math.min(n, words.length)
const total = words.reduce((s, w) => s + w.length + 1, 0)
const parts: string[][] = Array.from({ length: k }, () => [])
let at = 0
for (const w of words) {
// each word on the line its middle letter falls on
parts[Math.min(k - 1, Math.floor(((at + w.length / 2) / total) * k))].push(w)
at += w.length + 1
}
return parts.flatMap((p, l) => (p.length ? [[b[0], b[1] + (b[3] * l) / k, b[2], b[3] / k, p.join(" "), 1] as Line] : []))
}
/** the frame nearest a time, and the text it shows, as the scene reader would read lines: [x, y, w, h, text, score] in
* the pixels of a frame `h` high, a text laid out on several lines a line each */
export function textFrames(m: Manifest, at: number[]): { h: number; lines: Line[] }[] {
const fps = Number(m.fps) || 30
const H = Number(m.height) || 1920
const frames = byFrame(m)
return at.map((t) => {
const fr = frames.get(Math.round(t * fps))
const lines = (fr?.text ?? []).filter((x) => (x.opacity ?? 1) > 0.3 && String(x.text ?? "").trim()).flatMap((x) => linesOf(String(x.text).trim(), (x.ink ?? x.box ?? [0, 0, 0, 0]) as number[], Number(x.lines) || 1))
return { h: H, lines }
})
}
/** a frame's opaque fills over the whole frame: a cut's backgrounds are on every frame, so a frame with more than the
* fewest any frame with a video has holds a card over its videos (an end card), which hides them. (The manifest says
* where a fill is, not whether it's over a video or under it.) */
const covers = (fr: NonNullable<Manifest["frames"]>[number] | undefined, W: number, H: number) =>
(fr?.pictures ?? []).filter((p) => (p.opacity ?? 1) >= 0.9 && p.box && p.box[0] <= 1 && p.box[1] <= 1 && p.box[0] + p.box[2] >= W - 1 && p.box[1] + p.box[3] >= H - 1).length
// ---- the source frames' scenes, read by the farm and kept ------------------------------------------------------------
type Kept = { stamp: string; side: number; at: Record<string, Source> }
/** a read's key in a source's keeping: its second and its crop */
export const readKey = (at: number, crop: Rect) => `${at.toFixed(2)} ${crop.join(",")}`
type Want = { file: string; at: number; crop: Rect }
/** parts of source frames read for a plan, each (file, second, crop) once: from review/scenes/ when read before, else
* extracted (several ffmpeg at once where there's a shell) and read by the farm. Unmet when there's no farm here */
export async function sourceScenes(root: string, wants: Want[]): Promise<Map<string, Source>> {
const out = new Map<string, Source>()
const byFile = new Map<string, Map<string, Want>>()
for (const w of wants) byFile.set(w.file, (byFile.get(w.file) ?? new Map()).set(readKey(w.at, w.crop), w))
const dir = path.join(root, "review", "scenes")
for (const [file, mine] of byFile) {
const st = statSync(file)
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
const keep = path.join(dir, `${path.basename(file)}.json`)
let kept: Kept = { stamp, side: SIDE, at: {} }
try {
const k = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (k.stamp === stamp && k.side === SIDE) kept = k
} catch {}
const need = [...mine.entries()].filter(([k]) => !kept.at[k])
if (need.length) {
const read = await readAt(file, need.map(([, w]) => w))
need.forEach(([k], i) => {
const s = read.scenes[i]
const f = read.faces[i]
if (s && f) kept.at[k] = { scene: s, faces: f }
})
try {
mkdirSync(dir, { recursive: true })
// read again just before writing: a plan of another cut may have read other frames of the same file meanwhile
try {
const now = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (now.stamp === stamp && now.side === SIDE) kept.at = { ...now.at, ...kept.at }
} catch {}
const tmp = `${keep}.${process.pid}.tmp`
writeFileSync(tmp, JSON.stringify(kept))
renameSync(tmp, keep)
} catch {}
}
for (const k of mine.keys()) if (kept.at[k]) out.set(`${file}@${k}`, kept.at[k])
}
return out
}
/** parts of a file's frames (a second and a crop, in shares of the picture), read by the farm's scene reader at the
* reader's size, as the export's reader reads that part of the cut's frame */
async function readAt(file: string, wants: Want[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!process.env.RAEA_CLOUD_GPU_URL) throw new media.Unmet(`no scene reader on this machine for ${path.basename(file)}'s frames (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-plan-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
const jpgs = wants.map((_, i) => path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`))
const one = (w: Want, i: number) => {
const [x, y, cw, ch] = w.crop
const crop = `crop=iw*${cw}:ih*${ch}:iw*${x}:ih*${y}`
return ["-v", "error", "-y", "-ss", w.at.toFixed(3), "-i", file, "-frames:v", "1", "-vf", `${crop},${scale}`, "-q:v", "4", jpgs[i]]
}
if (process.platform !== "win32" && spawnSync("ffmpeg", ["-version"], { encoding: "utf8" }).status === 0) {
// eight at a time through the shell: this runtime has only spawnSync, and a plan reads 60-80 frames
const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
const lines = wants.map((w, i) => `ffmpeg ${one(w, i).map(q).join(" ")} &${(i + 1) % 8 === 0 ? "\nwait" : ""}`)
spawnSync("sh", ["-c", `${lines.join("\n")}\nwait`], { encoding: "utf8", maxBuffer: 1 << 24 })
}
wants.forEach((w, i) => {
if (!existsSync(jpgs[i])) media.ffmpeg(one(w, i))
})
return await media.readScenes(jpgs.map((j) => (existsSync(j) ? readFileSync(j) : null)))
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** a video file's picture as decoded: its width and height, swapped when it's stored rotated a quarter turn */
export function pictureOf(file: string): [number, number] | null {
const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_tags=rotate:stream_side_data=rotation", "-of", "json", file], { encoding: "utf8" })
try {
const s = JSON.parse(r.stdout ?? "").streams?.[0]
if (s?.width) {
const rot = Math.abs(Number(s.tags?.rotate ?? s.side_data_list?.find((d: { rotation?: number }) => d.rotation !== undefined)?.rotation ?? 0)) % 180
return rot === 90 ? [s.height, s.width] : [s.width, s.height]
}
} catch {}
const sh = media.shape(file)
return sh ? [sh.width, sh.height] : null
}
/** the scenes of a plan's frames, RATE a second: each composed from the parts of its videos' source frames it shows
* (`file`: a source on this machine, or null) */
export async function planScene(root: string, m: Manifest, file: (src: string) => string | null): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
const W = Number(m.width) || 1080
const H = Number(m.height) || 1920
const fps = Number(m.fps) || 30
const at = samples(m)
const frames = byFrame(m)
const withVideo = [...frames.values()].filter((f) => f.videos?.length)
const backgrounds = withVideo.length ? Math.min(...withVideo.map((f) => covers(f, W, H))) : 0
const missing = new Set<string>()
const sizes = new Map<string, [number, number] | null>()
const sizeOf = (v: ManifestVideo) => {
const f = file(v.src)
if (!f) {
missing.add(v.src)
return null
}
if (!sizes.has(f)) sizes.set(f, pictureOf(f))
return sizes.get(f) ?? null
}
const shows = at.map((t) => {
const fr = frames.get(Math.round(t * fps))
return covers(fr, W, H) > backgrounds ? [] : layersOf((fr?.videos ?? []) as ManifestVideo[], W, H, sizeOf)
})
const wants = shows.flatMap((ls) => ls.map((l) => ({ file: file(l.v.src)!, at: l.v.at, crop: l.crop })))
if (!wants.length && missing.size) throw new media.Unmet(`the plan's videos aren't on this machine (${[...missing].slice(0, 3).join(", ")}), so what its frames show can't be read`)
const read = await sourceScenes(root, wants)
const out = shows.map((ls) => compose(ls, W, H, (l) => read.get(`${file(l.v.src)}@${readKey(l.v.at, l.crop)}`) ?? null))
return { rate: media.RATE, faces: out.map((o) => o.faces), scenes: out.map((o) => o.scene) }
}
// ---- the floor's text rules, from the plan (apps/check/text's text_runs and text_rules) --------------------------------
export type Run = { text: string; from: number; to: number; box: Rect; boxes: Rect[]; size: number }
/** a text as it stays on screen, from the frame it comes on to the frame it leaves; typing (a text growing into the next)
* and counting (only its digits changing) are one run, judged by its last text */
export function textRuns(m: Manifest): Run[] {
const fps = Number(m.fps) || 30
const key = (s: string) => s.replace(/[0-9]/g, "").trim().toLowerCase()
let open: Run[] = []
const done: Run[] = []
for (const f of [...(m.frames ?? [])].sort((a, b) => a.frame - b.frame)) {
const t = Number(f.frame) / fps
const next: Run[] = []
for (const x of f.text ?? []) {
const text = String(x.text ?? "").trim()
if ((x.opacity ?? 1) <= 0.05 || !text) continue
const quad = (b?: number[]): Rect | null => (b ? [0, 1, 2, 3].map((i) => Number(b[i]) || 0) as Rect : null)
const b = quad(x.box) ?? [0, 0, 0, 0]
const ink = quad(x.ink)
const k = key(text)
const i = open.findIndex((r) => {
const rk = key(r.text)
return rk === k || (rk !== "" && k.startsWith(rk)) || (k !== "" && rk.startsWith(k) && k.length * 2 > rk.length)
})
const r: Run = i >= 0 ? open.splice(i, 1)[0] : { text, from: t, to: t, box: b, boxes: [], size: 0 }
if (text.length > r.text.length) r.boxes = []
if (text.length >= r.text.length) {
r.text = text
r.box = b
r.boxes.push(ink ?? b)
}
r.to = t + 1 / fps
r.size = Number(x.size) || 0
next.push(r)
}
done.push(...open)
open = next
}
done.push(...open)
return done.sort((a, b) => a.from - b.from)
}
/** the zones where text can't go, [top, right, bottom, left] at the frame's width (apps/check/text zones(): default) */
export function zones(w: number, h: number): [number, number, number, number] {
const r = w / h
const z: [number, number, number, number] | null = r < 0.7 ? [220, 140, 420, 60] : r < 0.9 ? [110, 60, 170, 60] : r < 1.2 ? [70, 60, 120, 60] : null
if (!z) return [(120 * h) / 1080, (60 * w) / 1920, (120 * h) / 1080, (60 * w) / 1920]
return z.map((v) => (v * w) / 1080) as [number, number, number, number]
}
const quote = (s: string) => `“${[...s].slice(0, 40).join("")}”`
/** what `raea check` says of a render's text from its manifest: clipped off the frame (an error), in the app's UI zones
* (an error), up too briefly to read (a warning, the reading pack holds it to its words) */
export function textRules(m: Manifest): { level: "error" | "warn"; rule: string; at: number; says: string }[] {
const w = Number(m.width) || 1080
const h = Number(m.height) || 1920
const [zt, zr, zb, zl] = zones(w, h)
const out: { level: "error" | "warn"; rule: string; at: number; says: string }[] = []
for (const r of textRuns(m)) {
const [x, y, bw, bh] = r.box
const q = quote(r.text)
const boxes = r.boxes.length ? r.boxes : [r.box]
const off = ([x, y, bw, bh]: Rect) => x < -1 || y < -1 || x + bw > w + 1 || y + bh > h + 1
const zoned = ([x, y, bw, bh]: Rect) => y < zt || x + bw > w - zr || y + bh > h - zb || x < zl
if (boxes.every(off)) out.push({ level: "error", rule: "clipped", at: r.from, says: `${q} runs off the frame (box ${x.toFixed(0)},${y.toFixed(0)} ${bw.toFixed(0)}x${bh.toFixed(0)} in ${w}x${h}); fit it or break the line` })
else if (boxes.every(zoned)) {
const [ix, iy, iw, ih] = boxes[boxes.length - 1]
const edge = iy < zt ? `the top (keep ${zt.toFixed(0)} px clear)` : iy + ih > h - zb ? `the bottom (keep ${zb.toFixed(0)} px clear)` : ix < zl ? `the left (keep ${zl.toFixed(0)} px clear)` : `the right (keep ${zr.toFixed(0)} px clear)`
out.push({ level: "error", rule: "safe-area", at: r.from, says: `${q} sits in the app's UI zone at ${edge}: its ${r.boxes.length && boxes[boxes.length - 1] !== r.box ? "letters" : "box"} ${ix.toFixed(0)},${iy.toFixed(0)} ${iw.toFixed(0)}x${ih.toFixed(0)} in ${w}x${h}` })
}
const words = r.text.split(/\s+/).filter(Boolean).length
const need = Math.max(1, 0.3 * words)
const held = r.to - r.from
if (held + 0.05 < need && r.size >= 24) out.push({ level: "warn", rule: "reading", at: r.from, says: `${q} is on for ${held.toFixed(1)} s; ${words} words need ${need.toFixed(1)} s to read` })
}
return out
}
/** the fix a UI-zone finding asks for, said once */
export const ZONE_FIX = "keep text inside the safe area: 220 px from the top, 420 px from the bottom, 140 px from the right and 60 px from the left of a 1080x1920 frame"
+54 -17
View File
@@ -3,6 +3,9 @@
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// (EDIT.tsx --at edit --manifest OUT.plan.json: one cut of the composition checked on its plan, `raea render
// --plan`, before it's drawn: plan.ts. Only that cut's file checks run, only what the plan knows exactly is an
// error, and a check that can't run waits, so exit 1 always names something in the cut to fix)
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
@@ -14,12 +17,13 @@
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import { fileFacts, type FileFacts, type Job, kindOf, planFacts, runIn } from "./facts.ts"
import { COMPOSITION, ON_PLAN_WARNS, PLAN_SOFT } from "./plan.ts"
import * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts"
@@ -137,13 +141,22 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const broke: Report["broke"] = []
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
const fps = file?.fps ?? 30
for (const x of r.findings)
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
for (const x of r.findings) {
// on a plan, what's read from the source frames or held against the takes' words is told, not held (ON_PLAN_WARNS)
const soft = file?.plan && x.level === "error" && ON_PLAN_WARNS.has(x.check)
findings.push({ goal, check: x.check, level: soft ? "warn" : x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: soft ? `${x.says}${PLAN_SOFT}` : x.says, fix: x.fix, by: x.by })
}
// on a plan, a check that couldn't run (the farm busy or down, a frame that wouldn't extract) waits: nothing in the
// cut to fix, and the render's own check runs it again
for (const t of r.threw) (t.waits || file?.plan ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.waits || !file?.plan ? t.says : `couldn't check the plan, so the render's check holds it: ${t.says}` })
}
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
// a composition named with a manifest: one of its cuts checked on its plan (`raea render --plan`), before it's drawn
// (plan.ts). It holds that cut alone: the project's own checks and the goals' job checks (the count, the brief's
// quotes) are the render's and publish's to hold, never a reason not to draw one cut
const planned = cutPlan(o.manifest, named, cwd)
// the project's own: once, whatever its goals
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
const once = planned ? [] : ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
const verdicts: GoalVerdict[] = []
const allFiles = new Set<string>()
@@ -155,10 +168,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
: at === "publish" || at === "done"
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
: []
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
const checks = checksOf(contract, at, o.only)
// a cut's plan (above), else a render's manifest kept away from its export (`raea render --manifest M`): the one
// file named reads it
const files: FileFacts[] = planned
? [planFacts(planned.manifest, planned.abs, root, at, contract)]
: wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
if (o.manifest && !planned && files.length === 1) {
files[0].manifest = JSON.parse(readFileSync(path.resolve(cwd, o.manifest), "utf8")) as FileFacts["manifest"]
files[0].fps = files[0].manifest?.fps ?? files[0].fps
}
const checks = checksOf(contract, at, o.only).filter((c) => !planned || c.over !== "job")
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
@@ -191,16 +210,32 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
}
}
/** a composition's plan: `--manifest` naming a plan (or any manifest) with one composition named */
export function cutPlan(manifest: string | undefined, named: string[], cwd = process.cwd()): { abs: string; manifest: FileFacts["manifest"] & object } | null {
if (!manifest || named.length !== 1 || !COMPOSITION.test(named[0])) return null
const abs = path.resolve(cwd, manifest)
return { abs, manifest: JSON.parse(readFileSync(abs, "utf8")) }
}
/** written whole or not at all: plans of several cuts are checked at once, each writing review/goal.json */
const writeWhole = (p: string, text: string) => {
const tmp = `${p}.${process.pid}.tmp`
writeFileSync(tmp, text)
renameSync(tmp, p)
}
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
* each file named */
export function writeReport(r: Report, named: string[]) {
* each file named (a plan's beside the plan: OUT.plan.check.json) */
export function writeReport(r: Report, named: string[], plan?: string) {
const dir = path.join(r.root, "review")
mkdirSync(dir, { recursive: true })
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
writeWhole(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
const one = (f: string, out: string) => {
const mine = r.findings.filter((x) => x.file === f)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
writeWhole(out, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
}
for (const f of named) one(f, `${media.stem(path.join(r.root, f))}.check.json`)
if (plan) for (const f of r.files) one(f, `${media.stem(plan)}.check.json`)
}
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
@@ -226,7 +261,8 @@ function flag(a: string[], name: string): string | undefined {
}
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
raea goal check EDIT.tsx --at edit --manifest OUT.plan.json (a cut checked on its plan, raea render --plan, before it's drawn)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
@@ -249,7 +285,8 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal check: ${(e as Error).message}`)
return 2
}
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
const plan = cutPlan(flag(a, "--manifest"), files.map((n) => path.relative(r.root, path.resolve(n))))
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))), plan?.abs)
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
return r.passed ? 0 : 1
}
-46
View File
@@ -1,46 +0,0 @@
import { expect, test } from "bun:test"
import { spawnSync } from "node:child_process"
import { mkdtempSync, readdirSync, readFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
// a stop's windows in one `raea ask --batch` (12-04): one after another its 18 beats took 7.7 minutes, and six `raea
// ask`s at once was a raea cloud box's ceiling, each decoding its cut. One batch reads the brief and each cut once and
// asks every window by reference (docs/ask.feature AK3b). A child with a stand-in raea (a second a run), since RAEA is
// read once, as goal.ts is loaded; on raea's runtime (no async spawn) and under node's spawn alike
for (const how of ["askClefMany", "askClefManyAsync"]) {
test(`${how} asks every job in one raea ask --batch and gives each job its answers in its rules' order`, () => {
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
const log = path.join(dir, "runs.log")
const script = `
import { ${how} as ask } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
const jobs = Array.from({ length: 6 }, (_, i) => ({ file: "out/cut " + i + "'s.mp4", says: i % 2 ? ["The product is on screen from 1 s to 2 s", "Someone speaks"] : ["one"], ...(i < 5 ? { from: String(i), to: String(i + 1.5) } : {}) }))
const t0 = Date.now()
const got = await ask(${JSON.stringify(dir)}, jobs)
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file, ids: got[1].map((a) => a.id), to: got[4][0].to, end: got[5][0].to }))
`
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea"), FAKE_ASK_LOG: log } })
expect(r.stderr.trim().split("\n").filter((l) => /error/i.test(l))).toEqual([])
const o = JSON.parse(r.stdout.trim().split("\n").at(-1)!)
expect(o.ms).toBeLessThan(3_000)
expect(o.n).toEqual([1, 2, 1, 2, 1, 2])
expect(o.file).toBe("out/cut 1's.mp4")
expect(o.ids).toEqual(["own-the-product-is-on-screen-from", "own-someone-speaks"])
expect([o.to, o.end]).toEqual([5.5, null])
const runs = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l))
expect(runs.length).toBe(1)
expect(runs[0].slice(0, 1).concat(runs[0].slice(3))).toEqual(["ask", "--json", "--jobs", "6"])
expect(readdirSync(path.join(dir, "review"))).toEqual([])
})
}
test("a job the batch doesn't answer says why", () => {
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-short-"))
const script = `
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
try { askClefMany(${JSON.stringify(dir)}, [{ file: "out/a.mp4", says: ["one"] }]) ; console.log("no error") } catch (e) { console.log(String(e.message)) }
`
// a raea that answers nothing (it only says its arguments back)
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: "/bin/echo" } })
expect(r.stdout).toContain("raea ask answered 0 of 1 about out/a.mp4: ask --batch")
})
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bun
// a stand-in `raea ask --batch FILE --json --jobs N`: after a second, one answer a line for each question of each line,
// as `raea ask --json` prints them; every run noted in $FAKE_ASK_LOG (one line a run, its arguments)
import { appendFileSync, readFileSync } from "node:fs"
const args = process.argv.slice(2)
if (process.env.FAKE_ASK_LOG) appendFileSync(process.env.FAKE_ASK_LOG, JSON.stringify(args) + "\n")
const at = args.indexOf("--batch")
if (args[0] !== "ask" || at < 0) { console.error(`the fake only answers a batch: ${args.join(" ")}`); process.exit(1) }
await Bun.sleep(1000)
for (const l of readFileSync(args[at + 1], "utf8").split("\n").filter(Boolean)) {
const e = JSON.parse(l)
for (const q of e.questions) console.log(JSON.stringify({ answer: "a", file: e.file, id: q.id, from: e.window?.from ?? 0, to: e.window?.to ?? null, choice: "true", says: "true (0.9)", problem: null }))
}
console.log(JSON.stringify({ summary: {} }))
+2 -3
View File
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { CLEF_AT_ONCE, clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
@@ -164,7 +164,6 @@ test("clef hears several cuts at once, and the critic reads while it does", asyn
now--
return says.map(() => ({ choice: "true", says: "fine" }))
})
// a caller's own ask is held to CLEF_AT_ONCE (24): all eight at once
expect(most).toBe(Math.min(CLEF_AT_ONCE, names.length))
expect(most).toBe(6)
expect(rules.seen?.pass).toBe(true)
})
+201
View File
@@ -0,0 +1,201 @@
// A cut checked on its plan before it's drawn (src/plan.ts): what its frames show read from its sources' frames, what it
// says from its takes' words, and the floor's text rules on every frame
import { expect, test } from "bun:test"
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { type Answer, useSender } from "../src/media.ts"
import { compose, drawn, layersOf, linesOf, PLAN_SOFT, said, samples, textRules, textRuns } from "../src/plan.ts"
import { goalCheck, text, writeReport } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
const full = (over: Record<string, unknown> = {}) => ({ src: "a.mp4", at: 1, box: [0, 0, 1080, 1920], fit: "cover", ...over })
test("a video is drawn by its fit and object-position, and what of it the frame shows is its crop", () => {
// a 16:9 picture covering a 9:16 frame, centred: 3413 px wide, 1167 px of it off each side
const c = drawn(full(), 1920, 1080)
expect(c.map(Math.round)).toEqual([-1167, 0, 3413, 1920])
// object-position 76% across (as `position: [0, 0.76, 0, 0.5]` says it)
expect(Math.round(drawn(full({ position: [0, 0.76, 0, 0.5] }), 1920, 1080)[0])).toBe(Math.round(0.76 * (1080 - 3413.33)))
// contain letterboxes it; fill stretches it
expect(drawn(full({ fit: "contain" }), 1920, 1080).map(Math.round)).toEqual([0, 656, 1080, 608])
expect(drawn(full({ fit: "fill" }), 1920, 1080)).toEqual([0, 0, 1080, 1920])
const [l] = layersOf([full() as never], 1080, 1920, () => [1920, 1080])
expect(l.crop).toEqual([0.342, 0, 0.316, 1])
// a box clipped by its parent (`clip`) shows only that part of it
const [h] = layersOf([full({ box: [-566, 0, 4096, 2304], clip: [0, 0, 1080, 1920] }) as never], 1080, 1920, () => [3840, 2160])
expect(h.seen).toEqual([0, 0, 1080, 1920])
expect(h.crop[3]).toBeCloseTo(1920 / 2304, 3)
// a fading video is left out while another shows; alone it's what's seen
expect(layersOf([full() as never, full({ opacity: 0.2 }) as never], 1080, 1920, () => [1920, 1080])).toHaveLength(1)
})
test("a source's scene, read of its crop, lands in the cut's frame: a face at the crop's edge is a face at the frame's", () => {
// the reader read the crop (304x540 of a 960x540 picture) at 540 wide: a face touching its right edge, a person
const scene = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array.from({ length: 48 }, (_, r) => (r > 20 ? "7".repeat(27) : "0".repeat(27))) }, things: [[100, 300, 300, 660, "person", 0.9]], faces: [[480, 200, 60, 80, "face", 0.9]] }
const faces = { w: 540, h: 960, faces: [[480, 200, 60, 80, 0.9]] }
const ls = layersOf([full() as never], 1080, 1920, () => [960, 540])
const out = compose(ls, 1080, 1920, () => ({ scene, faces }) as never)
expect(out.scene?.w).toBe(540)
const [x, y, w, h] = out.faces!.faces[0]
expect(Math.round(x + w)).toBe(540)
expect([Math.round(y), Math.round(h)]).toEqual([200, 80])
expect(out.scene!.grid.people[30]).toBe("7".repeat(27))
expect(out.scene!.things[0][4]).toBe("person")
// a video drawn over the bottom half hides what's under it there, and its top edge is a seam
const two = layersOf([full() as never, full({ box: [0, 960, 1080, 960] }) as never], 1080, 1920, () => [960, 540])
const low = { ...scene, things: [[100, 600, 300, 300, "dog", 0.9]] }
const o2 = compose(two, 1080, 1920, (l) => (l.v.box[1] ? ({ scene: { ...scene, things: [], faces: [] }, faces: { ...faces, faces: [] } } as never) : ({ scene: low, faces } as never)))
expect(o2.faces!.seams).toContainEqual(["h", 480, 1])
expect(o2.scene!.things).toEqual([])
})
test("what a plan's cut says is its voice clips' takes' words, where the clips put them", () => {
const take = [{ text: "one", start: 10, end: 10.4 }, { text: "two", start: 10.5, end: 10.9 }, { text: "three", start: 11, end: 11.5 }, { text: "four", start: 11.6, end: 12 }]
// frames 30-75 at 30 fps (1.0-2.5 s) show the take from 10.45 s: "one" is out, "three" whole, "four" cut a little
const w = said([{ from: 30, to: 75, src: "media/take.mp4", at: 10.45 }], 30, () => take)
expect(w.map((x) => x.text)).toEqual(["two", "three", "four"])
expect(w[0].start).toBeCloseTo(1.05, 5)
// music isn't speech
expect(said([{ from: 0, to: 30, src: "music/bed.mp3", at: 0 }], 30, () => take)).toEqual([])
})
test("the floor's text rules hold every frame of a plan: the UI zones, the frame's edges", () => {
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, text: [
{ text: "In the zone at the right", box: [100, 830, 900, 93], ink: [139, 830, 860, 93], size: 58 },
{ text: "Clear of everything", box: [200, 1000, 680, 93], size: 58 },
{ text: "Off the frame entirely here", box: [900, 1200, 600, 93], ink: [900, 1200, 600, 93], size: 58 },
] }))
const m = { width: 1080, height: 1920, fps: 30, length: 60, frames }
const r = textRules(m)
expect(r.map((x) => [x.rule, x.level])).toEqual([["safe-area", "error"], ["clipped", "error"]])
expect(r[0].says).toMatch(/sits in the app's UI zone at the right \(keep 140 px clear\)/)
// a typed text (growing into the next) is one run, judged by its last text
const typed = textRuns({ fps: 30, frames: ["Hel", "Hello", "Hello there"].map((t, f) => ({ frame: f, text: [{ text: t, box: [300, 900, 400, 80], size: 60 }] })) })
expect(typed.map((x) => x.text)).toEqual(["Hello there"])
expect(samples(m)).toEqual([0, 0.5, 1, 1.5])
// a text laid out on several lines is read a line each, as the export's reader reads it
expect(linesOf("Make your Wishlist and organize your Gift Exchange", [0, 100, 600, 200], 2).map((l) => l[4])).toEqual(["Make your Wishlist and", "organize your Gift Exchange"])
})
test("raea goal check --at edit --manifest PLAN EDIT.tsx: the cut's plan is checked, named for its export, before it's drawn", async () => {
const d = project(null)
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 90 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Down in the bottom zone", box: [140, 1600, 800, 90], size: 60 }] }))
const plan = put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 90, plan: true, frames, sounds: { fps: 30, clips: [] } }))
// the farm's reader, standing in: every crop read has a face cut by its right edge
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
let read = 0
useSender(async (_url, body): Promise<Answer> => {
const n = (JSON.parse(String(body)) as { frames: string[] }).frames.length
read += n
const g = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [[470, 300, 70, 120, "face", 0.9]], seams: [] }
return { status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(g) }) }
})
try {
const r = await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
const mine = r.findings.filter((x) => x.file === "out/cuts/ad_concept_v1_9x16.mp4")
expect(mine.some((x) => x.check === "floor" && x.level === "error" && /UI zone at the bottom/.test(x.says))).toBe(true)
// a face cut by the edge is read from the source frames: on a plan it's told, and the render's check holds it
expect(mine.some((x) => x.check === "frames" && x.level === "warn" && /right edge/.test(x.says) && x.says.endsWith(PLAN_SOFT))).toBe(true)
// only what the plan knows exactly holds it: floor, sound and text sizes
expect(mine.filter((x) => x.level === "error").every((x) => x.check === "floor" || x.check === "sound" || (x.check === "frames" && /px/.test(x.says)))).toBe(true)
expect(r.passed).toBe(false)
expect(read).toBe(6)
// each source frame's reading is kept: the plan checked again reads nothing
await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
expect(read).toBe(6)
writeReport(r, [], plan)
expect(existsSync(path.join(d, "out/cuts/ad_concept_v1_9x16.plan.check.json"))).toBe(true)
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
})
/** a plan of one cut with nothing in it to fix: its text inside the safe area, over the test clip */
function cleanPlan(d: string, name = "out/cuts/ad_concept_v1_9x16.plan.json") {
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Safe in the middle", box: [140, 900, 800, 90], size: 60 }] }))
return put(d, name, JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 60, plan: true, frames, sounds: { fps: 30, clips: [] } }))
}
/** the farm's reader, standing in for a test: `answer` gives each POST's reply */
async function withFarm<T>(answer: (n: number) => Answer, run: () => Promise<T>): Promise<T> {
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
useSender(async (_url, body) => answer((JSON.parse(String(body)) as { frames: string[] }).frames.length))
try {
return await run()
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
}
const EMPTY = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [], seams: [] }
test("a plan holds its own cut alone: the brief's count, its quotes and the project's checks don't stop it being drawn", async () => {
// the brief asks for 10 cuts, 1 is planned, and the open item about the count waits for a person (who answers at the
// first stop, after the first render); the brief's text isn't in the project either
const asked = { question: "Only 2 interviews came: cut fewer?", from: "10 total videos", about: "count" }
const d = project({ kind: "cut", packs: { naming: false }, cut: { brief: "media/brief.txt", count: { value: 10, from: "10 total videos" }, formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }], open: [asked] } })
const plan = cleanPlan(d)
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(EMPTY) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.checks).not.toContain("count")
expect(r.checks).not.toContain("quotes")
expect(r.checks).not.toContain("registered")
expect(r.passed).toBe(true)
// the same project checked at edit without a plan still holds the count
const whole = await goalCheck({ cwd: d, at: "edit" })
expect(whole.findings.some((x) => x.check === "count" && x.level === "error")).toBe(true)
})
test("a plan the farm can't read waits: nothing to fix, so it doesn't fail", async () => {
const d = project(null)
const plan = cleanPlan(d)
let asked = 0
const r = await withFarm(
() => {
asked++
return { status: 503, ok: false, text: "busy" }
},
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(asked).toBeGreaterThan(0)
expect(r.broke).toEqual([])
expect(r.waits.map((w) => w.check)).toContain("frames")
expect(r.waits.find((w) => w.check === "frames")?.says).toMatch(/render's check holds it.*503/)
expect(r.errors).toBe(0)
expect(r.passed).toBe(true)
expect(text(r)).toMatch(/^PASSED .*waiting/m)
})
test("on a plan, text over a face and talking with no captions are warnings: the render's check holds them", async () => {
const d = project({ kind: "cut", packs: { naming: false }, cut: { formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }] } })
// a caption with nothing said under it, straight over a face the farm reads in every frame
const plan = cleanPlan(d)
const m = JSON.parse(readFileSync(plan, "utf8"))
m.length = 240
m.frames = Array.from({ length: 240 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: (f % 90) / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: f < 60 ? [{ text: "Nobody says this at all", box: [140, 300, 800, 300], size: 60 }] : [] }))
// ... and from 5 s, past a text hook's opening, the take talks with no caption up
put(d, "media/take.words.json", JSON.stringify("so this is what we said".split(" ").map((t, i) => ({ text: t, start: 0.3 + i * 0.4, end: 0.6 + i * 0.4 }))))
m.sounds.clips = [{ key: "v", from: 150, to: 240, src: "media/take.mp4", at: 0 }]
put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify(m))
const face = { ...EMPTY, faces: [[170, 150, 200, 200, "face", 0.95]] }
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(face) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
const soft = r.findings.filter((x) => x.says.endsWith(PLAN_SOFT))
expect(soft.length).toBeGreaterThan(0)
expect(soft.every((x) => x.level === "warn" && ["place", "captions", "reading", "frames"].includes(x.check))).toBe(true)
expect(soft.some((x) => x.check === "place" && /covers a face/.test(x.says))).toBe(true)
expect(soft.some((x) => x.check === "captions" && /no captions over the talking/.test(x.says))).toBe(true)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.passed).toBe(true)
})