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.

FP2e, FP4b, FP6a, FP6d, FP8a, FP8b, FP14b, FP14c: a test that word heads score the spike's noise and clipping from words alone (0.987, 0.975); every mechanical axis carries a cheat (darkened half as much, a white flash, a gap a third as long, clipping a third as hard, beside the de-rez sharpened after, half glow, quiet noise and a zoomed freeze); raea fingerprint approve makes approved work clean on every axis away from its notes; another eye's readings teach a head but never count toward its gate; a project's or workspace's fingerprint keeps its evidence a folder a person and each machine trains its own heads (raea fingerprint share); raea fingerprint diff A B lists the axes two tastes rank the same evidence most differently on; a fingerprint that extends another inherits its axes and evidence, its own labels counted twice and measured against each alone, an override learning from its own only and the parent never from the child; raea fingerprint which PATH and use NAME --in project|workspace pick the one that judges a piece (the project's that applies to its kind, its default, the workspace's, then the person's)

shinyobjectz64dfd63cd718
diff --git a/apps/fingerprint/src/approve.rs b/apps/fingerprint/src/approve.rs
new file mode 100644
index 00000000..4197d29c
--- /dev/null
+++ b/apps/fingerprint/src/approve.rs
@@ -0,0 +1,85 @@
+//! Approvals are positives (docs/fingerprint.feature FP6a): an approved cut, a picture lock, a publish or a golden
+//! reference says every moment of it is clean on every axis, except where the person left a note. `raea fingerprint
+//! approve FILE... [--project P]` adds a clean row on every axis ("*") for each 2 s window of each file, skipping the
+//! windows within 2 s of a pinned note on that file in its project's feed (.raea/feed/*.json), since a note there may
+//! name a defect. Notes aren't read into labels here; that is FP5a.
+
+use crate::bootstrap::WIN;
+use crate::{flag, words};
+use anyhow::{Result, anyhow};
+use raea_sys_columns::Encoders;
+use raea_sys_fingerprint::evidence::{Row, features};
+use raea_sys_fingerprint::folder::Folder;
+use raea_sys_fingerprint::taxonomy::Fingerprint;
+use std::path::{Path, PathBuf};
+
+/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
+pub(crate) fn noted(file: &Path) -> Vec<f64> {
+ let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
+ let Some(feed) = file.ancestors().map(|d| d.join(".raea/feed")).find(|d| d.is_dir()) else { return Vec::new() };
+ let mut at = Vec::new();
+ for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
+ let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
+ let Ok(post) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
+ let shows = post["media"].as_array().into_iter().flatten().any(|m| m["path"].as_str().is_some_and(|p| p.ends_with(name)));
+ if shows {
+ at.extend(post["notes"].as_array().into_iter().flatten().filter_map(|n| n["pin"]["t"].as_f64()));
+ }
+ }
+ at
+}
+
+/// The windows an approval labels clean: every WIN seconds of the piece, away from its notes
+pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
+ let n = (dur / WIN).floor() as usize;
+ (0..n).map(|i| (i as f64 * WIN, (i + 1) as f64 * WIN)).filter(|(a, b)| !notes.iter().any(|t| *t > a - WIN && *t < b + WIN)).collect()
+}
+
+pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
+ let files: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| if Path::new(f).is_absolute() { PathBuf::from(f) } else { cwd.join(f) }).collect();
+ if files.is_empty() {
+ return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
+ }
+ let mut l = dir.ledger()?;
+ let mut out = String::new();
+ let mut added = 0;
+ for file in &files {
+ let c = enc.columns(file)?;
+ // an approval given again replaces the last one for that media
+ l.retain(|r| !(r.source == "approval" && r.media == c.media));
+ let notes = noted(file);
+ let w = windows(c.dur, &notes);
+ for (a, b) in &w {
+ let row = Row {
+ media: c.media.clone(),
+ a: *a,
+ b: *b,
+ axis: "*".into(),
+ bad: false,
+ weight: 1.0,
+ who: fp.who.clone().unwrap_or_else(|| "me".into()),
+ source: "approval".into(),
+ project: flag(args, "--project").map_or_else(|| project(file), str::to_string),
+ kind: None,
+ region: None,
+ words: None,
+ at: 0,
+ };
+ l.push(row, &features(&c, *a, *b));
+ }
+ added += w.len();
+ out += &format!("approved {}: {} clean windows on every axis{}\n", file.display(), w.len(), if notes.is_empty() { String::new() } else { format!(", {} noted moments left out", notes.len()) });
+ }
+ dir.write_ledger(&l)?;
+ Ok((out, added))
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn an_approval_leaves_out_the_windows_near_a_note() {
+ assert_eq!(super::windows(9.0, &[]), vec![(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]);
+ // a note at 5 s: the windows within 2 s of it go
+ assert_eq!(super::windows(12.0, &[5.0]), vec![(0.0, 2.0), (8.0, 10.0), (10.0, 12.0)]);
+ }
+}
diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rs
index a9a1c939..826982f1 100644
--- a/apps/fingerprint/src/lib.rs
+++ b/apps/fingerprint/src/lib.rs
@@ -4,7 +4,9 @@
//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on
//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.
+mod approve;
mod bootstrap;
+mod pick;
mod serve;
mod verbs;
@@ -12,13 +14,13 @@ use std::path::Path;
pub use serve::serve;
-pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] | raea fingerprint report [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends) and what it's for and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; report says each head's held-out score, labels, cheats, gate and what it can't judge)";
+pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends) and what it's for and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value
-pub(crate) const FLAGS: [(&str, bool); 18] = [
+pub(crate) const FLAGS: [(&str, bool); 19] = [
("--fp", true),
("--who", true),
("--about", true),
@@ -32,6 +34,7 @@ pub(crate) const FLAGS: [(&str, bool); 18] = [
("--words", true),
("--project", true),
("--sheet", true),
+ ("--in", true),
("--bad", false),
("--good", false),
("--json", false),
@@ -84,7 +87,11 @@ pub fn cli(args: &[String], eval: Eval) -> i32 {
}
},
"report" => verbs::report_here(args),
- "new" | "bootstrap" | "teach" | "score" | "stop" => {
+ "which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
+ "diff" => pick::diff_here(&args[1..]),
+ "share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
+ "use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
+ "new" | "bootstrap" | "teach" | "approve" | "score" | "stop" => {
let cwd = std::env::current_dir().unwrap_or_default();
let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();
let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };
diff --git a/apps/fingerprint/src/pick.rs b/apps/fingerprint/src/pick.rs
new file mode 100644
index 00000000..4ed2ae75
--- /dev/null
+++ b/apps/fingerprint/src/pick.rs
@@ -0,0 +1,144 @@
+//! Which fingerprint judges a piece (docs/fingerprint.feature FP14c): `raea fingerprint which PATH` says the one
+//! chosen, what it's for and why; `raea fingerprint use NAME [--in project|workspace] [PATH]` pins one by writing that
+//! level's `default`. score and teach use the chosen one unless --fp names another. No encoders are needed.
+
+use crate::{flag, has, words};
+use raea_sys_fingerprint::folder::{Folder, root};
+use raea_sys_fingerprint::which::{Choice, default_file, levels, piece, which};
+use std::path::{Path, PathBuf};
+
+/// The fingerprint a verb uses: --fp, else the one that judges `file`, else the account's default, else "me"
+pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Choice>) {
+ if let Some(n) = flag(args, "--fp") {
+ return (Folder::named(n), None);
+ }
+ if let Some(c) = file.and_then(which) {
+ return (Folder { dir: c.dir.clone() }, Some(c));
+ }
+ let n = std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into());
+ (Folder::named(&n), None)
+}
+
+fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
+ let w = words(args).unwrap_or_default();
+ w.get(at).map_or_else(|| cwd.to_path_buf(), |p| if Path::new(p).is_absolute() { PathBuf::from(p) } else { cwd.join(p) })
+}
+
+pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
+ let path = here(cwd, args, 0);
+ let Some(c) = which(&path) else {
+ eprintln!("raea fingerprint which: you have no fingerprint yet (`raea fingerprint new me` makes one)");
+ return 1;
+ };
+ if has(args, "--json") {
+ let p = piece(&path);
+ println!("{}", serde_json::json!({"chosen": c, "piece": p, "looked_in": levels(&p).iter().map(|(l, d)| serde_json::json!({"level": l, "dir": d})).collect::<Vec<_>>()}));
+ } else {
+ println!("{} {}", c.name, c.about.as_deref().unwrap_or(""));
+ println!(" why: {}", c.why);
+ println!(" at: {}", c.dir.display());
+ }
+ 0
+}
+
+pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
+ let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
+ eprintln!("raea fingerprint use: which one? raea fingerprint use NAME [--in project|workspace] [PATH]");
+ return 2;
+ };
+ let level = flag(args, "--in").unwrap_or("account");
+ if !matches!(level, "project" | "workspace" | "account") {
+ eprintln!("raea fingerprint use: --in takes project or workspace, not {level}");
+ return 2;
+ }
+ let path = here(cwd, args, 1);
+ let Some(file) = default_file(&path, level) else {
+ eprintln!("raea fingerprint use: {} isn't in a {level} (no .raea/{level} above it)", path.display());
+ return 1;
+ };
+ let p = piece(&path);
+ let all = levels(&p);
+ let from = all.iter().position(|(l, _)| *l == level).unwrap_or(0);
+ if !all[from..].iter().any(|(_, d)| Folder { dir: d.join(&name) }.exists()) {
+ eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
+ return 1;
+ }
+ if let Err(e) = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and_then(|()| std::fs::write(&file, &name)) {
+ eprintln!("raea fingerprint use: {}: {e}", file.display());
+ return 1;
+ }
+ println!("{name} judges this {level}'s pieces now ({})", file.display());
+ 0
+}
+
+/// `raea fingerprint diff A B [--json]` (FP8b): the axes two fingerprints rank the same evidence most differently on
+pub(crate) fn diff_here(args: &[String]) -> i32 {
+ let w = words(args).unwrap_or_default();
+ let [a, b] = w.as_slice() else {
+ eprintln!("raea fingerprint diff: which two? raea fingerprint diff A B");
+ return 2;
+ };
+ match raea_sys_fingerprint::diff::diff(&Folder::named(a), &Folder::named(b), 3) {
+ Ok(d) if has(args, "--json") => {
+ println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
+ 0
+ }
+ Ok(d) => {
+ println!("where {a} and {b} differ, most apart first (0 agree, 1 unrelated, 2 opposed):");
+ for x in &d {
+ println!(" {:16} {:.2} over {} windows", x.axis, x.apart, x.windows);
+ for m in &x.moments {
+ println!(" {} {:.1}-{:.1}s: {a} ranks it {:.0}%, {b} {:.0}%", &m.media[..m.media.len().min(12)], m.a, m.b, m.rank_a * 100.0, m.rank_b * 100.0);
+ }
+ }
+ 0
+ }
+ Err(e) => {
+ eprintln!("raea fingerprint diff: {e:#}");
+ 1
+ }
+ }
+}
+
+/// `raea fingerprint share NAME --in project|workspace [PATH]` (FP8a): the fingerprint's taxonomy, words and evidence
+/// copied into that level's .raea/fingerprints, to travel with its repo; never its heads (each machine retrains them)
+/// and never media (the rows hold embeddings, spans and labels)
+pub(crate) fn share_here(args: &[String], cwd: &Path) -> i32 {
+ let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
+ eprintln!("raea fingerprint share: which one? raea fingerprint share NAME --in project|workspace [PATH]");
+ return 2;
+ };
+ let level = flag(args, "--in").unwrap_or("project");
+ let path = here(cwd, args, 1);
+ let Some(to) = default_file(&path, level).and_then(|f| f.parent().map(|d| d.join(&name))) else {
+ eprintln!("raea fingerprint share: {} isn't in a {level} (no .raea/{level} above it)", path.display());
+ return 1;
+ };
+ let from = Folder::named(&name);
+ let run = || -> anyhow::Result<usize> {
+ from.read(None)?;
+ let dest = Folder { dir: to.clone() };
+ if dest.exists() {
+ anyhow::bail!("{} has a fingerprint {name} already", to.display());
+ }
+ std::fs::create_dir_all(&to)?;
+ for f in ["fingerprint.ts", "fingerprint.json", "words.json", "words.f16"] {
+ if from.dir.join(f).is_file() {
+ std::fs::copy(from.dir.join(f), to.join(f))?;
+ }
+ }
+ let l = from.ledger()?;
+ dest.write_ledger(&l)?;
+ Ok(l.rows.len())
+ };
+ match run() {
+ Ok(n) => {
+ println!("shared {name} into {} with {n} evidence rows, no heads and no media; commit it with the {level}", to.display());
+ 0
+ }
+ Err(e) => {
+ eprintln!("raea fingerprint share: {e:#}");
+ 1
+ }
+ }
+}
diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rs
index 6b377570..fa131ca7 100644
--- a/apps/fingerprint/src/verbs.rs
+++ b/apps/fingerprint/src/verbs.rs
@@ -5,6 +5,7 @@ use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, FPS, media};
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
use raea_sys_fingerprint::folder::{Folder, root};
+use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint::score::{Scored, clock, score, summary, timeline};
use raea_sys_fingerprint::sheet::{Tick, sheet};
use raea_sys_fingerprint::taxonomy::{Fingerprint, base};
@@ -16,9 +17,6 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
-fn name(args: &[String]) -> String {
- flag(args, "--fp").map(str::to_string).or_else(|| std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string())).unwrap_or_else(|| "me".into())
-}
fn at(cwd: &Path, p: &str) -> PathBuf {
let p = Path::new(p);
@@ -32,6 +30,7 @@ pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, s
"new" => new(enc, rest),
"bootstrap" => boot(enc, rest, cwd, eval, say),
"teach" => teach(enc, rest, cwd, eval),
+ "approve" => approved(enc, rest, cwd, eval),
"score" => scored(enc, rest, cwd, eval),
v => Err(anyhow!("no verb {v}")),
};
@@ -85,16 +84,20 @@ fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
}
/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed
-fn open(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(Folder, Fingerprint, Words)> {
- let dir = Folder::named(&name(args));
- let mut fp = dir.read(Some(eval))?;
+/// The fingerprint a verb uses (pick.rs: --fp, else the one that judges the file), its axes with its parents', and its
+/// words
+fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
+ let dir = crate::pick::chosen(args, file).0;
+ let mut raw = dir.read(Some(eval))?;
let here = pins(enc);
- if fp.encoders.is_empty() {
- fp.encoders = here;
- dir.rewrite(&fp)?;
- } else if fp.encoders != here {
- bail!("{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns", dir.ts().display(), fp.encoders, here);
+ if raw.encoders.is_empty() {
+ raw.encoders = here;
+ dir.rewrite(&raw)?;
+ } else if raw.encoders != here {
+ bail!("{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns", dir.ts().display(), raw.encoders, here);
}
+ // a fingerprint that extends another judges with its parents' axes too (FP14b)
+ let fp = inherit::axes(&raw, &inherit::parents(&raw, Some(eval)));
let w = match dir.words().filter(|w| !w.stale(&fp)) {
Some(w) => w,
None => {
@@ -103,11 +106,18 @@ fn open(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(Folder, Fing
w
}
};
+ // a shared fingerprint arrives with evidence and no heads: this machine trains its own (FP8a)
+ if !dir.dir.join("heads.safetensors").is_file() {
+ let l = dir.ledger()?;
+ if !l.rows.is_empty() {
+ retrain(&dir, &fp, &w, &l, None)?;
+ }
+ }
Ok((dir, fp, w))
}
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
- let (dir, fp, w) = open(enc, args, eval)?;
+ let (dir, fp, w) = open(enc, args, eval, None)?;
let mut files: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| at(cwd, f)).collect();
if let Some(list) = flag(args, "--from") {
let list = at(cwd, list);
@@ -142,9 +152,19 @@ fn project_of(file: &Path) -> String {
file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
}
+/// `approve`: approved work as clean rows on every axis (approve.rs, FP6a), then the heads retrained
+fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
+ let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
+ let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
+ let (mut out, _) = crate::approve::approve(enc, &dir, &fp, args, cwd, project_of)?;
+ let tr = retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
+ out += &format!("{} axes gating\n", tr.heads.iter().filter(|h| h.state == "gating").count());
+ Ok((out, 0))
+}
+
fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
- let (dir, fp, w) = open(enc, args, eval)?;
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
+ let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;
if axis != "*" && fp.axis(axis).is_none() {
bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
@@ -214,17 +234,19 @@ fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, Strin
}
fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
- let (dir, fp, w) = open(enc, args, eval)?;
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
+ let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
+ let why = crate::pick::chosen(args, Some(&file)).1.map_or_else(|| "named with --fp, or the account's default".to_string(), |c| c.why);
let c = enc.columns(&file)?;
let trained = dir.trained()?.map(|(t, _)| t);
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
let found = checks(&file);
arbitrate(&mut s, &fp, &found);
let mut out = if has(args, "--json") {
- serde_json::to_string_pretty(&json!({"scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>()}))?
+ serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>()}))?
} else {
- let mut t = summary(&s);
+ let mut t = format!("judged by {}: {why}\n", fp.name);
+ t += &summary(&s);
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
for (r, a, _, says) in &found {
t += &format!(" {} {r}: {says}\n", clock(*a));
@@ -247,7 +269,7 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
/// `raea fingerprint report`: report.json, read; no encoders needed
pub(crate) fn report_here(args: &[String]) -> i32 {
- let dir = Folder::named(&name(args));
+ let dir = crate::pick::chosen(args, None).0;
match dir.report() {
Some(r) if has(args, "--json") => {
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
diff --git a/systems/columns/src/damage.rs b/systems/columns/src/damage.rs
index d31bf516..3bd76da0 100644
--- a/systems/columns/src/damage.rs
+++ b/systems/columns/src/damage.rs
@@ -9,8 +9,18 @@ use image::{ImageBuffer, Rgb as Px, imageops};
pub const PICTURE: [&str; 5] = ["blur", "dark", "glow", "flash", "freeze"];
pub const SOUND: [&str; 3] = ["noise", "dropout", "clip"];
/// Each cheat and the defect it hides: a de-rez sharpened after, glow at half strength, noise at a third of the level,
-/// and a freeze with a slow zoom on it
-pub const CHEATS: [(&str, &str); 4] = [("sharpblur", "blur"), ("glow_half", "glow"), ("noise_low", "noise"), ("freeze_zoom", "freeze")];
+/// a freeze with a slow zoom on it, a picture darkened half as much, a white flash where the defect is black, a gap a
+/// third as long, and clipping a third as hard
+pub const CHEATS: [(&str, &str); 8] = [
+ ("sharpblur", "blur"),
+ ("glow_half", "glow"),
+ ("noise_low", "noise"),
+ ("freeze_zoom", "freeze"),
+ ("dark_half", "dark"),
+ ("flash_white", "flash"),
+ ("dropout_short", "dropout"),
+ ("clip_soft", "clip"),
+];
type Img = ImageBuffer<Px<u8>, Vec<u8>>;
@@ -54,13 +64,14 @@ pub fn picture(frames: &[Rgb], kind: &str) -> Vec<Rgb> {
"glow" => frames.iter().map(|f| glow(f, 0.7)).collect(),
"glow_half" => frames.iter().map(|f| glow(f, 0.35)).collect(),
"dark" => frames.iter().map(|f| f.iter().map(|&x| (x as f32 * 0.3) as u8).collect()).collect(),
+ "dark_half" => frames.iter().map(|f| f.iter().map(|&x| (x as f32 * 0.65) as u8).collect()).collect(),
"freeze" => frames.iter().map(|_| frames[0].clone()).collect(),
"freeze_zoom" => (0..frames.len()).map(|i| zoomed(&frames[0], i)).collect(),
- "flash" => {
+ "flash" | "flash_white" => {
let mut v = frames.to_vec();
if !v.is_empty() {
let m = v.len() / 2;
- v[m] = vec![0; SIDE * SIDE * 3];
+ v[m] = vec![if kind == "flash" { 0 } else { 255 }; SIDE * SIDE * 3];
}
v
}
@@ -89,12 +100,14 @@ pub fn sound(w: &[f32], kind: &str, rate: u32, noise: &mut Noise) -> Vec<f32> {
match kind {
"noise" => add(&mut w, 0.5),
"noise_low" => add(&mut w, 0.15),
- "dropout" => {
- let a = (w.len() / 2).saturating_sub((0.3 * rate as f64) as usize);
- let b = (a + (0.6 * rate as f64) as usize).min(w.len());
+ "dropout" | "dropout_short" => {
+ let gap = if kind == "dropout" { 0.6 } else { 0.2 };
+ let a = (w.len() / 2).saturating_sub((gap / 2.0 * rate as f64) as usize);
+ let b = (a + (gap * rate as f64) as usize).min(w.len());
w[a..b].iter_mut().for_each(|x| *x = 0.0);
}
"clip" => w.iter_mut().for_each(|x| *x = (*x * 10.0).clamp(-0.3, 0.3)),
+ "clip_soft" => w.iter_mut().for_each(|x| *x = (*x * 3.0).clamp(-0.6, 0.6)),
_ => {}
}
w
diff --git a/systems/fingerprint/src/diff.rs b/systems/fingerprint/src/diff.rs
new file mode 100644
index 00000000..b4a79ddb
--- /dev/null
+++ b/systems/fingerprint/src/diff.rs
@@ -0,0 +1,93 @@
+//! Where two tastes differ (FP8b): `raea fingerprint diff A B` scores the same evidence (both fingerprints' rows, no
+//! cheats) through each one's learned heads and lists the axes they rank most differently, each with the moments that
+//! show it: the windows one ranks high and the other low.
+
+use crate::evidence::Ledger;
+use crate::folder::Folder;
+use crate::train::AxisHead;
+use anyhow::{Result, anyhow};
+use serde::Serialize;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Moment {
+ pub media: String,
+ pub a: f64,
+ pub b: f64,
+ /// each fingerprint's rank of this window on the axis, 0 (least) to 1 (most)
+ pub rank_a: f32,
+ pub rank_b: f32,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Differs {
+ pub axis: String,
+ /// 1 minus the rank correlation of the two heads' scores: 0 agree, 1 unrelated, 2 opposed
+ pub apart: f32,
+ pub windows: usize,
+ pub moments: Vec<Moment>,
+}
+
+/// Each value's rank as a share, 0 to 1
+fn ranks(v: &[f32]) -> Vec<f32> {
+ let mut i: Vec<usize> = (0..v.len()).collect();
+ i.sort_by(|&x, &y| v[x].total_cmp(&v[y]));
+ let mut r = vec![0.0; v.len()];
+ let n = (v.len().max(2) - 1) as f32;
+ for (k, &j) in i.iter().enumerate() {
+ r[j] = k as f32 / n;
+ }
+ r
+}
+
+fn correlation(x: &[f32], y: &[f32]) -> f32 {
+ let n = x.len() as f32;
+ let (mx, my) = (x.iter().sum::<f32>() / n, y.iter().sum::<f32>() / n);
+ let (mut c, mut vx, mut vy) = (0.0, 0.0, 0.0);
+ for (a, b) in x.iter().zip(y) {
+ c += (a - mx) * (b - my);
+ vx += (a - mx).powi(2);
+ vy += (b - my).powi(2);
+ }
+ c / (vx * vy).sqrt().max(1e-9)
+}
+
+fn score(h: &AxisHead, l: &Ledger, i: usize) -> Option<f32> {
+ Some(h.head.as_ref()?.score(l.modality(i, h.modality?)))
+}
+
+/// The axes both have learned heads for, most apart first, each with its `top` most disputed moments
+pub fn diff(a: &Folder, b: &Folder, top: usize) -> Result<Vec<Differs>> {
+ let ta = a.trained()?.ok_or_else(|| anyhow!("{} has no trained heads yet", a.dir.display()))?.0;
+ let tb = b.trained()?.ok_or_else(|| anyhow!("{} has no trained heads yet", b.dir.display()))?.0;
+ let mut l = Ledger::default();
+ for dir in [a, b] {
+ let own = dir.ledger()?;
+ for i in 0..own.rows.len() {
+ if own.rows[i].source != "cheat" && !l.rows.iter().any(|r| r.media == own.rows[i].media && r.a == own.rows[i].a && r.axis == own.rows[i].axis && r.kind == own.rows[i].kind) {
+ l.push(own.rows[i].clone(), own.features(i));
+ }
+ }
+ }
+ let mut out = Vec::new();
+ for ha in &ta.heads {
+ let Some(hb) = tb.heads.iter().find(|h| h.axis == ha.axis) else { continue };
+ let (mut i, mut sa, mut sb) = (Vec::new(), Vec::new(), Vec::new());
+ for r in 0..l.rows.len() {
+ if let (Some(x), Some(y)) = (score(ha, &l, r), score(hb, &l, r)) {
+ i.push(r);
+ sa.push(x);
+ sb.push(y);
+ }
+ }
+ if i.len() < 4 {
+ continue;
+ }
+ let (ra, rb) = (ranks(&sa), ranks(&sb));
+ let mut by: Vec<usize> = (0..i.len()).collect();
+ by.sort_by(|&x, &y| (ra[y] - rb[y]).abs().total_cmp(&(ra[x] - rb[x]).abs()));
+ let moments = by.iter().take(top).map(|&k| Moment { media: l.rows[i[k]].media.clone(), a: l.rows[i[k]].a, b: l.rows[i[k]].b, rank_a: ra[k], rank_b: rb[k] }).collect();
+ out.push(Differs { axis: ha.axis.clone(), apart: 1.0 - correlation(&ra, &rb), windows: i.len(), moments });
+ }
+ out.sort_by(|x, y| y.apart.total_cmp(&x.apart));
+ Ok(out)
+}
diff --git a/systems/fingerprint/src/folder.rs b/systems/fingerprint/src/folder.rs
index 789316d2..5e25eb9f 100644
--- a/systems/fingerprint/src/folder.rs
+++ b/systems/fingerprint/src/folder.rs
@@ -141,12 +141,13 @@ impl Folder {
Ok(())
}
+ /// The evidence: one ledger, or a project's or workspace's every person's (share.rs, FP8a)
pub fn ledger(&self) -> Result<Ledger> {
- Ledger::read(&self.dir)
+ if crate::share::shared(&self.dir) { crate::share::read(&self.dir) } else { Ledger::read(&self.dir) }
}
pub fn write_ledger(&self, l: &Ledger) -> Result<()> {
- l.write(&self.dir)
+ if crate::share::shared(&self.dir) { crate::share::write(&self.dir, l) } else { l.write(&self.dir) }
}
/// The trained heads and the encoders they were trained on; None before the first training
diff --git a/systems/fingerprint/src/inherit.rs b/systems/fingerprint/src/inherit.rs
new file mode 100644
index 00000000..28efb0db
--- /dev/null
+++ b/systems/fingerprint/src/inherit.rs
@@ -0,0 +1,142 @@
+//! A child fingerprint (FP14b): one that `extends` another has its parent's axes plus its own, and trains on its
+//! parent's evidence as well as its own, its own counted twice. An axis of its own with a parent's axis's name but
+//! other words, polarity or check overrides it, and learns from the child's own labels only. The parent never reads
+//! a child's evidence: one client's taste doesn't move the person's own. The 2x is measured, not trusted: for each axis
+//! the child has labels on, held out by the child's own projects, training on both against its own labels alone and
+//! the parent's alone.
+
+use crate::evidence::Ledger;
+use crate::folder::{Eval, Folder};
+use crate::head::{Logistic, Scaler, auc};
+use crate::taxonomy::{Axis, Fingerprint};
+use crate::train::{C, folds};
+use serde::Serialize;
+use std::collections::BTreeSet;
+
+/// How much a child's own label counts against an inherited one
+pub const OWN: f32 = 2.0;
+/// How far up `extends` is followed
+const DEPTH: usize = 8;
+
+/// The fingerprints this one extends, nearest first; a missing or circular parent ends the chain
+pub fn parents(fp: &Fingerprint, eval: Option<Eval>) -> Vec<(Folder, Fingerprint)> {
+ let mut out: Vec<(Folder, Fingerprint)> = Vec::new();
+ let mut seen = BTreeSet::from([fp.name.clone()]);
+ let mut next = fp.extends.clone();
+ while let Some(name) = next.take() {
+ if out.len() >= DEPTH || !seen.insert(name.clone()) {
+ break;
+ }
+ let dir = Folder::named(&name);
+ let Ok(p) = dir.read(eval) else { break };
+ next = p.extends.clone();
+ out.push((dir, p));
+ }
+ out
+}
+
+/// Whether the child's axis says something other than the parent's of the same name
+fn differs(a: &Axis, b: &Axis) -> bool {
+ a.words != b.words || a.polarity != b.polarity || a.check != b.check || a.modality != b.modality
+}
+
+/// The axes the child overrides: its own, under a name a parent has, saying something else
+pub fn overrides(fp: &Fingerprint, parents: &[(Folder, Fingerprint)]) -> BTreeSet<String> {
+ let mut out = BTreeSet::new();
+ for a in &fp.axes {
+ if let Some(b) = parents.iter().find_map(|(_, p)| p.axis(&a.name)) {
+ if differs(a, b) {
+ out.insert(a.name.clone());
+ }
+ }
+ }
+ out
+}
+
+/// The child's axes, then every parent's axis it doesn't name, so an axis a parent gains later reaches it
+pub fn axes(fp: &Fingerprint, parents: &[(Folder, Fingerprint)]) -> Fingerprint {
+ let mut f = fp.clone();
+ for (_, p) in parents {
+ for a in &p.axes {
+ if f.axis(&a.name).is_none() {
+ f.axes.push(a.clone());
+ }
+ }
+ }
+ f
+}
+
+/// The rows a child trains on: its own, counted OWN times, then each parent's, except on the axes it overrides.
+/// Returns the ledger and how many of its first rows are the child's own.
+pub fn pooled(own: &Ledger, parents: &[(Folder, Fingerprint)], over: &BTreeSet<String>) -> (Ledger, usize) {
+ let mut l = Ledger::default();
+ let scale = if parents.is_empty() { 1.0 } else { OWN };
+ for i in 0..own.rows.len() {
+ let mut r = own.rows[i].clone();
+ r.weight *= scale;
+ l.push(r, own.features(i));
+ }
+ let n = l.rows.len();
+ for (dir, _) in parents {
+ let Ok(p) = dir.ledger() else { continue };
+ for i in 0..p.rows.len() {
+ if !over.contains(&p.rows[i].axis) {
+ l.push(p.rows[i].clone(), p.features(i));
+ }
+ }
+ }
+ (l, n)
+}
+
+/// One axis, held out by the child's own projects: AUC training on both, on its own labels alone, on the parent's alone
+#[derive(Clone, Debug, Default, Serialize)]
+pub struct Measured {
+ pub axis: String,
+ pub own_labels: usize,
+ pub both: Option<f64>,
+ pub own: Option<f64>,
+ pub parent: Option<f64>,
+}
+
+/// FP14b's measure, for every axis the child has labels on of both kinds
+pub fn measure(fp: &Fingerprint, l: &Ledger, own: usize) -> Vec<Measured> {
+ let mut out = Vec::new();
+ for a in &fp.axes {
+ let rows = l.for_axis(&a.name);
+ let mine: Vec<usize> = rows.iter().copied().filter(|&i| i < own).collect();
+ let bad = mine.iter().filter(|&&i| l.rows[i].bad).count();
+ if bad < 2 || mine.len() - bad < 2 || own == l.rows.len() {
+ continue;
+ }
+ let projects: BTreeSet<String> = mine.iter().map(|&i| l.rows[i].project.clone()).collect();
+ if projects.len() < 2 {
+ continue;
+ }
+ let m = a.modality;
+ let score = |pick: &dyn Fn(usize) -> bool| -> Option<f64> {
+ let (mut p, mut n) = (Vec::new(), Vec::new());
+ for fold in folds(&projects) {
+ let held = |i: usize| i < own && fold.contains(&l.rows[i].project);
+ let train: Vec<usize> = rows.iter().copied().filter(|&i| !held(i) && pick(i)).collect();
+ let (tb, tn) = (train.iter().filter(|&&i| l.rows[i].bad).count(), train.iter().filter(|&&i| !l.rows[i].bad).count());
+ if tb == 0 || tn == 0 {
+ continue;
+ }
+ let x: Vec<&[f32]> = train.iter().map(|&i| l.modality(i, m)).collect();
+ let y: Vec<bool> = train.iter().map(|&i| l.rows[i].bad).collect();
+ let w: Vec<f32> = train.iter().map(|&i| l.rows[i].weight).collect();
+ let f = Logistic::fit(Scaler::fit(&x), &x, &y, Some(&w), C, true);
+ for &i in mine.iter().filter(|&&i| held(i)) {
+ let s = f.score(l.modality(i, m));
+ if l.rows[i].bad { p.push(s) } else { n.push(s) }
+ }
+ }
+ Some(auc(&p, &n)).filter(|a| a.is_finite())
+ };
+ let both = score(&|_| true);
+ let own_ = score(&|i| i < own);
+ let parent = score(&|i| i >= own);
+ out.push(Measured { axis: a.name.clone(), own_labels: mine.len(), both, own: own_, parent });
+ }
+ out
+}
diff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rs
index 496716f6..afeaada2 100644
--- a/systems/fingerprint/src/lib.rs
+++ b/systems/fingerprint/src/lib.rs
@@ -7,15 +7,23 @@
//! - evidence.rs: the rows (FP2c)
//! - head.rs, train.rs: the heads, held-out scores, bands, cheats and the gate (FP2c, FP2d)
//! - words.rs: word heads from day one (FP2e)
+//! - inherit.rs: a fingerprint that extends another, its evidence and axes (FP14b)
+//! - diff.rs: where two fingerprints rank the same evidence differently (FP8b)
+//! - share.rs: a project's or workspace's fingerprint, its evidence a folder a person (FP8a)
+//! - which.rs: which fingerprint judges a piece: its project's, its workspace's, then the person's (FP14c)
//! - score.rs, sheet.rs: scoring a piece, its summary, timeline and sheet (FP3a, FP3c)
+pub mod diff;
pub mod evidence;
pub mod folder;
pub mod head;
+pub mod inherit;
pub mod score;
+pub mod share;
pub mod sheet;
pub mod taxonomy;
pub mod train;
+pub mod which;
pub mod words;
use anyhow::Result;
@@ -36,13 +44,28 @@ pub const LIMITS: [&str; 5] = [
"taste axes with only words: always advice, never a gate",
];
-/// Every head retrained from the ledger, written with the report; the bootstrap's measures are kept from the last
-/// report unless a new bootstrap gives its own
+/// Every head retrained from the ledger (with its parents' evidence when it extends one, FP14b), written with the
+/// report; the bootstrap's measures are kept from the last report unless a new bootstrap gives its own
pub fn retrain(dir: &Folder, fp: &Fingerprint, w: &Words, l: &Ledger, bootstrap: Option<serde_json::Value>) -> Result<Trained> {
- let t = train::train(fp, l, w);
+ let parents = inherit::parents(fp, None);
+ let over = inherit::overrides(fp, &parents);
+ let fp = &inherit::axes(fp, &parents);
+ let (all, own) = inherit::pooled(l, &parents, &over);
+ let t = train::train(fp, &all, w);
dir.write_trained(&t, &fp.encoders)?;
let kept = bootstrap.or_else(|| dir.report().and_then(|r| r.get("bootstrap").cloned()));
- dir.write_report(&report(fp, &t, l, kept))?;
+ let mut r = report(fp, &t, &all, kept);
+ if !parents.is_empty() {
+ r["inherits"] = json!({
+ "from": parents.iter().map(|(_, p)| p.name.as_str()).collect::<Vec<_>>(),
+ "own_rows": own,
+ "inherited_rows": all.rows.len() - own,
+ "own_weight": inherit::OWN,
+ "overrides": over,
+ "measured": inherit::measure(fp, &all, own),
+ });
+ }
+ dir.write_report(&r)?;
Ok(t)
}
diff --git a/systems/fingerprint/src/share.rs b/systems/fingerprint/src/share.rs
new file mode 100644
index 00000000..5645ec1b
--- /dev/null
+++ b/systems/fingerprint/src/share.rs
@@ -0,0 +1,49 @@
+//! A shared fingerprint (FP8a): one kept in a project's or workspace's .raea/fingerprints travels with that folder's
+//! repo, so sharing is evidence, never weights or media. Its rows are kept a folder a person (evidence/WHO/), so two
+//! teammates labelling at once never edit the same file, and every machine retrains the heads from all of them
+//! (heads.safetensors and report.json stay on the machine: the folder's .gitignore says so). A person's own
+//! fingerprint in ~/.raea keeps one evidence.jsonl.
+
+use crate::evidence::Ledger;
+use anyhow::Result;
+use std::path::Path;
+
+/// Whether a fingerprint folder is a project's or workspace's: PLACE/.raea/fingerprints/NAME
+pub fn shared(dir: &Path) -> bool {
+ let Some(raea) = dir.parent().filter(|p| p.file_name().is_some_and(|n| n == "fingerprints")).and_then(Path::parent) else { return false };
+ raea.file_name().is_some_and(|n| n == ".raea") && (raea.join("project").is_file() || raea.join("workspace").is_file())
+}
+
+/// Every person's rows, read together
+pub fn read(dir: &Path) -> Result<Ledger> {
+ let mut l = Ledger::read(dir)?;
+ let mut people: Vec<_> = std::fs::read_dir(dir.join("evidence")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
+ people.sort();
+ for p in people {
+ let one = Ledger::read(&p)?;
+ for i in 0..one.rows.len() {
+ l.push(one.rows[i].clone(), one.features(i));
+ }
+ }
+ Ok(l)
+}
+
+/// Each person's rows to their own folder
+pub fn write(dir: &Path, l: &Ledger) -> Result<()> {
+ let mut who: Vec<&str> = l.rows.iter().map(|r| r.who.as_str()).collect();
+ who.sort();
+ who.dedup();
+ for w in who {
+ let mut one = Ledger::default();
+ for i in (0..l.rows.len()).filter(|&i| l.rows[i].who == w) {
+ one.push(l.rows[i].clone(), l.features(i));
+ }
+ let safe: String = w.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
+ one.write(&dir.join("evidence").join(safe))?;
+ }
+ for f in ["evidence.jsonl", "evidence.f16"] {
+ let _ = std::fs::remove_file(dir.join(f));
+ }
+ std::fs::write(dir.join(".gitignore"), "# made on each machine from the evidence (docs/fingerprint.feature FP8a)\nheads.safetensors\nheads.part\nreport.json\n")?;
+ Ok(())
+}
diff --git a/systems/fingerprint/src/tests.rs b/systems/fingerprint/src/tests.rs
index 124ca1f8..1daf479c 100644
--- a/systems/fingerprint/src/tests.rs
+++ b/systems/fingerprint/src/tests.rs
@@ -131,3 +131,201 @@ fn about_extends_and_applies_round_trip() {
let old: crate::taxonomy::Fingerprint = serde_json::from_str(r#"{"name":"me","axes":[]}"#).unwrap();
assert_eq!((old.about, old.extends, old.applies), (None, None, None));
}
+
+/// FP2e's bar on FP0g's defects: the base taxonomy's words, with no labels, score noise and clipping at 0.97 or better
+/// (damaged against clean, 2 s windows of the spike's 26 sources). The clips are on Shane's machine, not in git
+/// (~/films/fingerprint-spike or $FP_SPIKE): `cargo test -p raea-sys-fingerprint -- --ignored`.
+#[test]
+#[ignore]
+fn word_heads_score_noise_and_clipping_from_words_alone() {
+ let spike = std::env::var_os("FP_SPIKE").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from(std::env::var("HOME").unwrap()).join("films/fingerprint-spike"));
+ let items: Vec<serde_json::Value> = serde_json::from_slice(&std::fs::read(spike.join("clap/items.json")).unwrap()).unwrap();
+ let mut enc = raea_sys_columns::Encoders::load().unwrap();
+ let w = Words::build(&mut enc, &base("me")).unwrap();
+ let mut z = std::collections::HashMap::<(&str, &str), Vec<f32>>::new();
+ for it in items.iter().filter(|i| i["len"].as_f64() == Some(2.0)) {
+ let cond = it["cond"].as_str().unwrap();
+ if !["clean", "noise", "clip"].contains(&cond) {
+ continue;
+ }
+ let pcm: Vec<f32> = std::fs::read(it["pcm"].as_str().unwrap()).unwrap().as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
+ let v = crate::words::unit(&enc.clap_clips(&[&pcm]).unwrap());
+ for axis in ["noise", "clip"] {
+ z.entry((axis, cond)).or_default().push(w.z_of(axis, &v).unwrap());
+ }
+ }
+ for axis in ["noise", "clip"] {
+ let a = auc(&z[&(axis, axis)], &z[&(axis, "clean")]);
+ eprintln!("{axis} from its words alone: AUC {a:.3} over {} damaged and {} clean windows", z[&(axis, axis)].len(), z[&(axis, "clean")].len());
+ assert!(a >= 0.97, "{axis} {a}");
+ }
+}
+
+/// FP14b: a child trains on its parent's evidence and its own, its own counted twice; an axis it rewords learns from
+/// its own labels only; the parent never reads the child's
+#[test]
+fn a_child_inherits_and_its_own_labels_count_more() {
+ let tmp = std::env::temp_dir().join(format!("raea-fp-inherit-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let (parent, child) = (Folder { dir: tmp.join("me") }, Folder { dir: tmp.join("client-ads") });
+ parent.create(&base("me")).unwrap();
+ let mut pl = Ledger::default();
+ for i in 0..40 {
+ let (axis, bad) = [("blur", true), ("dark", true), ("*", false), ("*", false)][i % 4];
+ pl.push(row(axis, bad, &format!("p{}", i % 5)), &feats(if bad { 1.0 } else { -1.0 }, i));
+ }
+ parent.write_ledger(&pl).unwrap();
+ let mut fp = base("client-ads");
+ fp.extends = Some(parent.dir.display().to_string());
+ fp.axes.iter_mut().find(|a| a.name == "dark").unwrap().words = vec!["a moody, low-key shot that is too dim for an ad".into()];
+ fp.axes.retain(|a| a.name != "noise");
+ child.create(&fp).unwrap();
+ let mut cl = Ledger::default();
+ for i in 0..12 {
+ cl.push(row(if i % 2 == 0 { "blur" } else { "*" }, i % 2 == 0, &format!("c{}", i % 3)), &feats(if i % 2 == 0 { 1.0 } else { -1.0 }, 100 + i));
+ }
+ child.write_ledger(&cl).unwrap();
+
+ let parents = crate::inherit::parents(&fp, None);
+ assert_eq!(parents.len(), 1);
+ let over = crate::inherit::overrides(&fp, &parents);
+ assert_eq!(over.into_iter().collect::<Vec<_>>(), vec!["dark".to_string()], "only the reworded axis is an override");
+ let merged = crate::inherit::axes(&fp, &parents);
+ assert!(merged.axis("noise").is_some(), "a parent's axis the child doesn't name still reaches it");
+ let (all, own) = crate::inherit::pooled(&cl, &parents, &crate::inherit::overrides(&fp, &parents));
+ assert_eq!(own, 12);
+ assert!(all.rows[..own].iter().all(|r| r.weight == crate::inherit::OWN));
+ assert!(all.rows[own..].iter().all(|r| r.axis != "dark"), "the override learns from the child's own labels only");
+ assert_eq!(all.rows.len() - own, 30, "the parent's blur and clean rows, not its dark ones");
+
+ crate::retrain(&child, &fp, &Words::default(), &cl, None).unwrap();
+ let r = child.report().unwrap();
+ assert_eq!(r["inherits"]["own_rows"], 12);
+ assert_eq!(r["inherits"]["inherited_rows"], 30);
+ assert!(r["inherits"]["measured"].as_array().unwrap().iter().any(|m| m["axis"] == "blur" && m["both"].as_f64().is_some()));
+ assert_eq!(parent.ledger().unwrap().rows.len(), 40, "the parent never takes the child's rows");
+ assert!(crate::inherit::parents(&base("me"), None).is_empty());
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+/// FP14c: the project's fingerprints first (the one that applies to the piece's kind, else the project's default),
+/// then the workspace's, then the person's own default
+#[test]
+fn which_one_judges_a_piece() {
+ use crate::which::{default_file, which};
+ let tmp = std::env::temp_dir().join(format!("raea-fp-which-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let (ws, home) = (tmp.join("ws"), tmp.join("home"));
+ let proj = ws.join("projects/brand");
+ std::fs::create_dir_all(ws.join(".raea")).unwrap();
+ std::fs::write(ws.join(".raea/workspace"), "[workspace]\n\tname = W\n").unwrap();
+ std::fs::create_dir_all(proj.join(".raea")).unwrap();
+ std::fs::write(proj.join(".raea/project"), "[project]\n\tname = brand\n\tkind = ad\n\ttags = brand-x, fast\n").unwrap();
+ // SAFETY: no other test in this crate reads RAEA_FINGERPRINTS
+ unsafe { std::env::set_var("RAEA_FINGERPRINTS", &home) };
+ let make = |dir: &std::path::Path, name: &str, kinds: &[&str]| {
+ let mut f = base(name);
+ f.about = Some(format!("{name}'s"));
+ if !kinds.is_empty() {
+ f.applies = Some(crate::taxonomy::Applies { kinds: kinds.iter().map(|k| k.to_string()).collect(), tags: vec![] });
+ }
+ Folder { dir: dir.join(name) }.create(&f).unwrap();
+ };
+ make(&home, "me", &[]);
+ let cut = proj.join("out/cut.mp4");
+ let c = which(&cut).unwrap();
+ assert_eq!((c.name.as_str(), c.level.as_str()), ("me", "account"), "nothing nearer: the person's own");
+
+ make(&ws.join(".raea/fingerprints"), "studio", &[]);
+ std::fs::write(ws.join(".raea/fingerprints/default"), "studio").unwrap();
+ assert_eq!(which(&cut).unwrap().name, "studio", "the workspace's default");
+
+ make(&proj.join(".raea/fingerprints"), "films", &["film"]);
+ make(&proj.join(".raea/fingerprints"), "ads", &["ad"]);
+ let c = which(&cut).unwrap();
+ assert_eq!((c.name.as_str(), c.level.as_str()), ("ads", "project"));
+ assert_eq!(c.why, "the project's, and it applies to ad pieces");
+
+ std::fs::write(proj.join(".raea/project"), "[project]\n\tname = brand\n").unwrap();
+ assert_eq!(which(&cut).unwrap().name, "studio", "no kind matches and no project default: the workspace's");
+ std::fs::write(proj.join(".raea/fingerprints/default"), "me").unwrap();
+ let c = which(&cut).unwrap();
+ assert_eq!((c.name.as_str(), c.level.as_str()), ("me", "project"), "a project can pin the person's own");
+ assert_eq!(default_file(&cut, "project").unwrap(), proj.join(".raea/fingerprints/default"));
+ assert_eq!(default_file(&home.join("x.mp4"), "project"), None);
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+/// FP6d: another eye's readings train the head but never count toward the gate as the person's labels
+#[test]
+fn another_eye_stays_another_eye() {
+ let fp = base("t");
+ let mut l = Ledger::default();
+ for i in 0..80 {
+ let mut r = row(if i % 2 == 0 { "blur" } else { "*" }, i % 2 == 0, &format!("p{}", i % 4));
+ r.source = "eye:kimi".into();
+ l.push(r, &feats(if i % 2 == 0 { 1.0 } else { -1.0 }, i));
+ }
+ let h = crate::train::axis(&fp, &l, &Words::default(), "blur");
+ assert!(h.head.is_some() && h.held_out.unwrap() > 0.9, "the eye's rows still teach the head");
+ assert_eq!(h.state, "advice", "{}", h.why);
+ assert!(h.why.contains("0 defect and 0 clean labels of yours"), "{}", h.why);
+}
+
+/// FP8b: two people who call opposite things blurry are far apart on blur, and the moments say where
+#[test]
+fn diff_finds_where_two_tastes_differ() {
+ let tmp = std::env::temp_dir().join(format!("raea-fp-diff-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let make = |name: &str, flip: bool| {
+ let dir = Folder { dir: tmp.join(name) };
+ dir.create(&base(name)).unwrap();
+ let mut l = Ledger::default();
+ for i in 0..60 {
+ let bad = i % 2 == 0;
+ let mut r = row("blur", bad, &format!("p{}", i % 4));
+ (r.a, r.b) = (i as f64 * 2.0, i as f64 * 2.0 + 2.0);
+ l.push(r, &feats(if bad != flip { 1.0 } else { -1.0 }, i));
+ }
+ dir.write_ledger(&l).unwrap();
+ crate::retrain(&dir, &base(name), &Words::default(), &l, None).unwrap();
+ dir
+ };
+ let (a, b, c) = (make("a", false), make("b", true), make("c", false));
+ let ab = crate::diff::diff(&a, &b, 2).unwrap();
+ let blur = ab.iter().find(|d| d.axis == "blur").unwrap();
+ assert!(blur.apart > 1.5, "opposed tastes: {}", blur.apart);
+ assert_eq!(blur.moments.len(), 2);
+ let ac = crate::diff::diff(&a, &c, 2).unwrap();
+ assert!(ac.iter().find(|d| d.axis == "blur").unwrap().apart < 0.2, "the same taste agrees");
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+/// FP8a: a project's fingerprint keeps each person's rows in their own folder, reads them all back together, and
+/// keeps its heads off the repo
+#[test]
+fn a_shared_fingerprint_keeps_evidence_a_person() {
+ let tmp = std::env::temp_dir().join(format!("raea-fp-share-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(tmp.join("proj/.raea")).unwrap();
+ std::fs::write(tmp.join("proj/.raea/project"), "[project]\n").unwrap();
+ let dir = Folder { dir: tmp.join("proj/.raea/fingerprints/team") };
+ assert!(crate::share::shared(&dir.dir) && !crate::share::shared(&tmp.join("home/me")));
+ dir.create(&base("team")).unwrap();
+ let mut l = Ledger::default();
+ for (i, who) in ["ana", "ben", "ana"].iter().enumerate() {
+ let mut r = row("blur", true, "p");
+ r.who = who.to_string();
+ l.push(r, &feats(1.0, i));
+ }
+ dir.write_ledger(&l).unwrap();
+ assert!(dir.dir.join("evidence/ana/evidence.jsonl").is_file() && dir.dir.join("evidence/ben/evidence.jsonl").is_file());
+ assert!(!dir.dir.join("evidence.jsonl").exists());
+ assert!(std::fs::read_to_string(dir.dir.join(".gitignore")).unwrap().contains("heads.safetensors"));
+ let back = dir.ledger().unwrap();
+ assert_eq!(back.rows.len(), 3);
+ assert_eq!(back.rows.iter().filter(|r| r.who == "ana").count(), 2);
+ let i = back.rows.iter().position(|r| r.who == "ben").unwrap();
+ assert!((back.features(i)[0] - l.features(1)[0]).abs() < 1e-2, "each row keeps its own features");
+ let _ = std::fs::remove_dir_all(&tmp);
+}
diff --git a/systems/fingerprint/src/train.rs b/systems/fingerprint/src/train.rs
index 18132a98..f8c6d2cc 100644
--- a/systems/fingerprint/src/train.rs
+++ b/systems/fingerprint/src/train.rs
@@ -159,11 +159,15 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHead
h.plausible = band(&hp, &hn, 0.7);
h.flag = Some(quantile(&hn, 0.9)).filter(|v| v.is_finite());
let mut why = Vec::new();
+ // another eye's readings (clef's, Kimi's: source "eye:NAME") train the head but never count as the person's (FP6d)
+ let theirs: Vec<usize> = rows.iter().copied().filter(|&i| !l.rows[i].source.starts_with("eye:")).collect();
+ let (pos, neg) = counts(l, &theirs);
+ let own_projects = theirs.iter().map(|&i| l.rows[i].project.as_str()).collect::<BTreeSet<_>>().len();
if pos < GATE_LABELS || neg < GATE_LABELS {
- why.push(format!("{pos} defect and {neg} clean labels (needs {GATE_LABELS} of each)"));
+ why.push(format!("{pos} defect and {neg} clean labels of yours (needs {GATE_LABELS} of each)"));
}
- if h.projects < GATE_PROJECTS {
- why.push(format!("labels from {} projects (needs {GATE_PROJECTS})", h.projects));
+ if own_projects < GATE_PROJECTS {
+ why.push(format!("your labels from {own_projects} projects (needs {GATE_PROJECTS})"));
}
match h.held_out {
Some(a) if a < GATE_AUC => why.push(format!("held-out AUC {a:.2} (needs {GATE_AUC})")),
diff --git a/systems/fingerprint/src/which.rs b/systems/fingerprint/src/which.rs
new file mode 100644
index 00000000..293600cb
--- /dev/null
+++ b/systems/fingerprint/src/which.rs
@@ -0,0 +1,132 @@
+//! Which fingerprint judges a piece (FP14c), found the way .editorconfig is: PROJECT/.raea/fingerprints, then
+//! WORKSPACE/.raea/fingerprints, then the person's own (folder::root). At each level the one whose `applies` matches
+//! the piece's kind and tags most closely wins, else that level's `default` file, else the next level up; the
+//! account's default always matches. A project or workspace pins one by writing its level's `default`.
+//!
+//! A piece's kind is its project's `kind` in .raea/project (film, ad, game, playable), else what the file is (a still
+//! or a sound); its tags are the project's `tags`.
+
+use crate::folder::{Folder, root};
+use crate::taxonomy::Fingerprint;
+use serde::Serialize;
+use std::path::{Path, PathBuf};
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Choice {
+ pub name: String,
+ pub dir: PathBuf,
+ pub about: Option<String>,
+ /// project, workspace or account
+ pub level: String,
+ /// the rule that chose it, in words
+ pub why: String,
+}
+
+/// The piece's kind and tags
+#[derive(Clone, Debug, Default, Serialize)]
+pub struct Piece {
+ pub kind: Option<String>,
+ pub tags: Vec<String>,
+ pub project: Option<PathBuf>,
+ pub workspace: Option<PathBuf>,
+}
+
+/// A key's value in a git-config style file (.raea/project, .raea/workspace)
+fn key(text: &str, k: &str) -> Option<String> {
+ text.lines().map(str::trim).find_map(|l| l.strip_prefix(k).map(str::trim_start).and_then(|r| r.strip_prefix('=')).map(|v| v.trim().to_string())).filter(|v| !v.is_empty())
+}
+
+fn up(from: &Path, marker: &str) -> Option<PathBuf> {
+ from.ancestors().find(|d| d.join(".raea").join(marker).is_file()).map(Path::to_path_buf)
+}
+
+pub fn piece(path: &Path) -> Piece {
+ let start = if path.is_dir() { path } else { path.parent().unwrap_or(path) };
+ let project = up(start, "project");
+ let workspace = up(start, "workspace");
+ let text = project.as_ref().and_then(|p| std::fs::read_to_string(p.join(".raea/project")).ok()).unwrap_or_default();
+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
+ let by_file = match ext.as_str() {
+ "png" | "jpg" | "jpeg" | "webp" => Some("still"),
+ "wav" | "mp3" | "flac" | "m4a" | "ogg" => Some("sound"),
+ _ => None,
+ };
+ let kind = key(&text, "kind").or_else(|| by_file.map(str::to_string));
+ let tags = key(&text, "tags").map(|t| t.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default();
+ Piece { kind, tags, project, workspace }
+}
+
+/// The fingerprints kept at a level: each folder under it with a fingerprint.ts
+pub fn at_level(dir: &Path) -> Vec<(Folder, Fingerprint)> {
+ let mut out: Vec<(Folder, Fingerprint)> = std::fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .map(|e| Folder { dir: e.path() })
+ .filter(Folder::exists)
+ .filter_map(|f| f.read(None).ok().map(|fp| (f, fp)))
+ .collect();
+ out.sort_by(|a, b| a.1.name.cmp(&b.1.name));
+ out
+}
+
+/// How closely a fingerprint's `applies` matches the piece: 2 for its kind, 1 a tag; 0 is no match
+fn closeness(fp: &Fingerprint, p: &Piece) -> usize {
+ let Some(a) = &fp.applies else { return 0 };
+ let kind = p.kind.as_ref().is_some_and(|k| a.kinds.contains(k));
+ if !a.kinds.is_empty() && !kind {
+ return 0;
+ }
+ 2 * usize::from(kind) + a.tags.iter().filter(|t| p.tags.contains(t)).count()
+}
+
+/// The levels to look in, nearest first
+pub fn levels(p: &Piece) -> Vec<(&'static str, PathBuf)> {
+ let mut v = Vec::new();
+ if let Some(d) = &p.project {
+ v.push(("project", d.join(".raea/fingerprints")));
+ }
+ if let Some(d) = &p.workspace {
+ v.push(("workspace", d.join(".raea/fingerprints")));
+ }
+ v.push(("account", root()));
+ v
+}
+
+/// A level's `default`, found at that level or above
+fn named(name: &str, levels: &[(&'static str, PathBuf)], from: usize) -> Option<(Folder, Fingerprint)> {
+ levels[from..].iter().map(|(_, d)| Folder { dir: d.join(name) }).find(Folder::exists).and_then(|f| f.read(None).ok().map(|fp| (f, fp)))
+}
+
+fn choice((f, fp): (Folder, Fingerprint), level: &str, why: String) -> Choice {
+ Choice { name: fp.name.clone(), dir: f.dir, about: fp.about, level: level.into(), why }
+}
+
+/// The fingerprint that judges the piece at `path`, and why; None only when the person has none at all
+pub fn which(path: &Path) -> Option<Choice> {
+ let p = piece(path);
+ let levels = levels(&p);
+ for (i, (level, dir)) in levels.iter().enumerate() {
+ let here = at_level(dir);
+ let best = here.iter().map(|x| (closeness(&x.1, &p), x)).filter(|(c, _)| *c > 0).max_by_key(|(c, _)| *c);
+ if let Some((_, (f, fp))) = best {
+ let what = p.kind.as_deref().map_or("the project's tags".to_string(), |k| format!("{k} pieces"));
+ return Some(choice((Folder { dir: f.dir.clone() }, fp.clone()), level, format!("the {level}'s, and it applies to {what}")));
+ }
+ let pinned = std::fs::read_to_string(dir.join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
+ if let Some(found) = pinned.as_deref().and_then(|n| named(n, &levels, i)) {
+ return Some(choice(found, level, format!("the {level}'s default")));
+ }
+ }
+ // the account always has one: its default, else "me", else the first it has
+ let here = at_level(&root());
+ let me = here.iter().position(|x| x.1.name == "me").unwrap_or(0);
+ here.into_iter().nth(me).map(|x| choice(x, "account", "the account's only fingerprint, with no default set".into()))
+}
+
+/// The `default` file `use` writes for a level: PROJECT/.raea/fingerprints, WORKSPACE/.raea/fingerprints or the
+/// account's
+pub fn default_file(path: &Path, level: &str) -> Option<PathBuf> {
+ let p = piece(path);
+ levels(&p).into_iter().find(|(l, _)| *l == level).map(|(_, d)| d.join("default"))
+}
diff --git a/systems/fingerprint/src/words.rs b/systems/fingerprint/src/words.rs
index 8a2c0be4..88564f8f 100644
--- a/systems/fingerprint/src/words.rs
+++ b/systems/fingerprint/src/words.rs
@@ -28,7 +28,7 @@ pub fn space(m: Modality) -> Option<Modality> {
}
}
-fn unit(v: &[f32]) -> Vec<f32> {
+pub fn unit(v: &[f32]) -> Vec<f32> {
let n = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
v.iter().map(|x| x / n).collect()
}
@@ -66,12 +66,18 @@ impl Words {
/// The axis's word score for a window: its similarity to the words as a z against the vocabulary
pub fn z(&self, axis: &str, row: &[f32]) -> Option<f32> {
- let (_, sp, v) = self.axes.iter().find(|a| a.0 == axis)?;
- let w = Self::window(row, *sp);
+ let sp = self.axes.iter().find(|a| a.0 == axis)?.1;
+ let w = Self::window(row, sp);
if w.iter().all(|x| *x == 0.0) {
return None;
}
- let dot = |a: &[f32]| a.iter().zip(&w).map(|(x, y)| x * y).sum::<f32>();
+ self.z_of(axis, &w)
+ }
+
+ /// The same z for a window's unit vector already in the axis's space (a CLAP or SigLIP 2 vector)
+ pub fn z_of(&self, axis: &str, w: &[f32]) -> Option<f32> {
+ let (_, sp, v) = self.axes.iter().find(|a| a.0 == axis)?;
+ let dot = |a: &[f32]| a.iter().zip(w).map(|(x, y)| x * y).sum::<f32>();
let bg: Vec<f32> = (if *sp == Modality::Sound { &self.sound_vocab } else { &self.picture_vocab }).iter().map(|b| dot(b)).collect();
let m = bg.iter().sum::<f32>() / bg.len() as f32;
let sd = (bg.iter().map(|x| (x - m).powi(2)).sum::<f32>() / bg.len() as f32).sqrt().max(1e-6);