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.

AK6-AK7: raea ask learns from the person: verdicts, notes and approvals label it, calibrate and try

shinyobjectz0daaeb5b38b9
diff --git a/Cargo.lock b/Cargo.lock
index 61149fb4..8076b221 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13761,6 +13761,8 @@ dependencies = [
"raea-io-assets",
"raea-io-clef",
"raea-io-home",
+ "raea-io-trace",
+ "raea-sys-fingerprint",
"serde",
"serde_json",
"sha2 0.10.9",
diff --git a/apps/ask/Cargo.toml b/apps/ask/Cargo.toml
index e88f68a2..55a4a746 100644
--- a/apps/ask/Cargo.toml
+++ b/apps/ask/Cargo.toml
@@ -11,6 +11,10 @@ description = "raea ask: questions about a piece's picture and sound, prepared f
raea-core-ask = { path = "../../core/ask" }
raea-io-clef = { path = "../../io/clef" }
raea-io-home = { path = "../../io/home" }
+# the fingerprint's AUC, quantile and gates, so a question is calibrated as an axis is (AK7)
+raea-sys-fingerprint = { path = "../../systems/fingerprint" }
+# today's date for a calibration
+raea-io-trace = { path = "../../io/trace" }
dunce = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/apps/ask/src/calibrate.rs b/apps/ask/src/calibrate.rs
new file mode 100644
index 00000000..c19cc6d4
--- /dev/null
+++ b/apps/ask/src/calibrate.rs
@@ -0,0 +1,214 @@
+//! Calibration (docs/ask.feature AK7): a question's answers held to the person's labels (labels.rs), per version of its
+//! words. Clef isn't trained on the labels, so its AUC on them is held out already; the one thing fitted is the
+//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
+//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
+//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
+//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
+//! sets both AUCs side by side.
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use raea_core_ask::{Calibration, Question};
+use raea_io_clef::Media;
+use raea_sys_fingerprint::head::{auc, quantile};
+use raea_sys_fingerprint::train::{GATE_AUC, GATE_LABELS, GATE_PROJECTS};
+use serde::Serialize;
+use serde_json::Value;
+
+use crate::labels::{self, Label};
+use crate::prepare::Piece;
+use crate::record;
+use crate::runner::{self, Event, Group, Kept, Opts, Summary};
+
+pub const FILE: &str = "calibration.json";
+/// An AUC under this after twice the gate's labels: the words don't separate the problem.
+const SEPARATES: f64 = 0.6;
+
+/// The person's calibrations that passed the gates, by question version.
+pub fn local() -> BTreeMap<String, Calibration> {
+ std::fs::read_to_string(record::dir().join(FILE)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
+}
+
+/// A question with the person's calibration in place of raea's, when it has one.
+pub fn apply(q: &mut Question, local: &BTreeMap<String, Calibration>) {
+ if let Some(c) = local.get(&q.version()) {
+ q.calibration = Some(c.clone());
+ }
+}
+
+/// A label the answers missed: a problem it scored low, or clean work it scored high.
+#[derive(Debug, Clone, Serialize)]
+pub struct Miss {
+ pub file: String,
+ pub span: String,
+ pub problem: f64,
+ pub bad: bool,
+ pub note: Option<String>,
+}
+
+/// One version's standing.
+#[derive(Debug, Clone, Serialize)]
+pub struct Standing {
+ pub id: String,
+ pub version: String,
+ pub ask: String,
+ pub problems: usize,
+ pub clean: usize,
+ pub projects: usize,
+ pub auc: Option<f64>,
+ pub threshold: Option<f64>,
+ /// calibrated, advice or "doesn't separate"
+ pub state: String,
+ pub why: String,
+ pub misses: Vec<Miss>,
+ /// other eyes' labels on its clips, kept and not counted
+ pub others: usize,
+}
+
+/// Each labelled clip's latest problem score for one version, beside its label.
+fn scored<'a>(version: &str, standing: &HashMap<(String, String), &'a Label>, calls: &HashMap<String, Value>) -> Vec<(f64, &'a Label)> {
+ let mut latest: HashMap<String, (f64, &Label)> = HashMap::new();
+ for a in record::rows("answers.jsonl").iter().filter(|a| a["version"] == version) {
+ let (Some(p), Some(call)) = (a["problem"].as_f64(), calls.get(a["call"].as_str().unwrap_or_default())) else { continue };
+ let key = (a["question"].as_str().unwrap_or_default().to_string(), labels::media_key(call));
+ if let Some(l) = standing.get(&key) {
+ latest.insert(key.1, (p, l));
+ }
+ }
+ latest.into_values().collect()
+}
+
+/// One version held to its labels.
+pub fn standing_of(q: &Question, all: &[Label], calls: &HashMap<String, Value>) -> Standing {
+ let standing = labels::standing(all);
+ let s = scored(&q.version(), &standing, calls);
+ let score = |bad: bool| s.iter().filter(|(_, l)| l.bad == bad).map(|(p, _)| *p as f32).collect::<Vec<f32>>();
+ let (pos, neg) = (score(true), score(false));
+ let projects = s.iter().map(|(_, l)| l.project.as_str()).collect::<BTreeSet<_>>().len();
+ let a = Some(auc(&pos, &neg)).filter(|a| a.is_finite());
+ let threshold = Some(quantile(&neg, 0.9) as f64).filter(|t| t.is_finite());
+ let mut why = Vec::new();
+ if pos.len() < GATE_LABELS || neg.len() < GATE_LABELS {
+ why.push(format!("{} problem and {} clean labels (needs {GATE_LABELS} of each)", pos.len(), neg.len()));
+ }
+ if projects < GATE_PROJECTS {
+ why.push(format!("labels from {projects} projects (needs {GATE_PROJECTS})"));
+ }
+ match a {
+ Some(v) if v < GATE_AUC => why.push(format!("AUC {v:.2} (needs {GATE_AUC})")),
+ None => why.push("no AUC yet: it needs labels of both kinds".into()),
+ _ => {}
+ }
+ let stuck = s.len() >= 2 * GATE_LABELS && a.is_some_and(|v| v < SEPARATES);
+ let mut misses: Vec<Miss> = Vec::new();
+ if stuck {
+ let mut by: Vec<&(f64, &Label)> = s.iter().collect();
+ by.sort_by(|x, y| x.0.total_cmp(&y.0));
+ let low = by.iter().filter(|(_, l)| l.bad).take(5);
+ let high = by.iter().rev().filter(|(_, l)| !l.bad).take(5);
+ misses = low.chain(high).map(|(p, l)| Miss { file: l.file.clone(), span: labels::span(l.from, l.to), problem: *p, bad: l.bad, note: l.note.clone() }).collect();
+ }
+ let others = all.iter().filter(|l| !l.counted() && l.question == q.id).count();
+ let state = match (why.is_empty(), stuck) {
+ (true, _) => "calibrated",
+ (false, true) => "doesn't separate",
+ (false, false) => "advice",
+ };
+ let why = if why.is_empty() { format!("earned: {} labels from {projects} projects, flags past {:.2}", s.len(), threshold.unwrap_or(0.0)) } else { why.join("; ") };
+ Standing { id: q.id.clone(), version: q.version(), ask: q.ask.clone(), problems: pos.len(), clean: neg.len(), projects, auc: a, threshold, state: state.into(), why, misses, others }
+}
+
+/// Every labelled question's versions as the record kept them (or only `id`'s), newest wording last.
+fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
+ let labelled: BTreeSet<&str> = all.iter().map(|l| l.question.as_str()).collect();
+ let mut seen = BTreeSet::new();
+ let mut out = Vec::new();
+ for a in record::rows("answers.jsonl") {
+ let id = a["question"].as_str().unwrap_or_default();
+ if only.is_some_and(|o| o != id) || !labelled.contains(id) || !seen.insert(a["version"].as_str().unwrap_or_default().to_string()) {
+ continue;
+ }
+ out.push(labels::question_of(&a));
+ }
+ out
+}
+
+/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
+/// pass are kept as the person's calibration; one that no longer passes loses it.
+pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
+ let feed = labels::from_feed()?;
+ let (all, calls) = (labels::all(), labels::calls());
+ let out: Vec<Standing> = versions(only, &all).iter().map(|q| standing_of(q, &all, &calls)).collect();
+ let mut keep = local();
+ for s in &out {
+ keep.remove(&s.version);
+ if s.state == "calibrated" {
+ let n = (s.problems + s.clean) as u32;
+ let c = Calibration { auc: s.auc.unwrap_or(0.0), n, positives: s.problems as u32, threshold: s.threshold, date: today(), by: "you".into() };
+ keep.insert(s.version.clone(), c);
+ }
+ }
+ record::write_whole(FILE, &serde_json::to_string_pretty(&keep).map_err(|e| e.to_string())?)?;
+ Ok((out, feed))
+}
+
+/// YYYY-MM-DD, UTC.
+fn today() -> String {
+ raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
+}
+
+/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
+pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
+ let all = labels::all();
+ let standing = labels::standing(&all);
+ let rows = record::rows("answers.jsonl");
+ let old = rows.iter().rev().find(|a| a["question"] == like).map(labels::question_of).ok_or_else(|| format!("ask try: no answers to {like} in the record"))?;
+ let new = Question { ask: words.to_string(), calibration: None, ..old.clone() };
+ let calls = labels::calls();
+ let mut groups: Vec<Group> = Vec::new();
+ let mut sent = BTreeSet::new();
+ for call in calls.values().filter(|c| standing.contains_key(&(like.to_string(), labels::media_key(c)))) {
+ let names: Vec<&str> = call["media"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
+ let Some(kept) = media(&names) else { continue };
+ if !sent.insert(labels::media_key(call)) {
+ continue;
+ }
+ let piece = Arc::new(Piece { file: PathBuf::from(call["file"].as_str().unwrap_or_default()), project: call["project"].as_str().map(PathBuf::from), ..Default::default() });
+ let (from, to) = (call["from"].as_f64().unwrap_or(0.0), call["to"].as_f64());
+ let seconds = to.map_or(60.0, |t| t - from);
+ let kept = Kept { video_seconds: if kept.videos.is_empty() { 0.0 } else { seconds }, sound_seconds: if kept.sounds.is_empty() { 0.0 } else { seconds }, media: kept, state: call["state"].as_str().unwrap_or_default().into() };
+ groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
+ }
+ if groups.is_empty() {
+ return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
+ }
+ Ok((old, new, groups))
+}
+
+/// A call's clips from the kept media, in the kinds they were sent as; None when one has been pruned.
+fn media(names: &[&str]) -> Option<Media> {
+ let mut m = Media::default();
+ for n in names {
+ let bytes = record::media(n)?;
+ match n.rsplit('.').next() {
+ Some("mp4") => m.videos.push(bytes),
+ Some("mp3") => m.sounds.push(bytes),
+ _ => m.stills.push(bytes),
+ }
+ }
+ Some(m)
+}
+
+/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
+/// the same labels.
+pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
+ let (old, new, groups) = try_groups(like, words)?;
+ let sum = runner::run_groups(groups, Vec::new(), o, out);
+ if o.dry {
+ return Ok((sum, None));
+ }
+ let (all, calls) = (labels::all(), labels::calls());
+ Ok((sum, Some((standing_of(&old, &all, &calls), standing_of(&new, &all, &calls)))))
+}
diff --git a/apps/ask/src/labels.rs b/apps/ask/src/labels.rs
new file mode 100644
index 00000000..179a5f6c
--- /dev/null
+++ b/apps/ask/src/labels.rs
@@ -0,0 +1,236 @@
+//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
+//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
+//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
+//! labels, which is what lets `raea ask try` measure new words.
+//!
+//! Where labels come from:
+//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
+//! a level). Theirs counts first.
+//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
+//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
+//! with no such note is a no. Read again by every `raea ask calibrate`.
+//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
+//! fingerprint keeps another eye's readings (FP6d).
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use raea_core_ask::{Kind, Question};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::record;
+
+pub const FILE: &str = "labels.jsonl";
+
+/// A note pinned at t covers 1.5 s before it to 0.5 s after (the fingerprint's span).
+const BEFORE: f64 = 1.5;
+const AFTER: f64 = 0.5;
+
+/// Whether a question's problem is there in one call's clips, and who said so.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Label {
+ pub question: String,
+ /// the clips the call sent, by hash
+ pub media: String,
+ pub bad: bool,
+ /// "verdict" (the person's), "note" or "approval" (read from the feed), or "eye:NAME" (kept, never counted)
+ pub source: String,
+ pub project: String,
+ pub file: String,
+ pub from: f64,
+ pub to: Option<f64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+ pub at: String,
+}
+
+impl Label {
+ /// The person's own: a verdict, a note or an approval.
+ pub fn counted(&self) -> bool {
+ self.rank() > 0
+ }
+ fn rank(&self) -> u8 {
+ match self.source.as_str() {
+ "verdict" => 3,
+ "note" => 2,
+ "approval" => 1,
+ _ => 0,
+ }
+ }
+}
+
+/// The clips a call sent, as one key.
+pub fn media_key(call: &Value) -> String {
+ let mut m: Vec<&str> = call["media"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
+ m.sort_unstable();
+ m.join("+")
+}
+
+/// The feed a call's render was posted to: its project's, else the nearest one above its file.
+fn feed_of(call: &Value) -> Option<PathBuf> {
+ let file = Path::new(call["file"].as_str().unwrap_or_default());
+ call["project"].as_str().map(Path::new).into_iter().chain(file.ancestors()).map(|d| d.join(".raea/feed")).find(|d| d.is_dir())
+}
+
+/// A call's project: the folder holding its brief, else the folder holding the feed it was posted to, else its file's.
+pub fn project_of(call: &Value) -> String {
+ if let Some(p) = call["project"].as_str() {
+ return p.to_string();
+ }
+ let home = feed_of(call).and_then(|f| f.parent()?.parent().map(Path::to_path_buf));
+ let file = Path::new(call["file"].as_str().unwrap_or_default());
+ home.as_deref().or(file.parent()).map(|p| p.display().to_string()).unwrap_or_default()
+}
+
+pub fn all() -> Vec<Label> {
+ record::rows(FILE).into_iter().filter_map(|v| serde_json::from_value(v).ok()).collect()
+}
+
+fn write(labels: &[Label]) -> Result<(), String> {
+ record::write_whole(FILE, &labels.iter().filter_map(|l| serde_json::to_string(l).ok()).map(|l| l + "\n").collect::<String>())
+}
+
+/// The label that stands for each question and clips: the person's verdict, else a note, else an approval.
+pub fn standing(labels: &[Label]) -> HashMap<(String, String), &Label> {
+ let mut out: HashMap<(String, String), &Label> = HashMap::new();
+ for l in labels.iter().filter(|l| l.counted()) {
+ let key = (l.question.clone(), l.media.clone());
+ if out.get(&key).is_none_or(|was| l.rank() >= was.rank()) {
+ out.insert(key, l);
+ }
+ }
+ out
+}
+
+/// A question as its answer kept it (the whole question, else its words).
+pub fn question_of(answer: &Value) -> Question {
+ serde_json::from_value(answer["q"].clone()).unwrap_or_else(|_| Question::plain(answer["question"].as_str().unwrap_or("q"), answer["ask"].as_str().unwrap_or_default()))
+}
+
+/// Whether the answer the person gives means the problem is there: yes's flagged answer (yes, or no for a question
+/// flagged on no), a flagged option, or a grade or rate in its lower half.
+pub fn means_problem(q: &Question, said: &str) -> Result<bool, String> {
+ let said = said.trim().to_lowercase();
+ let levels = q.levels();
+ if q.kind == Kind::Yes {
+ return match said.as_str() {
+ "yes" | "no" => Ok((said == "yes") != q.flags.first().is_some_and(|f| f == "no")),
+ _ => Err(format!("{}: answer yes or no", q.id)),
+ };
+ }
+ if q.kind == Kind::Choose && q.flags.is_empty() {
+ return Err(format!("{} picks without a wrong answer, so it isn't calibrated", q.id));
+ }
+ let Some(i) = levels.iter().position(|l| l.to_lowercase() == said) else { return Err(format!("{}: answer one of {}", q.id, levels.join(", "))) };
+ Ok(match q.kind {
+ Kind::Choose => q.flags.iter().any(|f| f.to_lowercase() == said),
+ _ => (i as f64) < (levels.len().max(2) - 1) as f64 / 2.0,
+ })
+}
+
+/// Every call in the record, by id.
+pub fn calls() -> HashMap<String, Value> {
+ record::rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c))).collect()
+}
+
+fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -> Label {
+ Label {
+ question: q.to_string(),
+ media: media_key(call),
+ bad,
+ source: source.into(),
+ project: project_of(call),
+ file: call["file"].as_str().unwrap_or_default().into(),
+ from: call["from"].as_f64().unwrap_or(0.0),
+ to: call["to"].as_f64(),
+ note,
+ at: record::now(),
+ }
+}
+
+/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
+/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
+pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
+ let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
+ let call = calls().remove(row["call"].as_str().unwrap_or_default()).ok_or_else(|| format!("ask verdict: answer {answer}'s call isn't in the record"))?;
+ let q = question_of(&row);
+ let bad = means_problem(&q, said)?;
+ let source = eye.map_or_else(|| "verdict".to_string(), |e| format!("eye:{e}"));
+ let new = label(&q.id, &call, bad, &source, None);
+ let mut labels = all();
+ labels.retain(|l| !(l.question == new.question && l.media == new.media && l.source == new.source));
+ let line = format!("{}: {} on {} ({}){}", q.id, if bad { "the problem is there" } else { "no problem" }, new.file, span(new.from, new.to), if eye.is_some() { format!(", kept as {source} and not counted") } else { String::new() });
+ labels.push(new);
+ write(&labels)?;
+ Ok(line)
+}
+
+pub fn span(from: f64, to: Option<f64>) -> String {
+ match to {
+ Some(t) => format!("{from:.1}-{t:.1} s"),
+ None if from > 0.0 => format!("from {from:.1} s"),
+ None => "the whole file".into(),
+ }
+}
+
+/// One post of a feed: whether it's approved, its person's notes (pinned second or none, words), and its files.
+struct Post {
+ done: bool,
+ notes: Vec<(Option<f64>, String)>,
+ files: Vec<PathBuf>,
+}
+
+fn posts(feed: &Path) -> Vec<Post> {
+ let project = feed.parent().and_then(Path::parent).unwrap_or(feed);
+ let lib = raea_io_home::user_home().unwrap_or_default().join(".raea/feed/media");
+ let mut out = Vec::new();
+ for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
+ let Some(p) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
+ let notes = p["notes"].as_array().into_iter().flatten().filter(|n| n["author"]["kind"] == "person").filter_map(|n| Some((n["pin"]["t"].as_f64(), n["text"].as_str()?.to_lowercase()))).collect();
+ let files = p["media"].as_array().into_iter().flatten().filter_map(|m| m["path"].as_str()).filter_map(|m| [lib.join(m), project.join(m)].into_iter().find(|f| f.is_file())).collect();
+ out.push(Post { done: p["status"] == "done", notes, files });
+ }
+ out
+}
+
+/// Labels read again from the person's notes and approvals, for every recorded answer whose question has label words.
+/// The feed's labels replace the last ones read; verdicts and other eyes' stay. Says how many of each it found.
+pub fn from_feed() -> Result<(usize, usize), String> {
+ let calls = calls();
+ let mut feeds: HashMap<PathBuf, Vec<Post>> = HashMap::new();
+ let mut idents: HashMap<PathBuf, Option<String>> = HashMap::new();
+ let mut found: HashMap<(String, String), Label> = HashMap::new();
+ for row in record::rows("answers.jsonl") {
+ let q = question_of(&row);
+ let Some(call) = calls.get(row["call"].as_str().unwrap_or_default()) else { continue };
+ let (Some(ident), false) = (call["ident"].as_str(), q.label_words.is_empty()) else { continue };
+ let Some(dir) = feed_of(call) else { continue };
+ let len = record::ident_len(ident);
+ let same = |f: &PathBuf, idents: &mut HashMap<PathBuf, Option<String>>| {
+ std::fs::metadata(f).is_ok_and(|m| Some(m.len()) == len) && idents.entry(f.clone()).or_insert_with(|| record::ident(f)).as_deref() == Some(ident)
+ };
+ let (from, to) = (call["from"].as_f64().unwrap_or(0.0), call["to"].as_f64().unwrap_or(f64::INFINITY));
+ let words: Vec<String> = q.label_words.iter().map(|w| w.to_lowercase()).collect();
+ for post in feeds.entry(dir.clone()).or_insert_with(|| posts(&dir)).iter().filter(|p| p.files.iter().any(|f| same(f, &mut idents))) {
+ let inside = |t: &Option<f64>| t.is_none_or(|t| t - BEFORE < to && t + AFTER > from);
+ let seen = post.notes.iter().find(|(t, text)| inside(t) && words.iter().any(|w| text.contains(w.as_str())));
+ let l = match (seen, post.done) {
+ (Some((_, text)), _) => label(&q.id, call, true, "note", Some(text.clone())),
+ (None, true) => label(&q.id, call, false, "approval", None),
+ (None, false) => continue,
+ };
+ let key = (l.question.clone(), l.media.clone());
+ if found.get(&key).is_none_or(|was| l.rank() > was.rank()) {
+ found.insert(key, l);
+ }
+ }
+ }
+ let mut labels = all();
+ labels.retain(|l| !matches!(l.source.as_str(), "note" | "approval"));
+ let yes = found.values().filter(|l| l.bad).count();
+ let no = found.len() - yes;
+ labels.extend(found.into_values());
+ write(&labels)?;
+ Ok((yes, no))
+}
diff --git a/apps/ask/src/labels_tests.rs b/apps/ask/src/labels_tests.rs
new file mode 100644
index 00000000..986b32e7
--- /dev/null
+++ b/apps/ask/src/labels_tests.rs
@@ -0,0 +1,132 @@
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+
+use raea_core_ask::{Kind, Question, Reading};
+use raea_io_clef::{Answered, Call, Fail};
+use serde_json::json;
+
+use crate::labels::{self, means_problem};
+use crate::prepare::Piece;
+use crate::runner::{self, Entry, Opts};
+use crate::{calibrate, record};
+
+/// The labels and calibration files are rewritten whole: one test at a time.
+static LOCK: Mutex<()> = Mutex::new(());
+
+fn reading(p: f64) -> Reading {
+ Reading { value: p, problem: Some(p), choice: None, says: format!("{p:.2}") }
+}
+
+fn question(id: &str, words: &[&str]) -> Question {
+ let mut q = Question::plain(id, &format!("Is there a problem the {id} test names?"));
+ q.label_words = words.iter().map(|w| w.to_string()).collect();
+ q
+}
+
+/// A call and its answer kept, as the runner keeps them; the answer's id.
+fn asked(file: &Path, project: &str, clip: &str, q: &Question, p: f64) -> String {
+ let call = record::call(&file.display().to_string(), Some(project), 0.0, Some(5.0), "a test", &[clip.to_string()], "a test", 0.0, false);
+ record::answer(&call, &file.display().to_string(), q, &reading(p), p >= 0.5)
+}
+
+fn write(p: &Path, bytes: &[u8]) {
+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+ std::fs::write(p, bytes).unwrap();
+}
+
+#[test]
+fn a_persons_note_on_the_posted_render_labels_it_and_an_approval_labels_it_clean() {
+ crate::tests::setup();
+ let _one = LOCK.lock().unwrap();
+ let proj = std::env::temp_dir().join(format!("raea-ask-notes-{}", std::process::id()));
+ let (a, b, other) = (proj.join("out/a.mp4"), proj.join("out/b.mp4"), proj.join("old/a.mp4"));
+ write(&a, b"render one");
+ write(&b, b"render two");
+ write(&other, b"another render, the same name");
+ let post = |media: &str, status: &str, notes: serde_json::Value| json!({"media": [{"kind": "video", "path": media}], "status": status, "notes": notes});
+ let person = |text: &str, t: Option<f64>| json!({"author": {"kind": "person", "name": "me"}, "text": text, "pin": t.map(|t| json!({"t": t}))});
+ write(&proj.join(".raea/feed/1.json"), post("out/a.mp4", "seen", json!([person("The caption runs OVER HER FACE here", Some(2.0))])).to_string().as_bytes());
+ let agent = json!({"author": {"kind": "agent"}, "text": "over her face"});
+ write(&proj.join(".raea/feed/2.json"), post("out/b.mp4", "done", json!([agent, person("lovely", None)])).to_string().as_bytes());
+ let q = question("notes.face", &["over her face"]);
+ let project = proj.display().to_string();
+ asked(&a, &project, "na.mp4", &q, 0.7);
+ asked(&b, &project, "nb.mp4", &q, 0.2);
+ asked(&other, &project, "nc.mp4", &q, 0.6);
+ assert_eq!(labels::from_feed().unwrap(), (1, 1));
+ let mine: Vec<_> = labels::all().into_iter().filter(|l| l.question == "notes.face").collect();
+ let on = |clip: &str| mine.iter().find(|l| l.media == clip).unwrap_or_else(|| panic!("{clip}: {mine:?}"));
+ assert!(on("na.mp4").bad && on("na.mp4").source == "note" && on("na.mp4").note.as_deref().is_some_and(|n| n.contains("over her face")));
+ assert!(!on("nb.mp4").bad && on("nb.mp4").source == "approval", "an agent's note isn't the person's");
+ assert!(!mine.iter().any(|l| l.media == "nc.mp4"), "another render with the same name isn't the one posted");
+}
+
+#[test]
+fn a_verdict_reads_in_the_questions_terms_and_another_eyes_isnt_counted() {
+ crate::tests::setup();
+ let _one = LOCK.lock().unwrap();
+ let mut q = question("verdict.logo", &[]);
+ assert!(means_problem(&q, "Yes").unwrap() && !means_problem(&q, "no").unwrap());
+ q.flags = vec!["no".into()];
+ assert!(means_problem(&q, "no").unwrap(), "a question flagged on no: no is the problem");
+ let mut g = q.clone();
+ g.kind = Kind::Grade;
+ assert!(means_problem(&g, "weak").unwrap() && !means_problem(&g, "acceptable").unwrap());
+ g.kind = Kind::Choose;
+ g.options = vec!["first".into(), "second".into()];
+ g.flags = vec![];
+ assert!(means_problem(&g, "first").is_err(), "a pick has no wrong answer");
+ let file = std::env::temp_dir().join("raea-ask-verdict.mp4");
+ let id = asked(&file, "p", "v1.mp4", &q, 0.3);
+ labels::verdict(&id, "no", Some("agent")).unwrap();
+ let said = labels::verdict(&id, "no", None).unwrap();
+ assert!(said.contains("the problem is there"), "{said}");
+ let all = labels::all();
+ let standing = labels::standing(&all);
+ let l = standing.get(&("verdict.logo".to_string(), "v1.mp4".to_string())).unwrap();
+ assert!(l.bad && l.source == "verdict");
+ assert!(all.iter().any(|l| l.source == "eye:agent" && !l.counted()));
+}
+
+/// clef as a fake: yes to anything sent a clip whose bytes start "bad".
+fn sees_bad(call: &Call) -> Result<Answered, Fail> {
+ let p = if call.media.videos.iter().any(|v| v.starts_with(b"bad")) { 0.9 } else { 0.1 };
+ let answers = call.questions.iter().map(|q| (q.id.clone(), json!({"noul": p}))).collect();
+ Ok(Answered { answers, cost: 0.001, cached: false, route: "a test".into(), pool_left: None })
+}
+
+#[test]
+fn labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on_the_same_clips() {
+ crate::tests::setup();
+ let _one = LOCK.lock().unwrap();
+ let (good, flat) = (question("cal.good", &[]), question("cal.flat", &[]));
+ let file = PathBuf::from("/nowhere/cal.mp4");
+ for i in 0..36 {
+ let bad = i % 2 == 0;
+ let clip = record::keep_media(format!("{}{i}", if bad { "bad" } else { "ok" }).as_bytes(), "mp4");
+ let project = format!("p{}", i % 3);
+ let call = record::call(&file.display().to_string(), Some(&project), 0.0, Some(3.0), "a test", &[clip], "a test", 0.0, false);
+ let (p, word) = if bad { (0.6 + i as f64 / 1000.0, "yes") } else { (0.3 + i as f64 / 1000.0, "no") };
+ for (q, p) in [(&good, p), (&flat, 0.5)] {
+ let id = record::answer(&call, &file.display().to_string(), q, &reading(p), false);
+ labels::verdict(&id, word, None).unwrap();
+ }
+ }
+ let (all, _) = calibrate::calibrate(None).unwrap();
+ let of = |id: &str| all.iter().find(|s| s.id == id).unwrap_or_else(|| panic!("{id}: {all:?}"));
+ let g = of("cal.good");
+ assert_eq!((g.state.as_str(), g.problems, g.clean, g.projects, g.auc), ("calibrated", 18, 18, 3, Some(1.0)), "{g:?}");
+ let f = of("cal.flat");
+ assert_eq!(f.state, "doesn't separate", "{f:?}");
+ assert!(!f.misses.is_empty() && f.auc == Some(0.5));
+ // the person's calibration goes out with the question from now on
+ let piece = Arc::new(Piece { file: file.clone(), ..Default::default() });
+ let (groups, _) = runner::plan(&[Entry { piece, window: None, questions: vec![good.clone()], dropped: vec![], with: vec![] }]);
+ let sent = &groups[0].questions[0];
+ assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
+ // new words for the flat question, asked of its labelled clips
+ let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad }, &mut |_| {}).unwrap();
+ let (old, new) = both.unwrap();
+ assert_eq!(sum.calls, 36);
+ assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
+}
diff --git a/apps/ask/src/lib.rs b/apps/ask/src/lib.rs
index 3cd85e82..d3140de0 100644
--- a/apps/ask/src/lib.rs
+++ b/apps/ask/src/lib.rs
@@ -1,8 +1,11 @@
//! `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.
+//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
+//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
+//! fingerprint's double-check go through the same runner.
+pub mod calibrate;
+pub mod labels;
pub mod prepare;
pub mod record;
pub mod runner;
@@ -12,3 +15,5 @@ pub use verbs::{USAGE, cli};
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod labels_tests;
diff --git a/apps/ask/src/record.rs b/apps/ask/src/record.rs
index be274d41..6499f73d 100644
--- a/apps/ask/src/record.rs
+++ b/apps/ask/src/record.rs
@@ -1,10 +1,13 @@
//! 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.
+//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
+//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
+//! question, so a verdict reads in its terms and `raea ask try` can reword it.
use std::io::Write as _;
-use std::path::PathBuf;
+use std::io::{Read as _, Seek as _, SeekFrom};
+use std::path::{Path, PathBuf};
use raea_core_ask::{Question, Reading};
use serde_json::{Value, json};
@@ -26,7 +29,7 @@ pub fn new_id(prefix: &str) -> String {
format!("{prefix}-{:012x}", h & 0xffff_ffff_ffff)
}
-fn now() -> String {
+pub 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()
}
@@ -36,15 +39,55 @@ fn append(file: &str, row: &Value) {
if std::fs::create_dir_all(&d).is_err() {
return;
}
+ // one write a row: several runs (a script's, two at once) append to the same file, and a row written in pieces
+ // could be split by another's
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(d.join(file)) {
- let _ = writeln!(f, "{row}");
+ let _ = f.write_all(format!("{row}\n").as_bytes());
}
}
+fn hex(digest: &[u8]) -> String {
+ digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
+}
+
+/// What a file is, cheaply: its size and a hash of its first and last MB. A render is known again by its copy in the
+/// feed, and a later render to the same path isn't taken for it.
+pub fn ident(path: &Path) -> Option<String> {
+ const MB: u64 = 1 << 20;
+ let mut f = std::fs::File::open(path).ok()?;
+ let len = f.metadata().ok()?.len();
+ let mut h = Sha256::new();
+ let mut part = vec![0u8; len.min(MB) as usize];
+ f.read_exact(&mut part).ok()?;
+ h.update(&part);
+ if len > 2 * MB {
+ f.seek(SeekFrom::Start(len - MB)).ok()?;
+ f.read_exact(&mut part).ok()?;
+ h.update(&part);
+ }
+ Some(format!("{len}-{}", hex(&h.finalize())))
+}
+
+/// The size an ident names, to pass over files that can't be it without reading them.
+pub fn ident_len(ident: &str) -> Option<u64> {
+ ident.split_once('-')?.0.parse().ok()
+}
+
+/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
+pub fn write_whole(file: &str, text: &str) -> Result<(), String> {
+ let d = dir();
+ let tmp = d.join(format!("{file}.{}.tmp", std::process::id()));
+ let put = || -> std::io::Result<()> {
+ std::fs::create_dir_all(&d)?;
+ std::fs::write(&tmp, text)?;
+ std::fs::rename(&tmp, d.join(file))
+ };
+ put().map_err(|e| format!("{}: {e}", d.display()))
+}
+
/// 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 name = format!("{}.{ext}", hex(&Sha256::digest(bytes)));
let d = dir().join("media");
let p = d.join(&name);
if !p.is_file() && std::fs::create_dir_all(&d).is_ok() {
@@ -82,16 +125,22 @@ pub fn prune(cap: u64) {
#[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}));
+ let row = json!({
+ "id": id, "at": now(), "file": file, "ident": ident(Path::new(file)), "project": project, "from": from, "to": to, "state": state,
+ "media": media, "route": route, "cost": cost, "cached": cached,
+ });
+ append("calls.jsonl", &row);
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 whole = serde_json::to_value(Question { calibration: None, ..q.clone() }).unwrap_or_default();
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(),
+ "q": whole,
});
append("answers.jsonl", &row);
id
diff --git a/apps/ask/src/runner.rs b/apps/ask/src/runner.rs
index 4dfa4bff..66ac870e 100644
--- a/apps/ask/src/runner.rs
+++ b/apps/ask/src/runner.rs
@@ -2,7 +2,9 @@
//! 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.
+//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
+//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
+//! person's own calibration when it has earned one (calibrate.rs).
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
@@ -15,7 +17,7 @@ use serde::Serialize;
use serde_json::{Value, json};
use crate::prepare::{self, Piece, VOICE};
-use crate::record;
+use crate::{calibrate, 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).
@@ -36,6 +38,16 @@ pub struct Group {
pub hears: bool,
pub with: Vec<PathBuf>,
pub questions: Vec<Question>,
+ /// clips kept from an earlier call, sent again in place of cutting the file
+ pub kept: Option<Arc<Kept>>,
+}
+
+/// An earlier call's clips and state, and their seconds of video and sound (for the estimate).
+pub struct Kept {
+ pub media: Media,
+ pub state: String,
+ pub video_seconds: f64,
+ pub sound_seconds: f64,
}
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
@@ -111,6 +123,7 @@ fn picks(p: Picks, files: usize) -> Vec<String> {
pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
let mut groups: Vec<Group> = Vec::new();
let mut unasked = Vec::new();
+ let mine = calibrate::local();
for e in entries {
let file = e.piece.file.display().to_string();
for (id, why) in &e.dropped {
@@ -120,6 +133,7 @@ pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
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();
+ calibrate::apply(&mut q, &mine);
if let Some(p) = q.picks {
q.kind = Kind::Choose;
q.options = picks(p, 1 + e.with.len());
@@ -136,7 +150,7 @@ pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
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] }),
+ None => groups.push(Group { piece: e.piece.clone(), from, to, sees: q.sees, hears: q.hears, with: e.with.clone(), questions: vec![q], kept: None }),
}
}
}
@@ -163,6 +177,9 @@ fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>)
/// A group's media, and its seconds of video and of sound (for the estimate).
fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
+ if let Some(k) = &g.kept {
+ return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
+ }
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));
@@ -208,6 +225,11 @@ enum Done {
/// 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);
+ run_groups(groups, unasked, o, out)
+}
+
+/// Planned groups asked, the questions not asked told first.
+pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut dyn FnMut(Event)) -> Summary {
let mut sum = Summary::default();
for a in &unasked {
out(Event::Answer(a));
@@ -229,7 +251,8 @@ pub fn run(entries: Vec<Entry>, o: &Opts, out: &mut dyn FnMut(Event)) -> Summary
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 state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
+ let call = Call { state, questions: g.questions.clone(), media: m };
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
if o.dry {
Done::Would(would(g, &call, estimate))
diff --git a/apps/ask/src/tests.rs b/apps/ask/src/tests.rs
index c3f33b8e..360c92ea 100644
--- a/apps/ask/src/tests.rs
+++ b/apps/ask/src/tests.rs
@@ -14,7 +14,7 @@ fn rubric() -> String {
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
}
-fn setup() {
+pub(crate) 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()))) });
diff --git a/apps/ask/src/verbs.rs b/apps/ask/src/verbs.rs
index 3113e026..21e8b581 100644
--- a/apps/ask/src/verbs.rs
+++ b/apps/ask/src/verbs.rs
@@ -1,7 +1,9 @@
//! `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.
+//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
+//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
+//! calibrate.rs; AK6-AK7).
use std::collections::{BTreeMap, HashMap};
use std::io::Read as _;
@@ -11,12 +13,14 @@ use std::sync::Arc;
use raea_core_ask::{Kind, Question, Window, library};
use serde_json::{Value, json};
+use crate::labels::{self, span};
use crate::prepare::{self, Piece};
use crate::runner::{self, Entry, Event, Opts};
+use crate::{calibrate, record};
-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|none] [--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)";
+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|none] [--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] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (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: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
-const VALUED: [&str; 15] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch"];
+const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
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`.
@@ -208,8 +212,10 @@ fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
None => library::SETS.iter().map(|s| s.to_string()).collect(),
};
let mut out = Vec::new();
+ let mine = calibrate::local();
for s in &sets {
- let qs = library::set(s, rubric)?;
+ let mut qs = library::set(s, rubric)?;
+ qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
if a.has("--json") {
out.push(json!({"set": s, "questions": qs}).to_string());
continue;
@@ -223,14 +229,6 @@ fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
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 {
@@ -278,16 +276,27 @@ pub fn cli(args: &[String]) -> i32 {
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 jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
+ let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
+ match sub {
+ Some("list") => {
+ println!("{}", list(&a, rubric.as_deref())?);
+ return Ok(0);
+ }
+ Some("verdict") => {
+ let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
+ println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
+ return Ok(0);
+ }
+ Some("calibrate") => return calibrated(&a),
+ Some("try") => return tried(&a, jobs),
+ _ => {}
}
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| {
@@ -322,3 +331,55 @@ fn run(args: &[String]) -> Result<i32, String> {
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
}
+
+/// A version's standing as a line, with its misses below when it doesn't separate.
+fn standing_line(s: &calibrate::Standing) -> String {
+ let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
+ let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
+ if s.others > 0 {
+ out += &format!(" ({} from other eyes, not counted)", s.others);
+ }
+ for m in &s.misses {
+ let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
+ out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
+ }
+ out
+}
+
+/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
+fn calibrated(a: &Args) -> Result<i32, String> {
+ let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
+ if a.has("--json") {
+ println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
+ all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
+ return Ok(0);
+ }
+ println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
+ if all.is_empty() {
+ println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
+ }
+ all.iter().for_each(|s| println!("{}", standing_line(s)));
+ Ok(0)
+}
+
+/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
+fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
+ let words = a.words[1..].join(" ");
+ let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
+ if words.trim().is_empty() {
+ return Err("ask try WORDS --like ID: the new words".into());
+ }
+ let json_out = a.has("--json");
+ let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
+ (Event::Would(v), true) => println!("{}", json!({"would": v})),
+ (Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
+ (e, false) => println!("{}", line(e, 2)),
+ })?;
+ match (both, json_out) {
+ (None, true) => println!("{}", json!({"summary": sum})),
+ (None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
+ (Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
+ (Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
+ }
+ Ok(i32::from(!a.has("--dry") && sum.calls == 0))
+}
diff --git a/docs/ask.feature b/docs/ask.feature
index 76622773..a5fd263d 100644
--- a/docs/ask.feature
+++ b/docs/ask.feature
@@ -165,14 +165,23 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
Rule: AK6-AK7. Better with use
- @needs:AK3
+ @needs:AK3 @done
Scenario: AK6. Labels
Given the plan
| crate | file | lines | job |
| raea-app-ask | apps/ask/src/labels.rs | 220 | an item's notes matched to the questions' label words (a match is yes, an approval with none is no); `raea ask verdict ANSWER yes|no`; an agent's own look kept as another eye |
Then the person's labels count toward calibration, and an agent's are kept as `eye:agent` and never counted
-
- @needs:AK6
+ Status 11-20: done. A label belongs to a question and the clips a call sent (by hash), never to one answer, so
+ new words asked of the same clips have the same labels. An approval is a post the person marked done (the
+ feed's PL8c approval). A note labels the render it was left on: each call keeps its file's identity (size and a
+ hash of its first and last MB), matched to the post's copy in the feed, so a later render to the same path
+ isn't labelled by an earlier one's note. Only the person's notes count (author kind person), pinned inside the
+ window (1.5 s before to 0.5 s after a pin) or not pinned. A verdict is the person's answer in the question's
+ own terms (a question flagged on no takes no as the problem; a grade's lower half is one) and beats a note,
+ which beats an approval. Tests: a_persons_note_on_the_posted_render_labels_it_and_an_approval_labels_it_clean,
+ a_verdict_reads_in_the_questions_terms_and_another_eyes_isnt_counted
+
+ @needs:AK6 @done
Scenario: AK7. Calibrate, and try new words
Given the plan
| crate | file | lines | job |
@@ -184,6 +193,17 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
question's words change only with a better AUC on raea's bench
And a standard question ships with raea's calibration from that bench, and the person's own replaces it once it
passes the gates
+ Status 11-20: done. `raea ask calibrate [ID]` reads the feed's labels again and holds each labelled version to
+ them through the fingerprint's own auc, quantile and gates (raea-sys-fingerprint). Clef isn't trained on the
+ labels, so its AUC on them is held out already; the threshold, the one thing fitted, flags 10% of the clean
+ labels. A version that passes is kept in ~/.raea/ask/calibration.json and goes out with the question from then
+ on (the runner's plan applies it, so every caller has it, and `raea ask list` shows it); one that stops passing
+ loses it. `raea ask try` sends the new words with each labelled call's kept clips and state through the same
+ runner, so its answers are recorded and calibrate as their own version later. The platform set's 17 questions
+ ship with the packs' calibration (AK1); the other sets have none from raea's bench yet. Test:
+ labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on_the_same_clips (18 of each from 3
+ projects calibrate at AUC 1.0, flat answers don't separate and list their misses, and new words on the same 36
+ clips go from 0.5 to 1.0)
Rule: AK8. The fingerprint asks too
@@ -191,8 +211,10 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
Scenario: AK8. A double check on the fingerprint's flags
Given the plan
| crate | file | lines | job |
- | raea-app-ask | apps/ask/src/double.rs | 160 | a score's flagged moments, each asked in its axis's own words on its own window; the answers beside the flags and kept as evidence |
- | raea-app-fingerprint | apps/fingerprint/src/verbs.rs | 15 | `score --ask` and fingerprint.ts's `ask` hand the flagged moments to raea-app-ask |
+ | raea-app-double | apps/double/src/lib.rs | 160 | a score's flagged moments, each asked in its axis's own words on its own window through raea-app-ask's runner; the answers beside the flags and kept as evidence |
+ | raea-app-fingerprint | apps/fingerprint/src/verbs.rs | 15 | `score --ask` and fingerprint.ts's `ask` hand the flagged moments to raea-app-double |
+ And 11-20: the double check is its own crate, using raea-app-ask and the fingerprint, since raea-app-ask holds
+ 1841 of its 2000 lines after AK7
Then `raea fingerprint score FILE --ask` (or `ask: "flags"` in fingerprint.ts) asks each flagged moment, and
`ask: "unsure"` also each moment between an axis's plausible and strong bands
And each flag says "clef agrees (0.71)" or "clef doesn't see it (0.08)", and each answer is an `eye:clef`
diff --git a/docs/manual/reference/cli/ask.md b/docs/manual/reference/cli/ask.md
index 1cb0baf5..b7c88f80 100644
--- a/docs/manual/reference/cli/ask.md
+++ b/docs/manual/reference/cli/ask.md
@@ -2,7 +2,7 @@
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"]
+sources: ["apps/ask/src/verbs.rs", "apps/ask/src/prepare.rs", "apps/ask/src/runner.rs", "apps/ask/src/labels.rs", "apps/ask/src/calibrate.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
@@ -35,17 +35,35 @@ A batch is a JSON list, or JSON lines, of `{file, questions?, set?, std?, window
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
+Answers are advice until a question is calibrated against your own eye, 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.
+A question learns from three kinds of label. Your verdict on an answer comes first: `raea ask verdict ANSWER WORD`,
+with the answer's id from `--json` and your own answer to the question (yes or no, an option, a level). Then your notes:
+a note of yours on the render in the project's feed, inside the window it looked at, that holds one of the question's
+label words says the problem was there, and a post you approved with no such note says it wasn't. An agent's own look
+(`--eye agent`) is kept beside them and never counted.
+
+`raea ask calibrate` reads your notes again and holds each labelled question to its labels. One with 16 labels of each
+kind, from 3 projects, and an AUC of 0.8 or more is calibrated: it flags where 10% of your clean work would, its answers
+are findings, and your calibration replaces the one raea ships. One under 0.6 after 32 labels doesn't separate, and
+lists the labels it missed so its words can be fixed. `raea ask try "new words" --like ID` asks new words of that
+question's labelled clips, kept from before, and prints both AUCs on the same labels.
+
+```sh
+raea ask verdict a-3f09c2e81b44 yes # yes, the music does fight the voice there
+raea ask calibrate # every labelled question, where it stands
+raea ask try "Is the voice hard to hear over the music?" --like own-does-the-music-fight-the-voice
+```
+
<!-- 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|none] [--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)
+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|none] [--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] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (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: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -59,12 +77,14 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| `--brief` | `brief.ts\|none` | The project's brief, so clef knows who it's for and what it should do (else the nearest brief.ts above the file; `none` for no brief, when `--state` says what the piece is). |
| `--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. |
+| `--eye` | `NAME` | With `verdict`: the verdict is another eye's (an agent's own look), kept and never counted toward calibration. |
| `--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, acceptable, strong, 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. |
+| `--like` | `ID` | With `try`: the question whose labelled clips the new words are asked of. |
| `--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. |