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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
FP5a, FP6b, FP6c, FP6e, FP8c, FP14c, FP14e: raea fingerprint pair WORSE BETTER records a pick or a hand edit as a pair, fit Bradley-Terry and held out by project, and an axis with pairs and no labels is ranked by them alone; versions makes weak pairs of noted moments the next version changed and nobody noted again; profile takes the ranges work you admire spans (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside, where and which way; read has a fresh session read a project's pinned notes into kinds and axes, readings puts them to you in the app and tallies your answers, and learn-notes trains on them only once you've agreed with 45 kinds and 40 axes in 50; reembed moves evidence to this machine's encoders where its media is found, each row keeping the pin it was embedded on; new --kinds --tags writes where a fingerprint applies; bootstrap leaves gaps and clipping out of windows too quiet for them to change. Scoring, the sheet, which, diff and profiles move to raea-sys-fingerprint-use, keeping raea-sys-fingerprint under its size. The guide (docs/manual/guides/fingerprint.md) and every new flag in the CLI reference
shinyobjectz6f253b3fe550
diff --git a/Cargo.lock b/Cargo.lockindex 40598b25..5f2f69c4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13677,6 +13677,7 @@ dependencies = ["raea-app-check","raea-sys-columns","raea-sys-fingerprint",+ "raea-sys-fingerprint-use","serde","serde_json",]@@ -15473,8 +15474,19 @@ version = "0.1.0"dependencies = ["anyhow","half",+ "raea-sys-columns",+ "serde",+ "serde_json",+]++[[package]]+name = "raea-sys-fingerprint-use"+version = "0.1.0"+dependencies = [+ "anyhow","image","raea-sys-columns",+ "raea-sys-fingerprint","serde","serde_json",]diff --git a/Cargo.toml b/Cargo.tomlindex fcff57f0..c57da15a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -83,6 +83,7 @@ members = ["systems/vision","systems/columns","systems/fingerprint",+ "systems/fingerprint-use","systems/song","systems/perceive","systems/footage",diff --git a/apps/fingerprint/Cargo.toml b/apps/fingerprint/Cargo.tomlindex 1e880228..be11f40a 100644--- a/apps/fingerprint/Cargo.toml+++ b/apps/fingerprint/Cargo.toml@@ -7,8 +7,10 @@ publish = falsedescription = "`raea fingerprint` (docs/fingerprint.feature FP3a): new, bootstrap, teach, score and report, run by a resident service on localhost that keeps the encoders loaded"[dependencies]-# the taxonomy, evidence, heads, bootstrap, scoring and sheet+# the taxonomy, evidence and headsraea-sys-fingerprint = { path = "../../systems/fingerprint" }+# scoring and the sheet, which one judges a piece, diff and profiles+raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }# the encoders and the columns they makeraea-sys-columns = { path = "../../systems/columns" }# raea check's floor on the file: its findings go in the summary, and a check wins over a head (FP4c)diff --git a/apps/fingerprint/src/approve.rs b/apps/fingerprint/src/approve.rsindex 4197d29c..97b7c8ee 100644--- a/apps/fingerprint/src/approve.rs+++ b/apps/fingerprint/src/approve.rs@@ -64,6 +64,7 @@ pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args:region: None,words: None,at: 0,+ pin: None,};l.push(row, &features(&c, *a, *b));}diff --git a/apps/fingerprint/src/bootstrap.rs b/apps/fingerprint/src/bootstrap.rsindex 82518be0..5e789e31 100644--- a/apps/fingerprint/src/bootstrap.rs+++ b/apps/fingerprint/src/bootstrap.rs@@ -48,9 +48,22 @@ pub struct Made {pub sources: usize,pub windows: usize,pub rows: usize,+ /// windows too quiet for a gap or clipping to change them, which get only the noise damage+ pub quiet: usize,pub skipped: Vec<String>,}+/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise+const QUIET_DB: f32 = -45.0;++/// The window's loudness in dB over all of it+fn loudness(pcm: &[f32]) -> f32 {+ if pcm.is_empty() {+ return -100.0;+ }+ (10.0 * (pcm.iter().map(|x| x * x).sum::<f32>() / pcm.len() as f32).max(1e-10).log10()).max(-100.0)+}+fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {v.resize(n, 0.0);v@@ -122,6 +135,7 @@ pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &muregion: None,words: None,at: 0,+ pin: None,};l.push(r, &features(c, 0.0, WIN));};@@ -131,8 +145,10 @@ pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mulet (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);}+ let quiet = loudness(&w16) < QUIET_DB;+ made.quiet += quiet as usize;let sound = SOUND.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| SOUND.contains(&c.1)).map(|c| (c.0, c.1, "cheat")));- for (kind, axis, source) in sound {+ for (kind, axis, source) in sound.filter(|s| !quiet || s.1 == "noise") {let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));let (clap, yam) = enc.sound(&d16, &d48)?;push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rsindex 826982f1..08006795 100644--- a/apps/fingerprint/src/lib.rs+++ b/apps/fingerprint/src/lib.rs@@ -6,7 +6,11 @@mod approve;mod bootstrap;+mod notes;+mod pairing;mod pick;+mod profiles;+mod reembed;mod serve;mod verbs;@@ -14,14 +18,16 @@ 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 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)";+pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [--ask N] [--tally] | raea fingerprint learn-notes | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50)";/// 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); 19] = [+pub(crate) const FLAGS: [(&str, bool); 28] = [("--fp", true),+ ("--kinds", true),+ ("--tags", true),("--who", true),("--about", true),("--extends", true),@@ -29,12 +35,19 @@ pub(crate) const FLAGS: [(&str, bool); 19] = [("--per", true),("--axis", true),("--at", true),+ ("--then", true),("--span", true),("--box", true),("--words", true),("--project", true),("--sheet", true),("--in", true),+ ("--as", true),+ ("--against", true),+ ("--profile", true),+ ("--by", true),+ ("--ask", true),+ ("--tally", false),("--bad", false),("--good", false),("--json", false),@@ -89,9 +102,11 @@ pub fn cli(args: &[String], eval: Eval) -> i32 {"report" => verbs::report_here(args),"which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),"diff" => pick::diff_here(&args[1..]),+ "read" => notes::read_here(&args[1..], &std::env::current_dir().unwrap_or_default()),+ "readings" => notes::readings_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" => {+ "new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "reembed" | "profile" | "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/notes.rs b/apps/fingerprint/src/notes.rsnew file mode 100644index 00000000..e3bda8d0--- /dev/null+++ b/apps/fingerprint/src/notes.rs@@ -0,0 +1,317 @@+//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`+//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or+//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them+//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show+//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only+//! once the kind is right 45 times in 50 and the axis 40 (FP5b) does `raea fingerprint learn-notes` make each defect+//! or praise an evidence row over its span (1.5 s before the pin to 0.5 s after). A direction goes to the brief and the+//! agent, never into a head.++use crate::{flag, has, words};+use raea_sys_fingerprint::folder::Folder;+use raea_sys_fingerprint::taxonomy::Fingerprint;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::path::{Path, PathBuf};++/// FP5b's bar, out of every 50 checked+pub const KIND_BAR: f64 = 45.0 / 50.0;+pub const AXIS_BAR: f64 = 40.0 / 50.0;+pub const INBOX: &str = "fingerprint";++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Reading {+ pub note: String,+ pub text: String,+ pub who: String,+ pub media: PathBuf,+ pub t: f64,+ pub project: String,+ /// defect, direction, praise or both+ pub kind: String,+ pub axis: Option<String>,+ /// how it was read: kimi or claude+ pub by: String,+ /// the person's check: Some(true) agreed, Some(false) not; None until asked+ #[serde(default)]+ pub kind_ok: Option<bool>,+ #[serde(default)]+ pub axis_ok: Option<bool>,+}++/// A post's video on this machine: the renders library, else the project's own folder+fn media(project: &Path, m: &Value) -> Option<PathBuf> {+ let p = m["path"].as_str()?;+ let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());+ [home.join(".raea/feed/media").join(p), project.join(p)].into_iter().find(|f| f.is_file())+}++/// Every person's pinned note on a video in the project's feed+pub fn pinned(project: &Path) -> Vec<Reading> {+ let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let mut out = Vec::new();+ for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {+ let Ok(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).ok_or(()) else { continue };+ let Some(video) = post["media"].as_array().into_iter().flatten().find(|m| m["kind"] == "video").and_then(|m| media(project, m)) else { continue };+ for n in post["notes"].as_array().into_iter().flatten() {+ let (Some(t), Some(text)) = (n["pin"]["t"].as_f64(), n["text"].as_str()) else { continue };+ if n["author"]["kind"] != "person" {+ continue;+ }+ out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), ..Default::default() });+ }+ }+ out+}++/// The reading prompt: the axes with their words, then the notes, and the JSON to answer+pub fn prompt(fp: &Fingerprint, notes: &[Reading]) -> String {+ let axes = fp.axes.iter().map(|a| format!("- {}: {}", a.name, a.words.join("; "))).collect::<Vec<_>>().join("\n");+ let list = notes.iter().map(|n| format!("{}: {}", n.note, n.text.replace('\n', " "))).collect::<Vec<_>>().join("\n");+ format!(+ "You read a person's review notes on their videos. Read each note only; open no file and change nothing.\n\+For each note say its kind: \"defect\" (it names something wrong at that moment), \"direction\" (it asks for a creative change, \+not a fault), \"praise\" (it says something is good) or \"both\" (a defect and a direction). Then the axis it is about, from \+these and only these, or null when none fits:\n{axes}\n\nThe notes, one a line, id first:\n{list}\n\n\+End with only this JSON, nothing after it: [{{\"id\": \"\", \"kind\": \"defect|direction|praise|both\", \"axis\": \"name or null\"}}]"+ )+}++/// The JSON array an answer ends with+pub fn answer(text: &str) -> Option<Vec<Value>> {+ let end = text.rfind(']')?;+ let start = text[..end].rfind("[{").or_else(|| text[..end].rfind('['))?;+ serde_json::from_str(&text[start..=end]).ok()+}++/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped+pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {+ for a in ans {+ let Some(n) = notes.iter_mut().find(|n| a["id"].as_str() == Some(n.note.as_str())) else { continue };+ let kind = a["kind"].as_str().unwrap_or("");+ if !matches!(kind, "defect" | "direction" | "praise" | "both") {+ continue;+ }+ n.kind = kind.into();+ n.axis = a["axis"].as_str().filter(|x| fp.axis(x).is_some()).map(str::to_string);+ n.by = by.into();+ }+}++/// One fresh session's words: kimi's or claude's stream, the assistant's text joined+fn ask(by: &str, p: &str) -> Result<String, String> {+ let mut c = std::process::Command::new(by);+ match by {+ "kimi" => c.args(["-p", p, "--output-format", "stream-json"]),+ "claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),+ o => return Err(format!("--by {o}: kimi or claude")),+ };+ let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;+ let mut text = String::new();+ for line in String::from_utf8_lossy(&out.stdout).lines() {+ let Ok(v) = serde_json::from_str::<Value>(line) else { continue };+ let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };+ match content {+ Value::String(s) => text += s,+ Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),+ _ => {}+ }+ text.push('\n');+ }+ if text.trim().is_empty() {+ return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));+ }+ Ok(text)+}++pub fn readings_of(dir: &Folder) -> Vec<Reading> {+ std::fs::read_to_string(dir.dir.join("readings.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()+}++pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {+ std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())+}++/// `raea fingerprint read PROJECT [--by kimi|claude]`+pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {+ let run = || -> Result<String, String> {+ let w = words(args)?;+ let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));+ let by = flag(args, "--by").unwrap_or("kimi");+ let dir = crate::pick::chosen(args, Some(&project.join("x.mp4"))).0;+ let fp = dir.read(None).map_err(|e| e.to_string())?;+ let mut notes = pinned(&project);+ let mut kept = readings_of(&dir);+ notes.retain(|n| !kept.iter().any(|k| k.note == n.note && k.media == n.media));+ if notes.is_empty() {+ return Ok(format!("no new pinned notes in {}", project.display()));+ }+ for chunk in notes.chunks_mut(40) {+ let text = ask(by, &prompt(&fp, chunk))?;+ let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;+ fold(chunk, &fp, &ans, by);+ eprintln!("read {} notes", chunk.len());+ }+ let read = notes.iter().filter(|n| !n.kind.is_empty()).count();+ kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));+ write_readings(&dir, &kept).map_err(|e| e.to_string())?;+ Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))+ };+ match run() {+ Ok(o) => {+ println!("{o}");+ 0+ }+ Err(e) => {+ eprintln!("raea fingerprint read: {e}");+ 1+ }+ }+}++/// The share of checked readings the person agreed with, for kind and for axis, and how many were checked+pub fn agreement(r: &[Reading]) -> (Option<f64>, Option<f64>, usize) {+ let share = |v: Vec<bool>| (!v.is_empty()).then(|| v.iter().filter(|x| **x).count() as f64 / v.len() as f64);+ let checked = r.iter().filter(|x| x.kind_ok.is_some()).count();+ (share(r.iter().filter_map(|x| x.kind_ok).collect()), share(r.iter().filter_map(|x| x.axis_ok).collect()), checked)+}++/// Whether the readings have earned training (FP5b): 50 checked, the kind right 45 times and the axis 40+pub fn earned(r: &[Reading]) -> bool {+ matches!(agreement(r), (Some(k), Some(a), n) if n >= 50 && k >= KIND_BAR && a >= AXIS_BAR)+}++/// The choices a reading is checked with, and what each says about kind and axis+pub const CHOICES: [(&str, bool, bool); 4] = [("Right", true, true), ("Right kind, wrong axis", true, false), ("Wrong kind", false, false), ("Right axis, wrong kind", false, true)];++/// `raea fingerprint readings [--ask N] [--tally]`+pub(crate) fn readings_here(args: &[String]) -> i32 {+ let dir = crate::pick::chosen(args, None).0;+ let mut r = readings_of(&dir);+ if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {+ let todo: Vec<usize> = (0..r.len()).filter(|&i| r[i].kind_ok.is_none()).take(n).collect();+ let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));+ cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);+ for &i in &todo {+ let x = &r[i];+ let q = format!("[{}] \"{}\" read as {} on {}", x.note, x.text.replace('\n', " "), x.kind, x.axis.as_deref().unwrap_or("no axis"));+ cmd.args(["--question", &q, "--preview", &x.media.display().to_string()]);+ for (c, _, _) in CHOICES {+ cmd.args(["--choice", c]);+ }+ }+ if todo.is_empty() {+ println!("every reading is checked");+ return 0;+ }+ let Ok(out) = cmd.output() else { return 1 };+ let said = String::from_utf8_lossy(&out.stdout).into_owned();+ // the item raea show made, so the answers can be matched to the notes asked, in order+ let Some(item) = said.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',').find(|w| w.starts_with("i-show-")) else {+ eprintln!("raea fingerprint readings: raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr));+ return 1;+ };+ let mut asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();+ asked.insert(item.to_string(), json!(todo.iter().map(|&i| [r[i].note.clone(), r[i].media.display().to_string()]).collect::<Vec<_>>()));+ let _ = std::fs::write(dir.dir.join("asked.json"), serde_json::to_vec_pretty(&asked).unwrap_or_default());+ println!("{} readings put to you in the app ({item}); `raea fingerprint readings --tally` counts your answers", todo.len());+ return 0;+ }+ if has(args, "--tally") {+ let asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();+ let inbox = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{INBOX}.jsonl"));+ for line in std::fs::read_to_string(inbox).unwrap_or_default().lines() {+ let Ok(v) = serde_json::from_str::<Value>(line) else { continue };+ let Some(batch) = v["item"].as_str().and_then(|i| asked.get(i)).and_then(Value::as_array) else { continue };+ for (k, who) in batch.iter().enumerate() {+ let Some(a) = v["answers"][format!("q{}", k + 1)].as_str() else { continue };+ let Some((_, ok_kind, ok_axis)) = CHOICES.iter().find(|c| c.0 == a) else { continue };+ if let Some(x) = r.iter_mut().find(|x| who[0].as_str() == Some(x.note.as_str()) && who[1].as_str() == Some(&x.media.display().to_string())) {+ (x.kind_ok, x.axis_ok) = (Some(*ok_kind), Some(*ok_axis));+ }+ }+ }+ let _ = write_readings(&dir, &r);+ }+ let (k, a, n) = agreement(&r);+ let f = |x: Option<f64>| x.map_or("-".into(), |v| format!("{:.0}%", v * 100.0));+ println!("{} readings, {n} checked: kind right {}, axis right {} (FP5b needs 50 checked, 90% and 80%): {}", r.len(), f(k), f(a), if earned(&r) { "notes may train" } else { "notes don't train yet" });+ println!("{}", json!({"readings": r.len(), "checked": n, "kind": k, "axis": a, "earned": earned(&r)}));+ 0+}++/// `learn-notes`: each checked-off reading's defect or praise as an evidence row over its span, once the readings+/// have earned it; a reading already learned is replaced, so learning again is safe+pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mut raea_sys_fingerprint::evidence::Ledger) -> anyhow::Result<String> {+ let r = readings_of(dir);+ if !earned(&r) {+ let (k, a, n) = agreement(&r);+ anyhow::bail!("notes don't train yet: {n} readings checked, kind right {:?}, axis right {:?} (FP5b needs 50 checked, 90% and 80%: raea fingerprint readings --ask 50)", k, a);+ }+ l.retain(|x| x.source != "note");+ let mut made = 0;+ for x in r.iter().filter(|x| x.kind_ok != Some(false) && x.axis_ok != Some(false)) {+ let bad = match x.kind.as_str() {+ "defect" | "both" => true,+ "praise" => false,+ _ => continue,+ };+ let axis = match (&x.axis, bad) {+ (Some(a), _) => a.clone(),+ (None, false) => "*".into(),+ (None, true) => continue,+ };+ let c = enc.columns(&x.media)?;+ let (a, b) = ((x.t - 1.5).max(0.0), (x.t + 0.5).min(c.dur));+ if b - a < 0.5 {+ continue;+ }+ let row = raea_sys_fingerprint::evidence::Row {+ media: c.media.clone(),+ a,+ b,+ axis,+ bad,+ weight: 1.0,+ who: x.who.clone(),+ source: "note".into(),+ project: x.project.clone(),+ kind: Some(x.note.clone()),+ region: None,+ words: Some(x.text.clone()),+ at: 0,+ pin: None,+ };+ l.push(row, &raea_sys_fingerprint::evidence::features(&c, a, b));+ made += 1;+ }+ Ok(format!("{made} notes are evidence now (defects and praise; directions stay with the brief)\n"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_reading_keeps_only_kinds_and_axes_it_knows() {+ let fp = raea_sys_fingerprint::taxonomy::base("me");+ let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];+ let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();+ fold(&mut n, &fp, &ans, "kimi");+ assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));+ assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");+ assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");+ assert!(prompt(&fp, &n).contains("n1: "));+ }++ #[test]+ fn notes_train_only_once_the_person_agrees_enough() {+ let r = |k: bool, a: bool| Reading { kind_ok: Some(k), axis_ok: Some(a), ..Default::default() };+ let mut v: Vec<Reading> = (0..45).map(|_| r(true, true)).collect();+ v.extend((0..5).map(|_| r(false, false)));+ assert!(earned(&v), "45 and 45 of 50");+ v[0] = r(false, true);+ assert!(!earned(&v), "44 kinds of 50 is under the bar");+ assert!(!earned(&v[..40]), "fewer than 50 checked");+ }+}diff --git a/apps/fingerprint/src/pairing.rs b/apps/fingerprint/src/pairing.rsnew file mode 100644index 00000000..bb6fdd1a--- /dev/null+++ b/apps/fingerprint/src/pairing.rs@@ -0,0 +1,94 @@+//! Pairs from what the person already does (docs/fingerprint.feature FP6b, FP6c). `raea fingerprint pair WORSE BETTER+//! --axis A [--at T] [--then T2]` records a pick between real options or a hand edit's before and after: the better+//! window against the worse on that axis. `raea fingerprint versions V1 V2...` (the files in version order) makes a+//! weak pair (weight 0.5, every axis) of each noted moment whose picture or sound changed in the next version (cosine+//! distance 0.01 or more) and wasn't noted again within 1 s there.++use crate::approve::noted;+use crate::{flag, words};+use anyhow::{Context, Result, anyhow, bail};+use raea_sys_columns::Encoders;+use raea_sys_columns::window::Modality;+use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};+use raea_sys_fingerprint::pairs::difference;+use std::path::{Path, PathBuf};++fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {+ Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None }+}++fn files(args: &[String], cwd: &Path) -> Result<Vec<PathBuf>> {+ Ok(words(args).map_err(|e| anyhow!(e))?.iter().map(|f| if Path::new(f).is_absolute() { PathBuf::from(f) } else { cwd.join(f) }).collect())+}++/// `pair`: one row, the worse window's features minus the better one's+pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {+ let f = files(args, cwd)?;+ let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };+ let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;+ let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;+ let t: f64 = flag(args, "--at").map_or(Ok(span / 2.0), str::parse).context("--at takes seconds")?;+ let t2: f64 = flag(args, "--then").map_or(Ok(t), str::parse).context("--then takes seconds")?;+ let (cw, cb) = (enc.columns(worse)?, enc.columns(better)?);+ let win = |dur: f64, t: f64| {+ let a = (t - span / 2.0).clamp(0.0, (dur - span).max(0.0));+ (a, (a + span).min(dur))+ };+ let ((a, b), (a2, b2)) = (win(cw.dur, t), win(cb.dur, t2));+ let d = difference(&features(&cw, a, b), &features(&cb, a2, b2));+ l.push(row(&cw.media, a, b, axis, 1.0, who, flag(args, "--project").map_or_else(|| project(worse), str::to_string), flag(args, "--words").map(str::to_string)), &d);+ Ok(format!("paired on {axis}: {} at {a:.1} s is worse than {} at {a2:.1} s\n", worse.display(), better.display()))+}++fn distance(x: &[f32], y: &[f32]) -> f32 {+ let d: f32 = x.iter().zip(y).map(|(a, b)| a * b).sum();+ 1.0 - d / (x.iter().map(|a| a * a).sum::<f32>().sqrt() * y.iter().map(|b| b * b).sum::<f32>().sqrt()).max(1e-9)+}++/// Whether a noted moment changed in the next version and wasn't noted there again+pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) -> bool {+ let changed = [Modality::Picture, Modality::Sound].iter().any(|&m| distance(&before[slice(m)], &after[slice(m)]) >= 0.01);+ changed && !next_notes.iter().any(|n| (n - t).abs() <= 1.0)+}++/// `versions`: weak pairs along a chain of versions+pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {+ let f = files(args, cwd)?;+ if f.len() < 2 {+ bail!("raea fingerprint versions V1 V2... takes the versions in order");+ }+ let mut made = 0;+ for w in f.windows(2) {+ let (now, next) = (&w[0], &w[1]);+ let (cn, cx) = (enc.columns(now)?, enc.columns(next)?);+ let next_notes = noted(next);+ for t in noted(now) {+ let (a, b) = ((t - 1.5).max(0.0), (t + 0.5).min(cn.dur.min(cx.dur)));+ if b - a < 1.0 {+ continue;+ }+ let (fb, fa) = (features(&cn, a, b), features(&cx, a, b));+ if weak(&fb, &fa, t, &next_notes) {+ l.push(row(&cn.media, a, b, "*", 0.5, who, flag(args, "--project").map_or_else(|| project(now), str::to_string), None), &difference(&fb, &fa));+ made += 1;+ }+ }+ }+ Ok(format!("{made} weak pairs from {} versions: noted moments the next version changed and nobody noted again\n", f.len()))+}++#[cfg(test)]+mod tests {+ use raea_sys_fingerprint::evidence::width;++ #[test]+ fn a_changed_moment_not_noted_again_is_a_weak_pair() {+ let a = vec![1.0; width()];+ let mut b = a.clone();+ assert!(!super::weak(&a, &b, 5.0, &[]), "unchanged: no pair");+ b.iter_mut().enumerate().for_each(|(i, x)| *x = if i % 2 == 0 { 1.0 } else { -1.0 });+ assert!(super::weak(&a, &b, 5.0, &[]));+ assert!(!super::weak(&a, &b, 5.0, &[5.6]), "noted again within 1 s: no pair");+ assert!(super::weak(&a, &b, 5.0, &[7.0]));+ }+}diff --git a/apps/fingerprint/src/pick.rs b/apps/fingerprint/src/pick.rsindex 4ed2ae75..cf2c3585 100644--- a/apps/fingerprint/src/pick.rs+++ b/apps/fingerprint/src/pick.rs@@ -4,7 +4,7 @@use crate::{flag, has, words};use raea_sys_fingerprint::folder::{Folder, root};-use raea_sys_fingerprint::which::{Choice, default_file, levels, piece, which};+use raea_sys_fingerprint_use::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"@@ -78,7 +78,7 @@ pub(crate) fn diff_here(args: &[String]) -> i32 {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) {+ match raea_sys_fingerprint_use::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());0diff --git a/apps/fingerprint/src/profiles.rs b/apps/fingerprint/src/profiles.rsnew file mode 100644index 00000000..7d372983--- /dev/null+++ b/apps/fingerprint/src/profiles.rs@@ -0,0 +1,85 @@+//! `raea fingerprint profile REFS... --as NAME [--against LIST]` and `score FILE --profile NAME` (docs/fingerprint.feature+//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a+//! piece critiqued against it, measure by measure, with where and which way to move.++use crate::{flag, words};+use anyhow::{Context, Result, anyhow, bail};+use raea_sys_columns::{Encoders, media};+use raea_sys_fingerprint::folder::Folder;+use raea_sys_fingerprint_use::profile::{Measures, NAMES, Out, Profile, critique, measures, profile};+use raea_sys_fingerprint_use::score::clock;+use std::path::{Path, PathBuf};++const BINS: usize = 12;+/// The windows the critique says "where" with, seconds+const WIN: f64 = 4.0;++fn at(cwd: &Path, p: &str) -> PathBuf {+ if Path::new(p).is_absolute() { PathBuf::from(p) } else { cwd.join(p) }+}++/// A piece's measures, whole and in windows+pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {+ let c = enc.columns(file)?;+ let pcm = media::sound(file, 16_000).unwrap_or_default();+ let cols = ((c.dur * 10.0) as usize).max(1);+ let spec = media::spectrogram(&pcm, 16_000, cols, BINS);+ let whole = measures(&c, &spec, BINS, 0.0, c.dur);+ let n = (c.dur / WIN).ceil() as usize;+ let windows = (0..n).map(|i| {+ let (a, b) = (i as f64 * WIN, ((i + 1) as f64 * WIN).min(c.dur));+ ((a, b), measures(&c, &spec, BINS, a, b))+ }).collect();+ Ok((whole, windows))+}++fn path(dir: &Folder, name: &str) -> PathBuf {+ dir.dir.join("profiles").join(format!("{name}.json"))+}++pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {+ let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;+ let refs: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| at(cwd, f)).collect();+ if refs.len() < 2 {+ bail!("a profile needs two references or more (three for its leave-one-out check)");+ }+ let mut r = Vec::new();+ for f in &refs {+ r.push((f.display().to_string(), measured(enc, f)?.0));+ }+ let mut other = Vec::new();+ if let Some(list) = flag(args, "--against") {+ let list = at(cwd, list);+ for l in std::fs::read_to_string(&list).with_context(|| list.display().to_string())?.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {+ other.push(measured(enc, &at(list.parent().unwrap_or(cwd), l))?.0);+ }+ }+ let p = profile(name, r, &other);+ std::fs::create_dir_all(dir.dir.join("profiles"))?;+ std::fs::write(path(dir, name), serde_json::to_vec_pretty(&p)?)?;+ let mut out = format!("profile {name} from {} references:\n", p.refs.len());+ for (k, words) in NAMES {+ if let Some((lo, hi)) = p.ranges.get(k) {+ out += &format!(" {words:40} {lo:.2} to {hi:.2}\n");+ }+ }+ out += &match (p.inside_own, p.inside_other) {+ (Some(o), Some(x)) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time, unrelated work {:.0}%: {}\n", o * 100.0, x * 100.0, if p.tells == Some(true) { "it tells this taste apart" } else { "it does NOT tell this taste apart" }),+ (Some(o), None) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time (give --against LIST to compare with unrelated work)\n", o * 100.0),+ _ => "leave-one-out needs three references\n".into(),+ };+ Ok(out)+}++/// The critique of a piece against a saved profile, as lines+pub(crate) fn against(enc: &mut Encoders, dir: &Folder, name: &str, file: &Path) -> Result<(String, Vec<Out>)> {+ let p: Profile = serde_json::from_slice(&std::fs::read(path(dir, name)).with_context(|| format!("no profile {name} (raea fingerprint profile REFS... --as {name})"))?)?;+ let (whole, windows) = measured(enc, file)?;+ let out = critique(&p, &whole, &windows);+ let words = |k: &str| NAMES.iter().find(|n| n.0 == k).map_or(k.to_string(), |n| n.1.to_string());+ let mut t = format!("against the {name} profile: {}\n", if out.is_empty() { "every measure in range".to_string() } else { format!("{} out of range", out.len()) });+ for o in &out {+ t += &format!(" {} {:.2} is outside {:.2} to {:.2}: {} it{}\n", words(&o.measure), o.value, o.range.0, o.range.1, o.move_, o.at.map_or(String::new(), |(a, _)| format!(", most at {}", clock(a))));+ }+ Ok((t, out))+}diff --git a/apps/fingerprint/src/reembed.rs b/apps/fingerprint/src/reembed.rsnew file mode 100644index 00000000..075ec8ed--- /dev/null+++ b/apps/fingerprint/src/reembed.rs@@ -0,0 +1,90 @@+//! Encoder upgrades keep the evidence (docs/fingerprint.feature FP8c). When this machine's encoders aren't the ones a+//! fingerprint was trained on, `raea fingerprint reembed PLACE...` re-embeds every row whose media it finds under+//! those files and folders (matched by content hash), moves the fingerprint to the new encoders and retrains. A row+//! whose media isn't found keeps its old pin and trains no head until it's re-embedded or labelled again; a bootstrap's+//! damaged rows are remade by running the bootstrap again.++use crate::words;+use anyhow::{Result, anyhow};+use raea_sys_columns::{Encoders, media};+use raea_sys_fingerprint::evidence::features;+use raea_sys_fingerprint::folder::Folder;+use raea_sys_fingerprint::taxonomy::Fingerprint;+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++const MEDIA: [&str; 9] = ["mp4", "mov", "m4v", "webm", "mkv", "wav", "mp3", "m4a", "flac"];++/// An encoder set's short name, as a row's pin+pub(crate) fn pin_of(p: &BTreeMap<String, String>) -> String {+ p.iter().map(|(k, v)| format!("{k}:{}", &v[..v.len().min(8)])).collect::<Vec<_>>().join(",")+}++/// The media files under each place, two folders deep+fn files(places: &[PathBuf]) -> Vec<PathBuf> {+ fn walk(d: &Path, depth: usize, out: &mut Vec<PathBuf>) {+ for e in std::fs::read_dir(d).into_iter().flatten().flatten() {+ let p = e.path();+ if p.is_dir() && depth > 0 {+ walk(&p, depth - 1, out);+ } else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| MEDIA.contains(&x.to_ascii_lowercase().as_str())) {+ out.push(p);+ }+ }+ }+ let mut out = Vec::new();+ for p in places {+ if p.is_dir() { walk(p, 2, &mut out) } else { out.push(p.clone()) }+ }+ out+}++/// Rows moved to `here`'s encoders where their media is found; returns the fingerprint as it is now and what happened+pub(crate) fn reembed(enc: &mut Encoders, dir: &Folder, mut fp: Fingerprint, here: BTreeMap<String, String>, args: &[String], cwd: &Path) -> Result<(Fingerprint, String)> {+ let places: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| cwd.join(f)).collect();+ let mut l = dir.ledger()?;+ if fp.encoders != here {+ let old = pin_of(&fp.encoders);+ l.rows.iter_mut().filter(|r| r.pin.is_none()).for_each(|r| r.pin = Some(old.clone()));+ fp.encoders = here;+ dir.rewrite(&fp)?;+ }+ let waiting: std::collections::BTreeSet<String> = l.rows.iter().filter(|r| r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat")).map(|r| r.media.clone()).collect();+ let mut done = 0;+ for f in files(&places) {+ if waiting.is_empty() {+ break;+ }+ let Ok(sha) = media::sha256(&f) else { continue };+ if !waiting.contains(&sha) {+ continue;+ }+ let c = enc.columns(&f)?;+ for i in 0..l.rows.len() {+ let r = &l.rows[i];+ if r.media == sha && r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat") {+ let x = features(&c, r.a, r.b);+ l.set_features(i, &x);+ l.rows[i].pin = None;+ done += 1;+ }+ }+ }+ dir.write_ledger(&l)?;+ let left = l.rows.iter().filter(|r| r.pin.is_some()).count();+ let damage = l.rows.iter().filter(|r| r.pin.is_some() && matches!(r.source.as_str(), "damage" | "cheat")).count();+ let mut out = format!("re-embedded {done} rows on this machine's encoders; {left} wait on their old ones");+ if damage > 0 {+ out += &format!(" ({damage} from a bootstrap: run raea fingerprint bootstrap again to remake them)");+ }+ Ok((fp, out + "\n"))+}++#[cfg(test)]+mod tests {+ #[test]+ fn a_pin_names_each_encoder_and_its_hash() {+ let p = std::collections::BTreeMap::from([("clap".to_string(), "0123456789abcdef".to_string()), ("siglip".to_string(), "fedcba".to_string())]);+ assert_eq!(super::pin_of(&p), "clap:01234567,siglip:fedcba");+ }+}diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rsindex fa131ca7..1b87497a 100644--- a/apps/fingerprint/src/verbs.rs+++ b/apps/fingerprint/src/verbs.rs@@ -6,9 +6,9 @@ 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};+use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};+use raea_sys_fingerprint_use::sheet::{Tick, sheet};+use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base};use raea_sys_fingerprint::words::Words;use crate::bootstrap;use raea_sys_fingerprint::{report_text, retrain};@@ -31,6 +31,13 @@ pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, s"bootstrap" => boot(enc, rest, cwd, eval, say),"teach" => teach(enc, rest, cwd, eval),"approve" => approved(enc, rest, cwd, eval),+ "reembed" => reembedded(enc, rest, cwd, eval),+ "pair" | "versions" => paired(enc, args[0].as_str(), rest, cwd, eval),+ "learn-notes" => learned(enc, rest, eval),+ "profile" => {+ let dir = crate::pick::chosen(rest, None).0;+ crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))+ }"score" => scored(enc, rest, cwd, eval),v => Err(anyhow!("no verb {v}")),};@@ -41,7 +48,8 @@ fn pins(enc: &Encoders) -> BTreeMap<String, String> {enc.pins().into_iter().collect()}-/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about+/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,+/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {let mut fp = base(short);if let Some(p) = parent {@@ -50,6 +58,11 @@ pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>)}fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);+ let list = |f: &str| -> Vec<String> { flag(args, f).map(|v| v.split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect()).unwrap_or_default() };+ let (kinds, tags) = (list("--kinds"), list("--tags"));+ if !kinds.is_empty() || !tags.is_empty() {+ fp.applies = Some(Applies { kinds, tags });+ }fp}@@ -94,7 +107,12 @@ fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) ->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);+ bail!(+ "{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",+ 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)));@@ -162,6 +180,40 @@ fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> ResuOk((out, 0))}+/// `reembed`: the evidence moved to this machine's encoders (reembed.rs, FP8c), the words remade and the heads retrained+fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {+ let dir = crate::pick::chosen(args, None).0;+ let raw = dir.read(Some(eval))?;+ let (fp, out) = crate::reembed::reembed(enc, &dir, raw, pins(enc), args, cwd)?;+ let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));+ let w = Words::build(enc, &fp)?;+ dir.write_words(&w)?;+ retrain(&dir, &fp, &w, &dir.ledger()?, None)?;+ Ok((out, 0))+}++/// `pair` and `versions` (pairing.rs, FP6b, FP6c), then the heads retrained+fn paired(enc: &mut Encoders, verb: &str, 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 who = fp.who.clone().unwrap_or_else(|| "me".into());+ let mut l = dir.ledger()?;+ let out = if verb == "pair" { crate::pairing::pair(enc, &mut l, &who, args, cwd, project_of)? } else { crate::pairing::versions(enc, &mut l, &who, args, cwd, project_of)? };+ dir.write_ledger(&l)?;+ retrain(&dir, &fp, &w, &l, None)?;+ Ok((out, 0))+}++/// `learn-notes` (notes.rs, FP5a): checked readings as evidence, then the heads retrained+fn learned(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(String, i32)> {+ let (dir, fp, w) = open(enc, args, eval, None)?;+ let mut l = dir.ledger()?;+ let out = crate::notes::learn(enc, &dir, &mut l)?;+ dir.write_ledger(&l)?;+ retrain(&dir, &fp, &w, &l, None)?;+ Ok((out, 0))+}+fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {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))?;@@ -193,6 +245,7 @@ fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<region: region.transpose()?,words: flag(args, "--words").map(str::to_string),at: 0,+ pin: None,};let mut l = dir.ledger()?;l.push(row, &features(&c, a, b));@@ -256,6 +309,9 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Resultif has(args, "--timeline") {out += &timeline(&s);}+ if let Some(p) = flag(args, "--profile") {+ out += &crate::profiles::against(enc, &dir, p, &file)?.0;+ }if let Some(png) = flag(args, "--sheet") {let png = at(cwd, png);let frames: Vec<media::Rgb> = (0..12).filter_map(|i| media::frames(&file, FPS, c.dur * (i as f64 + 0.5) / 12.0, 0.25).ok()?.into_iter().next()).collect();@@ -289,7 +345,7 @@ pub(crate) fn report_here(args: &[String]) -> i32 {#[cfg(test)]mod tests {use super::shaped;- use raea_sys_fingerprint::taxonomy::base;+ use raea_sys_fingerprint::taxonomy::{Applies, base};fn args(xs: &[&str]) -> Vec<String> {xs.iter().map(|x| x.to_string()).collect()@@ -311,5 +367,8 @@ mod tests {assert_eq!(ads.extends.as_deref(), Some("me"));assert_eq!(ads.axes, parent.axes);assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);+ assert_eq!(own.applies, None);+ let judged = shaped("ads", &args(&["ads", "--kinds", "ad, Playable", "--tags", "brand,"]), None);+ assert_eq!(judged.applies, Some(Applies { kinds: vec!["ad".into(), "playable".into()], tags: vec!["brand".into()] }));}}diff --git a/docs/fingerprint.feature b/docs/fingerprint.featureindex 2213ab3a..b50f7e0a 100644--- a/docs/fingerprint.feature+++ b/docs/fingerprint.feature@@ -24,7 +24,7 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on thei11 other renders, 33 videos and 34 minutesAnd the encoders on disk: SigLIP 2 base p16-224 and YAMNet (~/.local/share/raea-models), EmbeddingGemma 2 q8(~/.raea/models, the Library's model through apps/app host/library/embed.ts), CLAP htsat-unfused (Xenova's- ONNX, q8: audio 34 MB, text 127 MB, through the same transformers.js)+ ONNX, fp32: audio 117 MB, text 502 MB; q8 copies at 34 MB and 127 MB are off by default)And every encoder runs locally on consumer hardware or isn't used (Shane, 11-12, dropping PE-AV: "if it cant runlocally on consumer hardware its not usable"); the smallest PE-AV is a ViT-L/14 at 336 px per frame, 3.4 GBAnd Rust goes through the lanes' build rules, new code in small files and a small crate (systems/fingerprint),@@ -110,16 +110,22 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiclip costs 33 ms on the CPU (spike: ~/films/fingerprint-spike/clap, results/fp0g-clap*.txt)Rule: FP1. Columns are made once at ingest and read by every fingerprint- @needs:FP0b+ @needs:FP0b @doneScenario: FP1a. Each video gets its fingerprint columnsGiven the plan| crate | file | lines | job |- | raea-sys-columns | systems/columns/src/lib.rs | 40 | the crate's surface: a file in, its columns out |- | raea-sys-columns | systems/columns/src/columns.rs | 250 | SigLIP 2 (through raea-sys-vision), CLAP, YAMNet, change and look columns for a file, cached by content hash and step version |- | raea-sys-columns | systems/columns/src/clap.rs | 200 | CLAP's audio tower on ort (raea-sys-ml): the 48 kHz log-mel front end and the session, checked against the spike's vectors at cosine 0.999 |- | raea-sys-columns | systems/columns/src/clap_text.rs | 100 | CLAP's text tower on ort with its tokenizer (the tokenizers crate), for axis words only |- | raea-sys-columns | systems/columns/src/look.rs | 120 | luminance histogram, saturation, local contrast and sharpness per frame |+ | raea-sys-columns | systems/columns/src/lib.rs | 180 | the crate's surface: the encoders loaded once, a file in, its columns out |+ | raea-sys-columns | systems/columns/src/models.rs | 120 | where each encoder's files are (RAEA_MODELS), fetched once, pinned by sha256 |+ | raea-sys-columns | systems/columns/src/media.rs | 110 | a file's frames at 4 fps and its sound at 16 and 48 kHz (raea-io-media), its levels |+ | raea-sys-columns | systems/columns/src/siglip.rs | 120 | SigLIP 2's image and text towers on ort (ONNX fp32 image tower) |+ | raea-sys-columns | systems/columns/src/clap.rs | 150 | CLAP's audio tower on ort (raea-sys-ml): the 48 kHz log-mel front end and the session, checked against the spike's vectors at cosine 0.999 |+ | raea-sys-columns | systems/columns/src/clap_text.rs | 50 | CLAP's text tower on ort with its tokenizer (the tokenizers crate), for axis words only |+ | raea-sys-columns | systems/columns/src/yamnet.rs | 40 | YAMNet's embeddings on ort, when its model is here |+ | raea-sys-columns | systems/columns/src/look.rs | 60 | luminance histogram, saturation, local contrast and sharpness per frame || raea-sys-columns | systems/columns/src/window.rs | 120 | a span's features from the columns (mean, change, look), as the heads read them |+ | raea-sys-columns | systems/columns/src/cache.rs | 80 | columns cached by the file's sha256 and step version, fp16 |+ | raea-sys-columns | systems/columns/src/damage.rs | 110 | the bootstrap's damage and cheats on frames and sound (FP2b) |+ | raea-sys-columns | systems/columns/src/tests.rs | 130 | parity with the spike: CLAP audio and text, SigLIP 2 against ONNX fp32 |When a video is ingested or renderedThen it gets SigLIP 2 per frame at 4 fps (the pooled vector, fp16), CLAP per 2 s window with a 1 s hop, YAMNet per0.48 s, change (frame-to-frame SigLIP distance) and look (luminance histogram, saturation, local contrast,@@ -132,6 +138,11 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theidocs/mlx.feature MX5 gives it a path, never Core ML's GPU, and any new runtime path is checked against ONNX fp32at cosine 0.999 or better before its columns are keptAnd no encoder runs through transformers.js or Python; the spike's transformers.js vectors are only the reference+ And 11-12: raea-sys-columns makes every column above but the patch tokens (FP12a) and the Library's EmbeddingGemma 2+ rows (FP1b), in the resident service `raea fingerprint serve` rather than the feed host; on ort, SigLIP on the+ CPU. Parity with the spike (`cargo test -p raea-sys-columns -- --ignored`): CLAP audio on 260 clips mean and+ worst cosine 1.00000, CLAP text on 40 descriptions 1.00000, SigLIP 2 against Python onnxruntime on 16 frames+ 1.000000@needs:FP1aScenario: FP1b. Not only video@@ -139,30 +150,41 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theifingerprint can hold axes about them (a script that reads the buttons aloud, a board with wide empty shots)Rule: FP2. The fingerprint is a folder, its taxonomy is TypeScript- @needs:FP1a+ @needs:FP1a @doneScenario: FP2a. What's in itThen a fingerprint is ~/.raea/fingerprints/NAME/ (a person's), or PROJECT/.raea/fingerprints/NAME/ (a project'sor team's), holding fingerprint.ts (`export default fingerprint({...})` from "raea/brief"), heads.safetensors,evidence.jsonl with evidence.f16 beside it, and report.jsonAnd fingerprint.ts names its encoders by id and hash, and a head refuses columns from any other+ And 11-12: the folder is as above, with fingerprint.json beside fingerprint.ts (what it last evaluated to, for+ hosts without a TS evaluator) and words.json beside words.f16; a fingerprint pins its encoders by id and sha256+ and a verb refuses columns from others (`reembed` moves it, FP8c)- @needs:FP2a+ @needs:FP2a @doneScenario: FP2b. An axis+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint | systems/fingerprint/src/taxonomy.rs| 140 | an axis, a fingerprint, raea's base taxonomy and the background vocabularies |Then an axis has a name, the words people use for it, a modality (picture, change, look, sound, words), a scope(moment, shot, whole piece), a polarity, and optionally the taste check it maps to (text-hold, loudness...)And raea's base taxonomy is drawn from Shane's notes: glitch and continuity, sound, pace, camera, cut, light andlook, realism and detail, interaction, design and type, storyAnd a person or team adds axes in their fingerprint.ts; directions are never axes+ And 11-12: taxonomy.rs's Axis and raea's base taxonomy (15 axes: 8 mechanical, 7 taste axes from words); sdk/raea's+ `fingerprint({...})` types it- @needs:FP2b,FP1a+ @needs:FP2b,FP1a @doneScenario: FP2e. Every axis scores from its words on day oneGiven the plan| crate | file | lines | job |- | raea-sys-fingerprint | systems/fingerprint/src/words.rs | 120 | word heads: an axis's words against the background vocabulary as a z, per window |+ | raea-sys-fingerprint | systems/fingerprint/src/words.rs | 100 | word heads: an axis's words against the background vocabulary as a z, per window |Then each axis's words are embedded when they change (CLAP's text tower for sound, SigLIP 2's for picture, on ort) and stored in the fingerprint as words.f16, with a background vocabulary of about 40 ordinarydescriptions; the text towers never run at score timeAnd a word head is always advice, and hands over to the learned head once that beats it on held-out evidenceAnd on FP0g's defects the base taxonomy's words score noise and clipping at 0.97 or better with no labels+ And 11-12, word_heads_score_noise_and_clipping_from_words_alone on the spike's 130 two-second windows: noise 0.987,+ clipping 0.975 from their words alone; on 40 of Shane's renders (FP4b's bootstrap) noise 1.00, clip 0.90, blur+ 0.87, dark 0.74, glow 0.61@needs:FP1a,FP2cScenario: FP2f. Realness, measured before it ships@@ -172,23 +194,27 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiAnd it ships as an axis only at 0.85 or better held out by generator; it's a taste check ("real material only"),never a claim that a sound is or isn't AI-made- @needs:FP2a+ @needs:FP2a @doneScenario: FP2c. Heads train in milliseconds, on the deviceGiven the plan| crate | file | lines | job |- | raea-sys-fingerprint | systems/fingerprint/src/lib.rs | 60 | the crate's surface: columns and evidence in, scores out |- | raea-sys-fingerprint | systems/fingerprint/src/folder.rs | 200 | the fingerprint folder read and written: heads.safetensors, evidence.jsonl and .f16, report.json |- | raea-sys-fingerprint | systems/fingerprint/src/evidence.rs| 180 | an evidence row (hash, span, axis, polarity, weight, who, source, columns) |- | raea-sys-fingerprint | systems/fingerprint/src/head.rs | 220 | logistic and Bradley-Terry heads on standardised columns, their encoder pin |- | raea-sys-fingerprint | systems/fingerprint/src/train.rs | 250 | fitting (L-BFGS), the person's weighting, held-out by project scores, the gate |- | raea | sdk/raea/src/fingerprint.ts | 60 | `fingerprint({...})` and the Axis type, re-exported from raea/brief beside `taste` |+ | raea-sys-fingerprint | systems/fingerprint/src/lib.rs | 120 | the crate's surface: columns and evidence in, scores out; retraining and report.json |+ | raea-sys-fingerprint | systems/fingerprint/src/folder.rs | 250 | the fingerprint folder read and written: fingerprint.ts, words.f16, heads.safetensors, evidence.jsonl and .f16, report.json |+ | raea-sys-fingerprint | systems/fingerprint/src/evidence.rs| 140 | an evidence row (hash, span, axis, polarity, weight, who, source, columns) |+ | raea-sys-fingerprint | systems/fingerprint/src/head.rs | 210 | logistic and Bradley-Terry heads on standardised columns, their encoder pin |+ | raea-sys-fingerprint | systems/fingerprint/src/train.rs | 210 | fitting (L-BFGS), the person's weighting, held-out by project scores, the gate |+ | raea-sys-fingerprint | systems/fingerprint/src/tests.rs | 120 | a head learns, the folder round-trips, a ledger drops rows, a gate needs projects |+ | raea | sdk/raea/src/fingerprint.ts | 40 | `fingerprint({...})` and the Axis type, re-exported from raea/brief beside `taste` |Then each axis's head is a logistic fit on its modality's columns, standardised with the encoder's shippedstatistics; an axis with pairs adds a Bradley-Terry fit on their differences; a person's weighting is alogistic fit over the axis scoresAnd a retrain runs after every new evidence row and takes under a second for 10,000 rows on the CPUAnd the trainer is a Rust crate (systems/fingerprint), with no Python at run time+ And 11-12: head.rs (logistic and Bradley-Terry by L-BFGS), train.rs and folder.rs as planned; every verb that adds+ evidence retrains every head; no Python at run time. Tests: a_head_learns_a_separable_axis,+ the_folder_keeps_heads_words_and_evidence, a_ledger_keeps_features_when_it_drops_rows- @needs:FP2c+ @needs:FP2c @doneScenario: FP2d. A head is advice until it's earned its placeThen a head gates only once it has 16 labels of each polarity or more, from 3 projects or more, and a held-outby project AUC of 0.8 or better; until then `raea fingerprint score` marks it advice@@ -196,14 +222,19 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theievidence (earshot's verdict bands)And report.json gives each head's held-out score, its labels by source, its red-team results, and what it can'tjudge (earshot's LIMITS.md)+ And 11-12: the gate is 16 labels of each kind from 3 projects, held-out AUC 0.8 and every cheat caught 0.8; a head+ reports its strong (precision 0.9) and plausible (0.7) thresholds and report.json says each head's why and what+ it can't judge. Test: a_gate_needs_projectsRule: FP3. Scoring a piece- @needs:FP2c+ @needs:FP2c @doneScenario: FP3a. raea fingerprint scoreGiven the plan| crate | file | lines | job |- | raea-sys-fingerprint | systems/fingerprint/src/score.rs | 160 | per-window axis scores and the expected notes, as JSON |- | raea-cli | engine/cli/src/fingerprint.ts | 200 | `raea fingerprint` new, score, teach, bootstrap, profile, report, postmortem and diff, through the feed host |+ | raea-sys-fingerprint-use | systems/fingerprint-use/src/score.rs | 220 | per-window axis scores, the moments a note is expected on, the summary and the timeline |+ | raea-app-fingerprint | apps/fingerprint/src/lib.rs | 120 | `raea fingerprint`: its usage, flags and the verbs' dispatch (raea-cli is at its 2,000-line limit, so the verbs are their own crate) |+ | raea-app-fingerprint | apps/fingerprint/src/verbs.rs | 260 | new, bootstrap, teach, score (with raea check's findings, the check winning) and report |+ | raea-app-fingerprint | apps/fingerprint/src/serve.rs | 150 | the resident service that keeps the encoders loaded, on localhost; the verbs start it on demand |When I run `raea fingerprint score FILE [--fp NAME]`Then it prints a summary first: the moments the fingerprint expects a note on, each with its axis named in theperson's words and the checks' findings; every axis's score per window with --json@@ -211,49 +242,79 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiAnd `raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1]` adds an evidencerow from the CLI or an agentAnd the watch timeline shows the same as a lane (the player's lane plugins)+ And 11-12: `raea fingerprint score` prints which fingerprint judged and why (FP14c), the moments first, raea check's+ findings beside them; a check wins over a head on an axis it measures. The watch timeline's lane is FP11's- @needs:FP3a+ @needs:FP3a @doneScenario: FP3c. A sheet and a timeline an agent can readGiven the plan| crate | file | lines | job |- | raea-sys-fingerprint | systems/fingerprint/src/sheet.rs | 220 | one PNG: frames with heatmaps, axis lanes, the spectrogram with flagged sounds boxed, check findings |+ | raea-sys-fingerprint-use | systems/fingerprint-use/src/sheet.rs | 180 | one PNG: frames (heatmaps with FP12), axis lanes, the level, the spectrogram with flagged sounds boxed, check findings |When I run `raea fingerprint score FILE --sheet out.png` or `--timeline`Then the sheet shows the whole piece in one picture (earshot's `sheet`), and the timeline reads it second bysecond in words: what is seen, what is heard, which axes flag (earshot's `timeline`)And `raea show` opens the sheet for a person+ And 11-12: `--sheet` writes the PNG (frames, axis lanes, the level, the spectrogram, the checks' ticks) and+ `--timeline` the piece second by second, the nearest vocabulary words for what is seen and heard@needs:FP3a,FP4aScenario: FP3b. The golden references stay clean, and a known bad cut doesn'tThen the five golden references' approved.mp4 raise no gating flagAnd the cut Shane called "explicitly a bad one" raises more flags, on the same axes, than the approved reelmade from the same footage (both in the golden references' private media, never in git)+ And 11-12, scored with a scratch copy of FP4b's 40-render fingerprint: the five golden references raise no gating+ flag (advice only: 9, 9, 6, 9 and 7 moments, mostly noise under music beds, blur and flash); the Kimi cut raises+ no gating flag either and fewer advice moments than the approved reel from the same footage (4 against 9),+ though raea check finds more in it (4 findings against 1). What makes that cut bad isn't a mechanical defect, so+ this waits on taste axes trained from Shane's notes (FP5) before it can passRule: FP4. Damage variants bootstrap the axes- @needs:FP2c+ @needs:FP2c @doneScenario: FP4a. Labels by construction, on real work+ Given the plan+ | crate | file | lines | job |+ | raea-app-fingerprint | apps/fingerprint/src/bootstrap.rs | 250 | damaged windows of real work as evidence, FP0b's few-shot curves held out by source, word heads' AUCs and cheats |Then for each mechanical axis (blur, dark, glow, flash, freeze, noise, dropout, clip, and the ones added later)`raea fingerprint bootstrap` makes damaged windows of the person's own approved work and trains the axis head,held out by source, to FP0b's numbers or betterAnd no placeholder footage: the sources are real renders and footage+ And 11-12, `raea fingerprint bootstrap` on 40 of Shane's renders (28 long enough, 280 windows, 4,760 rows), held+ out by source at k = 4 / 16 / 32: blur 0.99 / 1.00 / 1.00, dark 0.78 / 0.97 / 0.99, glow (picture) 0.58 / 0.73 /+ 0.84, flash 0.96 / 0.97 / 0.97, freeze 1.00, noise 0.99 / 1.00 / 1.00; dropout 0.70 / 0.88 / 0.93 and clip 0.84 /+ 0.94 / 0.95 fall under FP0g's CLAP numbers (0.99, 1.00) on these renders, many of them quiet- @needs:FP4a+ @needs:FP4a @doneScenario: FP4b. Every axis has cheats that must still be caughtThen each axis carries a red-team set (sharpened after a de-rez, half-strength glow, quieter noise, a one-frameflash, a freeze with a slow zoom on it), and report.json shows each cheat's catch rate at the threshold thatflags 10% of clean workAnd a cheat caught under 0.8 holds that axis at adviceAnd glow gates only once the look columns exist and its cheats pass+ And 11-12: damage.rs's cheats are sharpblur, glow_half, noise_low, freeze_zoom, dark_half (darkened half as much),+ flash_white, dropout_short (0.2 s) and clip_soft; on FP4a's 40 renders sharpblur, noise_low and flash_white are+ caught 1.00 and dark_half 0.80, and glow_half 0.50, freeze_zoom 0.27, dropout_short 0.60 and clip_soft 0.61 hold+ glow, freeze, dropout and clip at advice- @needs:FP1a+ @needs:FP1a @doneScenario: FP4c. What can be measured is a check, and the arbiter+ Given the plan+ | crate | file | lines | job |+ | raea-app-check | apps/check/src/defects.rs | 150 | clipping, a dropout and a flash frame as raea check rules, with red-team tests |Then dropout (a silence gap in a sound that had level), clipping (samples at full scale), loudness, a flash frameand a freeze are measured from the columns and the sound as `raea check` findings, each with red-team casesAnd where a check and a head disagree, the check wins: earshot's search fooled its learned critics while itsmeasurements held, and FP0g shows silence matching no words+ And 11-12: defects.rs (clipping, dropout, flash frames) beside raea check's loudness, peak and freeze rules, with+ red-team tests (clipping_is_found_and_a_loud_clean_tone_isnt, a_dropout_is_found_and_a_faded_pause_isnt,+ a_flash_frame_is_found_and_a_cut_or_a_fade_isnt); flash, freeze, dropout and clip name their check, and a moment on+ one isn't a gate unless its check found it tooRule: FP5. Notes become evidence@needs:FP2bScenario: FP5a. A pinned note is read into a label+ Given the plan+ | crate | file | lines | job |+ | raea-app-fingerprint | apps/fingerprint/src/notes.rs | 320 | notes read by a fresh session, checked by the person, then evidence |When a person pins a note on a video (docs/review.feature R1)Then the Director reads it into: defect, direction or praise; the axis, from the fingerprint's own axes and theirwords; the span (by default the 1.5 s before the pin to 0.5 s after); and the layer under the pin's x,y@@ -273,27 +334,46 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiprevious version's note times as a predictor (0.60 in FP0)Rule: FP6. Positives and pairs come from what the person already does- @needs:FP2c+ @needs:FP2c @doneScenario: FP6a. Approvals+ Given the plan+ | crate | file | lines | job |+ | raea-app-fingerprint | apps/fingerprint/src/approve.rs | 90 | approved work as clean rows on every axis, away from its notes |Then an approval, a picture lock, a publish or a golden reference is a positive on every axis over every span withno defect note- @needs:FP6a+ And 11-12: `raea fingerprint approve FILE... [--project P]` adds a clean row on every axis for each 2 s window,+ leaving out windows within 2 s of a note pinned on that file in its project's feed. Test:+ an_approval_leaves_out_the_windows_near_a_note+ @needs:FP6a @doneScenario: FP6b. Picks and hand edits+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint | systems/fingerprint/src/pairs.rs | 70 | Bradley-Terry fits on pairs, held out by project |+ | raea-app-fingerprint | apps/fingerprint/src/pairing.rs | 130 | pair and versions |Then a pick between real options (docs/craft-system.md F) is a pair on the axes the options differ on, and a handedit's before and after (~/.raea/taste/corrections.jsonl) is a pair on the axis the edit touched- @needs:FP6a+ And 11-12: `raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]` records either one: the worse+ window's columns minus the better one's, fit Bradley-Terry with no intercept, held out by project; an axis with+ 4 or more pairs and no labels of each kind is ranked by its pairs alone, as advice. corrections.jsonl's rows say+ what was said, not which files came before and after, so an edit is recorded with `pair` rather than read from+ it. Tests: pairs_alone_rank+ @needs:FP6a @doneScenario: FP6c. Version pairsThen a noted moment whose picture or sound changed in the next version (cosine distance 0.01 or more) and thatisn't noted again within 1 s is a weak pair (weight 0.5)- @needs:FP6a+ And 11-12: `raea fingerprint versions V1 V2...` (apps/fingerprint/src/pairing.rs). Test:+ a_changed_moment_not_noted_again_is_a_weak_pair+ @needs:FP6a @doneScenario: FP6d. Another eye stays another eyeThen clef's or Kimi's readings are evidence from that eye, with their source, and never count as the person's+ And 11-12: rows with source eye:NAME train a head but are left out of the gate's label and project counts, which+ say "labels of yours". Test: another_eye_stays_another_eye- @needs:FP2c,FP4c+ @needs:FP2c,FP4c @doneScenario: FP6e. Profiles: ranges from work the person admiresGiven the plan| crate | file | lines | job |- | raea-sys-fingerprint | systems/fingerprint/src/profile.rs | 180 | a profile's ranges over measures and axis scores, the leave-one-out check, critique against it |+ | raea-sys-fingerprint-use | systems/fingerprint-use/src/profile.rs | 180 | a profile's ranges over measures and axis scores, the leave-one-out check, critique against it |When I run `raea fingerprint profile REFS... --as NAME`Then each measure (loudness, spectral balance, cut rate, motion, brightness and contrast) and each axis score getsthe range the references span, and `raea fingerprint score --profile NAME` says which fall outside it, where,@@ -303,6 +383,9 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theithis taste apartAnd the golden references and approved cuts are the first profiles, and give the positives notes don't (3approvals in 205 notes)+ And 11-12: measures are loudness, loudness range, tilt (bass against treble), cuts a minute, motion, brightness,+ contrast, saturation and sharpness, each range widened 10%; the profile says when it doesn't tell its taste+ apart. Test: a_profile_critiques_a_pieceRule: FP7. The post-mortem@needs:FP5a,FP6a@@ -314,23 +397,109 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiAnd each answer is an evidence row, and the report says how each head's held-out score movedRule: FP8. Teams- @needs:FP2d+ @needs:FP2d @doneScenario: FP8a. Sharing is evidence, not weights+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint | systems/fingerprint/src/share.rs | 60 | a shared folder's evidence a folder a person, its heads kept off the repo |Then sharing a fingerprint shares fingerprint.ts and the evidence rows (embeddings, spans, labels, who), throughthe project's repo (Git + LFS) or raea's API, under the project's permissions; never mediaAnd each teammate's machine retrains the shared heads from the pooled evidence (FP0c: pooled 0.76 againstaveraged heads 0.74 and one person's 0.66)And each person's weighting stays their own; a team fingerprint's weighting is fit on everyone's labels+ And 11-12: `raea fingerprint share NAME --in project|workspace` copies fingerprint.ts and the evidence into+ PLACE/.raea/fingerprints/NAME, a folder a person (evidence/<who>/), with heads and the report git-ignored; a+ shared one with no heads trains on open. Test: a_shared_fingerprint_keeps_evidence_a_person- @needs:FP8a+ @needs:FP8a @doneScenario: FP8b. Where tastes differ+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint-use | systems/fingerprint-use/src/diff.rs | 110 | two fingerprints' heads on the same evidence: the axes most apart and their moments |Then `raea fingerprint diff A B` lists the axes where two fingerprints disagree most on the same evidence, withthe moments that show it+ And 11-12: rows are counted once by media, span, axis and kind. Test: diff_finds_where_two_tastes_differ- @needs:FP8a+ @needs:FP8a @doneScenario: FP8c. Encoder upgrades keep the evidence+ Given the plan+ | crate | file | lines | job |+ | raea-app-fingerprint | apps/fingerprint/src/reembed.rs | 110 | rows moved to this machine's encoders where their media is found |Then when an encoder is replaced, rows whose media is present are re-embedded and the heads retrained; rowswithout media keep the old pin until re-labelled+ And 11-12: `raea fingerprint reembed PLACE...`; each row carries the pin it was embedded on, and a scoring+ fingerprint on other encoders refuses and names reembed. Tests: a_row_on_old_encoders_waits,+ a_pin_names_each_encoder_and_its_hash++ Rule: FP14. Many fingerprints: one person's evidence, a fingerprint for each kind of work+ # Separate fingerprints that each start from nothing split a person's labels, and their labels are the scarce part.+ # So a fingerprint isn't a silo: it extends another and inherits its axes and evidence, and adds or overrides only+ # where its kind of work differs (a client's ads cut fast, a film holds). Which one judges a piece is decided by+ # where the piece lives, as .editorconfig is, not picked each time; the person can always see why.+ @needs:FP2a @done+ Scenario: FP14a. Each says what it is for+ Then fingerprint.ts has `about`, one line naming what it tracks and when it judges ("Short ads for one brand:+ pace, type on screen, the brand's colours"), shown wherever the fingerprint is named and given to agents+ And it may have `extends` (another fingerprint by name, the person's own or one in a parent folder) and+ `applies` ({ kinds?: film, ad, game, playable, still, sound; tags?: the project's }), both optional+ And 11-12: `raea fingerprint new NAME --about TEXT --extends FP` writes them (raea-sys-fingerprint Fingerprint+ about/extends/applies, sdk/raea fingerprint.ts Applies); --extends starts from FP's axes and its evidence is+ FP14b's; the app shows `about` in its switcher, the card and Settings. Tests: about_extends_and_applies_round_trip,+ a_new_fingerprint_says_what_its_for_and_what_it_builds_on, raea-cli a_verb_refuses_what_it_doesnt_take (bootstrap+ takes many files: the usage named each sub-verb with `raea fingerprint`, or the arity check held them all to new's 2)++ @needs:FP14a @done+ Scenario: FP14b. A child inherits, and its own labels count more+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint | systems/fingerprint/src/inherit.rs | 160 | a child's parents, its axes with theirs, its evidence with theirs (its own 2x), overrides, the measure |+ When a fingerprint extends another+ Then it has its parent's axes plus its own; an axis of its own with the parent's name overrides that axis's words,+ polarity or check, and an override's evidence starts from its own labels only+ And its heads train on its parent's evidence and its own, its own weighted up (2x, then measured: held out by+ project, the child's own projects, against training on its own labels alone and on the parent's alone)+ And the parent never trains on a child's evidence, so one client's taste doesn't move the person's own+ And 11-12: the report's `inherits` gives own and inherited rows, the overrides and each axis's measure. Test:+ a_child_inherits_and_its_own_labels_count_more++ @needs:FP14a @done+ Scenario: FP14c. Which one judges a piece+ Given the plan+ | crate | file | lines | job |+ | raea-sys-fingerprint-use | systems/fingerprint-use/src/which.rs | 160 | the levels, a piece's kind and tags, the one chosen and why |+ | raea-app-fingerprint | apps/fingerprint/src/pick.rs | 170 | which, use, share and diff, and the fingerprint a verb uses |+ Given a piece in PROJECT, inside a WORKSPACE folder, on a person's account+ Then the fingerprints are looked for in PROJECT/.raea/fingerprints, then WORKSPACE/.raea/fingerprints, then+ ~/.raea/fingerprints; 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+ And `raea fingerprint which PATH` prints the one chosen, its `about`, and why (the level and the rule that matched)+ And a project or workspace can pin one with `raea fingerprint use NAME [--project|--workspace]`, which writes that+ level's `default`+ And the agent scores with the chosen one only, and says its name when it reports a flag+ And 11-12: `raea fingerprint which PATH [--json]`, `use NAME --in project|workspace`, and `new --kinds --tags`+ for `applies`; a piece's kind is .raea/project's `kind =`, else its file type, its tags `tags =`; score prints+ "judged by NAME: why". Tests: which_one_judges_a_piece, a_new_fingerprint_says_what_its_for_and_what_it_builds_on++ @needs:FP14b,FP5a+ Scenario: FP14d. A note teaches the one that judged+ Then a note or mark on a piece is evidence in the fingerprint that judged that piece, so labels land where the+ taste they express applies, and a parent sees them only if the person moves them up (`raea fingerprint move`)++ @needs:FP14c+ Scenario: FP14e. Managing them in the app+ Then the fingerprint page lists the person's fingerprints as a tree by `extends`, each with its `about`, where it+ applies, its labels and what it knows; one is shown at a time, and a project's page names the one judging it+ And "New fingerprint" asks for a name, what it's for, what it builds on (the account default by default) and+ where it applies (this project, this workspace, or kinds of work), and writes fingerprint.ts there+ And a fingerprint kept in a project or workspace folder travels with that folder's repo and is shared as FP8a+ says; one in ~/.raea is the person's own+ And so far (11-12, raea-feed fingerprint-page): the page's title has a switcher of ~/.raea/fingerprints with each+ one's `about` and how many axes it knows, "New fingerprint" asks for a name, what it's for and what it builds on,+ Settings makes one the default and trains it; headless, the app made client-ads from me in 34 s and trained it+ from 12 renders in 3m54s (910 rows, 6 axes gating). Since: the switcher is a tree by `extends`, each saying+ which kinds and tags it judges; "New fingerprint" asks which it judges (`new --kinds --tags`); a project's header+ names the one `raea fingerprint which` picks, why in its tooltip. Not yet: making one in a project's or+ workspace's folder from the app (`share` does it from the CLI)Rule: FP9. Agents use it, and can't game it@needs:FP3a,FP4b,FP5c@@ -402,5 +571,8 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiThen an axis under its bar with 300 labels or more, after its own columns were added, may try a LoRA adapter onSigLIP 2's last blocks trained on the device through raea-sys-mlx with a heatmap loss as well as the axis's own(checked against PyTorch to cosine 0.999), or another encoder that runs locally on consumer hardware+ And the trainer for that adapter is chosen then, between MLX's autograd and Burn (a Rust training framework with+ Metal, CUDA and CPU backends), on which matches PyTorch and runs on the person's device; the heads never need+ either, since a head is a logistic fit by L-BFGS in plain Rust (head.rs) in millisecondsAnd either is kept only if it raises that axis's held-out by project AUC by 0.05 or more, at a cost the person'sdevice can pay, and the result is recorded here with the datediff --git a/docs/fingerprint.md b/docs/fingerprint.mdindex a043c74e..8f43bb11 100644--- a/docs/fingerprint.md+++ b/docs/fingerprint.md@@ -46,15 +46,16 @@ media ─► columns (once, at ingest, cached by content hash)| part | model | size on disk | runs at score time | cost for a 90 s render ||---|---|---|---|---|| picture columns | SigLIP 2 base p16-224 (image tower) | 95 MB int8, 372 MB fp32 | yes | 17 s on ort's CPU path (47 ms a frame); MLX on the Mac once MX5 lands; never Core ML's GPU |-| sound columns | CLAP htsat-unfused (audio tower) | 34 MB q8, 117 MB fp32 | yes | about 3 s (33 ms a 2 s clip) |+| sound columns | CLAP htsat-unfused (audio tower) | 117 MB fp32 (34 MB q8 copy, off by default) | yes | about 3 s (33 ms a 2 s clip) || sound events | YAMNet | 16 MB | yes | under 1 s || change and look | none | none | yes | negligible || words, scripts, boards, stills | EmbeddingGemma 2 | 841 MB q8, already the Library's | only for non-video items | 2.3 s a window; reads Library rows instead where they exist |-| axis words → vectors | CLAP text tower (127 MB q8), SigLIP 2 text tower | | **no**: only when an axis's words change; the vectors are stored in the fingerprint | |+| axis words → vectors | CLAP text tower (502 MB fp32), SigLIP 2 text tower | | **no**: only when an axis's words change; the vectors are stored in the fingerprint | || heads, weighting, profile | ours | 7 KB a head | yes | milliseconds || things (footage only) | EdgeTAM, Depth Anything 3 Small | 37 MB, 51 MB (both already in perception) | only for thing-level axes and checks | about 86 ms a frame for EdgeTAM |-Only CLAP is a new download. Its q8 audio and text towers come to 161 MB. Every encoder runs in Rust:+Only CLAP is a new download. Its fp32 audio and text towers come to 619 MB. The q8 copies (161 MB) match fp32 only to+cosine 0.998, and differ between ONNX Runtime builds, so fp32 is the default (RAEA_CLAP_DTYPE=q8 picks the copies). Every encoder runs in Rust:- **ONNX Runtime** (ort, through raea-sys-ml) is the path on every platform and the reference. YAMNet already runs onit, CLAP's audio and text towers join it, and CLAP's tokenizer is the `tokenizers` crate raea-sys-speech alreadyuses.@@ -73,6 +74,12 @@ safer than earshot's cache key of path, size, modification time and sampled blocgrowing a click into a region, the open-vocabulary grounder (gated, FP13b), the damage and red-team generators, thetext towers, and the gated LoRA trainer (FP10).+**Training stays plain Rust until FP10.** The encoders are frozen and inference only, so they stay on ort. A head is+a logistic fit on a few hundred to a few thousand rows of at most 1,024 values; L-BFGS in plain Rust fits one in+milliseconds and needs no framework. A training framework earns its place only with FP10's adapter, which back-propagates+through SigLIP 2; then MLX's autograd and Burn (Metal, CUDA and CPU backends) are compared on PyTorch parity and on+what the person's device can run.+### Axes and their headsAn axis is declared in TypeScript beside `taste` (`fingerprint({...})` from "raea/brief"). It has:@@ -254,6 +261,15 @@ source. Each cell is AUC at k = 4 / 16 / 32 labelled windows a class:- **q8 copy.** It holds the numbers (words 0.99 / 0.67 / 0.97), with audio vectors at cosine 0.9975 to fp32.- **Cost.** 33 ms a clip on the CPU.+**FP1a. The Rust columns match, measured 11-12.** raea-sys-columns runs every encoder on ONNX Runtime's CPU kernels+(raea-sys-ml), and its tests check it against the spike (systems/columns/src/tests.rs, run with --ignored):+- **SigLIP 2's image tower** against ONNX fp32 in Python on the same frames: cosine 1.000000.+- **CLAP's audio tower**, fp32, its log-mel front end in Rust: mean and worst cosine 1.00000 over 260 clips. The q8+ copy came to a worst cosine of 0.9978, a difference between ONNX Runtime builds rather than the front end (fp32+ against fp32 matches), so fp32 is the default.+- **CLAP's text tower**: 1.00000 over the 40 vocabulary descriptions, once padded as transformers.js padded the+ batch. The export takes no attention mask, so raea embeds each text alone, unpadded.+**FP0b's lessons on method.**- Standardise columns. Unstandardised, SigLIP hid behind YAMNet's larger values: blur scored 0.75 at k = 32.- Keep each axis on its own modality. A head given both modalities was worse at small k: dropout scored 0.68 at k = 4.diff --git a/docs/manual/guides/fingerprint.md b/docs/manual/guides/fingerprint.mdnew file mode 100644index 00000000..d32c9a3f--- /dev/null+++ b/docs/manual/guides/fingerprint.md@@ -0,0 +1,101 @@+---+title: "Fingerprint: teach raea your eye"+summary: "What raea learns about good work from your notes, marks and approvals, on your Mac: the axes it judges, how one is trained and trusted, keeping one fingerprint for each kind of work, and sharing one with a team."+order: 6+sources: ["docs/fingerprint.feature", "docs/fingerprint.md", "apps/fingerprint/src", "systems/fingerprint/src", "systems/fingerprint-use/src", "apps/app/src/fingerprint"]+---++A fingerprint is your sense of good work, as raea has learned it on your Mac. It's a list of axes, the things you+notice: blur, a black frame, hiss, clipping, a glow over everything, a frozen picture, and taste axes such as fake,+barren or unreadable text. Each axis has a small model over encoders that run on your Mac (SigLIP 2 for pictures, CLAP+for sound, YAMNet for sound events), so nothing leaves the machine unless you share it.++Your agents use it before they post a cut: `raea fingerprint score` lists the moments your fingerprint expects a note+on, each named in your words, and the agent fixes them or tells you why it didn't. It tells you the axis and the+moment, never a number.++## The Fingerprint page++Open **Fingerprint** in the sidebar. The card at the top is your mark, one column of bits for each axis, grouped by+sense: pictures, sound and motion. Point at a sense to see its axes and how well each one judges. Below it, every axis+says whether it **knows** (it's trusted, and can hold a post back until you've looked), is **learning** (it gives+advice), or is still **to learn** (it only has its words). **Can't judge yet** lists what no axis can see, such as+whether a piece works as a whole.++The name in the page's title is a menu of your fingerprints. **Settings** holds what one is for, what it builds on,+whether it's your default, and **Learn from renders**.++## Training one++A new fingerprint judges from the words for each axis on day one. To train the mechanical axes, choose **Learn from+renders**, or run:++```sh+raea fingerprint bootstrap ~/renders/*.mp4+```++raea damages moments of your own finished work on purpose (a blur, a black frame, a gap in the sound) and learns the+difference, held out by source, so it can't learn a shortcut. Each axis also has disguised versions of its defect, such+as a blur that was sharpened afterwards or a freeze hidden under a slow zoom. An axis that misses its disguises stays+advice.++Your own reviewing teaches it the rest:++```sh+raea fingerprint teach cut.mp4 --axis blur --at 4.2 --bad # a moment you marked+raea fingerprint approve final.mp4 # approved work is clean, except where you left a note+raea fingerprint pair v1.mp4 v2.mp4 --axis glow # v2 is better on glow+raea fingerprint read projects/stay # read your pinned notes into labels+raea fingerprint readings --ask 50 # check 50 of those readings in the app+```++Notes become evidence only after you've checked how they were read: the kind right 45 times in 50 and the axis 40. A+note that asks for a creative change goes to the brief, never into an axis. An axis is trusted once it has 16 labels of+each kind from 3 projects, ranks real defects above clean work on projects it never saw, and catches its disguises.+`raea fingerprint report` says where each one stands.++## One for each kind of work++You can keep several fingerprints, each saying what it's for. One can build on another: a client's ads can start from+your own and add what that client cares about. It inherits your axes and evidence, counts its own labels twice, and+never changes yours.++```sh+raea fingerprint new client-ads --about "Short ads for one brand: pace, type on screen" --extends me+raea fingerprint which projects/brand/out/cut.mp4 # which one judges this, and why+raea fingerprint use client-ads --in project projects/brand+```++Which one judges a piece is decided by where it lives: the project's fingerprints first, then the workspace's, then+your own. At each level, the one whose `applies` matches the piece's kind wins, else that level's default.++## Profiles of work you admire++```sh+raea fingerprint profile golden/*.mp4 --as reels --against others.txt+raea fingerprint score cut.mp4 --profile reels+```++A profile takes the ranges your references span: loudness, bass against treble, cuts a minute, motion, brightness,+contrast, saturation and sharpness. A cut scored against it hears which measures fall outside, where, and which way+to move. The profile checks itself: each reference has to fit the others' ranges more often than unrelated work does,+or raea says it doesn't tell this taste apart.++## Sharing with a team++```sh+raea fingerprint share studio --in workspace+raea fingerprint diff me ana # where two tastes differ, and the moments that show it+```++Sharing copies the axes and the evidence (embeddings, spans and labels) into the workspace or project, to travel with+its repository. It never shares media or trained weights: each teammate's Mac trains its own from everyone's+evidence, and each person's evidence sits in its own folder so two people labelling at once never edit the same+file. When raea's encoders change, `raea fingerprint reembed FOLDER` moves the evidence to the new ones wherever it+finds the media.++## What it can't do yet++Axes judge two-second moments, so a fingerprint can't say whether a piece works as a whole, or judge story and pace+across shots. It says when a moment is wrong, not where in the frame, until marks teach it to point. A stylised look+or a held shot can read as a defect. And taste axes with only words never hold a post back.diff --git a/docs/manual/reference/cli/fingerprint.md b/docs/manual/reference/cli/fingerprint.mdindex 62f20346..aa7d02a3 100644--- a/docs/manual/reference/cli/fingerprint.md+++ b/docs/manual/reference/cli/fingerprint.md@@ -27,7 +27,7 @@ raea fingerprint report## Usage```sh-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)+raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [--ask N] [--tally] | raea fingerprint learn-notes | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.@@ -37,19 +37,29 @@ Headless: it needs nothing running and opens no window. Takes any number of argu| Flag | Takes | What it does || --- | --- | --- || `--about` | `TEXT` | What this fingerprint is for, in a sentence, shown beside its name in the app |+| `--against` | `LIST` | With profile: a file listing unrelated work, one path a line, that the references must fit their own ranges better than |+| `--as` | `NAME` | With profile: the name the profile is kept under, for score --profile |+| `--ask` | `N` | With readings: put N of the readings to you in the app, one question each, to check before notes train || `--at` | `T` | The moment a label is for, in seconds || `--axis` | `A` | The axis a label is for, by name, such as blur or clip || `--bad` | – | The moment has the problem the axis names (the default) || `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |+| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude || `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own || `--fp` | `NAME` | Which fingerprint to use, by name; without it, the default || `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped || `--good` | – | The moment is fine on that axis |+| `--in` | `project\|workspace` | With use or share: the level the fingerprint is pinned or copied to, the project's or the workspace's folder || `--json` | – | Print the result as JSON |+| `--kinds` | `K,K` | With new: the kinds of piece it judges (film, ad, game, playable, still, sound), comma-separated || `--per` | `N` | How many moments to take from each render (10 if not given) |+| `--profile` | `NAME` | With score: also say which measures fall outside this profile's ranges, where, and which way to move || `--project` | `P` | The project the label came from, so evidence is held out by project || `--sheet` | `out.png` | Also write a contact sheet PNG of the moments it expects a note on || `--span` | `S` | How long the labelled moment lasts, in seconds |+| `--tags` | `T,T` | With new: the project tags it judges, comma-separated; a project picks the one matching its kind and tags best |+| `--tally` | – | With readings: count your answers so far against the readings asked, and say whether notes have earned training |+| `--then` | `T2` | With pair: the moment in BETTER, when it isn't at the same time as --at in WORSE || `--timeline` | – | Describe the piece second by second in words || `--who` | `W` | Whose fingerprint it is, shown on its card || `--words` | `W` | The label's own words, as the note said them |diff --git a/systems/fingerprint-use/Cargo.toml b/systems/fingerprint-use/Cargo.tomlnew file mode 100644index 00000000..86b4b940--- /dev/null+++ b/systems/fingerprint-use/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-sys-fingerprint-use"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Using a fingerprint (docs/fingerprint.feature FP3, FP6e, FP8b, FP14c): a piece scored per moment and drawn as a sheet, which fingerprint judges a piece, where two differ, and profiles of admired work"++[dependencies]+# the fingerprint: its taxonomy, folder, evidence, heads and words+raea-sys-fingerprint = { path = "../fingerprint" }+# a piece's columns, and the frames and sound the sheet draws+raea-sys-columns = { path = "../columns" }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+anyhow = "1"+# the sheet (sheet.rs) is a PNG+image = { version = "0.25", default-features = false, features = ["png"] }diff --git a/systems/fingerprint/src/diff.rs b/systems/fingerprint-use/src/diff.rssimilarity index 96%rename from systems/fingerprint/src/diff.rsrename to systems/fingerprint-use/src/diff.rsindex b4a79ddb..d6b7d444 100644--- a/systems/fingerprint/src/diff.rs+++ b/systems/fingerprint-use/src/diff.rs@@ -2,9 +2,9 @@//! 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 raea_sys_fingerprint::evidence::Ledger;+use raea_sys_fingerprint::folder::Folder;+use raea_sys_fingerprint::train::AxisHead;use anyhow::{Result, anyhow};use serde::Serialize;diff --git a/systems/fingerprint-use/src/lib.rs b/systems/fingerprint-use/src/lib.rsnew file mode 100644index 00000000..cde4dd0b--- /dev/null+++ b/systems/fingerprint-use/src/lib.rs@@ -0,0 +1,16 @@+//! Using a fingerprint (docs/fingerprint.feature, docs/fingerprint.md); the fingerprint itself, its evidence and its+//! heads are raea-sys-fingerprint.+//!+//! - score.rs, sheet.rs: scoring a piece, its summary, timeline and sheet (FP3a, FP3c)+//! - which.rs: which fingerprint judges a piece: its project's, its workspace's, then the person's (FP14c)+//! - diff.rs: where two fingerprints rank the same evidence differently (FP8b)+//! - profile.rs: ranges from work the person admires, and a piece critiqued against them (FP6e)++pub mod diff;+pub mod profile;+pub mod score;+pub mod sheet;+pub mod which;++#[cfg(test)]+mod tests;diff --git a/systems/fingerprint-use/src/profile.rs b/systems/fingerprint-use/src/profile.rsnew file mode 100644index 00000000..4dbceb0f--- /dev/null+++ b/systems/fingerprint-use/src/profile.rs@@ -0,0 +1,153 @@+//! Profiles (FP6e): ranges taken from work the person admires, and a piece critiqued against them (earshot's `profile`+//! and `critique`). Each measure (loudness and its range, spectral tilt, cut rate, motion, brightness, contrast,+//! saturation, sharpness) gets the range the references span; a piece is told which measures fall outside it, where,+//! and which way to move. A profile is checked leave-one-out: each reference against a profile of the others must fall+//! in range more often than against unrelated work, or it's reported as not telling this taste apart.++use raea_sys_columns::{Columns, FPS, SIG};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++pub type Measures = BTreeMap<String, f32>;++/// What a measure is, in words, for the critique+pub const NAMES: [(&str, &str); 9] = [+ ("loudness", "loudness (dB)"),+ ("loudness_range", "the range between quiet and loud (dB)"),+ ("tilt", "bass against treble (dB)"),+ ("cuts_per_min", "cuts a minute"),+ ("motion", "how much the picture moves"),+ ("brightness", "brightness"),+ ("contrast", "contrast"),+ ("saturation", "colour saturation"),+ ("sharpness", "sharpness"),+];++fn mean(v: &[f32]) -> f32 {+ if v.is_empty() { 0.0 } else { v.iter().sum::<f32>() / v.len() as f32 }+}++fn pct(v: &[f32], q: f32) -> f32 {+ let mut s = v.to_vec();+ s.sort_by(f32::total_cmp);+ s.get(((s.len().max(1) - 1) as f32 * q) as usize).copied().unwrap_or(0.0)+}++/// Frame-to-frame SigLIP distances over [a, b) seconds+fn steps(c: &Columns, a: f64, b: f64) -> Vec<f32> {+ let n = c.sig.len() / SIG;+ let (fa, fb) = (((a * FPS) as usize).min(n), ((b * FPS) as usize).min(n));+ (fa.max(1)..fb).map(|i| {+ let (x, y) = (&c.sig[(i - 1) * SIG..i * SIG], &c.sig[i * SIG..(i + 1) * SIG]);+ let d: f32 = x.iter().zip(y).map(|(p, q)| p * q).sum();+ let nx = x.iter().map(|p| p * p).sum::<f32>().sqrt() * y.iter().map(|q| q * q).sum::<f32>().sqrt();+ 1.0 - d / nx.max(1e-6)+ }).collect()+}++/// A distance this far is a cut+const CUT: f32 = 0.25;++/// The measures over [a, b) seconds of a piece: its columns, and its spectrogram (`spec`, `bins` bands a column, one+/// column a tenth of a second, from raea_sys_columns::media::spectrogram) for the tilt+pub fn measures(c: &Columns, spec: &[f32], bins: usize, a: f64, b: f64) -> Measures {+ let lv: Vec<f32> = c.level.iter().enumerate().filter(|(i, _)| (*i as f64 / 10.0) >= a && (*i as f64 / 10.0) < b).map(|(_, v)| *v).filter(|v| *v > -60.0).collect();+ let look = raea_sys_columns::look::LOOK;+ let n = c.look.len() / look;+ let (fa, fb) = (((a * FPS) as usize).min(n), ((b * FPS) as usize).min(n));+ let col = |k: usize| mean(&(fa..fb).map(|i| c.look[i * look + k]).collect::<Vec<_>>());+ let st = steps(c, a, b);+ let cols = spec.len() / bins.max(1);+ let (sa, sb) = (((a * 10.0) as usize).min(cols), ((b * 10.0) as usize).min(cols));+ let band = |r: std::ops::Range<usize>| mean(&(sa..sb).flat_map(|i| r.clone().map(move |k| (i, k))).map(|(i, k)| spec[i * bins + k]).collect::<Vec<_>>());+ let minutes = ((b - a) / 60.0).max(1e-3) as f32;+ let mut m = Measures::new();+ m.insert("loudness".into(), mean(&lv));+ m.insert("loudness_range".into(), pct(&lv, 0.9) - pct(&lv, 0.1));+ m.insert("tilt".into(), band(0..bins / 3) - band(bins * 2 / 3..bins));+ m.insert("cuts_per_min".into(), st.iter().filter(|d| **d > CUT).count() as f32 / minutes);+ m.insert("motion".into(), mean(&st.iter().copied().filter(|d| *d <= CUT).collect::<Vec<_>>()));+ m.insert("brightness".into(), col(8));+ m.insert("contrast".into(), col(11));+ m.insert("saturation".into(), col(10));+ m.insert("sharpness".into(), col(12));+ m+}++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Profile {+ pub name: String,+ /// each reference's file and its measures+ pub refs: Vec<(String, Measures)>,+ /// each measure's range over the references+ pub ranges: BTreeMap<String, (f32, f32)>,+ /// leave-one-out: share of a reference's measures inside the others' ranges, and of unrelated work's+ pub inside_own: Option<f32>,+ pub inside_other: Option<f32>,+ pub tells: Option<bool>,+}++/// The ranges the references span, widened by a tenth of their width each way+pub fn ranges(refs: &[&Measures]) -> BTreeMap<String, (f32, f32)> {+ let mut out = BTreeMap::new();+ for (k, _) in NAMES {+ let v: Vec<f32> = refs.iter().filter_map(|m| m.get(k).copied()).collect();+ if v.is_empty() {+ continue;+ }+ let (lo, hi) = (v.iter().copied().fold(f32::MAX, f32::min), v.iter().copied().fold(f32::MIN, f32::max));+ let pad = (hi - lo) * 0.1;+ out.insert(k.to_string(), (lo - pad, hi + pad));+ }+ out+}++fn inside(m: &Measures, r: &BTreeMap<String, (f32, f32)>) -> f32 {+ let hits: Vec<bool> = r.iter().filter_map(|(k, (lo, hi))| m.get(k).map(|v| v >= lo && v <= hi)).collect();+ hits.iter().filter(|h| **h).count() as f32 / hits.len().max(1) as f32+}++/// A profile from the references, checked leave-one-out against `other` (unrelated work's measures)+pub fn profile(name: &str, refs: Vec<(String, Measures)>, other: &[Measures]) -> Profile {+ let all: Vec<&Measures> = refs.iter().map(|r| &r.1).collect();+ let spans = ranges(&all);+ let (mut own, mut oth) = (Vec::new(), Vec::new());+ if refs.len() >= 3 {+ for i in 0..refs.len() {+ let rest: Vec<&Measures> = all.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, m)| *m).collect();+ let r = ranges(&rest);+ own.push(inside(all[i], &r));+ oth.extend(other.iter().map(|m| inside(m, &r)));+ }+ }+ let (inside_own, inside_other) = ((!own.is_empty()).then(|| mean(&own)), (!oth.is_empty()).then(|| mean(&oth)));+ let tells = inside_own.zip(inside_other).map(|(a, b)| a > b);+ Profile { name: name.into(), refs, ranges: spans, inside_own, inside_other, tells }+}++/// One measure out of range: by how much, which way to move, and the window where it's furthest out+#[derive(Clone, Debug, Serialize)]+pub struct Out {+ pub measure: String,+ pub value: f32,+ pub range: (f32, f32),+ /// "raise" or "lower"+ pub move_: String,+ pub at: Option<(f64, f64)>,+}++/// The piece against the profile: the whole piece's measures, and its windows' for where+pub fn critique(p: &Profile, whole: &Measures, windows: &[((f64, f64), Measures)]) -> Vec<Out> {+ let mut out = Vec::new();+ for (k, (lo, hi)) in &p.ranges {+ let Some(&v) = whole.get(k) else { continue };+ if v >= *lo && v <= *hi {+ continue;+ }+ let low = v < *lo;+ let far = |m: &Measures| m.get(k).map_or(0.0, |x| if low { lo - x } else { x - hi });+ let at = windows.iter().max_by(|a, b| far(&a.1).total_cmp(&far(&b.1))).filter(|w| far(&w.1) > 0.0).map(|w| w.0);+ out.push(Out { measure: k.clone(), value: v, range: (*lo, *hi), move_: if low { "raise".into() } else { "lower".into() }, at });+ }+ out+}diff --git a/systems/fingerprint/src/score.rs b/systems/fingerprint-use/src/score.rssimilarity index 97%rename from systems/fingerprint/src/score.rsrename to systems/fingerprint-use/src/score.rsindex da5ba716..fbe3996b 100644--- a/systems/fingerprint/src/score.rs+++ b/systems/fingerprint-use/src/score.rs@@ -3,10 +3,10 @@//! axis above the score that flags 10% of clean held-out work; a gating flag is a gating head's flag in its strong//! band (precision 0.9 held out). Flagged windows in a row make a moment, the thing a note is expected on.-use crate::evidence::{features, slice};-use crate::taxonomy::Fingerprint;-use crate::train::{AxisHead, Trained, scores};-use crate::words::Words;+use raea_sys_fingerprint::evidence::{features, slice};+use raea_sys_fingerprint::taxonomy::Fingerprint;+use raea_sys_fingerprint::train::{AxisHead, Trained, scores};+use raea_sys_fingerprint::words::Words;use raea_sys_columns::Columns;use raea_sys_columns::window::Modality;use serde::Serialize;diff --git a/systems/fingerprint/src/sheet.rs b/systems/fingerprint-use/src/sheet.rssimilarity index 100%rename from systems/fingerprint/src/sheet.rsrename to systems/fingerprint-use/src/sheet.rsdiff --git a/systems/fingerprint-use/src/tests.rs b/systems/fingerprint-use/src/tests.rsnew file mode 100644index 00000000..b99c1ee8--- /dev/null+++ b/systems/fingerprint-use/src/tests.rs@@ -0,0 +1,109 @@+//! The crate's own checks: which fingerprint judges a piece, where two differ, and a profile's critique.++use raea_sys_fingerprint::evidence::{Ledger, Row, width};+use raea_sys_fingerprint::folder::Folder;+use raea_sys_fingerprint::taxonomy::base;+use raea_sys_fingerprint::words::Words;++/// A blur label in a project, its window `at` seconds in+fn row(bad: bool, project: &str, at: f64) -> Row {+ Row { media: "m".into(), a: at, b: at + 2.0, axis: "blur".into(), bad, weight: 1.0, who: "t".into(), source: "teach".into(), project: project.into(), kind: None, region: None, words: None, at: 0, pin: None }+}++/// Features with the label's sign in the picture's first values and a little made-up spread in the rest+fn signal(x: f32, seed: usize) -> Vec<f32> {+ (0..width()).map(|i| if i < 16 { x } else { (((i * 31 + seed * 17) % 97) as f32 / 97.0 - 0.5) * 0.1 }).collect()+}++/// 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(raea_sys_fingerprint::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);+}++/// 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;+ l.push(row(bad, &format!("p{}", i % 4), i as f64 * 2.0), &signal(if bad != flip { 1.0 } else { -1.0 }, i));+ }+ dir.write_ledger(&l).unwrap();+ raea_sys_fingerprint::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);+}++/// FP6e: a profile's ranges come from its references, the leave-one-out check says whether it tells a taste apart, and+/// a critique says what's out, which way and where+#[test]+fn a_profile_critiques_a_piece() {+ use crate::profile::{Measures, critique, profile};+ let m = |b: f32, l: f32| Measures::from([("brightness".to_string(), b), ("loudness".to_string(), l)]);+ let refs = vec![("a".to_string(), m(0.40, -18.0)), ("b".to_string(), m(0.45, -16.0)), ("c".to_string(), m(0.50, -17.0)), ("d".to_string(), m(0.42, -16.5))];+ let other = vec![m(0.10, -30.0), m(0.90, -8.0)];+ let p = profile("bright", refs, &other);+ assert_eq!(p.tells, Some(true), "own {:?}, other {:?}", p.inside_own, p.inside_other);+ let (lo, hi) = p.ranges["brightness"];+ assert!(lo < 0.40 && hi > 0.50);+ let windows = vec![((0.0, 4.0), m(0.45, -17.0)), ((4.0, 8.0), m(0.12, -17.0))];+ let out = critique(&p, &m(0.30, -17.0), &windows);+ assert_eq!(out.len(), 1);+ assert_eq!((out[0].measure.as_str(), out[0].move_.as_str(), out[0].at), ("brightness", "raise", Some((4.0, 8.0))));+}diff --git a/systems/fingerprint/src/which.rs b/systems/fingerprint-use/src/which.rssimilarity index 98%rename from systems/fingerprint/src/which.rsrename to systems/fingerprint-use/src/which.rsindex 293600cb..86cee46e 100644--- a/systems/fingerprint/src/which.rs+++ b/systems/fingerprint-use/src/which.rs@@ -6,8 +6,8 @@//! 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 raea_sys_fingerprint::folder::{Folder, root};+use raea_sys_fingerprint::taxonomy::Fingerprint;use serde::Serialize;use std::path::{Path, PathBuf};diff --git a/systems/fingerprint/Cargo.toml b/systems/fingerprint/Cargo.tomlindex a96f1522..278b0f2b 100644--- a/systems/fingerprint/Cargo.toml+++ b/systems/fingerprint/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "Fingerprint (docs/fingerprint.feature FP2-FP4): a taxonomy of axes with small heads over frozen on-device encoders' columns, trained on the device in milliseconds from evidence rows, gated, scored per moment, drawn as a sheet"+description = "Fingerprint (docs/fingerprint.feature FP2-FP4): a taxonomy of axes with small heads over frozen on-device encoders' columns, trained on the device in milliseconds from evidence rows and gated"[dependencies]# the columns every head reads, the encoders that make them, and the damage the bootstrap puts in@@ -14,5 +14,3 @@ half = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"anyhow = "1"-# the sheet (sheet.rs) is a PNG-image = { version = "0.25", default-features = false, features = ["png"] }diff --git a/systems/fingerprint/src/evidence.rs b/systems/fingerprint/src/evidence.rsindex 5b3917a7..f855abe4 100644--- a/systems/fingerprint/src/evidence.rs+++ b/systems/fingerprint/src/evidence.rs@@ -55,6 +55,10 @@ pub struct Row {pub words: Option<String>,/// the row's index in evidence.f16pub at: u64,+ /// the encoders its features came from, when they aren't the fingerprint's own any more (FP8c): such a row waits+ /// to be re-embedded or re-labelled, and no head trains on it+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pin: Option<String>,}fn one() -> f32 {@@ -122,13 +126,20 @@ impl Ledger {}}- /// Rows for training `axis`: its own labels (not cheats), and "*" rows that say it's clean+ /// Rows for training `axis`: its own labels (not cheats, not rows on old encoders), and "*" rows that say it's cleanpub fn for_axis(&self, axis: &str) -> Vec<usize> {(0..self.rows.len()).filter(|&i| {let r = &self.rows[i];- r.source != "cheat" && (r.axis == axis || (r.axis == "*" && !r.bad))+ r.source != "cheat" && r.source != "pair" && r.pin.is_none() && (r.axis == axis || (r.axis == "*" && !r.bad))}).collect()}++ /// A row's features replaced, as re-embedding does+ pub fn set_features(&mut self, i: usize, f: &[f32]) {+ let w = width();+ let at = self.rows[i].at as usize * w;+ self.feats[at..at + w].copy_from_slice(f);+ }}/// A window's features for a row, every modality, from a file's columnsdiff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rsindex afeaada2..8749788e 100644--- a/systems/fingerprint/src/lib.rs+++ b/systems/fingerprint/src/lib.rs@@ -1,6 +1,7 @@//! Fingerprint (docs/fingerprint.feature FP2-FP4, docs/fingerprint.md): a person's or a team's sense of good work as//! a taxonomy of axes, each with a small head over the frozen encoders' columns (raea-sys-columns), trained on the-//! device in milliseconds from evidence rows, gated until it has earned it, and scored per moment.+//! device in milliseconds from evidence rows, and gated until it has earned it. Scoring a piece with one, and the+//! tools around it, are raea-sys-fingerprint-use.//!//! - taxonomy.rs: the axes and raea's base taxonomy (FP2b)//! - folder.rs: the fingerprint's folder (FP2a)@@ -8,22 +9,17 @@//! - 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)+//! - pairs.rs: Bradley-Terry fits on picks, hand edits and version pairs (FP6b, FP6c)//! - 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 pairs;pub mod share;-pub mod sheet;pub mod taxonomy;pub mod train;-pub mod which;pub mod words;use anyhow::Result;diff --git a/systems/fingerprint/src/pairs.rs b/systems/fingerprint/src/pairs.rsnew file mode 100644index 00000000..4bc58ac8--- /dev/null+++ b/systems/fingerprint/src/pairs.rs@@ -0,0 +1,54 @@+//! Pairs (FP6b, FP6c): "this one is better than that one on this axis", from a pick between real options, a hand edit's+//! before and after, or a noted moment that changed in the next version. A pair row's features are the better window's+//! minus the worse one's (source "pair", `bad` true: the first had more of the defect); an axis with pairs adds a+//! Bradley-Terry fit, the logistic fit on the differences with no intercept, held out by project as share ordered right.+//! A pair on "*" (a version pair, which names no axis) counts for every axis at its own weight.++use crate::evidence::Ledger;+use crate::head::{Logistic, Scaler};+use crate::train::{C, folds};+use raea_sys_columns::window::Modality;+use std::collections::BTreeSet;++/// The pair rows for an axis+pub fn rows(l: &Ledger, axis: &str) -> Vec<usize> {+ (0..l.rows.len()).filter(|&i| l.rows[i].source == "pair" && l.rows[i].pin.is_none() && (l.rows[i].axis == axis || l.rows[i].axis == "*")).collect()+}++/// Bradley-Terry: each difference and its negation, no intercept+pub fn fit(l: &Ledger, rows: &[usize], m: Modality) -> Logistic {+ let d: Vec<Vec<f32>> = rows.iter().map(|&i| l.modality(i, m).to_vec()).collect();+ let neg: Vec<Vec<f32>> = d.iter().map(|v| v.iter().map(|x| -x).collect()).collect();+ let x: Vec<&[f32]> = d.iter().chain(&neg).map(Vec::as_slice).collect();+ let mut sc = Scaler::fit(&x);+ sc.mean.iter_mut().for_each(|v| *v = 0.0);+ let y: Vec<bool> = (0..x.len()).map(|i| i < d.len()).collect();+ let w: Vec<f32> = rows.iter().chain(rows).map(|&i| l.rows[i].weight).collect();+ Logistic::fit(sc, &x, &y, Some(&w), C, false)+}++/// Share of held-out pairs (by project) the fit orders right+pub fn held_out(l: &Ledger, rows: &[usize], m: Modality) -> Option<f64> {+ let projects: BTreeSet<String> = rows.iter().map(|&i| l.rows[i].project.clone()).collect();+ if projects.len() < 2 {+ return None;+ }+ let (mut right, mut n) = (0usize, 0usize);+ for fold in folds(&projects) {+ let (test, train): (Vec<usize>, Vec<usize>) = rows.iter().copied().partition(|&i| fold.contains(&l.rows[i].project));+ if train.len() < 2 {+ continue;+ }+ let f = fit(l, &train, m);+ for &i in &test {+ right += usize::from(f.score(l.modality(i, m)) > 0.0);+ n += 1;+ }+ }+ (n > 0).then(|| right as f64 / n as f64)+}++/// A pair's features: the worse window's minus the better one's, so a positive score means the first is worse+pub fn difference(worse: &[f32], better: &[f32]) -> Vec<f32> {+ worse.iter().zip(better).map(|(a, b)| a - b).collect()+}diff --git a/systems/fingerprint/src/tests.rs b/systems/fingerprint/src/tests.rsindex 1daf479c..7447837f 100644--- a/systems/fingerprint/src/tests.rs+++ b/systems/fingerprint/src/tests.rs@@ -25,6 +25,7 @@ fn row(axis: &str, bad: bool, project: &str) -> Row {region: None,words: None,at: 0,+ pin: None,}}@@ -208,54 +209,6 @@ fn a_child_inherits_and_its_own_labels_count_more() {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() {@@ -272,35 +225,6 @@ fn another_eye_stays_another_eye() {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]@@ -329,3 +253,40 @@ fn a_shared_fingerprint_keeps_evidence_a_person() {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);}++/// FP8c: a row still on an old encoder's features trains no head until it's re-embedded+#[test]+fn a_row_on_old_encoders_waits() {+ let mut l = Ledger::default();+ for i in 0..4 {+ let mut r = row("blur", i % 2 == 0, "p");+ if i == 0 {+ r.pin = Some("siglip:old".into());+ }+ l.push(r, &feats(1.0, i));+ }+ assert_eq!(l.for_axis("blur"), vec![1, 2, 3]);+ let new = vec![0.5; width()];+ l.set_features(0, &new);+ l.rows[0].pin = None;+ assert_eq!(l.features(0), new.as_slice());+ assert_eq!(l.for_axis("blur"), vec![0, 1, 2, 3]);+}++/// FP6b: pairs alone make a Bradley-Terry head that ranks, held out by project+#[test]+fn pairs_alone_rank() {+ let fp = base("t");+ let mut l = Ledger::default();+ for i in 0..24 {+ let mut r = row("blur", true, &format!("p{}", i % 4));+ r.source = "pair".into();+ // the worse minus the better: the blur signal up+ l.push(r, &crate::pairs::difference(&feats(1.0, i), &feats(-1.0, 100 + i)));+ }+ let h = crate::train::axis(&fp, &l, &Words::default(), "blur");+ assert_eq!((h.pairs, h.state.as_str()), (24, "advice"), "{}", h.why);+ assert!(h.pairs_held_out.unwrap() > 0.9, "{:?}", h.pairs_held_out);+ let head = h.head.unwrap();+ assert!(head.score(&feats(1.0, 999)[crate::evidence::slice(raea_sys_columns::window::Modality::Picture)]) > head.score(&feats(-1.0, 998)[crate::evidence::slice(raea_sys_columns::window::Modality::Picture)]));+}diff --git a/systems/fingerprint/src/train.rs b/systems/fingerprint/src/train.rsindex f8c6d2cc..95edbba9 100644--- a/systems/fingerprint/src/train.rs+++ b/systems/fingerprint/src/train.rs@@ -45,6 +45,11 @@ pub struct AxisHead {pub flag: Option<f32>,/// what this head can't judge (earshot's LIMITS.md)pub cannot: Vec<String>,+ /// pairs on this axis (FP6b, FP6c), and the share of held-out pairs its Bradley-Terry fit orders right+ #[serde(default)]+ pub pairs: usize,+ #[serde(default)]+ pub pairs_held_out: Option<f64>,}#[derive(Clone, Debug, Default, Serialize, Deserialize)]@@ -112,7 +117,7 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHeadlet (pos, neg) = counts(l, &rows);let projects: BTreeSet<String> = rows.iter().map(|&i| l.rows[i].project.clone()).collect();h.projects = projects.len();- let plain: Vec<usize> = (0..l.rows.len()).filter(|&i| l.rows[i].source != "cheat").collect();+ let plain: Vec<usize> = (0..l.rows.len()).filter(|&i| !matches!(l.rows[i].source.as_str(), "cheat" | "pair")).collect();let worded = words.axes.iter().any(|a| a.0 == name);if worded {let s: Vec<(f32, bool)> = rows.iter().filter_map(|&i| words.z(name, l.features(i)).map(|z| (z, l.rows[i].bad))).collect();@@ -120,6 +125,18 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHeadh.words = Some(auc(&p, &n)).filter(|a| a.is_finite());h.word_flag = Some(quantile(&n, 0.9)).filter(|v| v.is_finite());}+ let pairs = crate::pairs::rows(l, name);+ h.pairs = pairs.len();+ if pairs.len() >= 2 {+ h.pairs_held_out = crate::pairs::held_out(l, &pairs, m);+ }+ if (pos < 2 || neg < 2) && pairs.len() >= 4 {+ // only pairs: the Bradley-Terry fit is the head, advice until labels earn a gate+ h.head = Some(crate::pairs::fit(l, &pairs, m));+ h.state = "advice".into();+ h.why = format!("{} pairs and no labels of each kind yet: it ranks, it doesn't gate", pairs.len());+ return h;+ }if pos < 2 || neg < 2 {h.state = if worded { "words".into() } else { "none".into() };h.why = format!("{pos} defect and {neg} clean labels: the head needs some of each");