Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

AK3: raea ask: questions about a piece's picture and sound, prepared, asked in parallel and kept

shinyobjectz68433ab526a8
diff --git a/Cargo.lock b/Cargo.lock
index d57f661a..61149fb4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13752,6 +13752,20 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"
+[[package]]
+name = "raea-app-ask"
+version = "0.1.0"
+dependencies = [
+ "dunce",
+ "raea-core-ask",
+ "raea-io-assets",
+ "raea-io-clef",
+ "raea-io-home",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+]
+
[[package]]
name = "raea-app-capcut"
version = "0.1.0"
@@ -13995,6 +14009,7 @@ name = "raea-app-solid"
version = "0.1.0"
dependencies = [
"dunce",
+ "raea-app-ask",
"raea-app-judge",
"raea-core-facts",
"raea-core-meshcheck",
@@ -14268,6 +14283,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"dunce",
+ "raea-app-ask",
"raea-app-capcut",
"raea-app-check",
"raea-app-ci",
diff --git a/Cargo.toml b/Cargo.toml
index 1e01a25c..18a78ac3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -188,6 +188,7 @@ members = [
"runtime/scene",
"runtime/scene2d",
"runtime/shared",
+ "apps/ask",
"apps/check",
"apps/check/flash",
"apps/check/inbox",
diff --git a/apps/ask/Cargo.toml b/apps/ask/Cargo.toml
new file mode 100644
index 00000000..e88f68a2
--- /dev/null
+++ b/apps/ask/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "raea-app-ask"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
+
+[dependencies]
+# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
+raea-core-ask = { path = "../../core/ask" }
+raea-io-clef = { path = "../../io/clef" }
+raea-io-home = { path = "../../io/home" }
+dunce = "1"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+sha2 = "0.10"
+
+[dev-dependencies]
+raea-io-assets = { path = "../../io/assets" }
diff --git a/apps/ask/src/lib.rs b/apps/ask/src/lib.rs
new file mode 100644
index 00000000..3cd85e82
--- /dev/null
+++ b/apps/ask/src/lib.rs
@@ -0,0 +1,14 @@
+//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
+//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
+//! `record` keeps every call and answer for labels and calibration; `verbs` is the command. `raea check`, the app's
+//! critique and the fingerprint's double-check go through the same runner.
+
+pub mod prepare;
+pub mod record;
+pub mod runner;
+pub mod verbs;
+
+pub use verbs::{USAGE, cli};
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/ask/src/prepare.rs b/apps/ask/src/prepare.rs
new file mode 100644
index 00000000..1c69c673
--- /dev/null
+++ b/apps/ask/src/prepare.rs
@@ -0,0 +1,156 @@
+//! Ask understands a question before it spends (docs/ask.feature AK2): what the file holds (ffprobe), what the project's
+//! brief says it's for, whether anyone speaks in it, and from those which questions can be asked, which are swapped for
+//! their variant (sound for sound-silent) and which are dropped, each with why. The state paragraph tells clef what the
+//! piece is, as the app's critique writes it. When it isn't known whether anyone speaks, both variants are kept, the
+//! voice question goes in the same call (runner.rs), free, and the variant that doesn't apply is set aside.
+
+use std::path::{Path, PathBuf};
+
+use raea_core_ask::{Facts, Question, library};
+use raea_io_clef::media::{self, Probe};
+use serde_json::{Value, json};
+
+/// The question asked beside the rest when no one knows yet whether anyone speaks in the piece.
+pub const VOICE: &str = "voice-heard";
+
+/// What raea knows of the piece.
+#[derive(Debug, Clone, Default)]
+pub struct Piece {
+ pub file: PathBuf,
+ pub probe: Probe,
+ /// the brief's fields, as `raea spec brief.ts --as brief` reads them ({} without a brief)
+ pub brief: Value,
+ /// the project's folder (the one holding the brief), when there is one
+ pub project: Option<PathBuf>,
+ /// the words heard, when a words file was given
+ pub words: Option<String>,
+ /// someone speaks: from --voice, or from the words file (none heard is no)
+ pub voice: Option<bool>,
+ /// what the caller adds to the state (what raea measured, the platform)
+ pub extra: Option<String>,
+}
+
+/// The brief nearest the file: brief.ts in its folder or any folder above it.
+pub fn brief_near(file: &Path) -> Option<PathBuf> {
+ let abs = dunce::canonicalize(file).ok()?;
+ abs.ancestors().skip(1).map(|d| d.join("brief.ts")).find(|b| b.is_file())
+}
+
+/// A brief's fields, through `raea spec FILE --as brief` (this raea), or {} when it can't be read.
+fn brief_of(path: &Path) -> Value {
+ let Ok(exe) = std::env::current_exe() else { return json!({}) };
+ let Ok(out) = std::process::Command::new(exe).args(["spec"]).arg(path).args(["--as", "brief"]).output() else { return json!({}) };
+ let text = String::from_utf8_lossy(&out.stdout);
+ let v: Value = text.find('{').and_then(|i| serde_json::from_str(&text[i..]).ok()).unwrap_or_else(|| json!({}));
+ v.get("brief").cloned().unwrap_or(v)
+}
+
+/// The words heard, from a words file (a JSON list of words, each a string or {word} or {text}): their text, and
+/// whether anyone speaks (an empty list is no one).
+pub fn words_of(path: &Path) -> Result<(String, bool), String> {
+ let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?).map_err(|e| format!("{}: {e}", path.display()))?;
+ let list = v.as_array().or(v["words"].as_array()).ok_or_else(|| format!("{}: a list of words", path.display()))?;
+ let words: Vec<&str> = list.iter().filter_map(|w| w.as_str().or(w["word"].as_str()).or(w["text"].as_str())).collect();
+ Ok((words.join(" "), !words.is_empty()))
+}
+
+impl Piece {
+ /// The piece as raea finds it: the file probed, its brief (given or the nearest), its words.
+ pub fn read(file: &Path, brief: Option<&Path>, words: Option<&Path>, voice: Option<bool>, extra: Option<String>) -> Result<Piece, String> {
+ let probe = media::probe(file)?;
+ let brief_file = brief.map(Path::to_path_buf).or_else(|| brief_near(file));
+ let (words, heard) = match words {
+ Some(w) => words_of(w).map(|(t, h)| (Some(t).filter(|t| !t.is_empty()), Some(h)))?,
+ None => (None, None),
+ };
+ Ok(Piece {
+ file: file.to_path_buf(),
+ probe,
+ brief: brief_file.as_deref().map(brief_of).unwrap_or_else(|| json!({})),
+ project: brief_file.and_then(|b| b.parent().map(Path::to_path_buf)),
+ words,
+ voice: voice.or(heard).or((!probe.sound).then_some(false)),
+ extra,
+ })
+ }
+
+ pub fn modes(&self) -> Vec<String> {
+ let m = &self.brief["mode"];
+ let list: Vec<&str> = m.as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_else(|| m.as_str().into_iter().collect());
+ list.iter().flat_map(|s| s.split(',')).map(|s| s.replace("(assumed)", "").trim().to_string()).filter(|s| !s.is_empty()).collect()
+ }
+
+ pub fn facts(&self) -> Facts {
+ let modes = self.modes();
+ Facts { game: modes.iter().any(|m| m == "play"), modes, voice: self.voice, sound: self.probe.sound, video: self.probe.video }
+ }
+
+ /// What clef reads before the media: what the piece is and what's known of it.
+ pub fn state(&self) -> String {
+ let b = &self.brief;
+ let modes = self.modes();
+ let what = if modes.is_empty() { "video".to_string() } else { modes.join(" and ") };
+ let mut s = vec![match b["title"].as_str() {
+ Some(t) => format!("A {what} piece: \"{t}\"."),
+ None => format!("A {what} piece."),
+ }];
+ for (k, say) in [("audience", "It's for"), ("believe", "It should leave them believing"), ("logline", "Its storyboard"), ("voice", "Its voice")] {
+ if let Some(v) = b[k].as_str().filter(|v| !v.trim().is_empty()) {
+ s.push(format!("{say}: {}.", v.trim().trim_end_matches('.')));
+ }
+ }
+ if self.voice == Some(false) {
+ s.push("No one speaks in it: its sound is the music and the effects, with no voice.".into());
+ }
+ if let Some(w) = &self.words {
+ let cut: String = w.chars().take(1200).collect();
+ s.push(format!("The words heard: \"{cut}{}\"", if cut.len() < w.len() { "..." } else { "" }));
+ }
+ if self.probe.seconds > 0.0 {
+ s.push(format!("It runs {:.0} s.", self.probe.seconds));
+ }
+ if let Some(x) = &self.extra {
+ s.push(x.trim().to_string());
+ }
+ s.join(" ")
+ }
+}
+
+/// Is anyone heard speaking: asked beside the questions that depend on it, at no cost (clef costs by media, not by
+/// questions), when no one knows yet.
+pub fn voice_question() -> Question {
+ let mut v = Question::plain(VOICE, "Is anyone heard speaking in it (a voice saying words, not singing)?");
+ v.sees = raea_core_ask::Sees::Nothing;
+ v
+}
+
+/// The questions kept for this piece, and those dropped with why. A question that doesn't apply is swapped for its
+/// variant when that one does; not knowing whether anyone speaks, both are kept.
+pub fn keep(questions: Vec<Question>, f: &Facts, rubric_md: Option<&str>) -> (Vec<Question>, Vec<(String, String)>) {
+ let mut asked: Vec<Question> = Vec::new();
+ let mut dropped = Vec::new();
+ let add = |q: Question, asked: &mut Vec<Question>| {
+ if !asked.iter().any(|a| a.id == q.id) {
+ asked.push(q);
+ }
+ };
+ for q in questions {
+ let Some(why) = q.not_for(f) else {
+ // not knowing whether anyone speaks, its variant goes in too: one call answers either way
+ let twin = (f.voice.is_none() && q.when.voice.is_some()).then(|| q.swap.as_deref().and_then(|s| library::find(s, rubric_md))).flatten();
+ add(q, &mut asked);
+ if let Some(t) = twin {
+ add(t, &mut asked);
+ }
+ continue;
+ };
+ match q.swap.as_deref().and_then(|s| library::find(s, rubric_md)).filter(|s| s.not_for(f).is_none()) {
+ Some(s) => {
+ dropped.push((q.id.clone(), format!("{why}: asked {} instead", s.id)));
+ add(s, &mut asked);
+ }
+ None => dropped.push((q.id.clone(), why)),
+ }
+ }
+ (asked, dropped)
+}
diff --git a/apps/ask/src/record.rs b/apps/ask/src/record.rs
new file mode 100644
index 00000000..f66b9f68
--- /dev/null
+++ b/apps/ask/src/record.rs
@@ -0,0 +1,106 @@
+//! Every answer kept (docs/ask.feature AK3), so a question can be labelled, calibrated and reworded later (AK6, AK7):
+//! each call in calls.jsonl (the file, the window, the state, the clips it sent by hash, the route and the cost) and each
+//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
+//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media.
+
+use std::io::Write as _;
+use std::path::PathBuf;
+
+use raea_core_ask::{Question, Reading};
+use serde_json::{Value, json};
+use sha2::{Digest, Sha256};
+
+/// How much cut media is kept.
+pub const MEDIA_CAP: u64 = 2 << 30;
+
+pub fn dir() -> PathBuf {
+ raea_io_clef::cache::dir()
+}
+
+/// A new id: a prefix and twelve hex digits, from the time, the process and a counter.
+pub fn new_id(prefix: &str) -> String {
+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
+ let seed = format!("{t}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
+ let h = seed.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
+ format!("{prefix}-{:012x}", h & 0xffff_ffff_ffff)
+}
+
+fn now() -> String {
+ let s = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
+ s.to_string()
+}
+
+fn append(file: &str, row: &Value) {
+ let d = dir();
+ if std::fs::create_dir_all(&d).is_err() {
+ return;
+ }
+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(d.join(file)) {
+ let _ = writeln!(f, "{row}");
+ }
+}
+
+/// A clip kept by its hash, as `HASH.EXT` (already kept is left alone).
+pub fn keep_media(bytes: &[u8], ext: &str) -> String {
+ let hash: String = Sha256::digest(bytes).iter().take(16).map(|b| format!("{b:02x}")).collect();
+ let name = format!("{hash}.{ext}");
+ let d = dir().join("media");
+ let p = d.join(&name);
+ if !p.is_file() && std::fs::create_dir_all(&d).is_ok() {
+ let _ = std::fs::write(&p, bytes);
+ prune(MEDIA_CAP);
+ }
+ name
+}
+
+/// A kept clip's bytes, by its name.
+pub fn media(name: &str) -> Option<Vec<u8>> {
+ std::fs::read(dir().join("media").join(name)).ok()
+}
+
+/// The kept media held to `cap` bytes, the least recently written going first.
+pub fn prune(cap: u64) {
+ let Ok(rd) = std::fs::read_dir(dir().join("media")) else { return };
+ let mut files: Vec<(std::time::SystemTime, u64, PathBuf)> = rd
+ .flatten()
+ .filter_map(|e| {
+ let m = e.metadata().ok()?;
+ Some((m.modified().ok()?, m.len(), e.path()))
+ })
+ .collect();
+ let mut total: u64 = files.iter().map(|f| f.1).sum();
+ files.sort();
+ for (_, len, p) in files {
+ if total <= cap {
+ break;
+ }
+ if std::fs::remove_file(&p).is_ok() {
+ total -= len;
+ }
+ }
+}
+
+/// One call kept; its id.
+#[allow(clippy::too_many_arguments)]
+pub fn call(file: &str, project: Option<&str>, from: f64, to: Option<f64>, state: &str, media: &[String], route: &str, cost: f64, cached: bool) -> String {
+ let id = new_id("c");
+ append("calls.jsonl", &json!({"id": id, "at": now(), "file": file, "project": project, "from": from, "to": to, "state": state, "media": media, "route": route, "cost": cost, "cached": cached}));
+ id
+}
+
+/// One answer kept; its id.
+pub fn answer(call: &str, file: &str, q: &Question, r: &Reading, flagged: bool) -> String {
+ let id = new_id("a");
+ let row = json!({
+ "id": id, "at": now(), "call": call, "file": file, "question": q.id, "version": q.version(), "ask": q.ask,
+ "value": r.value, "problem": r.problem, "choice": r.choice, "says": r.says, "flagged": flagged, "calibrated": q.calibrated(),
+ });
+ append("answers.jsonl", &row);
+ id
+}
+
+/// Every row of one of the record's files.
+pub fn rows(file: &str) -> Vec<Value> {
+ std::fs::read_to_string(dir().join(file)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
+}
diff --git a/apps/ask/src/runner.rs b/apps/ask/src/runner.rs
new file mode 100644
index 00000000..4dfa4bff
--- /dev/null
+++ b/apps/ask/src/runner.rs
@@ -0,0 +1,342 @@
+//! One runner for every caller (docs/ask.feature AK3): a batch planned into calls (grouped by file, window, the files
+//! beside it and what of the picture its questions look at, at most 64 questions a call, the voice question added to a
+//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
+//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
+//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing.
+
+use std::collections::{BTreeSet, HashMap};
+use std::path::{Path, PathBuf};
+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, Call, Fail, Media, media};
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use crate::prepare::{self, Piece, VOICE};
+use crate::record;
+
+/// What to ask of one file: its questions (prepared), those dropped with why, a window over all of them (else each
+/// question's own), and files set beside it (to pick between, or before and after).
+pub struct Entry {
+ pub piece: Arc<Piece>,
+ pub window: Option<Window>,
+ pub questions: Vec<Question>,
+ pub dropped: Vec<(String, String)>,
+ pub with: Vec<PathBuf>,
+}
+
+/// One call's worth.
+pub struct Group {
+ pub piece: Arc<Piece>,
+ pub from: f64,
+ pub to: Option<f64>,
+ pub sees: Sees,
+ pub hears: bool,
+ pub with: Vec<PathBuf>,
+ pub questions: Vec<Question>,
+}
+
+/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct Answer {
+ /// its id in the record (`raea ask verdict` takes it)
+ pub answer: Option<String>,
+ pub file: String,
+ pub id: String,
+ pub version: String,
+ pub from: f64,
+ pub to: Option<f64>,
+ pub says: Option<String>,
+ pub value: Option<f64>,
+ pub problem: Option<f64>,
+ pub choice: Option<String>,
+ pub flagged: bool,
+ pub calibrated: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub not_asked: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub waits: Option<String>,
+ pub route: Option<String>,
+ pub cached: bool,
+}
+
+/// What the run came to.
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct Summary {
+ pub asked: usize,
+ pub answered: usize,
+ pub calls: usize,
+ pub cost: f64,
+ pub estimate: f64,
+ pub pool_left: Option<f64>,
+ pub waiting: usize,
+ pub flagged: usize,
+ pub flagged_calibrated: usize,
+ pub routes: BTreeSet<String>,
+ /// the clips cut (each once, however many calls used it)
+ pub clips: usize,
+}
+
+/// What the runner tells its caller as it goes: an answer, or (dry) a call it would make.
+pub enum Event<'a> {
+ Answer(&'a Answer),
+ Would(&'a Value),
+}
+
+pub struct Opts {
+ pub jobs: usize,
+ pub dry: bool,
+ /// how a call is made: `raea_io_clef::ask` (a test gives its own)
+ pub ask: fn(&Call) -> Result<Answered, Fail>,
+}
+
+impl Opts {
+ pub fn new(jobs: usize, dry: bool) -> Opts {
+ Opts { jobs, dry, ask: raea_io_clef::ask }
+ }
+}
+
+const NAMES: [&str; 4] = ["first", "second", "third", "fourth"];
+
+/// A pick's options: the files given, in order (all, or all but the first, the reference).
+fn picks(p: Picks, files: usize) -> Vec<String> {
+ let n = files.min(NAMES.len());
+ let skip = usize::from(p == Picks::AfterFirst);
+ NAMES[skip.min(n)..n].iter().map(|s| s.to_string()).collect()
+}
+
+/// The batch as calls.
+pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
+ let mut groups: Vec<Group> = Vec::new();
+ let mut unasked = Vec::new();
+ for e in entries {
+ let file = e.piece.file.display().to_string();
+ for (id, why) in &e.dropped {
+ unasked.push(Answer { file: file.clone(), id: id.clone(), not_asked: Some(why.clone()), ..Default::default() });
+ }
+ for q in &e.questions {
+ let w = e.window.or(q.window).unwrap_or_default();
+ let (from, to) = (w.from.unwrap_or(0.0).max(0.0), w.to);
+ let mut q = q.clone();
+ if let Some(p) = q.picks {
+ q.kind = Kind::Choose;
+ q.options = picks(p, 1 + e.with.len());
+ }
+ let compares = q.picks.is_some_and(|_| q.options.len() < 2) || (q.uses.iter().any(|u| u == "with") && e.with.is_empty());
+ if compares {
+ unasked.push(Answer { file: file.clone(), version: q.version(), not_asked: Some("it compares files: set one or more beside it (--with)".into()), id: q.id, ..Default::default() });
+ continue;
+ }
+ // one place in each call is kept for the voice question
+ let same = |g: &&mut Group| Arc::ptr_eq(&g.piece, &e.piece) && g.from == from && g.to == to && g.sees == q.sees && g.with == e.with && g.questions.len() < limits::QUESTIONS - 1;
+ match groups.iter_mut().find(same) {
+ Some(g) => {
+ g.hears |= q.hears;
+ g.questions.push(q);
+ }
+ None => groups.push(Group { piece: e.piece.clone(), from, to, sees: q.sees, hears: q.hears, with: e.with.clone(), questions: vec![q] }),
+ }
+ }
+ }
+ for g in &mut groups {
+ g.hears &= g.piece.probe.sound || g.with.iter().any(|f| media::probe(f).is_ok_and(|p| p.sound));
+ if g.hears && g.piece.voice.is_none() && g.questions.iter().any(|q| q.when.voice.is_some()) {
+ g.questions.push(prepare::voice_question());
+ }
+ }
+ (groups, unasked)
+}
+
+/// Clips cut once a run, by what they are.
+type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
+
+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();
+ }
+ let r = make().map(Arc::new);
+ cuts.lock().unwrap().insert(key, r.clone());
+ r
+}
+
+/// A group's media, and its seconds of video and of sound (for the estimate).
+fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
+ let files: Vec<&Path> = std::iter::once(g.piece.file.as_path()).chain(g.with.iter().map(PathBuf::as_path)).collect();
+ let (from, to) = (g.from, g.to);
+ let span = |p: &media::Probe| (to.unwrap_or(p.seconds) - from).clamp(0.0, p.seconds.max(0.1));
+ let mut m = Media::default();
+ 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| format!("{what}:{}:{from}:{to:?}", f.display());
+ match g.sees {
+ Sees::Video if p.video => {
+ m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
+ vs += span(&p).min(limits::VIDEO_SECONDS);
+ }
+ Sees::Video | Sees::Stills if !p.video => m.stills.push(cut(cuts, k("still"), || media::still(f, None))?.to_vec()),
+ Sees::Stills if files.len() == 1 => {
+ let len = span(&p);
+ for i in 0..limits::STILLS {
+ let at = from + len * (i as f64 + 0.5) / limits::STILLS as f64;
+ m.stills.push(cut(cuts, k(&format!("frame{i}")), || media::still(f, Some(at)))?.to_vec());
+ }
+ }
+ Sees::Stills => m.stills.push(cut(cuts, k("frame"), || media::still(f, Some(from + span(&p) / 2.0)))?.to_vec()),
+ _ => {}
+ }
+ if g.hears && p.sound {
+ m.sounds.push(cut(cuts, k("sound"), || media::sound(f, from, to))?.to_vec());
+ ss += span(&p).min(limits::SOUND_SECONDS);
+ }
+ }
+ if m.videos.len() > limits::VIDEOS || m.stills.len() > limits::STILLS || m.sounds.len() > limits::SOUNDS {
+ return Err(format!("too many files for one call: at most {} videos, {} stills and {} sounds", limits::VIDEOS, limits::STILLS, limits::SOUNDS));
+ }
+ Ok((m, vs, ss))
+}
+
+enum Done {
+ Asked(Answered, Vec<String>, String),
+ Would(Value),
+ Failed(String),
+ Waits(String),
+}
+
+/// Every entry asked, at most `jobs` calls at once, each event told to `out` as it comes (in the caller's thread).
+pub fn run(entries: Vec<Entry>, o: &Opts, out: &mut dyn FnMut(Event)) -> Summary {
+ let (groups, unasked) = plan(&entries);
+ let mut sum = Summary::default();
+ for a in &unasked {
+ out(Event::Answer(a));
+ }
+ let cuts: Cuts = Mutex::default();
+ 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, 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 done = if spent.load(Ordering::Relaxed) {
+ Done::Waits(spent_why.lock().unwrap().clone())
+ } else {
+ match media_of(g, cuts) {
+ Err(e) => Done::Failed(e),
+ Ok((m, vs, ss)) => {
+ let call = Call { state: g.piece.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;
+ }
+ }
+ });
+ }
+ drop(tx);
+ for (i, done) in rx {
+ told(&groups[i], done, &mut sum, out);
+ }
+ });
+ sum.clips = cuts.lock().unwrap().values().filter(|c| c.is_ok()).count();
+ sum
+}
+
+/// 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<_>>();
+ [each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
+}
+
+fn would(g: &Group, call: &Call, estimate: f64) -> Value {
+ let sizes = |v: &[Vec<u8>]| v.iter().map(Vec::len).collect::<Vec<_>>();
+ json!({
+ "file": g.piece.file.display().to_string(), "from": g.from, "to": g.to,
+ "questions": call.questions.iter().map(|q| json!({"id": q.id, "ask": q.ask, "type": q.kind})).collect::<Vec<_>>(),
+ "state": call.state,
+ "media": {"videos": sizes(&call.media.videos), "stills": sizes(&call.media.stills), "sounds": sizes(&call.media.sounds)},
+ "estimate_usd": estimate,
+ })
+}
+
+/// A finished call's answers told, kept and counted. When the voice question went along, the variant that doesn't
+/// apply (sound where no one speaks, sound-silent where someone does) is set aside.
+fn told(g: &Group, done: Done, sum: &mut Summary, out: &mut dyn FnMut(Event)) {
+ let file = g.piece.file.display().to_string();
+ // the voice question only decides between variants: it isn't told
+ let asked: Vec<&Question> = g.questions.iter().filter(|q| q.id != VOICE).collect();
+ let base = |q: &Question| Answer { file: file.clone(), id: q.id.clone(), version: q.version(), from: g.from, to: g.to, calibrated: q.calibrated(), ..Default::default() };
+ match done {
+ Done::Would(v) => {
+ sum.calls += 1;
+ sum.estimate += v["estimate_usd"].as_f64().unwrap_or(0.0);
+ out(Event::Would(&v));
+ }
+ Done::Failed(why) | Done::Waits(why) if g.questions.is_empty() => drop(why),
+ Done::Failed(why) => asked.iter().for_each(|q| out(Event::Answer(&Answer { not_asked: Some(why.clone()), ..base(q) }))),
+ Done::Waits(why) => {
+ sum.waiting += asked.len();
+ asked.iter().for_each(|q| out(Event::Answer(&Answer { waits: Some(format!("waits for the pool: {why}")), ..base(q) })));
+ }
+ Done::Asked(a, clips, state) => {
+ sum.calls += 1;
+ sum.asked += asked.len();
+ sum.cost += a.cost;
+ sum.pool_left = a.pool_left.or(sum.pool_left);
+ sum.routes.insert(a.route.clone());
+ let project = g.piece.project.as_ref().map(|p| p.display().to_string());
+ let call = record::call(&file, project.as_deref(), g.from, g.to, &state, &clips, &a.route, a.cost, a.cached);
+ let heard = a.answers.get(VOICE).and_then(|v| v["noul"].as_f64());
+ for q in g.questions.iter().filter(|q| q.id != VOICE) {
+ let Some(ans) = a.answers.get(&q.id) else {
+ out(Event::Answer(&Answer { not_asked: Some("no answer came back for it".into()), ..base(q) }));
+ continue;
+ };
+ if let (Some(p), Some(v)) = (heard, q.when.voice) {
+ if v != (p >= 0.5) {
+ let who = if p >= 0.5 { "someone speaks" } else { "no one speaks" };
+ out(Event::Answer(&Answer { not_asked: Some(format!("set aside: {who} ({p:.2})")), ..base(q) }));
+ continue;
+ }
+ }
+ let r = q.read(ans);
+ let flagged = q.flagged(&r);
+ sum.answered += 1;
+ sum.flagged += usize::from(flagged);
+ sum.flagged_calibrated += usize::from(flagged && q.calibrated());
+ let id = record::answer(&call, &file, q, &r, flagged);
+ out(Event::Answer(&Answer {
+ answer: Some(id),
+ says: Some(r.says),
+ value: Some(r.value),
+ problem: r.problem,
+ choice: r.choice,
+ flagged,
+ route: Some(a.route.clone()),
+ cached: a.cached,
+ ..base(q)
+ }));
+ }
+ }
+ }
+}
diff --git a/apps/ask/src/tests.rs b/apps/ask/src/tests.rs
new file mode 100644
index 00000000..70fb8886
--- /dev/null
+++ b/apps/ask/src/tests.rs
@@ -0,0 +1,171 @@
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use raea_core_ask::{Facts, Kind, Picks, Question, Sees, Window, library};
+use raea_io_clef::media::Probe;
+use raea_io_clef::{Answered, Call, Fail};
+use serde_json::{Map, Value, json};
+
+use crate::prepare::{self, Piece, VOICE};
+use crate::runner::{self, Answer, Entry, Event, Opts};
+
+fn rubric() -> String {
+ std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
+}
+
+fn setup() {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ // SAFETY: set once, before any test reads it, to the same value for every test
+ ONCE.call_once(|| unsafe { std::env::set_var("RAEA_ASK_DIR", std::env::temp_dir().join(format!("raea-ask-test-{}", std::process::id()))) });
+}
+
+fn ids(qs: &[Question]) -> Vec<&str> {
+ qs.iter().map(|q| q.id.as_str()).collect()
+}
+
+fn piece(file: &str, voice: Option<bool>) -> Arc<Piece> {
+ let probe = Probe { seconds: 10.0, video: true, still: false, sound: true };
+ Arc::new(Piece { file: PathBuf::from(file), probe, voice, ..Default::default() })
+}
+
+fn entry(p: &Arc<Piece>, window: Option<Window>, questions: Vec<Question>) -> Entry {
+ Entry { piece: p.clone(), window, questions, dropped: vec![], with: vec![] }
+}
+
+#[test]
+fn no_one_speaking_asks_sound_silent_and_a_file_without_sound_isnt_listened_to() {
+ let r = rubric();
+ let sound = library::find("sound", Some(&r)).unwrap();
+ let silent = Facts { voice: Some(false), sound: true, video: true, ..Default::default() };
+ let (asked, dropped) = prepare::keep(vec![sound.clone()], &silent, Some(&r));
+ assert_eq!(ids(&asked), ["sound-silent"]);
+ assert!(dropped[0].1.contains("no one speaks") && dropped[0].1.contains("sound-silent instead"), "{dropped:?}");
+ let mut listen = Question::plain("loud", "Is it loud?");
+ listen.sees = Sees::Nothing;
+ let (asked, dropped) = prepare::keep(vec![listen], &Facts { video: true, ..Default::default() }, None);
+ assert!(asked.is_empty() && dropped[0].1.contains("no sound"), "{dropped:?}");
+ // not knowing whether anyone speaks, both are kept, and the plan adds the voice question to their call
+ let unknown = Facts { sound: true, video: true, ..Default::default() };
+ let (asked, _) = prepare::keep(vec![sound], &unknown, Some(&r));
+ assert_eq!(ids(&asked), ["sound", "sound-silent"]);
+ let (groups, _) = runner::plan(&[entry(&piece("a.mp4", None), None, asked)]);
+ assert_eq!(groups.len(), 1);
+ assert_eq!(ids(&groups[0].questions), ["sound", "sound-silent", VOICE]);
+}
+
+#[test]
+fn the_state_says_what_the_piece_is() {
+ let mut p = (*piece("a.mp4", Some(false))).clone();
+ p.brief = json!({"title": "Spring launch", "mode": ["pitch"], "audience": "busy founders", "believe": "it saves them an hour."});
+ p.extra = Some("raea measured -14 LUFS.".into());
+ let s = p.state();
+ for want in ["A pitch piece: \"Spring launch\".", "It's for: busy founders.", "believing: it saves them an hour.", "No one speaks", "runs 10 s", "-14 LUFS"] {
+ assert!(s.contains(want), "{want}: {s}");
+ }
+ assert_eq!(p.facts().modes, ["pitch"]);
+}
+
+#[test]
+fn calls_hold_64_questions_and_split_by_window_and_what_they_look_at() {
+ let p = piece("a.mp4", Some(true));
+ let many: Vec<Question> = (0..65).map(|i| Question::plain(&format!("q{i}"), "Is it loud?")).collect();
+ let (groups, _) = runner::plan(&[entry(&p, None, many)]);
+ assert_eq!(groups.iter().map(|g| g.questions.len()).collect::<Vec<_>>(), [63, 2], "one place a call is kept for the voice question");
+ let hook = Window { from: Some(0.0), to: Some(3.0) };
+ let mut still = Question::plain("s", "Is the text readable?");
+ still.sees = Sees::Stills;
+ let (groups, _) = runner::plan(&[entry(&p, None, vec![Question::plain("a", "Is it loud?"), still]), entry(&p, Some(hook), vec![Question::plain("b", "Is it loud?")])]);
+ assert_eq!(groups.len(), 3);
+ let mut pick = Question::plain("best", "Which suits the brief best?");
+ pick.picks = Some(Picks::All);
+ let (groups, unasked) = runner::plan(&[entry(&p, None, vec![pick])]);
+ assert!(groups.is_empty() && unasked[0].not_asked.as_deref().is_some_and(|n| n.contains("--with")), "{unasked:?}");
+ let (groups, unasked) = runner::plan(&[entry(&p, None, vec![library::find("decide.changed", None).unwrap()])]);
+ assert!(groups.is_empty() && !unasked[0].version.is_empty(), "{unasked:?}");
+}
+
+/// clef's answers as a fake gives them: yes 0.8 to every yes question (0.9 to the voice question), the lowest level of
+/// a grade.
+fn answers(call: &Call) -> Map<String, Value> {
+ call.questions
+ .iter()
+ .map(|q| {
+ let a = match q.kind {
+ Kind::Yes => json!({"noul": if q.id == VOICE { 0.9 } else { 0.8 }}),
+ _ => json!({"choice": q.levels()[0], "probabilities": {q.levels()[0].clone(): 1.0}}),
+ };
+ (q.id.clone(), a)
+ })
+ .collect()
+}
+
+fn answered(call: &Call) -> Answered {
+ Answered { answers: answers(call), cost: 0.001, cached: false, route: "a test".into(), pool_left: Some(1.5) }
+}
+
+/// A 2 s clip with a picture and a tone, made with FFmpeg.
+fn clip(name: &str) -> PathBuf {
+ let out = std::env::temp_dir().join(format!("raea-ask-{}-{name}.mp4", std::process::id()));
+ let ff = raea_io_assets::ffmpeg_tool("ffmpeg", false).expect("FFmpeg");
+ let ok = std::process::Command::new(ff)
+ .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=10:duration=2", "-f", "lavfi", "-i", "sine=frequency=440:duration=2"])
+ .args(["-c:v", "mpeg4", "-c:a", "aac", "-shortest"])
+ .arg(&out)
+ .status()
+ .expect("FFmpeg ran");
+ assert!(ok.success());
+ out
+}
+
+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 }, &mut |e| {
+ if let Event::Answer(a) = e {
+ got.push(a.clone());
+ }
+ });
+ (sum, got)
+}
+
+#[test]
+fn each_clip_is_cut_once_and_the_voice_answer_sets_a_variant_aside() {
+ let file = clip("once");
+ let p = Arc::new(Piece::read(&file, None, None, None, None).unwrap());
+ assert!(p.probe.video && p.probe.sound && p.voice.is_none());
+ let r = rubric();
+ let (asked, _) = prepare::keep(vec![library::find("sound", Some(&r)).unwrap()], &p.facts(), Some(&r));
+ let mut listen = Question::plain("loud", "Is it too loud?");
+ listen.sees = Sees::Nothing;
+ let (sum, got) = run(vec![entry(&p, None, [asked, vec![listen]].concat())], 4, |c| Ok(answered(c)));
+ assert_eq!((sum.calls, sum.clips), (2, 2), "the picture's call and the sound's call share one cut of the sound");
+ let by = |id: &str| got.iter().find(|a| a.id == id).unwrap_or_else(|| panic!("{id}: {got:?}"));
+ assert!(by("sound").says.is_some() && by("loud").flagged);
+ assert!(by("sound-silent").not_asked.as_deref().is_some_and(|n| n.contains("someone speaks (0.90)")), "{:?}", by("sound-silent"));
+ assert!(!got.iter().any(|a| a.id == VOICE), "the voice question isn't told");
+ assert_eq!((sum.answered, sum.cost, sum.pool_left), (2, 0.002, Some(1.5)));
+}
+
+static CALLS: AtomicUsize = AtomicUsize::new(0);
+
+#[test]
+fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
+ let file = clip("spent");
+ let p = Arc::new(Piece::read(&file, None, None, Some(true), None).unwrap());
+ let at = |s: f64| Some(Window { from: Some(s), to: Some(s + 0.5) });
+ let entries = (0..4).map(|i| entry(&p, at(i as f64 * 0.4), vec![Question::plain(&format!("w{i}"), "Is it loud?")])).collect();
+ let (sum, got) = run(entries, 1, |c| match CALLS.fetch_add(1, Ordering::SeqCst) {
+ 2 => Err(Fail::Spent("this month's pool is used up".into())),
+ _ => Ok(answered(c)),
+ });
+ assert_eq!((sum.calls, sum.answered, sum.waiting), (2, 2, 2));
+ assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
+ assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
+}
+
+#[test]
+fn own_words_keep_their_id() {
+ assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
+ assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
+}
diff --git a/apps/ask/src/verbs.rs b/apps/ask/src/verbs.rs
new file mode 100644
index 00000000..f094dd19
--- /dev/null
+++ b/apps/ask/src/verbs.rs
@@ -0,0 +1,324 @@
+//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
+//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
+//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
+//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline.
+
+use std::collections::{BTreeMap, HashMap};
+use std::io::Read as _;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use raea_core_ask::{Kind, Question, Window, library};
+use serde_json::{Value, json};
+
+use crate::prepare::{self, Piece};
+use crate::runner::{self, Entry, Event, Opts};
+
+pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated)";
+
+const VALUED: [&str; 15] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch"];
+const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
+
+/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
+#[derive(Default)]
+struct Args {
+ words: Vec<String>,
+ flags: BTreeMap<String, Vec<String>>,
+ gate_any: bool,
+}
+
+impl Args {
+ fn parse(args: &[String]) -> Result<Args, String> {
+ let mut a = Args::default();
+ let mut i = 0;
+ while i < args.len() {
+ let s = args[i].as_str();
+ if VALUED.contains(&s) {
+ let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
+ a.flags.entry(s.into()).or_default().push(v.clone());
+ i += 1;
+ } else if BARE.contains(&s) {
+ a.flags.entry(s.into()).or_default();
+ if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
+ a.gate_any = true;
+ i += 1;
+ }
+ } else if s.starts_with("--") {
+ return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
+ } else {
+ a.words.push(s.into());
+ }
+ i += 1;
+ }
+ Ok(a)
+ }
+ fn has(&self, f: &str) -> bool {
+ self.flags.contains_key(f)
+ }
+ fn one(&self, f: &str) -> Option<&str> {
+ self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
+ }
+ fn num(&self, f: &str) -> Result<Option<f64>, String> {
+ self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
+ }
+ fn list(&self, f: &str) -> Vec<String> {
+ self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
+ }
+}
+
+/// The craft rubric's text, where the guides are installed, for the `rubric` set.
+pub fn rubric_md() -> Option<String> {
+ std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
+}
+
+/// A question's id from its words: `own-` and its first words, so the same words keep their id.
+pub fn own_id(words: &str) -> String {
+ let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
+ let mut id = format!("own-{}", slug.join("-"));
+ id.truncate(raea_core_ask::limits::ID_LEN);
+ id
+}
+
+/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
+fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
+ let mut qs = own.to_vec();
+ for s in sets {
+ qs.extend(library::set(s, rubric)?);
+ }
+ for id in std {
+ qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
+ }
+ Ok(qs)
+}
+
+fn shaped(words: &str, a: &Args) -> Result<Question, String> {
+ let mut q = Question::plain(&own_id(words), words);
+ if let Some(c) = a.one("--choose") {
+ q.kind = Kind::Choose;
+ q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
+ } else if let Some(n) = a.one("--rate") {
+ let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
+ q.kind = Kind::Rate;
+ q.options = (1..=n).map(|i| i.to_string()).collect();
+ } else if a.has("--grade") {
+ q.kind = Kind::Grade;
+ }
+ q.flags = a.list("--flag");
+ if let Some(why) = raea_core_ask::limits::check(&q) {
+ return Err(format!("ask: {why}"));
+ }
+ Ok(q)
+}
+
+/// The window from --from, --to and --at (three seconds around it).
+fn window(a: &Args) -> Result<Option<Window>, String> {
+ if let Some(at) = a.num("--at")? {
+ return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
+ }
+ let (from, to) = (a.num("--from")?, a.num("--to")?);
+ Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
+}
+
+fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
+ match v {
+ None => Ok(None),
+ Some("yes" | "true") => Ok(Some(true)),
+ Some("no" | "false") => Ok(Some(false)),
+ Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
+ }
+}
+
+/// Pieces read once a run, by what they were read with.
+type Pieces = HashMap<String, Arc<Piece>>;
+
+#[allow(clippy::too_many_arguments)]
+fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
+ let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
+ if let Some(p) = pieces.get(&key) {
+ return Ok(p.clone());
+ }
+ let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
+ pieces.insert(key, p.clone());
+ Ok(p)
+}
+
+fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
+ let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
+ Entry { piece: p, window, questions, dropped, with }
+}
+
+/// The command line's one entry.
+fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
+ let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
+ let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
+ let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
+ if qs.is_empty() {
+ return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
+ }
+ let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
+ let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
+ Ok(vec![entry(p, window(a)?, qs, with, rubric)])
+}
+
+/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
+/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
+fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
+ let text = match path {
+ "-" => {
+ let mut s = String::new();
+ std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
+ s
+ }
+ p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
+ };
+ let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
+ Ok(Value::Array(a)) => a,
+ Ok(v @ Value::Object(_)) => vec![v],
+ _ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
+ };
+ let strs = |v: &Value| -> Vec<String> {
+ match v {
+ Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
+ Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ _ => vec![],
+ }
+ };
+ let mut out = Vec::new();
+ for (n, r) in rows.iter().enumerate() {
+ let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
+ let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
+ let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
+ Value::String(w) => Ok(Question::plain(&own_id(w), w)),
+ q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
+ });
+ let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
+ let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
+ let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
+ let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
+ let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
+ out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
+ }
+ Ok(out)
+}
+
+/// `raea ask list [SET]`: the standard questions.
+fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
+ let sets: Vec<String> = match a.words.get(1) {
+ Some(s) => vec![s.clone()],
+ None => library::SETS.iter().map(|s| s.to_string()).collect(),
+ };
+ let mut out = Vec::new();
+ for s in &sets {
+ let qs = library::set(s, rubric)?;
+ if a.has("--json") {
+ out.push(json!({"set": s, "questions": qs}).to_string());
+ continue;
+ }
+ out.push(format!("{s}:"));
+ for q in qs {
+ let how = if q.calibrated() { "calibrated" } else { "advice" };
+ out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
+ }
+ }
+ Ok(out.join("\n"))
+}
+
+fn span(from: f64, to: Option<f64>) -> String {
+ match to {
+ Some(t) => format!("{from:.0}-{t:.0} s"),
+ None if from > 0.0 => format!("from {from:.0} s"),
+ None => "whole".into(),
+ }
+}
+
+/// An event as a line of text.
+fn line(e: &Event, files: usize) -> String {
+ match e {
+ Event::Would(v) => {
+ let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
+ let m = &v["media"];
+ let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
+ format!(
+ "would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
+ qs.len(),
+ span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
+ v["file"].as_str().unwrap_or(""),
+ qs.join(", "),
+ kb("videos"),
+ kb("stills"),
+ kb("sounds"),
+ v["estimate_usd"].as_f64().unwrap_or(0.0),
+ v["state"].as_str().unwrap_or("")
+ )
+ }
+ Event::Answer(a) => {
+ let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
+ let what = match (&a.says, &a.not_asked, &a.waits) {
+ (Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
+ (_, Some(n), _) => format!("not asked: {n}"),
+ (.., Some(w)) => w.clone(),
+ _ => "no answer".into(),
+ };
+ format!("{who}{:<34} {what}", a.id)
+ }
+ }
+}
+
+/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
+pub fn cli(args: &[String]) -> i32 {
+ match run(args) {
+ Ok(code) => code,
+ Err(e) => {
+ eprintln!("{e}");
+ 1
+ }
+ }
+}
+
+fn run(args: &[String]) -> Result<i32, String> {
+ let a = Args::parse(args)?;
+ let rubric = rubric_md();
+ if a.words.first().is_some_and(|w| w == "list") && !Path::new("list").exists() {
+ println!("{}", list(&a, rubric.as_deref())?);
+ return Ok(0);
+ }
+ let mut pieces = Pieces::new();
+ let entries = match a.one("--batch") {
+ Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
+ None => from_args(&a, rubric.as_deref(), &mut pieces)?,
+ };
+ let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
+ let (json_out, dry) = (a.has("--json"), a.has("--dry"));
+ let files = pieces.len();
+ let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
+ match (&e, json_out) {
+ (Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
+ (Event::Would(v), true) => println!("{}", json!({"would": v})),
+ (e, false) => println!("{}", line(e, files)),
+ }
+ });
+ if json_out {
+ println!("{}", json!({"summary": sum}));
+ } else if dry {
+ println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
+ } else if sum.calls > 0 {
+ let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
+ let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
+ let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
+ println!(
+ "asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
+ sum.asked,
+ if sum.asked == 1 { "" } else { "s" },
+ sum.calls,
+ if sum.calls == 1 { "" } else { "s" },
+ routes.join(" and "),
+ sum.cost
+ );
+ }
+ if !dry && sum.calls == 0 {
+ return Err("ask: nothing was asked (each question's line says why)".into());
+ }
+ // a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
+ let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
+ Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
+}
diff --git a/apps/judge/src/lib.rs b/apps/judge/src/lib.rs
index 63d988cc..a2bebd5f 100644
--- a/apps/judge/src/lib.rs
+++ b/apps/judge/src/lib.rs
@@ -30,7 +30,7 @@ fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
- let a = raea_io_clef::ask(&call)?;
+ let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
Ok((Value::Object(a.answers), a.cost))
}
diff --git a/apps/solid/Cargo.toml b/apps/solid/Cargo.toml
index e923db93..af643c8d 100644
--- a/apps/solid/Cargo.toml
+++ b/apps/solid/Cargo.toml
@@ -16,6 +16,7 @@ serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
# `raea judge`, dispatched with `raea solid` (verb())
raea-app-judge = { path = "../judge" }
+raea-app-ask = { path = "../ask" }
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
raea-core-shape = { path = "../../core/shape" }
raea-core-meshcheck = { path = "../../core/meshcheck" }
diff --git a/apps/solid/src/lib.rs b/apps/solid/src/lib.rs
index 2adfdefa..60a4a001 100644
--- a/apps/solid/src/lib.rs
+++ b/apps/solid/src/lib.rs
@@ -91,11 +91,13 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
Ok(m)
}
-/// `raea solid ...` and `raea judge ...`, the scene loop's verbs (engine/cli hands them over), or None for another verb.
+/// `raea solid ...`, `raea judge ...` and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
+/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
match args.first().map(String::as_str) {
Some("solid") => Some(cli(args)),
Some("judge") => Some(raea_app_judge::cli(args)),
+ Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
_ => None,
}
}
diff --git a/core/ask/library/decide.json b/core/ask/library/decide.json
index af77db91..8f34131a 100644
--- a/core/ask/library/decide.json
+++ b/core/ask/library/decide.json
@@ -1,5 +1,5 @@
[
{"id": "decide.best", "type": "choose", "ask": "Which of these best fits what the piece is for, for the audience it's for?", "picks": "all", "uses": ["brief"]},
{"id": "decide.nearest", "type": "choose", "ask": "The first is the reference. Of the others, which looks and sounds most like it?", "picks": "after-first"},
- {"id": "decide.changed", "ask": "These are two versions, before and after a change. Does the second change what a viewer sees or hears?", "flags": ["no"]}
+ {"id": "decide.changed", "ask": "These are two versions, before and after a change. Does the second change what a viewer sees or hears?", "flags": ["no"], "uses": ["with"]}
]
diff --git a/core/ask/src/question.rs b/core/ask/src/question.rs
index 22c25f9d..264147e7 100644
--- a/core/ask/src/question.rs
+++ b/core/ask/src/question.rs
@@ -119,7 +119,8 @@ pub struct Question {
#[serde(default = "yes", skip_serializing_if = "is_true")]
#[ts(as = "Option<bool>", optional)]
pub hears: bool,
- /// what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform
+ /// what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform; and
+ /// with: it compares the file with the files set beside it, so it isn't asked without them
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub uses: Vec<String>,
diff --git a/docs/ask.feature b/docs/ask.feature
index 92a1733d..686957a2 100644
--- a/docs/ask.feature
+++ b/docs/ask.feature
@@ -48,6 +48,7 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
Rule: AK1. One question format and one client
+ @done
Scenario: AK1. Questions, and the standard library
Given the plan
| crate | file | lines | job |
@@ -67,8 +68,11 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
flags, a choice's on its flagging options, one less a grade's level over its top), so one calibration fits all
And the limits are raea-api's where they're stricter than clef's (ids of 64 characters, 16 options), so a call that
passes them passes on every route
+ Status: done 11-20. raea-core-ask: four types, 49 standard questions in five sets (the rubric's read from
+ rubric.md), the platform packs' three calibrated questions keeping their thresholds; its tests read every
+ standard question, check the limits and the TypeScript declarations (sdk/raea/src/ask.gen.ts).
- @needs:AK1
+ @needs:AK1 @done
Scenario: AK1b. One clef client, routed to the person's plan
Given the plan
| crate | file | lines | job |
@@ -82,22 +86,30 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
And with none it refuses: "sign in to raea on Pro or Studio, set RAEA_AGENT_KEY, or add your Cloudflare keys
(docs/settings.md)"
And `raea judge` asks through it, and apps/judge's own clef.rs is gone
+ Status: done 11-20. raea-io-clef's tests, on a fake transport: a route that can't answer hands on, a spent pool
+ stops unless the person has their own keys, the plan's answer carries what's left and a repeat comes from the
+ cache, none open refuses with how to get one, a call over the limits is never sent. A real call went the
+ own-keys route (AK3's status); the app route answers once AK4 adds /host/ask. raea judge's tests pass on it.
Rule: AK2-AK3. `raea ask`
- @needs:AK1b
+ @needs:AK1b @done
Scenario: AK2. Ask understands the question before it spends
Given the plan
| crate | file | lines | job |
- | raea-app-ask | apps/ask/src/prepare.rs | 260 | the file's facts (length, sound, words heard, words on screen, the render's manifest and record) and the project's brief (audience, believe, mode, voice); each question kept, swapped or dropped with why; the state paragraph |
+ | raea-app-ask | apps/ask/src/prepare.rs | 260 | the file's facts (length, picture, sound, the words heard from a words file, whether anyone speaks) and the project's brief (title, mode, audience, believe, logline, voice); each question kept, swapped or dropped with why (not knowing whether anyone speaks, both variants kept); the state paragraph, with what the caller measured (`--state`; raea check passes its own, AK5) |
Then a question about sound on a file with none, or a stills-only render, isn't asked, and says it waits for one
And a piece where no one speaks is asked `sound-silent` in place of `sound`, and told it has no voice
And the state says what the piece is (its modes, the brief's audience and belief, its storyboard's logline, what
raea measured), as critique.ts writes it today
And `--dry` prints exactly what would be sent (the state, each call's questions, the media and its size) and an
estimated cost, and spends nothing
+ Status: done 11-20. prepare.rs reads the file (ffprobe), the nearest brief.ts (`raea spec --as brief`) and a words
+ file; apps/ask tests: a silent piece asks sound-silent with why, a file with no sound isn't listened to, the
+ state names the modes, audience, belief and what the caller measured. `--dry` on an 8 s clip printed one call
+ of 11 questions, its state, 26 KB of video and 63 KB of sound, about $0.0009, and sent nothing.
- @needs:AK2
+ @needs:AK2 @done
Scenario: AK3. The runner, the record and the verb
Given the plan
| crate | file | lines | job |
@@ -116,6 +128,13 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
And sdk/raea's `raea/ask` gives scripts `ask` and `askMany`, typed from the generated questions, over
`raea ask --batch --json`, from a `.ts` check, a `raea run` script or plain Node
And docs/manual/reference/cli/ask.md is its reference, written in the same change
+ Status: done 11-20. One call on the person's own Cloudflare keys asked 4 questions of a test pattern with a tone
+ for $0.0003 (test pattern 0.88 yes, anyone speaking 0.00, the sound fits 0.06), and the same again came from the
+ cache for $0; calls.jsonl, answers.jsonl and the two cut clips were kept. apps/ask tests: 65 questions make two
+ calls, windows and what a question looks at split calls, a pick or a before-and-after without `--with` isn't
+ asked, a clip used by two calls is cut once, the voice answer sets the variant that doesn't apply aside, and a
+ 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.
Rule: AK4. On the person's plan
diff --git a/docs/manual/reference/cli/ask.md b/docs/manual/reference/cli/ask.md
new file mode 100644
index 00000000..088c1df7
--- /dev/null
+++ b/docs/manual/reference/cli/ask.md
@@ -0,0 +1,77 @@
+---
+title: "raea ask"
+summary: "Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated."
+order: 130
+sources: ["apps/ask/src/verbs.rs", "apps/ask/src/prepare.rs", "apps/ask/src/runner.rs", "io/clef/src/route.rs", "core/ask/src/library.rs"]
+---
+
+`raea ask` puts questions about a video, a sound or a picture to clef-omni, the decision model raea's checks use, and
+prints each answer in words with its probability, the window it looked at and what it cost. Ask in your own words, or
+use the standard questions: the craft rubric's (`rubric`), picture and sound together (`av`), the defects the
+fingerprint can't judge yet (`defects`), the platform checks (`platform`) and picking between versions (`decide`).
+`raea ask list` lists them all.
+
+Before it spends anything it reads what it can about the piece: what the file holds, the project's brief (the nearest
+`brief.ts` above the file, or `--brief`) and whether anyone speaks (`--words`, `--voice`). A question that doesn't
+apply isn't asked, and its line says why: a sound question of a silent file, or the rubric's `sound` question of a piece
+where no one speaks, which asks `sound-silent` instead. Every question about the same clip goes in one call, and
+many questions cost about what one does.
+
+It pays from your raea plan's monthly pool when the raea app is signed in on Pro or Studio, or with an agent key
+(`RAEA_AGENT_KEY` with `RAEA_API`) where the app isn't running, as in a pipeline or CI. Otherwise it uses your own
+Cloudflare keys ([settings](../../settings.md)). When the pool is spent, the questions not yet asked wait for next
+month, and their lines say so. The same question about the same media comes from a cache and costs nothing.
+
+```sh
+raea ask out/piece.mp4 "Does the music fight the voice?"
+raea ask out/piece.mp4 --set av --brief brief.ts
+raea ask out/piece.mp4 "Which ending lands harder?" --with out/v2.mp4 --std decide.best
+raea ask out/piece.mp4 "Is the logo readable?" --at 12.5 --flag no
+raea ask out/piece.mp4 --set defects --dry # what would be sent and its cost; nothing is spent
+raea ask --batch asks.jsonl --json --gate # a pipeline: one JSON line an answer, exit 1 on a finding
+```
+
+A batch is a JSON list, or JSON lines, of `{file, questions?, set?, std?, window?, with?, brief?, words?, voice?,
+state?}`, with `-` reading stdin. Its clips are each cut once, and its calls go four at a time (`--jobs`). Scripts can
+ask through [`raea/ask`](../sdk/ask.md) instead.
+
+Answers are advice until a question is calibrated against your own verdicts, and the answers say which they are. With
+`--gate`, a calibrated question that flags exits 1; with `--gate any`, any question that flags does. Every call and
+answer is kept in `~/.raea/ask` (`RAEA_ASK_DIR`), with the clips it cut, so that a question can be labelled and
+calibrated later.
+
+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+
+## Usage
+
+```sh
+raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated)
+```
+
+Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
+
+## Flags
+
+| Flag | Takes | What it does |
+| --- | --- | --- |
+| `--at` | `S` | The three seconds around this moment: every question looks at that window. |
+| `--batch` | `FILE` | A file of entries to ask, a JSON list or JSON lines (`-` reads stdin); each is a file with its questions. |
+| `--brief` | `brief.ts` | The project's brief, so clef knows who it's for and what it should do (else the nearest brief.ts above the file). |
+| `--choose` | `A,B,C` | Your questions pick one of these options, rather than answering yes or no. |
+| `--dry` | – | Cut the media and print each call that would be made (its state, questions, media sizes) with an estimated cost, and send nothing. |
+| `--flag` | `ANSWERS` | The answers that mean a problem: `no` for a question where no is bad ("Is the logo readable?"), or a choice's options. |
+| `--from` | `S` | Where the window starts, in seconds. |
+| `--gate` | – | Exit 1 when a calibrated question flags, or questions wait for the pool; `--gate any` exits 1 when any question flags. |
+| `--grade` | – | Your questions answer on a graded scale (poor, weak, fair, good, excellent). |
+| `--jobs` | `N` | How many calls go at once (4). |
+| `--json` | – | One JSON object a line: each answer, each call `--dry` would make, then the summary. |
+| `--rate` | `N` | Your questions answer with a score from 1 to N. |
+| `--set` | `NAME` | A standard set to ask: rubric, av, defects, platform or decide (comma-separated for several). |
+| `--state` | `TEXT` | More for clef to read before the media: what you measured, the platform it's for. |
+| `--std` | `ID` | Standard questions by id (`raea ask list`), comma-separated. |
+| `--to` | `S` | Where the window ends, in seconds. |
+| `--voice` | `yes\|no` | Whether anyone speaks in it, when no words file says: it decides which of the voice questions' variants is asked. |
+| `--with` | `FILE2` | Another file beside this one, to pick between or compare (repeat it for up to four in all). |
+| `--words` | `words.json` | A words file (a JSON list of the words heard): clef reads what is said, and none heard means no one speaks. |
+
+<!-- generated:end -->
diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.md
index c4e151da..7a5e5247 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -131,5 +131,6 @@ What an agent reads and shows the person, and the tools raea installs.
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
+| [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. |
<!-- generated:end -->
diff --git a/docs/manual/reference/sdk/ask.md b/docs/manual/reference/sdk/ask.md
new file mode 100644
index 00000000..fa2fabe4
--- /dev/null
+++ b/docs/manual/reference/sdk/ask.md
@@ -0,0 +1,177 @@
+---
+title: "raea/ask"
+summary: "Ask about a piece's picture and sound from a script: the same questions, runner and record as raea ask, typed."
+order: 106
+sources: ["sdk/raea/src/ask.ts"]
+---
+
+`raea/ask` asks from a script what [`raea ask`](../cli/ask.md) asks from the command line: a script run with `raea run`,
+a `.ts` check, or plain Node or Bun. It runs `raea ask --batch - --json`, so every question about one clip goes in one
+call, the clips are cut once, the calls go in parallel, and every answer is kept for calibration. It pays the same way:
+your raea plan when the app is signed in, an agent key, or your own Cloudflare keys. It throws when nothing could be
+asked, and the error says why.
+
+```ts
+import { ask, askMany } from "raea/ask";
+
+const { answers } = ask("out/piece.mp4", "Does the music fight the voice?");
+const run = askMany([
+ { file: "out/a.mp4", set: "av", brief: "brief.ts" },
+ { file: "out/b.mp4", std: ["defect.glitch"], window: { from: 0, to: 3 } },
+]);
+for (const a of run.answers) if (a.flagged) console.log(a.file, a.id, a.says, a.calibrated ? "finding" : "advice");
+```
+
+<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
+
+```ts
+import { ask, askMany, SETS } from "raea/ask"
+```
+
+`raea/ask` exports 2 functions, 1 value, 12 types. Source: [sdk/raea/src/ask.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/ask.ts).
+
+## Functions
+
+### `ask`
+
+Questions about one file: your own words (yes or no), written-out questions, or with `std`/`set` the standard ones.
+
+```ts
+function ask(file: string, question?: string | Question | (string | Question)[], more?: Omit<AskEntry, "file" | "questions"> & AskOptions): Asked
+```
+
+### `askMany`
+
+Many files asked in one run, in parallel; throws when nothing could be asked (the error says why).
+
+```ts
+function askMany(entries: AskEntry[], o?: AskOptions): Asked
+```
+
+## Values
+
+### `SETS`
+
+## Types
+
+### `Answer`
+
+One question's answer, or why it wasn't asked or still waits: a line of `raea ask --json`.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `answer` | `string` | its id in the record, for `raea ask verdict` |
+| `file` (required) | `string` | the file asked about |
+| `id` (required) | `string` | the question's id |
+| `version` (required) | `string` | a hash of its words, type and options: a new wording is a new version, calibrated on its own |
+| `from` (required) | `number` | the window's start, in seconds |
+| `to` | `number` | the window's end, in seconds (unset: the file's end) |
+| `says` | `string` | the answer in words with its probability |
+| `value` | `number` | yes's probability, a pick's probability, or a level |
+| `problem` | `number` | 0 to 1, higher is likelier a problem (none for a pick) |
+| `choice` | `string` | the option or level chosen |
+| `flagged` (required) | `boolean` | past the question's threshold (its calibrated one, else even odds) |
+| `calibrated` (required) | `boolean` | its labels separate well enough for its answers to be findings; until then they're advice |
+| `not_asked` | `string` | why it wasn't asked (it doesn't apply to this piece, or the call failed) |
+| `waits` | `string` | why it still waits (this month's pool is spent) |
+| `route` | `string` | the way it was paid: your raea plan through the app, an agent key, or your Cloudflare account |
+| `cached` (required) | `boolean` | answered from the cache, at no cost |
+
+### `Asked`
+
+A run's answers, the calls `dry` would make, and its summary.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `answers` (required) | `Answer[]` | every question's answer, or why it wasn't asked, in the order they came |
+| `would` (required) | `unknown[]` | with `dry`: each call that would be made (its state, questions, media sizes and estimate) |
+| `summary` (required) | `Summary` | what it came to |
+
+### `AskEntry`
+
+One file and what to ask of it: a line of `raea ask --batch`.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `file` (required) | `string` | the video, sound or picture asked about |
+| `questions` | `(string \| Question)[]` | questions in your own words (yes or no) or written out |
+| `set` | `string \| string[]` | standard sets by name: rubric, av, defects, platform, decide |
+| `std` | `string[]` | standard questions by id (`raea ask list` lists them) |
+| `window` | `Window` | the seconds to look at, for every question here (else each question's own, else the whole file) |
+| `with` | `string[]` | files set beside it: to pick between, or a before and after |
+| `brief` | `string` | the project's brief (else the nearest brief.ts above the file) |
+| `words` | `string` | a words file (a JSON list of the words heard), so ask knows what's said and whether anyone speaks |
+| `voice` | `boolean` | whether anyone speaks in it, when no words file says |
+| `state` | `string` | more for clef to read before the media: what raea measured, the platform |
+
+### `AskOptions`
+
+How a run goes.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `jobs` | `number` | calls at once (4 unless set) |
+| `dry` | `boolean` | cut the media and say what would be sent, spending nothing |
+| `bin` | `string` | the raea to run (RAEA_BIN, else raea on the PATH) |
+
+### `Calibration`
+
+```ts
+type Calibration = { auc: number, n: number, positives: number, /** * the problem score at which it flags (10% false positives on its labels) */ threshold?: number, /** * YYYY-MM-DD */ date: string, /** * whose labels: "raea" (raea's bench, shipped) or "you" */ by: string, }
+```
+
+### `Kind`
+
+```ts
+type Kind = "yes" | "choose" | "grade" | "rate"
+```
+
+### `Picks`
+
+```ts
+type Picks = "all" | "after-first"
+```
+
+### `Question`
+
+```ts
+type Question = { /** * letters, digits, `_`, `.` and `-` */ id: string, /** * the question in words, as clef reads it */ ask: string, type?: Kind, /** * choose: its options; grade and rate: its levels, lowest first (a grade's are LEVELS unless given) */ options?: Array<string>, /** * what an option (or yes and …
+```
+
+### `Sees`
+
+```ts
+type Sees = "video" | "stills" | "nothing"
+```
+
+### `Summary`
+
+What a run came to.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `asked` (required) | `number` | the questions sent |
+| `answered` (required) | `number` | the answers read |
+| `calls` (required) | `number` | the calls made (with `dry`, the calls that would be) |
+| `cost` (required) | `number` | what the calls cost, in dollars |
+| `estimate` (required) | `number` | with `dry`, what the calls would cost, in dollars |
+| `pool_left` | `number` | what's left of this month's pool, in dollars, when the plan paid |
+| `waiting` (required) | `number` | the questions waiting for the pool |
+| `flagged` (required) | `number` | the answers past their threshold |
+| `flagged_calibrated` (required) | `number` | the calibrated answers past their threshold: findings |
+| `routes` (required) | `string[]` | the ways the calls were paid |
+| `clips` (required) | `number` | the clips cut, each once |
+
+### `When`
+
+```ts
+type When = { /** * the brief's modes it's for (pitch, story, explain, play, tool); empty is every mode */ modes?: Array<string>, /** * true: only when someone is heard speaking; false: only when no one is */ voice?: boolean, /** * true: only for a game; false: never for one */ game?: boolean, }
+```
+
+### `Window`
+
+```ts
+type Window = { from?: number, to?: number, }
+```
+
+<!-- generated:end -->
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index 41a086b8..437a90c4 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -99,5 +99,6 @@ Checks, lints and a headless App you can drive.
| [`raea/fingerprint`](fingerprint.md) | A fingerprint (fingerprint.ts, docs/fingerprint.md): a person's or a team's sense of good work as axes, each with a small head over on-device encoders that `raea fingerprint` trains from their labels. `raea fingerprint new NAME` writes one with raea's base taxonomy; add an axis, reword one, or remove one, and raea retrains. Rust reads the default export (systems/fingerprint/src/taxonomy.rs), so these types follow its fields. | 1 function, 4 types |
| [`raea/dev_tools`](dev_tools.md) | Checks and lints you can run from code: a motion performance's lint report. | 2 functions, 3 types |
| [`raea/remote`](remote.md) | A headless Bevy App you open, step and query from TypeScript, through Bevy's remote protocol. | 1 class, 1 type |
+| [`raea/ask`](ask.md) | Ask about a piece's picture and sound from a script: the same questions, runner and record as raea ask, typed. | 2 functions, 1 value, 12 types |
<!-- generated:end -->
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index 70303b31..e09ab534 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -70,6 +70,7 @@ raea-app-engines = { path = "../../apps/engines" }
raea-app-solid = { path = "../../apps/solid" }
# raea judge: review sheets judged by clef-omni
raea-app-judge = { path = "../../apps/judge" }
+raea-app-ask = { path = "../../apps/ask" }
raea-app-media = { path = "../../apps/media" }
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
raea-app-targets = { path = "../../apps/targets" }
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 85191cf0..5f1aa4c5 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -145,7 +145,7 @@ pub fn run(args: &[String]) -> R<String> {
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE);
- let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
+ let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
@@ -279,7 +279,7 @@ pub fn run(args: &[String]) -> R<String> {
Some("gen") => return raea_app_tools::generate::generate(args),
// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())
Some(v) if SHELL.contains(&v) => return shell(args),
- _ => if let Some(r) = raea_app_solid::verb(args) { return r }, // `solid info|view FILE.ts`, `judge DIR` (apps/solid)
+ _ => if let Some(r) = raea_app_solid::verb(args) { return r }, // `solid info|view FILE.ts`, `judge DIR`, `ask FILE` (apps/solid)
}
// `master-gain BUNDLE.js DIR`: the gain and ceiling a composition's render masters its sound with, as JSON (live
// play asks this of a child process, so its second React and the whole mix never sit in the game's memory)
diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rs
index 48cf1de5..211d44df 100644
--- a/engine/cli/src/tests.rs
+++ b/engine/cli/src/tests.rs
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
- for usage in [raea_app_check::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
+ for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
diff --git a/io/clef/src/client.rs b/io/clef/src/client.rs
index 6a95af51..20700f1a 100644
--- a/io/clef/src/client.rs
+++ b/io/clef/src/client.rs
@@ -34,12 +34,21 @@ pub struct Answered {
pub pool_left: Option<f64>,
}
-/// Why a route didn't answer: `Next` means try the next one (no plan, signed out, not running, no ask scope); `Stop`
-/// means asking again elsewhere won't help (the call itself is wrong, or the pool is spent and nothing else is set).
+/// Why a route didn't answer: `Next` means try the next one (no plan, signed out, not running, no ask scope; from
+/// `route::ask`, that none did); `Stop` means asking again won't help (the call itself is wrong); `Spent` means the
+/// month's pool is used up and nothing else is set, so a batch's remaining calls wait for the pool.
#[derive(Debug, Clone, PartialEq)]
pub enum Fail {
Next(String),
Stop(String),
+ Spent(String),
+}
+
+impl std::fmt::Display for Fail {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let (Fail::Next(s) | Fail::Stop(s) | Fail::Spent(s)) = self;
+ f.write_str(s)
+ }
}
/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.
@@ -153,7 +162,7 @@ pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>,
route: route.into(),
pool_left: j["pool_left_usd"].as_f64(),
}),
- (402, Some("pool_spent")) if !own_keys => Err(Fail::Stop(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)))),
}
diff --git a/io/clef/src/lib.rs b/io/clef/src/lib.rs
index c3fd5ac4..aca51670 100644
--- a/io/clef/src/lib.rs
+++ b/io/clef/src/lib.rs
@@ -11,7 +11,7 @@ pub use client::{Answered, Call, Fail, Http, Media, Transport};
pub use route::Route;
/// One call, by the routes open on this computer.
-pub fn ask(call: &Call) -> Result<Answered, String> {
+pub fn ask(call: &Call) -> Result<Answered, Fail> {
route::ask(&Http, call, &route::open())
}
diff --git a/io/clef/src/route.rs b/io/clef/src/route.rs
index 10e36e08..4ae0382f 100644
--- a/io/clef/src/route.rs
+++ b/io/clef/src/route.rs
@@ -67,18 +67,18 @@ pub fn open() -> Vec<Route> {
pub const NONE: &str = "sign in to raea on Pro or Studio (the app), set RAEA_AGENT_KEY and RAEA_API, or add CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN to ~/.raea/env (docs/settings.md)";
-fn replay(call: &Call, file: &PathBuf) -> Result<Answered, String> {
- let all: Map<String, Value> = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?)
- .map_err(|e| format!("{}: {e}", file.display()))?;
+fn replay(call: &Call, file: &PathBuf) -> Result<Answered, Fail> {
+ let text = std::fs::read_to_string(file).map_err(|e| Fail::Stop(format!("{}: {e}", file.display())))?;
+ let all: Map<String, Value> = serde_json::from_str(&text).map_err(|e| Fail::Stop(format!("{}: {e}", file.display())))?;
let answers = call.questions.iter().filter_map(|q| all.get(&q.id).map(|a| (q.id.clone(), a.clone()))).collect();
Ok(Answered { answers, cost: 0.0, cached: false, route: Route::Replay(file.clone()).name().into(), pool_left: None })
}
/// One call answered: from the cache, else by the first route that answers. Every route's reason is kept for the
/// refusal when none does.
-pub fn ask(t: &dyn Transport, call: &Call, routes: &[Route]) -> Result<Answered, String> {
+pub fn ask(t: &dyn Transport, call: &Call, routes: &[Route]) -> Result<Answered, Fail> {
if let Some(p) = call.problem() {
- return Err(p);
+ return Err(Fail::Stop(p));
}
if let Some(Route::Replay(f)) = routes.first() {
return replay(call, f);
@@ -88,7 +88,7 @@ pub fn ask(t: &dyn Transport, call: &Call, routes: &[Route]) -> Result<Answered,
return Ok(Answered { answers, cost: 0.0, cached: true, route: "asked before (cache)".into(), pool_left: None });
}
if routes.is_empty() {
- return Err(format!("nothing to ask with: {NONE}"));
+ return Err(Fail::Next(format!("nothing to ask with: {NONE}")));
}
let own = routes.iter().any(|r| matches!(r, Route::Own { .. }));
let mut why = Vec::new();
@@ -97,16 +97,16 @@ pub fn ask(t: &dyn Transport, call: &Call, routes: &[Route]) -> Result<Answered,
Route::App(url) => raea_api(t, call, &format!("{url}/host/ask"), None, r.name(), own),
Route::Agent { api, key } => raea_api(t, call, &format!("{api}/v1/clef/ask"), Some(key), r.name(), own),
Route::Own { account, token } => workers_ai(t, call, account, token),
- Route::Replay(f) => replay(call, f).map_err(Fail::Stop),
+ Route::Replay(f) => replay(call, f),
};
match got {
Ok(a) => {
cache::put(&key, &a.answers);
return Ok(a);
}
- Err(Fail::Stop(e)) => return Err(e),
Err(Fail::Next(e)) => why.push(e),
+ Err(f) => return Err(f),
}
}
- Err(format!("nothing answered ({}): {NONE}", why.join("; ")))
+ Err(Fail::Next(format!("nothing answered ({}): {NONE}", why.join("; "))))
}
diff --git a/io/clef/src/tests.rs b/io/clef/src/tests.rs
index 40d5e867..f64e0b33 100644
--- a/io/clef/src/tests.rs
+++ b/io/clef/src/tests.rs
@@ -57,7 +57,7 @@ fn each_route_that_cant_answer_hands_on_to_the_next() {
fn a_spent_pool_stops_unless_the_person_has_their_own_keys() {
let spent = || Fake { replies: vec![("/host/ask", 402, json!({"error": "pool_spent", "message": "this month's checks are used up"}))], seen: RefCell::default() };
let e = route::ask(&spent(), &call("spent"), &routes()[..1]).unwrap_err();
- assert!(e.contains("used up"), "{e}");
+ assert!(matches!(&e, crate::Fail::Spent(m) if m.contains("used up")), "{e:?}");
let mut f = spent();
f.replies.push(("/clef-omni", 200, serde_json::from_str(ANSWER).unwrap()));
let a = route::ask(&f, &call("spent-own"), &[routes()[0].clone(), routes()[2].clone()]).unwrap();
@@ -78,9 +78,9 @@ fn the_plan_answers_with_whats_left_and_a_second_ask_costs_nothing() {
#[test]
fn with_nothing_open_it_says_how_to_get_one() {
let f = Fake { replies: vec![], seen: RefCell::default() };
- let e = route::ask(&f, &call("none"), &[]).unwrap_err();
+ let e = route::ask(&f, &call("none"), &[]).unwrap_err().to_string();
assert!(e.contains("RAEA_AGENT_KEY") && e.contains("CLOUDFLARE_API_TOKEN"), "{e}");
- let e = route::ask(&f, &call("refused"), &routes()[..1]).unwrap_err();
+ let e = route::ask(&f, &call("refused"), &routes()[..1]).unwrap_err().to_string();
assert!(e.contains("connection refused") && e.contains("Pro or Studio"), "{e}");
}
@@ -89,10 +89,10 @@ fn a_call_that_breaks_the_limits_is_refused_before_anything_is_sent() {
let f = Fake { replies: vec![], seen: RefCell::default() };
let mut c = call("limits");
c.media = Media::default();
- assert!(route::ask(&f, &c, &routes()).unwrap_err().contains("look at or listen to"));
+ assert!(route::ask(&f, &c, &routes()).unwrap_err().to_string().contains("look at or listen to"));
let mut c = call("too-many");
c.questions = (0..65).map(|i| Question::plain(&format!("q{i}"), "Is it loud?")).collect();
- assert!(route::ask(&f, &c, &routes()).unwrap_err().contains("1 to 64"));
+ assert!(route::ask(&f, &c, &routes()).unwrap_err().to_string().contains("1 to 64"));
assert!(f.seen.borrow().is_empty());
}
diff --git a/sdk/raea/src/ask.gen.ts b/sdk/raea/src/ask.gen.ts
index 479e672a..4e2fa3a9 100644
--- a/sdk/raea/src/ask.gen.ts
+++ b/sdk/raea/src/ask.gen.ts
@@ -26,7 +26,8 @@ flags?: Array<string>, sees?: Sees,
*/
hears?: boolean,
/**
- * what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform
+ * what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform; and
+ * with: it compares the file with the files set beside it, so it isn't asked without them
*/
uses?: Array<string>, when?: When,
/**
diff --git a/sdk/raea/src/ask.ts b/sdk/raea/src/ask.ts
new file mode 100644
index 00000000..db651de8
--- /dev/null
+++ b/sdk/raea/src/ask.ts
@@ -0,0 +1,151 @@
+// raea/ask: questions about a piece's picture and sound, answered by clef-omni and paid from the person's raea plan
+// (docs/ask.feature AK3). It runs `raea ask --batch - --json`, so a script, a `.ts` check, a `raea run` script and plain
+// Node all ask through the same runner as the command: every question about one clip goes in one call, the clips are
+// cut once, the calls go in parallel, and every answer is kept for calibration. Answers are advice until a question is
+// calibrated (`calibrated` on each answer).
+//
+// import { ask, askMany } from "raea/ask";
+// const { answers } = ask("out/piece.mp4", "Does the music fight the voice?");
+// const all = askMany([
+// { file: "out/a.mp4", set: "av" },
+// { file: "out/b.mp4", std: ["defect.glitch"], window: { from: 0, to: 3 } },
+// ]);
+
+import { spawnSync } from "child_process";
+import type { Question, Window } from "./ask.gen";
+
+export type * from "./ask.gen";
+export { SETS } from "./ask.gen";
+
+/** One file and what to ask of it: a line of `raea ask --batch`. */
+export interface AskEntry {
+ /** the video, sound or picture asked about */
+ file: string;
+ /** questions in your own words (yes or no) or written out */
+ questions?: (string | Question)[];
+ /** standard sets by name: rubric, av, defects, platform, decide */
+ set?: string | string[];
+ /** standard questions by id (`raea ask list` lists them) */
+ std?: string[];
+ /** the seconds to look at, for every question here (else each question's own, else the whole file) */
+ window?: Window;
+ /** files set beside it: to pick between, or a before and after */
+ with?: string[];
+ /** the project's brief (else the nearest brief.ts above the file) */
+ brief?: string;
+ /** a words file (a JSON list of the words heard), so ask knows what's said and whether anyone speaks */
+ words?: string;
+ /** whether anyone speaks in it, when no words file says */
+ voice?: boolean;
+ /** more for clef to read before the media: what raea measured, the platform */
+ state?: string;
+}
+
+/** One question's answer, or why it wasn't asked or still waits: a line of `raea ask --json`. */
+export interface Answer {
+ /** its id in the record, for `raea ask verdict` */
+ answer?: string;
+ /** the file asked about */
+ file: string;
+ /** the question's id */
+ id: string;
+ /** a hash of its words, type and options: a new wording is a new version, calibrated on its own */
+ version: string;
+ /** the window's start, in seconds */
+ from: number;
+ /** the window's end, in seconds (unset: the file's end) */
+ to?: number;
+ /** the answer in words with its probability */
+ says?: string;
+ /** yes's probability, a pick's probability, or a level */
+ value?: number;
+ /** 0 to 1, higher is likelier a problem (none for a pick) */
+ problem?: number;
+ /** the option or level chosen */
+ choice?: string;
+ /** past the question's threshold (its calibrated one, else even odds) */
+ flagged: boolean;
+ /** its labels separate well enough for its answers to be findings; until then they're advice */
+ calibrated: boolean;
+ /** why it wasn't asked (it doesn't apply to this piece, or the call failed) */
+ not_asked?: string;
+ /** why it still waits (this month's pool is spent) */
+ waits?: string;
+ /** the way it was paid: your raea plan through the app, an agent key, or your Cloudflare account */
+ route?: string;
+ /** answered from the cache, at no cost */
+ cached: boolean;
+}
+
+/** What a run came to. */
+export interface Summary {
+ /** the questions sent */
+ asked: number;
+ /** the answers read */
+ answered: number;
+ /** the calls made (with `dry`, the calls that would be) */
+ calls: number;
+ /** what the calls cost, in dollars */
+ cost: number;
+ /** with `dry`, what the calls would cost, in dollars */
+ estimate: number;
+ /** what's left of this month's pool, in dollars, when the plan paid */
+ pool_left?: number;
+ /** the questions waiting for the pool */
+ waiting: number;
+ /** the answers past their threshold */
+ flagged: number;
+ /** the calibrated answers past their threshold: findings */
+ flagged_calibrated: number;
+ /** the ways the calls were paid */
+ routes: string[];
+ /** the clips cut, each once */
+ clips: number;
+}
+
+/** A run's answers, the calls `dry` would make, and its summary. */
+export interface Asked {
+ /** every question's answer, or why it wasn't asked, in the order they came */
+ answers: Answer[];
+ /** with `dry`: each call that would be made (its state, questions, media sizes and estimate) */
+ would: unknown[];
+ /** what it came to */
+ summary: Summary;
+}
+
+/** How a run goes. */
+export interface AskOptions {
+ /** calls at once (4 unless set) */
+ jobs?: number;
+ /** cut the media and say what would be sent, spending nothing */
+ dry?: boolean;
+ /** the raea to run (RAEA_BIN, else raea on the PATH) */
+ bin?: string;
+}
+
+type Env = { process?: { env?: Record<string, string | undefined> } };
+
+/** Many files asked in one run, in parallel; throws when nothing could be asked (the error says why). */
+export function askMany(entries: AskEntry[], o: AskOptions = {}): Asked {
+ const bin = o.bin ?? (globalThis as Env).process?.env?.RAEA_BIN ?? "raea";
+ const args = ["ask", "--batch", "-", "--json", ...(o.dry ? ["--dry"] : []), ...(o.jobs ? ["--jobs", String(o.jobs)] : [])];
+ const r = spawnSync(bin, args, { input: JSON.stringify(entries), encoding: "utf8", maxBuffer: 64 << 20 });
+ if (r.error) throw new Error(`raea ask: ${r.error.message}`);
+ const out: Asked = { answers: [], would: [], summary: undefined as unknown as Summary };
+ for (const line of String(r.stdout ?? "").split("\n")) {
+ if (!line.trim().startsWith("{")) continue;
+ const j = JSON.parse(line);
+ if (j.summary) out.summary = j.summary;
+ else if (j.would) out.would.push(j.would);
+ else out.answers.push(j as Answer);
+ }
+ if (r.status !== 0 || !out.summary) throw new Error(String(r.stderr ?? "").trim() || `raea ask exited ${r.status}`);
+ return out;
+}
+
+/** Questions about one file: your own words (yes or no), written-out questions, or with `std`/`set` the standard ones. */
+export function ask(file: string, question: string | Question | (string | Question)[] = [], more: Omit<AskEntry, "file" | "questions"> & AskOptions = {}): Asked {
+ const { jobs, dry, bin, ...entry } = more;
+ const questions = Array.isArray(question) ? question : [question];
+ return askMany([{ file, questions, ...entry }], { jobs, dry, bin });
+}
diff --git a/tools/layers.toml b/tools/layers.toml
index c175ff27..f33ae8d8 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -194,6 +194,7 @@ raea-app-motion = "apps"
raea-app-engines = "apps"
raea-app-interchange = "apps"
raea-app-judge = "apps"
+raea-app-ask = "apps"
raea-app-solid = "apps"
raea-app-media = "apps"
raea-app-targets = "apps"
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index 4ec21161..813e920e 100644
--- a/tools/manual-ref/cli.ts
+++ b/tools/manual-ref/cli.ts
@@ -31,7 +31,7 @@ const GROUPS: [string, string, string[]][] = [
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],
["Generate and 3D tools", "Generated media, physics and weathering bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "wear", "clothes", "motion", "blender", "godot"]],
- ["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "context", "notes", "show", "skill", "skills", "setup", "bug"]],
+ ["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "context", "notes", "show", "skill", "skills", "setup", "bug", "ask"]],
]
/** A verb's page: VERB.md, but index.md is this section's own page, so raea index's is indexer.md */
const pageOf = (verb: string) => (verb === "index" ? "indexer.md" : `${verb}.md`)
diff --git a/tools/manual-ref/sdk.ts b/tools/manual-ref/sdk.ts
index c7143e51..6bea86ee 100644
--- a/tools/manual-ref/sdk.ts
+++ b/tools/manual-ref/sdk.ts
@@ -27,7 +27,7 @@ const GROUPS: [string, string, string[]][] = [
["Video, sound and text", "Footage, pictures, sound, words and colour, and the timeline they are edited on.", ["video", "audio", "text", "image", "asset", "color", "editor"]],
["3D", "Bevy's 3D: cameras, lights, materials, meshes and the frame after it's drawn.", ["3d", "camera", "light", "pbr", "mesh", "transform", "post_process", "picking", "gizmos"]],
["2D and UI", "Sprites and flat shapes, bevy_ui and Bevy's widgets.", ["sprite", "ui", "feathers"]],
- ["Tools", "Checks, lints and a headless App you can drive.", ["check", "fingerprint", "dev_tools", "remote"]],
+ ["Tools", "Checks, lints and a headless App you can drive.", ["check", "fingerprint", "dev_tools", "remote", "ask"]],
]
const groupAt = new Map(GROUPS.flatMap(([, , ps], g) => ps.map((p, i) => [p, g * 20 + i + 2] as const)))
const BEGIN = "<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->"