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
FP1-FP4, FP14a: raea fingerprint. raea-sys-columns turns a video into one-second windows read by encoders that run on this Mac (SigLIP 2 for pictures, CLAP for sound, YAMNet for sound events, on ort; SigLIP never on Core ML's GPU), cached by content hash. raea-sys-fingerprint holds the taxonomy (each axis with its words, a fingerprint saying what it's for and what it builds on), the evidence ledger, small heads trained held out by source, scoring and the contact sheet. apps/fingerprint is the verb: new, bootstrap (known defects put into windows of real work), teach, score (--json, --sheet, --timeline), report, and a service that keeps the encoders loaded. raea check finds clipping, dropouts and flash frames as its own findings. sdk/raea types a fingerprint.
shinyobjectzfb11b58f6f22
diff --git a/Cargo.lock b/Cargo.lockindex 31218599..40598b25 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13668,6 +13668,19 @@ dependencies = ["zip",]+[[package]]+name = "raea-app-fingerprint"+version = "0.1.0"+dependencies = [+ "anyhow",+ "fastrand",+ "raea-app-check",+ "raea-sys-columns",+ "raea-sys-fingerprint",+ "serde",+ "serde_json",+]+[[package]]name = "raea-app-game"version = "0.1.0"@@ -14036,6 +14049,7 @@ dependencies = ["raea-app-ci","raea-app-direction","raea-app-engines",+ "raea-app-fingerprint","raea-app-game","raea-app-judge","raea-app-media",@@ -15376,6 +15390,24 @@ dependencies = ["usvg 0.48.1",]+[[package]]+name = "raea-sys-columns"+version = "0.1.0"+dependencies = [+ "anyhow",+ "fastrand",+ "half",+ "image",+ "ort",+ "raea-io-media",+ "raea-sys-ml",+ "rustfft",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokenizers",+]+[[package]]name = "raea-sys-compose"version = "0.1.0"@@ -15435,6 +15467,18 @@ dependencies = ["wgpu",]+[[package]]+name = "raea-sys-fingerprint"+version = "0.1.0"+dependencies = [+ "anyhow",+ "half",+ "image",+ "raea-sys-columns",+ "serde",+ "serde_json",+]+[[package]]name = "raea-sys-fog"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex e1d64cb7..fcff57f0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -81,6 +81,8 @@ members = ["systems/speech","systems/layout","systems/vision",+ "systems/columns",+ "systems/fingerprint","systems/song","systems/perceive","systems/footage",@@ -163,6 +165,7 @@ members = ["apps/check/flash","apps/direction","apps/notes",+ "apps/fingerprint","apps/sound","apps/workspace","apps/workspace/registry",diff --git a/apps/check/src/defects.rs b/apps/check/src/defects.rsnew file mode 100644index 00000000..b6e99543--- /dev/null+++ b/apps/check/src/defects.rs@@ -0,0 +1,147 @@+use super::*;++/// The defects Fingerprint's axes map to that a measure finds exactly (docs/fingerprint.feature FP4c), so the check+/// wins over a head: clipping, a dropout, and a flash frame. Each on the same decoded sound or a small grey picture;+/// each with red-team cases in tests.rs (a loud clean tone, a faded pause, a cut).+///+/// Clipping: a run of 3 samples or more at full scale (|x| 0.999 or more), or a flat top: 4 or more samples the same+/// to the bit at a level a sound rarely holds still at (0.05 or more), as a hard limiter or a clamp leaves them.+/// Counted per second; a second with CLIP_RUNS runs or more is a finding.+pub(crate) const FULL: f32 = 0.999;+pub(crate) const FLAT_LEVEL: f32 = 0.05;+pub(crate) const CLIP_RUNS: usize = 3;++pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {+ let mut per: Vec<usize> = vec![0; x.len() / SR + 1];+ let mut i = 0;+ while i < x.len() {+ let v = x[i];+ let mut j = i + 1;+ if v.abs() >= FULL {+ while j < x.len() && x[j].abs() >= FULL && x[j].signum() == v.signum() {+ j += 1;+ }+ if j - i >= 3 {+ per[i / SR] += 1;+ }+ } else if v.abs() >= FLAT_LEVEL {+ while j < x.len() && x[j].to_bits() == v.to_bits() {+ j += 1;+ }+ if j - i >= 4 {+ per[i / SR] += 1;+ }+ }+ i = j;+ }+ let mut out = Vec::new();+ let mut s = 0;+ while s < per.len() {+ if per[s] < CLIP_RUNS {+ s += 1;+ continue;+ }+ let mut e = s;+ while e + 1 < per.len() && per[e + 1] >= CLIP_RUNS {+ e += 1;+ }+ let runs: usize = per[s..=e].iter().sum();+ out.push((s as f64, format!("the sound clips: {runs} flat-topped runs over {} s; bring the level down before it hits the ceiling", e - s + 1)));+ s = e + 1;+ }+ out+}++/// A dropout: the sound falls from level (-45 dBFS or more) to digital silence (under -80 dBFS) in one 10 ms step and+/// comes back within two, to within 10 dB of where it was, 50 ms to 3 s later. A pause that fades out or in isn't one.+pub(crate) const SILENT: f64 = -80.0;+pub(crate) const HAD_LEVEL: f64 = -45.0;++pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {+ let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| 20.0 * ((f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64).sqrt() + 1e-9).log10()).collect();+ let step = HOP as f64 / SR as f64;+ let mut out = Vec::new();+ let mut i = 1;+ while i < rms.len() {+ // a step that is silent, or nearly (the source cut partway through it), after one with level+ if !(rms[i] < HAD_LEVEL - 20.0 && rms[i - 1] >= HAD_LEVEL) {+ i += 1;+ continue;+ }+ let mut j = i + 1;+ while j < rms.len() && rms[j] < SILENT {+ j += 1;+ }+ let gap = (j - i) as f64 * step;+ let silent_inside = j > i + 1;+ // back at once: within two steps, to within 10 dB of the level before the gap (a fade in takes longer)+ let before = rms[i - 1];+ let back = rms[j.min(rms.len())..(j + 2).min(rms.len())].iter().any(|l| *l >= HAD_LEVEL.max(before - 10.0));+ if silent_inside && back && (0.05..=3.0).contains(&gap) {+ out.push((i as f64 * step, format!("the sound drops out for {:.2} s and comes back; a dropout, not a pause (no fade either side)", gap)));+ }+ i = j.max(i + 1);+ }+ out+}++/// A flash frame: one or two frames whose mean brightness differs from the frames either side by FLASH_STEP or more+/// (0-1), while those two agree within FLASH_SAME: a black or white frame dropped into a shot. A cut (the brightness+/// moves and stays) and a fade aren't flash frames.+pub(crate) const FLASH_STEP: f32 = 0.25;+pub(crate) const FLASH_SAME: f32 = 0.08;++pub(crate) fn flash_frames(luma: &[f32], fps: f64) -> Vec<(f64, String)> {+ let mut out = Vec::new();+ let mut i = 1;+ while i + 1 < luma.len() {+ let found = (1..=2).find(|&k| {+ let (before, after) = (luma[i - 1], luma.get(i + k - 1 + 1).copied());+ let Some(after) = after else { return false };+ (before - after).abs() <= FLASH_SAME && luma[i..i + k].iter().all(|&l| (l - before).abs() >= FLASH_STEP && (l - after).abs() >= FLASH_STEP)+ });+ match found {+ Some(k) => {+ out.push((i as f64 / fps, format!("{k} frame{} flash{} {} in the middle of a shot; a dropped or stray frame", if k == 1 { "" } else { "s" }, if k == 1 { "es" } else { "" }, if luma[i] < luma[i - 1] { "dark" } else { "bright" })));+ i += k + 1;+ }+ None => i += 1,+ }+ }+ out+}++/// Each frame's mean brightness (0-1), decoded small and grey+fn lumas(video: &str) -> R<(Vec<f32>, f64)> {+ let out = Command::new("ffmpeg")+ .args(["-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"])+ .output()+ .map_err(|e| format!("ffmpeg: {e}"))?;+ if !out.status.success() {+ return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));+ }+ let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();+ let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;+ let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);+ Ok((l, fps))+}++pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {+ let (l, fps) = lumas(video)?;+ let found = flash_frames(&l, fps);+ if found.is_empty() {+ passed.push("flash-frame: no stray black or white frame".into());+ }+ issues.extend(found.into_iter().map(|(at, says)| Issue { rule: "flash-frame", p: 1, at: Some(at), says }));+ Ok(())+}++/// The sound's defects on the decoded mix (sound.rs decodes it once)+pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {+ for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {+ if found.is_empty() {+ passed.push(ok.into());+ }+ issues.extend(found.into_iter().map(|(at, says)| Issue { rule, p: 1, at: Some(at), says }));+ }+}diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rsindex 0c7dae14..fe30c6c8 100644--- a/apps/check/src/lib.rs+++ b/apps/check/src/lib.rs@@ -20,6 +20,8 @@ mod picture;use picture::*;mod flash;use flash::*;+mod defects;+use defects::*;mod text;use text::*;pub mod quick;@@ -156,6 +158,7 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<St}freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;flashing(&video, &probe, &mut issues, &mut passed)?;+ flash_frame_rule(&video, &mut issues, &mut passed)?;blotching(&video, &probe, &mut issues, &mut passed)?;brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);if let Some(manifest) = &manifest {diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rsindex 0e06cc7b..c062bd5f 100644--- a/apps/check/src/sound.rs+++ b/apps/check/src/sound.rs@@ -163,6 +163,7 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>}let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();let (rms, bands) = levels(&x);+ sound_defects(&x, issues, passed);let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });let stops = dead_stops(&rms, &bands);if stops.is_empty() {diff --git a/apps/check/src/tests.rs b/apps/check/src/tests.rsindex 38a594c5..bd58fc7f 100644--- a/apps/check/src/tests.rs+++ b/apps/check/src/tests.rs@@ -351,3 +351,50 @@ fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {cues(&[run("a Sora campaign", 39.7)], &words, &mut issues, &mut passed);assert_eq!(issues.len(), 1, "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());}++#[test]+fn clipping_is_found_and_a_loud_clean_tone_isnt() {+ // a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale+ let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);+ assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));+ let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();+ assert_eq!(clipped(&clamped).len(), 1);+ let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();+ assert_eq!(clipped(&over).len(), 1);+ // one transient hitting full scale once isn't clipping+ let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);+ once[SR] = 1.0;+ assert!(clipped(&once).is_empty());+}++#[test]+fn a_dropout_is_found_and_a_faded_pause_isnt() {+ // a bed at -20 dBFS with 0.6 s cut out of it, as the bootstrap's dropout does+ let mut cut = tone(4.0, &[(0.0, 4.0, -20.0)]);+ cut[(1.7 * SR as f64) as usize..(2.3 * SR as f64) as usize].iter_mut().for_each(|v| *v = 0.0);+ let found = dropouts(&cut);+ assert_eq!(found.len(), 1, "{found:?}");+ assert!((found[0].0 - 1.7).abs() < 0.02, "{found:?}");+ // a pause that fades out over 300 ms and back in isn't one, nor a sound that stops and stays stopped+ let gain = |t: f32| ((1.7 - t) / 0.3).max((t - 2.3) / 0.3).clamp(0.0, 1.0);+ let paused: Vec<f32> = tone(4.0, &[(0.0, 4.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * gain(i as f32 / SR as f32)).collect();+ assert!(dropouts(&paused).is_empty(), "{:?}", dropouts(&paused));+ assert!(dropouts(&tone(4.0, &[(0.0, 2.0, -20.0)])).is_empty());+}++#[test]+fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {+ let mut shot = vec![0.5f32; 60];+ shot[30] = 0.0;+ assert_eq!(flash_frames(&shot, 30.0).len(), 1);+ shot[31] = 0.0;+ assert_eq!(flash_frames(&shot, 30.0).len(), 1, "two frames are one flash");+ let cut: Vec<f32> = (0..60).map(|i| if i < 30 { 0.6 } else { 0.1 }).collect();+ assert!(flash_frames(&cut, 30.0).is_empty());+ let fade: Vec<f32> = (0..60).map(|i| 0.6 * (1.0 - i as f32 / 59.0)).collect();+ assert!(flash_frames(&fade, 30.0).is_empty());+ // a white frame, too+ let mut white = vec![0.3f32; 20];+ white[10] = 1.0;+ assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);+}diff --git a/apps/fingerprint/Cargo.toml b/apps/fingerprint/Cargo.tomlnew file mode 100644index 00000000..1e880228--- /dev/null+++ b/apps/fingerprint/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "raea-app-fingerprint"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "`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+raea-sys-fingerprint = { path = "../../systems/fingerprint" }+# the encoders and the columns they make+raea-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)+raea-app-check = { path = "../check" }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+anyhow = "1"+# the draws of FP0b's few-shot curves, seeded (bootstrap.rs)+fastrand = "2"diff --git a/apps/fingerprint/src/bootstrap.rs b/apps/fingerprint/src/bootstrap.rsnew file mode 100644index 00000000..82518be0--- /dev/null+++ b/apps/fingerprint/src/bootstrap.rs@@ -0,0 +1,244 @@+//! The bootstrap (FP4a, FP4b): known defects put into windows of the person's own real work, so the mechanical axes+//! learn from labels by construction, and the cheats each must still catch. Each source gives `per` 2 s windows+//! from 0.5 s to its end less 2.5 s (FP0b's protocol); each window gives a clean row ("*"), a row per picture and+//! sound defect, and a row per cheat. Only what the damage changed is embedded again: a freeze reuses the first+//! frame's vector, a flash re-embeds one frame, a sound defect leaves the picture alone.+//!+//! Then it measures what FP0b measured, in Rust: each axis's AUC from k = 4, 16 and 32 labelled windows a class, held+//! out by source (5 folds x 5 draws, the scaler fit on every plain row of the training sources), on its own+//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).++use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};+use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile};+use raea_sys_fingerprint::taxonomy::Fingerprint;+use raea_sys_fingerprint::train::{C, folds};+use raea_sys_fingerprint::words::Words;+use anyhow::Result;+use raea_sys_columns::damage::{self, CHEATS, Noise, PICTURE, SOUND};+use raea_sys_columns::media::{self, Rgb};+use raea_sys_columns::window::Modality;+use raea_sys_columns::{Columns, Encoders, FPS};+use serde::Serialize;+use std::collections::{BTreeMap, BTreeSet};+use std::path::PathBuf;++/// The window, seconds+pub const WIN: f64 = 2.0;+/// Sources shorter than this are skipped (FP0b's)+pub const SHORTEST: f64 = 6.0;+pub const KS: [usize; 3] = [4, 16, 32];++/// FP0b's AUC at k = 32 for each axis, on the modality it was measured on (docs/fingerprint.md FP0b, FP0g)+pub const FP0B: [(&str, Modality, f64); 11] = [+ ("blur", Modality::Picture, 1.00),+ ("dark", Modality::Picture, 0.95),+ ("glow", Modality::Picture, 0.80),+ ("flash", Modality::Change, 0.97),+ ("freeze", Modality::Change, 1.00),+ ("noise", Modality::Events, 1.00),+ ("dropout", Modality::Events, 0.97),+ ("clip", Modality::Events, 0.98),+ ("noise", Modality::Sound, 1.00),+ ("dropout", Modality::Sound, 0.99),+ ("clip", Modality::Sound, 1.00),+];++#[derive(Debug, Default, Serialize)]+pub struct Made {+ pub sources: usize,+ pub windows: usize,+ pub rows: usize,+ pub skipped: Vec<String>,+}++fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {+ v.resize(n, 0.0);+ v+}++/// The picture columns of damaged frames, embedding only frames the damage changed+fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &[Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {+ let (sd, ld) = (sig.len() / clean.len().max(1), look.len() / clean.len().max(1));+ let mut fresh: Vec<Rgb> = Vec::new();+ let mut from: Vec<Result<usize, usize>> = Vec::new();+ for f in d {+ match clean.iter().position(|c| c == f) {+ Some(j) => from.push(Ok(j)),+ None => {+ fresh.push(f.clone());+ from.push(Err(fresh.len() - 1));+ }+ }+ }+ let (fs, fl) = if fresh.is_empty() { (Vec::new(), Vec::new()) } else { enc.picture(&fresh)? };+ let (mut s, mut l) = (Vec::with_capacity(sig.len()), Vec::with_capacity(look.len()));+ for f in from {+ let (ss, ll, j) = match f {+ Ok(j) => (sig, look, j),+ Err(k) => (&fs[..], &fl[..], k),+ };+ s.extend_from_slice(&ss[j * sd..(j + 1) * sd]);+ l.extend_from_slice(&ll[j * ld..(j + 1) * ld]);+ }+ Ok((s, l))+}++/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.+pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {+ l.retain(|r| !matches!(r.source.as_str(), "damage" | "cheat"));+ let mut made = Made::default();+ let mut noise = Noise::new(0);+ for (n, file) in files.iter().enumerate() {+ let dur = media::duration(file).unwrap_or(0.0);+ if dur < SHORTEST {+ made.skipped.push(format!("{} ({dur:.1} s, under {SHORTEST} s)", file.display()));+ continue;+ }+ let sha = media::sha256(file)?;+ let frames = media::frames(file, FPS, 0.0, dur)?;+ let (p16, p48) = (media::sound(file, 16_000)?, media::sound(file, 48_000)?);+ made.sources += 1;+ for w in 0..per {+ let t = 0.5 + (dur - 3.0) * w as f64 / (per - 1).max(1) as f64;+ let i0 = (t * FPS).round() as usize;+ let Some(fr) = frames.get(i0..i0 + (WIN * FPS) as usize) else { continue };+ let cut = |p: &[f32], rate: f64| zeros_to(p.get((t * rate) as usize..).unwrap_or(&[]).iter().take((WIN * rate) as usize).copied().collect(), (WIN * rate) as usize);+ let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));+ let (sig, look) = enc.picture(fr)?;+ let (clap, yam) = enc.sound(&w16, &w48)?;+ let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000) };+ let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {+ let r = Row {+ media: sha.clone(),+ a: t,+ b: t + WIN,+ axis: axis.into(),+ bad: axis != "*",+ weight: 1.0,+ who: who.into(),+ source: source.into(),+ project: sha[..12].to_string(),+ kind: Some(kind.into()),+ region: None,+ words: None,+ at: 0,+ };+ l.push(r, &features(c, 0.0, WIN));+ };+ push(l, &clean, "*", "clean", "damage");+ let picture = PICTURE.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| PICTURE.contains(&c.1)).map(|c| (c.0, c.1, "cheat")));+ for (kind, axis, source) in picture {+ let (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 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 {+ 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);+ }+ made.windows += 1;+ }+ say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));+ }+ made.rows = l.rows.iter().filter(|r| matches!(r.source.as_str(), "damage" | "cheat")).count();+ Ok(made)+}++#[derive(Debug, Serialize)]+pub struct Curve {+ pub axis: String,+ pub modality: Modality,+ /// AUC at each k+ pub k: BTreeMap<usize, f64>,+ /// FP0b's at k = 32 on this modality, and whether this run came within 0.03 of it or beat it+ pub fp0b: Option<f64>,+ pub holds: Option<bool>,+}++fn sample(rng: &mut fastrand::Rng, from: &[usize], k: usize) -> Vec<usize> {+ let mut v = from.to_vec();+ rng.shuffle(&mut v);+ v.truncate(k);+ v+}++/// FP0b's few-shot curve for one axis on one modality, from the bootstrap's rows+pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Curve {+ let s = slice(m);+ let row = |i: usize| &l.features(i)[s.clone()];+ let plain = |i: &usize| l.rows[*i].source == "damage";+ let clean: Vec<usize> = (0..l.rows.len()).filter(|i| plain(i) && l.rows[*i].axis == "*").collect();+ let bad: Vec<usize> = (0..l.rows.len()).filter(|i| plain(i) && l.rows[*i].axis == axis).collect();+ let projects: BTreeSet<String> = clean.iter().map(|&i| l.rows[i].project.clone()).collect();+ let mut k_auc = BTreeMap::new();+ for k in KS {+ let mut aucs = Vec::new();+ for fold in folds(&projects) {+ let held = |i: &usize| fold.contains(&l.rows[*i].project);+ let base: Vec<&[f32]> = (0..l.rows.len()).filter(|i| plain(i) && !held(i)).map(row).collect();+ let sc = Scaler::fit(&base);+ let (tc, tb): (Vec<usize>, Vec<usize>) = (clean.iter().copied().filter(|i| !held(i)).collect(), bad.iter().copied().filter(|i| !held(i)).collect());+ if tc.len() < k || tb.len() < k {+ continue;+ }+ for _ in 0..5 {+ let (a, b) = (sample(rng, &tc, k), sample(rng, &tb, k));+ let x: Vec<&[f32]> = a.iter().chain(&b).map(|&i| row(i)).collect();+ let y: Vec<bool> = (0..2 * k).map(|i| i >= k).collect();+ let f = Logistic::fit(sc.clone(), &x, &y, None, C, true);+ let score = |v: &Vec<usize>| -> Vec<f32> { v.iter().filter(|i| held(i)).map(|&i| f.score(row(i))).collect() };+ aucs.push(auc(&score(&bad), &score(&clean)));+ }+ }+ let ok: Vec<f64> = aucs.into_iter().filter(|a| a.is_finite()).collect();+ if !ok.is_empty() {+ k_auc.insert(k, ok.iter().sum::<f64>() / ok.len() as f64);+ }+ }+ let fp0b = FP0B.iter().find(|(a, mm, _)| *a == axis && *mm == m).map(|x| x.2);+ let holds = fp0b.zip(k_auc.get(&32)).map(|(want, got)| *got >= want - 0.03);+ Curve { axis: axis.into(), modality: m, k: k_auc, fp0b, holds }+}++/// Every mechanical axis's curve on its own modality and on FP0b's+pub fn curves(fp: &Fingerprint, l: &Ledger) -> Vec<Curve> {+ let mut rng = fastrand::Rng::with_seed(1);+ let mut out = Vec::new();+ for axis in PICTURE.iter().chain(&SOUND) {+ let own = fp.axis(axis).map(|a| a.modality);+ let mut ms: Vec<Modality> = own.into_iter().chain(FP0B.iter().filter(|x| x.0 == *axis).map(|x| x.1)).collect();+ ms.dedup();+ for m in ms.into_iter().collect::<BTreeSet<_>>() {+ out.push(curve(l, axis, m, &mut rng));+ }+ }+ out+}++#[derive(Debug, Serialize)]+pub struct WordScore {+ pub axis: String,+ /// AUC, damaged against clean windows, with no labels+ pub auc: f64,+ /// the share of damaged windows over the score that flags 10% of clean ones+ pub caught: f64,+ /// each cheat's share over that same score+ pub cheats: BTreeMap<String, f64>,+}++/// Each word head on the bootstrap's windows (FP0g)+pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {+ let z = |i: usize, axis: &str| words.z(axis, l.features(i));+ let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { (0..l.rows.len()).filter(|&i| pick(&l.rows[i])).filter_map(|i| z(i, axis)).collect() };+ let mut out = Vec::new();+ for axis in PICTURE.iter().chain(&SOUND).filter(|a| words.axes.iter().any(|w| w.0 == **a)) {+ let clean = of(axis, &|r| r.source == "damage" && r.axis == "*");+ let bad = of(axis, &|r| r.source == "damage" && r.axis == *axis);+ let thr = quantile(&clean, 0.9);+ let share = |v: &[f32]| v.iter().filter(|x| **x > thr).count() as f64 / v.len().max(1) as f64;+ let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();+ out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });+ }+ out+}diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rsnew file mode 100644index 00000000..a9a1c939--- /dev/null+++ b/apps/fingerprint/src/lib.rs@@ -0,0 +1,110 @@+//! `raea fingerprint` (docs/fingerprint.feature FP3a): a person's fingerprint made, bootstrapped, taught and used to+//! score a piece. The encoders take seconds to load, so the verbs run in a resident service (`raea fingerprint+//! serve`, serve.rs) that keeps them loaded: the first verb starts it, on localhost, and later verbs reach it in+//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on+//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.++mod bootstrap;+mod serve;+mod verbs;++use std::path::Path;++pub use serve::serve;++pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] | raea fingerprint report [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends) and what it's for and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; report says each head's held-out score, labels, cheats, gate and what it can't judge)";++/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)+pub type Eval = fn(&Path) -> Result<String, String>;++/// The flags each verb takes, and whether each takes a value+pub(crate) const FLAGS: [(&str, bool); 18] = [+ ("--fp", true),+ ("--who", true),+ ("--about", true),+ ("--extends", true),+ ("--from", true),+ ("--per", true),+ ("--axis", true),+ ("--at", true),+ ("--span", true),+ ("--box", true),+ ("--words", true),+ ("--project", true),+ ("--sheet", true),+ ("--bad", false),+ ("--good", false),+ ("--json", false),+ ("--timeline", false),+ ("--here", false),+];++/// A flag's value+pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)+}++pub(crate) fn has(args: &[String], name: &str) -> bool {+ args.iter().any(|a| a == name)+}++/// The words that aren't flags or their values; an unknown flag is an error+pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {+ let mut out = Vec::new();+ let mut it = args.iter();+ while let Some(a) = it.next() {+ match FLAGS.iter().find(|(f, _)| f == a) {+ Some((_, true)) => {+ it.next().ok_or_else(|| format!("{a} takes a value"))?;+ }+ Some(_) => {}+ None if a.starts_with("--") => return Err(format!("no flag {a}")),+ None => out.push(a.as_str()),+ }+ }+ Ok(out)+}++/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)+pub fn cli(args: &[String], eval: Eval) -> i32 {+ let Some(verb) = args.first().map(String::as_str).filter(|v| !matches!(*v, "--help" | "-h" | "help")) else {+ println!("{USAGE}");+ return 0;+ };+ if let Err(e) = words(&args[1..]) {+ eprintln!("raea fingerprint: {e}\n{USAGE}");+ return 2;+ }+ match verb {+ "serve" => match serve(eval) {+ Ok(()) => 0,+ Err(e) => {+ eprintln!("raea fingerprint serve: {e:#}");+ 1+ }+ },+ "report" => verbs::report_here(args),+ "new" | "bootstrap" | "teach" | "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) };+ if !out.is_empty() {+ println!("{}", out.trim_end());+ }+ code+ }+ v => {+ eprintln!("raea fingerprint: no verb {v}\n{USAGE}");+ 2+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn the_usage_names_every_flag() {+ let missing: Vec<_> = super::FLAGS.iter().filter(|(f, _)| *f != "--here" && !super::USAGE.contains(f)).collect();+ assert!(missing.is_empty(), "raea fingerprint takes flags its usage doesn't name: {missing:?}");+ }+}diff --git a/apps/fingerprint/src/serve.rs b/apps/fingerprint/src/serve.rsnew file mode 100644index 00000000..fa263d57--- /dev/null+++ b/apps/fingerprint/src/serve.rs@@ -0,0 +1,141 @@+//! The resident service: the encoders loaded once, on 127.0.0.1 at a port the host file names+//! (~/.raea/fingerprints/.serve.json). A request is one JSON line, {"args": [...], "cwd": "..."}; the answer is+//! progress lines, {"say": "..."}, then {"out": "...", "code": N}. One request at a time, in order.++use crate::{Eval, verbs};+use anyhow::{Context, Result};+use raea_sys_columns::Encoders;+use raea_sys_fingerprint::folder::root;+use serde_json::{Value, json};+use std::io::{BufRead, BufReader, Write};+use std::net::{TcpListener, TcpStream};+use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};++/// The service leaves after this long with no request+const IDLE: Duration = Duration::from_secs(30 * 60);+/// How long a verb waits for a service it started to come up (the first run fetches the models)+const UP: Duration = Duration::from_secs(900);++fn host() -> PathBuf {+ root().join(".serve.json")+}++fn now() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+}++/// `raea fingerprint serve`: load the encoders, listen, answer until idle or stopped+pub fn serve(eval: Eval) -> Result<()> {+ let started = Instant::now();+ let mut enc = Encoders::load().context("loading the encoders")?;+ let listener = TcpListener::bind("127.0.0.1:0")?;+ let port = listener.local_addr()?.port();+ std::fs::create_dir_all(root())?;+ std::fs::write(host(), json!({"port": port, "pid": std::process::id()}).to_string())?;+ eprintln!("raea fingerprint serve: encoders loaded in {:.1} s, on 127.0.0.1:{port}", started.elapsed().as_secs_f64());+ let last = Arc::new(AtomicU64::new(now()));+ let seen = last.clone();+ std::thread::spawn(move || {+ loop {+ std::thread::sleep(Duration::from_secs(60));+ if now().saturating_sub(seen.load(Ordering::Relaxed)) > IDLE.as_secs() {+ let _ = std::fs::remove_file(host());+ eprintln!("raea fingerprint serve: idle for {} min, leaving", IDLE.as_secs() / 60);+ std::process::exit(0);+ }+ }+ });+ for stream in listener.incoming() {+ let Ok(mut s) = stream else { continue };+ last.store(now(), Ordering::Relaxed);+ let mut line = String::new();+ if BufReader::new(&s).read_line(&mut line).is_err() {+ continue;+ }+ let req: Value = serde_json::from_str(&line).unwrap_or_default();+ let args: Vec<String> = serde_json::from_value(req["args"].clone()).unwrap_or_default();+ let cwd = PathBuf::from(req["cwd"].as_str().unwrap_or("."));+ if args.first().is_some_and(|v| v == "stop") {+ let _ = writeln!(s, "{}", json!({"out": "raea fingerprint serve: stopped", "code": 0}));+ let _ = std::fs::remove_file(host());+ return Ok(());+ }+ let mut say = |m: String| {+ let _ = writeln!(s, "{}", json!({ "say": m }));+ };+ let (out, code) = verbs::run(&mut enc, &args, &cwd, eval, &mut say);+ let _ = writeln!(s, "{}", json!({"out": out, "code": code}));+ last.store(now(), Ordering::Relaxed);+ }+ Ok(())+}++/// A verb run in this process, with the encoders loaded for it+pub(crate) fn here(args: &[String], cwd: &Path, eval: Eval) -> (String, i32) {+ match Encoders::load() {+ Ok(mut enc) => verbs::run(&mut enc, args, cwd, eval, &mut |m| eprintln!("{m}")),+ Err(e) => (format!("raea fingerprint: loading the encoders: {e:#}"), 1),+ }+}++fn reach() -> Option<TcpStream> {+ let h: Value = serde_json::from_slice(&std::fs::read(host()).ok()?).ok()?;+ TcpStream::connect(("127.0.0.1", h["port"].as_u64()? as u16)).ok()+}++/// The service started in the background, its output in ~/.raea/fingerprints/.serve.log; its stream once it's up+fn start() -> Result<TcpStream, String> {+ let _ = std::fs::remove_file(host());+ std::fs::create_dir_all(root()).map_err(|e| e.to_string())?;+ let log = root().join(".serve.log");+ let file = std::fs::File::create(&log).map_err(|e| e.to_string())?;+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let mut cmd = std::process::Command::new(exe);+ cmd.args(["fingerprint", "serve"]).stdin(std::process::Stdio::null()).stdout(file.try_clone().map_err(|e| e.to_string())?).stderr(file);+ #[cfg(unix)]+ std::os::unix::process::CommandExt::process_group(&mut cmd, 0);+ let mut child = cmd.spawn().map_err(|e| format!("starting the service: {e}"))?;+ eprintln!("raea fingerprint: starting the service (loading the encoders once; its log is {})", log.display());+ let t = Instant::now();+ while t.elapsed() < UP {+ if let Some(s) = reach() {+ return Ok(s);+ }+ if let Ok(Some(status)) = child.try_wait() {+ let tail = std::fs::read_to_string(&log).unwrap_or_default();+ return Err(format!("the service stopped ({status}):\n{}", tail.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n")));+ }+ std::thread::sleep(Duration::from_millis(200));+ }+ let _ = child.kill();+ Err(format!("the service didn't come up in {} s (see {})", UP.as_secs(), log.display()))+}++/// A verb sent to the service, started if it isn't running; its progress printed as it comes+pub(crate) fn call(args: &[String], cwd: &Path) -> (String, i32) {+ let stream = match reach() {+ Some(s) => Ok(s),+ None if args.first().is_some_and(|v| v == "stop") => return ("raea fingerprint: no service running".into(), 0),+ None => start(),+ };+ let mut s = match stream {+ Ok(s) => s,+ Err(e) => return (format!("raea fingerprint: {e}"), 1),+ };+ if writeln!(s, "{}", json!({"args": args, "cwd": cwd})).is_err() {+ return ("raea fingerprint: the service closed the connection".into(), 1);+ }+ for line in BufReader::new(s).lines() {+ let Ok(line) = line else { break };+ let v: Value = serde_json::from_str(&line).unwrap_or_default();+ if let Some(m) = v["say"].as_str() {+ eprintln!("{m}");+ } else if v.get("code").is_some() {+ return (v["out"].as_str().unwrap_or("").to_string(), v["code"].as_i64().unwrap_or(1) as i32);+ }+ }+ ("raea fingerprint: the service ended without an answer (see ~/.raea/fingerprints/.serve.log)".into(), 1)+}diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rsnew file mode 100644index 00000000..6b377570--- /dev/null+++ b/apps/fingerprint/src/verbs.rs@@ -0,0 +1,293 @@+//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.++use crate::{Eval, flag, has, words};+use anyhow::{Context, Result, anyhow, bail};+use raea_sys_columns::{Encoders, FPS, media};+use raea_sys_fingerprint::evidence::{Ledger, Row, features};+use raea_sys_fingerprint::folder::{Folder, root};+use raea_sys_fingerprint::score::{Scored, clock, score, summary, timeline};+use raea_sys_fingerprint::sheet::{Tick, sheet};+use raea_sys_fingerprint::taxonomy::{Fingerprint, base};+use raea_sys_fingerprint::words::Words;+use crate::bootstrap;+use raea_sys_fingerprint::{report_text, retrain};+use serde_json::json;+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"+fn name(args: &[String]) -> String {+ flag(args, "--fp").map(str::to_string).or_else(|| std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string())).unwrap_or_else(|| "me".into())+}++fn at(cwd: &Path, p: &str) -> PathBuf {+ let p = Path::new(p);+ if p.is_absolute() { p.to_path_buf() } else { cwd.join(p) }+}++/// A verb's answer and exit code+pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {+ let rest = &args[1..];+ let ran = match args[0].as_str() {+ "new" => new(enc, rest),+ "bootstrap" => boot(enc, rest, cwd, eval, say),+ "teach" => teach(enc, rest, cwd, eval),+ "score" => scored(enc, rest, cwd, eval),+ v => Err(anyhow!("no verb {v}")),+ };+ ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))+}++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+pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {+ let mut fp = base(short);+ if let Some(p) = parent {+ fp.axes = p.axes;+ fp.extends = Some(p.name);+ }+ 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);+ fp+}++fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {+ let n = *words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("name it: raea fingerprint new NAME"))?;+ let dir = Folder::named(n);+ let short = dir.dir.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| n.into());+ let parent = match flag(args, "--extends") {+ Some(p) => Some(Folder::named(p).read(None).with_context(|| format!("--extends {p}"))?),+ None => None,+ };+ let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());+ let mut fp = shaped(&short, args, parent);+ fp.encoders = pins(enc);+ dir.create(&fp)?;+ let w = Words::build(enc, &fp)?;+ dir.write_words(&w)?;+ retrain(&dir, &fp, &w, &Ledger::default(), None)?;+ if !root().join("default").exists() && dir.dir.parent() == Some(root().as_path()) {+ std::fs::write(root().join("default"), &short)?;+ }+ Ok((+ format!(+ "made {}: {} axes from {from}, {} scoring from their words today (advice until they earn a gate)\n edit {} to add, remove or reword axes\n next: raea fingerprint bootstrap FILE... with your own finished work trains the mechanical axes",+ dir.dir.display(),+ fp.axes.len(),+ w.axes.len(),+ dir.ts().display()+ ),+ 0,+ ))+}++/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed+fn open(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(Folder, Fingerprint, Words)> {+ let dir = Folder::named(&name(args));+ let mut fp = dir.read(Some(eval))?;+ let here = pins(enc);+ if fp.encoders.is_empty() {+ fp.encoders = here;+ dir.rewrite(&fp)?;+ } else if fp.encoders != here {+ bail!("{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns", dir.ts().display(), fp.encoders, here);+ }+ let w = match dir.words().filter(|w| !w.stale(&fp)) {+ Some(w) => w,+ None => {+ let w = Words::build(enc, &fp)?;+ dir.write_words(&w)?;+ w+ }+ };+ Ok((dir, fp, w))+}++fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {+ let (dir, fp, w) = open(enc, args, eval)?;+ let mut files: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| at(cwd, f)).collect();+ if let Some(list) = flag(args, "--from") {+ let list = at(cwd, list);+ let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;+ files.extend(text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(|l| at(list.parent().unwrap_or(cwd), l)));+ }+ if files.is_empty() {+ bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");+ }+ let per: usize = flag(args, "--per").map_or(Ok(10), str::parse).context("--per takes a count")?;+ let mut l = dir.ledger()?;+ let who = fp.who.clone().unwrap_or_else(|| "me".into());+ let made = bootstrap::rows(enc, &who, &files, per, &mut l, say)?;+ dir.write_ledger(&l)?;+ say(format!("{} windows from {} sources; measuring held out by source", made.windows, made.sources));+ let curves = bootstrap::curves(&fp, &l);+ let ws = bootstrap::word_scores(&l, &w);+ let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws});+ retrain(&dir, &fp, &w, &l, Some(b))?;+ Ok((report_text(&dir.report().unwrap_or_default()), 0))+}++/// The project a file belongs to: the folder holding .raea/project above it, else the folder it's in+fn project_of(file: &Path) -> String {+ let mut d = file.parent();+ while let Some(p) = d {+ if p.join(".raea/project").exists() {+ return p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();+ }+ d = p.parent();+ }+ file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()+}++fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {+ let (dir, fp, w) = open(enc, args, eval)?;+ let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);+ let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;+ if axis != "*" && fp.axis(axis).is_none() {+ bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));+ }+ let t: f64 = flag(args, "--at").ok_or_else(|| anyhow!("--at SECONDS"))?.parse().context("--at takes seconds")?;+ let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;+ let region = flag(args, "--box").map(|b| -> Result<[f32; 4]> {+ let v: Vec<f32> = b.split(',').map(str::parse).collect::<Result<_, _>>().context("--box takes x0,y0,x1,y1 in 0-1")?;+ v.try_into().map_err(|_| anyhow!("--box takes four numbers"))+ });+ let c = enc.columns(&file)?;+ let a = (t - span / 2.0).clamp(0.0, (c.dur - span).max(0.0));+ let b = (a + span).min(c.dur);+ let bad = !has(args, "--good");+ let row = Row {+ media: c.media.clone(),+ a,+ b,+ axis: axis.into(),+ bad,+ weight: 1.0,+ who: fp.who.clone().unwrap_or_else(|| "me".into()),+ source: "teach".into(),+ project: flag(args, "--project").map_or_else(|| project_of(&file), str::to_string),+ kind: None,+ region: region.transpose()?,+ words: flag(args, "--words").map(str::to_string),+ at: 0,+ };+ let mut l = dir.ledger()?;+ l.push(row, &features(&c, a, b));+ dir.write_ledger(&l)?;+ let tr = retrain(&dir, &fp, &w, &l, None)?;+ let h = tr.heads.iter().find(|h| h.axis == axis);+ let (p, n) = l.for_axis(axis).iter().fold((0, 0), |(p, n), &i| if l.rows[i].bad { (p + 1, n) } else { (p, n + 1) });+ Ok((+ format!(+ "taught {axis}: {} at {} in {}\n {axis} has {p} defect and {n} clean labels; its head: {}",+ if bad { "the defect" } else { "clean" },+ clock(t),+ file.display(),+ h.map_or("every axis's clean labels grew".to_string(), |h| format!("{} ({})", h.state, h.why))+ ),+ 0,+ ))+}++/// raea check's findings on the file, in seconds: (rule, from, to, what)+fn checks(file: &Path) -> Vec<(String, f64, f64, String)> {+ let Ok(found) = raea_app_check::floor(&[file.display().to_string()], &[], &[]) else { return Vec::new() };+ found.into_iter().map(|f| {+ let (a, b) = f.frames.map_or((0.0, 0.0), |[a, b]| (a as f64 / 30.0, b as f64 / 30.0));+ (f.check, a, b, f.says)+ }).collect()+}++/// A check wins over a head (FP4c): a moment on an axis a check measures is no gate unless the check found it too+fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, String)]) {+ for m in &mut s.moments {+ let Some(rule) = fp.axis(&m.axis).and_then(|a| a.check.as_deref()) else { continue };+ let agrees = found.iter().any(|(r, a, b, _)| r == rule && *a <= m.b + 1.0 && *b >= m.a - 1.0);+ if !agrees {+ m.gating = false;+ m.state = format!("{}; the {rule} check found none", m.state);+ }+ }+}++fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {+ let (dir, fp, w) = open(enc, args, eval)?;+ let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);+ let c = enc.columns(&file)?;+ let trained = dir.trained()?.map(|(t, _)| t);+ let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());+ let found = checks(&file);+ arbitrate(&mut s, &fp, &found);+ let mut out = if has(args, "--json") {+ serde_json::to_string_pretty(&json!({"scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>()}))?+ } else {+ let mut t = summary(&s);+ t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });+ for (r, a, _, says) in &found {+ t += &format!(" {} {r}: {says}\n", clock(*a));+ }+ t+ };+ if has(args, "--timeline") {+ out += &timeline(&s);+ }+ 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();+ let pcm = media::sound(&file, 16_000)?;+ let ticks: Vec<Tick> = found.iter().map(|(r, a, b, _)| Tick { a: *a, b: *b, what: r.clone() }).collect();+ sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;+ out += &format!("sheet: {}\n", png.display());+ }+ Ok((out, i32::from(s.moments.iter().any(|m| m.gating))))+}++/// `raea fingerprint report`: report.json, read; no encoders needed+pub(crate) fn report_here(args: &[String]) -> i32 {+ let dir = Folder::named(&name(args));+ match dir.report() {+ Some(r) if has(args, "--json") => {+ println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+ 0+ }+ Some(r) => {+ println!("{}", report_text(&r).trim_end());+ 0+ }+ None => {+ eprintln!("raea fingerprint report: no report at {} (`raea fingerprint new NAME` makes one)", dir.dir.display());+ 1+ }+ }+}++#[cfg(test)]+mod tests {+ use super::shaped;+ use raea_sys_fingerprint::taxonomy::base;++ fn args(xs: &[&str]) -> Vec<String> {+ xs.iter().map(|x| x.to_string()).collect()+ }++ /// FP14a: a new fingerprint says what it's for, and one that extends another starts from its axes+ #[test]+ fn a_new_fingerprint_says_what_its_for_and_what_it_builds_on() {+ let own = shaped("me", &args(&["me", "--who", "w"]), None);+ assert_eq!((own.about.as_deref(), own.extends.as_deref(), own.who.as_deref()), (None, None, Some("w")));+ assert_eq!(own.axes, base("me").axes);++ let mut parent = base("me");+ parent.axes.truncate(2);+ parent.axes[0].words = vec!["a soft picture".into()];+ let ads = shaped("ads", &args(&["ads", "--about", " Short ads for one brand ", "--extends", "me"]), Some(parent.clone()));+ assert_eq!(ads.name, "ads");+ assert_eq!(ads.about.as_deref(), Some("Short ads for one brand"));+ assert_eq!(ads.extends.as_deref(), Some("me"));+ assert_eq!(ads.axes, parent.axes);+ assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);+ }+}diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.tomlindex 1aaddf99..c12b8d99 100644--- a/engine/cli/Cargo.toml+++ b/engine/cli/Cargo.toml@@ -53,6 +53,8 @@ raea-app-check = { path = "../../apps/check" }raea-app-direction = { path = "../../apps/direction" }# `raea notes`: a person's notes as files the work is held to (docs/direction.feature DR5)raea-app-notes = { path = "../../apps/notes" }+# `raea fingerprint`: axes with small heads over on-device encoders, and the service that keeps them loaded (docs/fingerprint.feature FP3a)+raea-app-fingerprint = { path = "../../apps/fingerprint" }raea-app-sound = { path = "../../apps/sound" }raea-app-ci = { path = "../../apps/ci" }raea-app-tools = { path = "../../apps/tools" }diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 17175b04..f0ee48b2 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -137,7 +137,7 @@ pub fn run(args: &[String]) -> R<String> {// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);- let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE);+ let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE);return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)@@ -210,6 +210,7 @@ pub fn run(args: &[String]) -> R<String> {if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)+ if args[0] == "fingerprint" { std::process::exit(raea_app_fingerprint::cli(&args[1..], spec::spec_json)); } // a person's sense of good work as axes over on-device encoders (docs/fingerprint.feature FP3a, FP14a)if args[0] == "traces" { return traces(args); }if args.first().map(String::as_str) == Some("play") {return raea_app_play::play(args);diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rsindex 3c788b2a..e0643e35 100644--- a/engine/cli/src/tests.rs+++ b/engine/cli/src/tests.rs@@ -70,6 +70,8 @@ fn a_verb_refuses_what_it_doesnt_take() {&["part", "add", "captions", "face-frame", "--force"],&["component", "add", "reel", "--shared", "--force"],&["mezz", "--check", "a.mov", "b.mov"],+ &["fingerprint", "bootstrap", "--fp", "client-ads", "a.mp4", "b.mp4", "c.mp4"],+ &["fingerprint", "new", "client-ads", "--about", "Short ads for one brand", "--extends", "me"],&["traces", "show", "last"],&["media", "ffmpeg", "-i", "x", "--anything"],&["physics", "bake", "r.json", "--whatever"],diff --git a/sdk/raea/src/brief.ts b/sdk/raea/src/brief.tsindex 35c144bc..c15d8d6c 100644--- a/sdk/raea/src/brief.ts+++ b/sdk/raea/src/brief.ts@@ -10,6 +10,8 @@import type { Brief, Controller, Field, Group, Plan, Script, Taste } from "./brief.gen";export type * from "./brief.gen";+export { fingerprint } from "./fingerprint";+export type { Applies, Axis, Fingerprint, Modality } from "./fingerprint";/** A field as written: its id is filled in from its label when left out. */export type FieldInput = Field extends infer F ? (F extends Field ? Omit<F, "id"> & { id?: string } : never) : never;diff --git a/sdk/raea/src/fingerprint.ts b/sdk/raea/src/fingerprint.tsnew file mode 100644index 00000000..952269ba--- /dev/null+++ b/sdk/raea/src/fingerprint.ts@@ -0,0 +1,47 @@+// A fingerprint (fingerprint.ts, docs/fingerprint.md): a person's or a team's sense of good work as axes, each with a+// small head over on-device encoders that `raea fingerprint` trains from their labels. `raea fingerprint new NAME`+// writes one with raea's base taxonomy; add an axis, reword one, or remove one, and raea retrains. Rust reads the+// default export (systems/fingerprint/src/taxonomy.rs), so these types follow its fields.++/** What an axis's head reads: the frames (SigLIP 2), how they change, their look, the sound (CLAP) or its events (YAMNet). */+export type Modality = "picture" | "change" | "look" | "sound" | "events";++export interface Axis {+ name: string;+ /** What people say for it, best first: the word head scores it from these on day one. */+ words: string[];+ modality: Modality;+ /** "moment" (the default), "shot" or "whole". */+ scope?: string;+ /** "bad" (the default): a high score is the defect; "good": a high score is the quality. */+ polarity?: "bad" | "good";+ /** The `raea check` rule that measures it exactly, when one does: the check wins over the head. */+ check?: string;+ /** False where words can't find it (silence matches no description). */+ word_head?: boolean;+ group?: string;+}++/** Which pieces a fingerprint judges, when a project or workspace holds more than one (docs/fingerprint.feature FP14c). */+export interface Applies {+ /** film, ad, game, playable, still, sound */+ kinds?: string[];+ /** the project's tags */+ tags?: string[];+}++export interface Fingerprint {+ name: string;+ who?: string;+ /** One line: what it tracks and when it judges ("Short ads for one brand: pace, type on screen, the brand's colours"). */+ about?: string;+ /** The fingerprint it builds on, by name: it started from that one's axes. */+ extends?: string;+ applies?: Applies;+ axes: Axis[];+ /** Each encoder's id and its file's sha256: heads trained on other encoders' columns are refused. */+ encoders?: Record<string, string>;+}++/** A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained on. */+export const fingerprint = (f: Fingerprint): Fingerprint => f;diff --git a/systems/columns/Cargo.toml b/systems/columns/Cargo.tomlnew file mode 100644index 00000000..d81cb64a--- /dev/null+++ b/systems/columns/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "raea-sys-columns"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Fingerprint's columns (docs/fingerprint.feature FP1a): a file's frames and sound read once by frozen on-device encoders (SigLIP 2, CLAP and YAMNet on ONNX Runtime) with change and look columns, cached by content hash; and the damage that makes labels by construction (FP4a)"++[dependencies]+# every encoder is an ONNX model on ONNX Runtime's CPU kernels (raea-sys-ml), never Core ML's GPU+raea-sys-ml = { path = "../ml" }+ort = { version = "=2.0.0-rc.13", features = ["half"] }+# frames from the media plane (VideoToolbox on Apple), sound through Symphonia+raea-io-media = { path = "../../io/media", default-features = false, features = ["apple", "soft-audio"] }+tokenizers = { version = "0.23", default-features = false, features = ["onig"] }+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }+rustfft = "6"+sha2 = "0.10"+# the seeded noise the bootstrap puts in sound (damage.rs)+fastrand = "2"+half = "2"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+anyhow = "1"diff --git a/systems/columns/src/cache.rs b/systems/columns/src/cache.rsnew file mode 100644index 00000000..5a342f66--- /dev/null+++ b/systems/columns/src/cache.rs@@ -0,0 +1,72 @@+//! Columns are a cache (docs/platform.feature: derived files are a cache): one file per media sha256 and STEP under+//! $RAEA_COLUMNS, else ~/.cache/raea-fingerprint/columns. The file: a JSON header line (media, dur, step, each+//! column's length), then the columns in order as little-endian fp16.++use crate::{Columns, STEP};+use anyhow::Result;+use half::f16;+use serde::{Deserialize, Serialize};+use std::path::PathBuf;++/// The file's first line+#[derive(Serialize, Deserialize)]+struct Head {+ media: String,+ dur: f64,+ step: u32,+ /// each column's length, in the order saved+ lens: Vec<usize>,+}++pub fn root() -> PathBuf {+ crate::under("RAEA_COLUMNS", ".cache/raea-fingerprint")+}++fn path(media: &str) -> PathBuf {+ root().join("columns").join(format!("{media}-{STEP}.cols"))+}++pub fn save(c: &Columns) -> Result<()> {+ let cols = [&c.sig, &c.look, &c.clap, &c.yam, &c.level];+ let head = Head { media: c.media.clone(), dur: c.dur, step: STEP, lens: cols.iter().map(|v| v.len()).collect() };+ let mut b = serde_json::to_vec(&head)?;+ b.push(b'\n');+ for v in cols {+ for x in v.iter() {+ b.extend(f16::from_f32(*x).to_le_bytes());+ }+ }+ let p = path(&c.media);+ std::fs::create_dir_all(p.parent().unwrap())?;+ let tmp = p.with_extension("part");+ std::fs::write(&tmp, b)?;+ std::fs::rename(tmp, p)?;+ Ok(())+}++pub fn load(media: &str) -> Option<Columns> {+ let b = std::fs::read(path(media)).ok()?;+ let nl = b.iter().position(|&x| x == b'\n')?;+ let head: Head = serde_json::from_slice(&b[..nl]).ok()?;+ if head.lens.len() != 5 || head.step != STEP {+ return None;+ }+ let mut at = nl + 1;+ let mut cols: Vec<Vec<f32>> = Vec::new();+ for &n in &head.lens {+ let end = at + 2 * n;+ let raw = b.get(at..end)?;+ cols.push(raw.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect());+ at = end;+ }+ let mut it = cols.into_iter();+ Some(Columns {+ media: media.to_string(),+ dur: head.dur,+ sig: it.next()?,+ look: it.next()?,+ clap: it.next()?,+ yam: it.next()?,+ level: it.next()?,+ })+}diff --git a/systems/columns/src/clap.rs b/systems/columns/src/clap.rsnew file mode 100644index 00000000..5110705d--- /dev/null+++ b/systems/columns/src/clap.rs@@ -0,0 +1,143 @@+//! CLAP htsat-unfused's audio tower on ONNX Runtime (Xenova's q8 export, Apache-2.0), with its front end written out+//! here the way its feature extractor computes it (transformers' ClapFeatureExtractor, "rand_trunc" with+//! "repeatpad"): 48 kHz mono padded to 10 s by whole repeats while one more fits, then zeros; a 1024-point periodic+//! Hann STFT, hop 480, centred with reflect padding (1001 frames); power through a 64-band slaney mel bank (50 Hz to+//! 14 kHz, slaney-normalised); 10 log10 of each band, floored at 1e-10. The tower sees [1, 1, 1001, 64].++use crate::siglip::{Input, run};+use anyhow::{Context, Result};+use ort::session::Session;+use rustfft::{Fft, FftPlanner, num_complex::Complex};+use std::path::Path;+use std::sync::Arc;++pub const RATE: u32 = 48_000;+const MAX: usize = 480_000;+const NFFT: usize = 1024;+const HOP: usize = 480;+const MELS: usize = 64;+const BINS: usize = NFFT / 2 + 1;+const FRAMES: usize = 1 + MAX / HOP;++pub struct Audio {+ s: Session,+ bank: Vec<f64>,+ /// each band's first and last bin with weight (the bank is mostly zeros)+ span: Vec<(usize, usize)>,+ window: Vec<f64>,+ fft: Arc<dyn Fft<f64>>,+}++fn slaney_mel(f: f64) -> f64 {+ let logstep = 27.0 / 6.4f64.ln();+ if f >= 1000.0 { 15.0 + (f / 1000.0).ln() * logstep } else { 3.0 * f / 200.0 }+}++fn slaney_hz(m: f64) -> f64 {+ let logstep = 6.4f64.ln() / 27.0;+ if m >= 15.0 { 1000.0 * (logstep * (m - 15.0)).exp() } else { 200.0 * m / 3.0 }+}++/// The mel bank, [MELS][BINS]+pub(crate) fn bank() -> Vec<f64> {+ let (lo, hi) = (slaney_mel(50.0), slaney_mel(14_000.0));+ // MELS + 2 edges evenly spaced in mels, and each FFT bin's centre in Hz+ let step = (hi - lo) / (MELS + 1) as f64;+ let mut edges = Vec::with_capacity(MELS + 2);+ for i in 0..MELS + 2 {+ edges.push(slaney_hz(lo + step * i as f64));+ }+ let bin = (RATE / 2) as f64 / (BINS - 1) as f64;+ let mut fft = Vec::with_capacity(BINS);+ for j in 0..BINS {+ fft.push(bin * j as f64);+ }+ let mut out = vec![0f64; MELS * BINS];+ for i in 0..MELS {+ let enorm = 2.0 / (edges[i + 2] - edges[i]);+ for (j, &f) in fft.iter().enumerate() {+ let down = (f - edges[i]) / (edges[i + 1] - edges[i]);+ let up = (edges[i + 2] - f) / (edges[i + 2] - edges[i + 1]);+ out[i * BINS + j] = down.min(up).max(0.0) * enorm;+ }+ }+ out+}++/// The clip as the tower reads it: padded to MAX samples by repeats, then zeros (a longer clip keeps its first MAX)+pub(crate) fn padded(x: &[f32]) -> Vec<f64> {+ let mut p = vec![0f64; MAX];+ let n = x.len().min(MAX);+ for (d, s) in p.iter_mut().zip(&x[..n]) {+ *d = *s as f64;+ }+ if n > 0 && n < MAX {+ let mut i = n;+ while i < MAX - n {+ for k in 0..n {+ p[i + k] = x[k] as f64;+ }+ i += n;+ }+ }+ p+}++impl Audio {+ pub fn load(file: &Path) -> Result<Audio> {+ let window = (0..NFFT).map(|i| 0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / NFFT as f64).cos()).collect();+ let fft = FftPlanner::new().plan_fft_forward(NFFT);+ let bank = bank();+ let span = (0..MELS)+ .map(|m| {+ let row = &bank[m * BINS..(m + 1) * BINS];+ let lo = row.iter().position(|x| *x > 0.0).unwrap_or(0);+ (lo, row.iter().rposition(|x| *x > 0.0).map_or(lo, |h| h + 1))+ })+ .collect();+ Ok(Audio { s: raea_sys_ml::session(file).context("CLAP's audio tower")?, bank, span, window, fft })+ }++ /// The log-mel features, [FRAMES][MELS]+ pub fn features(&self, x: &[f32]) -> Vec<f32> {+ let w = padded(x);+ let half = NFFT / 2;+ // reflect padding: w[1..=half] mirrored before, w[MAX-1-half..MAX-1] mirrored after+ let at = |i: isize| -> f64 {+ let n = MAX as isize;+ let j = if i < 0 { -i } else if i >= n { 2 * (n - 1) - i } else { i };+ w[j as usize]+ };+ let mut out = vec![0f32; FRAMES * MELS];+ let mut buf = vec![Complex::new(0.0, 0.0); NFFT];+ // power and the mel sums in single precision, as transformers.js keeps them (its magnitudes are a Float32Array)+ let mut power = vec![0f32; BINS];+ for f in 0..FRAMES {+ let start = (f * HOP) as isize - half as isize;+ for (j, b) in buf.iter_mut().enumerate() {+ *b = Complex::new(at(start + j as isize) * self.window[j], 0.0);+ }+ self.fft.process(&mut buf);+ for (j, p) in power.iter_mut().enumerate() {+ *p = buf[j].norm_sqr() as f32;+ }+ for m in 0..MELS {+ let (lo, hi) = self.span[m];+ let e: f32 = self.bank[m * BINS + lo..m * BINS + hi].iter().zip(&power[lo..hi]).map(|(a, b)| *a as f32 * b).sum();+ out[f * MELS + m] = (10.0 * (e as f64).max(1e-10).log10()) as f32;+ }+ }+ out+ }++ /// Each clip's vector, L2-normalised: [clips][512]+ pub fn embed(&mut self, clips: &[&[f32]]) -> Result<Vec<f32>> {+ let mut v = Vec::with_capacity(clips.len() * crate::CLAP);+ for c in clips {+ let x = self.features(c);+ v.extend(run(&mut self.s, ("input_features", vec![1, 1, FRAMES as i64, MELS as i64], Input::F32(x)), &["audio_embeds"])?.remove(0));+ }+ crate::normalise(&mut v, crate::CLAP);+ Ok(v)+ }+}diff --git a/systems/columns/src/clap_text.rs b/systems/columns/src/clap_text.rsnew file mode 100644index 00000000..0bec8c2d--- /dev/null+++ b/systems/columns/src/clap_text.rs@@ -0,0 +1,41 @@+//! CLAP's text tower on ONNX Runtime (Xenova's q8 export) with its RoBERTa tokenizer: an axis's words as a 512-d+//! vector in the space of CLAP's sounds. Run only when an axis's words change (FP2e); one text at a time, so no+//! padding reaches the tower (its export takes no attention mask).++use crate::siglip::{Input, run};+use anyhow::{Context, Result, anyhow};+use ort::session::Session;+use std::path::Path;++pub struct Text {+ s: Session,+ tok: tokenizers::Tokenizer,+}++impl Text {+ pub fn load(file: &Path, tokenizer: &Path) -> Result<Text> {+ let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("CLAP's tokenizer: {e}"))?;+ Ok(Text { s: raea_sys_ml::session(file).context("CLAP's text tower")?, tok })+ }++ /// Each text's vector, L2-normalised: [texts][512]+ pub fn embed(&mut self, texts: &[String]) -> Result<Vec<f32>> {+ self.embed_padded(texts, 0)+ }++ /// The same with each text padded to `len` tokens (RoBERTa's pad, 1): only to compare with a batch embedded+ /// padded, as transformers.js does, since the export sees the pads without a mask+ pub fn embed_padded(&mut self, texts: &[String], len: usize) -> Result<Vec<f32>> {+ let mut v = Vec::with_capacity(texts.len() * crate::CLAP);+ for t in texts {+ let e = self.tok.encode(t.as_str(), true).map_err(|e| anyhow!("tokenizing {t:?}: {e}"))?;+ let mut ids: Vec<i64> = e.get_ids().iter().map(|&i| i as i64).take(77).collect();+ if ids.len() < len {+ ids.resize(len, 1);+ }+ v.extend(run(&mut self.s, ("input_ids", vec![1, ids.len() as i64], Input::I64(ids)), &["text_embeds"])?.remove(0));+ }+ crate::normalise(&mut v, crate::CLAP);+ Ok(v)+ }+}diff --git a/systems/columns/src/damage.rs b/systems/columns/src/damage.rsnew file mode 100644index 00000000..d31bf516--- /dev/null+++ b/systems/columns/src/damage.rs@@ -0,0 +1,101 @@+//! Known defects put into real work: labels by construction for the mechanical axes (FP4a), and the cheats each axis+//! must still catch (FP4b). The same damage the 11-12 spike measured (docs/fingerprint.md FP0b, FP0d), on the 224 x 224+//! frames the encoder sees and on the sound at its own rate. Noise is seeded, so a bootstrap is the same run to run.++use crate::media::{Rgb, SIDE};+use image::{ImageBuffer, Rgb as Px, imageops};++/// The picture defects, then the sound defects, each with the axis it labels; cheats last+pub const PICTURE: [&str; 5] = ["blur", "dark", "glow", "flash", "freeze"];+pub const SOUND: [&str; 3] = ["noise", "dropout", "clip"];+/// Each cheat and the defect it hides: a de-rez sharpened after, glow at half strength, noise at a third of the level,+/// and a freeze with a slow zoom on it+pub const CHEATS: [(&str, &str); 4] = [("sharpblur", "blur"), ("glow_half", "glow"), ("noise_low", "noise"), ("freeze_zoom", "freeze")];++type Img = ImageBuffer<Px<u8>, Vec<u8>>;++fn img(f: &Rgb) -> Img {+ Img::from_raw(SIDE as u32, SIDE as u32, f.clone()).expect("a 224 x 224 frame")+}++fn soft(f: &Rgb) -> Img {+ let small = imageops::resize(&img(f), (SIDE / 5) as u32, (SIDE / 5) as u32, imageops::FilterType::Triangle);+ imageops::resize(&small, SIDE as u32, SIDE as u32, imageops::FilterType::Triangle)+}++fn glow(f: &Rgb, k: f32) -> Rgb {+ let g = imageops::blur(&img(f), SIDE as f32 / 22.0);+ f.iter().zip(g.as_raw()).map(|(&x, &b)| (255.0 * (1.0 - (1.0 - x as f32 / 255.0) * (1.0 - k * b as f32 / 255.0))).clamp(0.0, 255.0) as u8).collect()+}++/// An unsharp mask (radius 4, 250%, threshold 2) over the de-rez: crisp edges with the detail still gone+fn sharpened(f: &Rgb) -> Rgb {+ let s = soft(f);+ let b = imageops::blur(&s, 4.0);+ s.as_raw().iter().zip(b.as_raw()).map(|(&x, &y)| {+ let d = x as f32 - y as f32;+ if d.abs() < 2.0 { x } else { (x as f32 + 2.5 * d).clamp(0.0, 255.0) as u8 }+ }).collect()+}++/// The first frame held, pushed in 1% a frame from its centre+fn zoomed(f: &Rgb, i: usize) -> Rgb {+ let side = (SIDE as f32 / (1.0 + 0.01 * i as f32)).round() as u32;+ let at = (SIDE as u32 - side) / 2;+ let crop = imageops::crop_imm(&img(f), at, at, side, side).to_image();+ imageops::resize(&crop, SIDE as u32, SIDE as u32, imageops::FilterType::Triangle).into_raw()+}++/// A window's frames with a picture defect (or cheat) put in+pub fn picture(frames: &[Rgb], kind: &str) -> Vec<Rgb> {+ match kind {+ "blur" => frames.iter().map(|f| soft(f).into_raw()).collect(),+ "sharpblur" => frames.iter().map(sharpened).collect(),+ "glow" => frames.iter().map(|f| glow(f, 0.7)).collect(),+ "glow_half" => frames.iter().map(|f| glow(f, 0.35)).collect(),+ "dark" => frames.iter().map(|f| f.iter().map(|&x| (x as f32 * 0.3) as u8).collect()).collect(),+ "freeze" => frames.iter().map(|_| frames[0].clone()).collect(),+ "freeze_zoom" => (0..frames.len()).map(|i| zoomed(&frames[0], i)).collect(),+ "flash" => {+ let mut v = frames.to_vec();+ if !v.is_empty() {+ let m = v.len() / 2;+ v[m] = vec![0; SIDE * SIDE * 3];+ }+ v+ }+ _ => frames.to_vec(),+ }+}++/// A seeded normal source (fastrand's, Box-Muller)+pub struct Noise(fastrand::Rng);++impl Noise {+ pub fn new(seed: u64) -> Noise {+ Noise(fastrand::Rng::with_seed(seed))+ }+ pub fn normal(&mut self) -> f32 {+ let (u, v) = (self.0.f64().max(1e-12), self.0.f64());+ ((-2.0 * u.ln()).sqrt() * (2.0 * std::f64::consts::PI * v).cos()) as f32+ }+}++/// A window's sound (at `rate`) with a sound defect (or cheat) put in+pub fn sound(w: &[f32], kind: &str, rate: u32, noise: &mut Noise) -> Vec<f32> {+ let mut w = w.to_vec();+ let rms = (w.iter().map(|x| x * x).sum::<f32>() / w.len().max(1) as f32 + 1e-9).sqrt();+ let mut add = |w: &mut Vec<f32>, k: f32| w.iter_mut().for_each(|x| *x += noise.normal() * rms.max(0.02) * k);+ match kind {+ "noise" => add(&mut w, 0.5),+ "noise_low" => add(&mut w, 0.15),+ "dropout" => {+ let a = (w.len() / 2).saturating_sub((0.3 * rate as f64) as usize);+ let b = (a + (0.6 * rate as f64) as usize).min(w.len());+ w[a..b].iter_mut().for_each(|x| *x = 0.0);+ }+ "clip" => w.iter_mut().for_each(|x| *x = (*x * 10.0).clamp(-0.3, 0.3)),+ _ => {}+ }+ w+}diff --git a/systems/columns/src/lib.rs b/systems/columns/src/lib.rsnew file mode 100644index 00000000..a69b4197--- /dev/null+++ b/systems/columns/src/lib.rs@@ -0,0 +1,179 @@+//! Fingerprint's columns (docs/fingerprint.feature FP1a, docs/fingerprint.md "The stack"): a file is read once by+//! frozen encoders that run on the person's own machine, and every fingerprint reads the same columns.+//!+//! - picture: SigLIP 2 base p16-224 per frame at 4 fps, its pooled vector (L2-normalised); the 14 x 14 patch tokens+//! come with FP12's heatmaps+//! - change: from the picture column (window.rs)+//! - look: luminance histogram, contrast, saturation, local contrast and sharpness per frame (look.rs)+//! - sound: CLAP htsat-unfused per 2 s window, 1 s hop (L2-normalised); YAMNet per 0.48 s when its model is here+//! - level: the sound's RMS in dBFS per 0.1 s, for checks, the sheet and the timeline+//!+//! Every encoder is ONNX on ONNX Runtime's CPU kernels (raea-sys-ml): never Core ML's GPU, which computes SigLIP wrong+//! on this Mac. The text towers (CLAP's, SigLIP's) only turn an axis's words into vectors (FP2e). Columns are cached by+//! the file's sha256 and STEP (cache.rs).++pub mod cache;+mod clap;+mod clap_text;+pub mod damage;+pub mod look;+pub mod media;+pub mod models;+mod siglip;+pub mod window;+mod yamnet;++use anyhow::{Context, Result};+use std::path::{Path, PathBuf};++/// Frames a second in the picture column+pub const FPS: f64 = 4.0;+/// CLAP's window and hop, seconds+pub const CLAP_WIN: f64 = 2.0;+pub const CLAP_HOP: f64 = 1.0;+/// YAMNet's hop, seconds+pub const YAM_HOP: f64 = 0.48;+pub const SIG: usize = 768;+pub const CLAP: usize = 512;+pub const YAM: usize = 1024;+/// The column version: a change to how any column is made bumps it, and the cache makes them again+pub const STEP: u32 = 1;++/// A file's columns, row-major, each row one step of its column.+#[derive(Clone, Debug, Default)]+pub struct Columns {+ /// the file's sha256+ pub media: String,+ pub dur: f64,+ pub sig: Vec<f32>,+ pub look: Vec<f32>,+ pub clap: Vec<f32>,+ pub yam: Vec<f32>,+ pub level: Vec<f32>,+}++impl Columns {+ pub fn clap_windows(&self) -> usize {+ self.clap.len() / CLAP+ }+}++/// The encoders, loaded once (the resident service keeps one): the text towers load on first use.+pub struct Encoders {+ files: models::Files,+ vision: siglip::Vision,+ clap: clap::Audio,+ yam: Option<yamnet::Yamnet>,+ vision_text: Option<siglip::Text>,+ clap_text: Option<clap_text::Text>,+}++impl Encoders {+ pub fn load() -> Result<Encoders> {+ let files = models::locate()?;+ let vision = siglip::Vision(raea_sys_ml::session(&files.sig_vision).context("SigLIP 2's image tower")?);+ let clap = clap::Audio::load(&files.clap_audio)?;+ let yam = match files.yam.as_deref() {+ Some(f) => Some(yamnet::Yamnet(raea_sys_ml::session(f).context("YAMNet")?)),+ None => None,+ };+ Ok(Encoders { files, vision, clap, yam, vision_text: None, clap_text: None })+ }++ /// Each encoder's id and its file's sha256: a fingerprint's heads are pinned to these+ pub fn pins(&self) -> Vec<(String, String)> {+ self.files.pins()+ }++ /// A file's columns, from the cache when it has them+ pub fn columns(&mut self, file: &Path) -> Result<Columns> {+ let media = media::sha256(file)?;+ if let Some(c) = cache::load(&media) {+ return Ok(c);+ }+ let dur = media::duration(file)?;+ let frames = media::frames(file, FPS, 0.0, dur)?;+ let (pcm16, pcm48) = (media::sound(file, 16_000)?, media::sound(file, clap::RATE)?);+ let mut c = self.of(&frames, &pcm16, &pcm48, dur)?;+ c.media = media;+ cache::save(&c)?;+ Ok(c)+ }++ /// Columns of frames (at FPS) and sound given directly: a damaged window (damage.rs) or a span already decoded+ pub fn of(&mut self, frames: &[media::Rgb], pcm16: &[f32], pcm48: &[f32], dur: f64) -> Result<Columns> {+ let (sig, look) = self.picture(frames)?;+ let (clap, yam) = self.sound(pcm16, pcm48)?;+ Ok(Columns { media: String::new(), dur, sig, look, clap, yam, level: media::levels(pcm16, 16_000) })+ }++ /// The picture columns of frames at FPS: SigLIP 2's pooled vectors and each frame's look+ pub fn picture(&mut self, frames: &[media::Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {+ let sig = self.vision.embed(frames)?;+ Ok((sig, frames.iter().flat_map(|f| look::look(f)).collect()))+ }++ /// The sound columns of mono sound at 16 and 48 kHz: CLAP per CLAP_WIN window every CLAP_HOP (one window at+ /// least), and YAMNet's when its model is here+ pub fn sound(&mut self, pcm16: &[f32], pcm48: &[f32]) -> Result<(Vec<f32>, Vec<f32>)> {+ let mut clips: Vec<&[f32]> = Vec::new();+ let (win, hop) = ((CLAP_WIN * clap::RATE as f64) as usize, (CLAP_HOP * clap::RATE as f64) as usize);+ let mut s = 0;+ while s == 0 || s + win <= pcm48.len() {+ clips.push(&pcm48[s.min(pcm48.len())..(s + win).min(pcm48.len())]);+ s += hop;+ }+ let clap = self.clap.embed(&clips)?;+ let yam = match &mut self.yam {+ Some(y) => y.embed(pcm16)?,+ None => Vec::new(),+ };+ Ok((clap, yam))+ }++ /// Words as CLAP text vectors (sound axes), L2-normalised, one row each+ pub fn words_sound(&mut self, texts: &[String]) -> Result<Vec<f32>> {+ if self.clap_text.is_none() {+ self.clap_text = Some(clap_text::Text::load(&self.files.clap_text, &self.files.clap_tokenizer)?);+ }+ self.clap_text.as_mut().unwrap().embed(texts)+ }++ /// CLAP text vectors padded to `len` tokens: only for checking against a padded batch (tests)+ pub fn words_sound_padded(&mut self, texts: &[String], len: usize) -> Result<Vec<f32>> {+ self.words_sound(&[])?;+ self.clap_text.as_mut().unwrap().embed_padded(texts, len)+ }++ /// Words as SigLIP 2 text vectors (picture axes), L2-normalised, one row each+ pub fn words_picture(&mut self, texts: &[String]) -> Result<Vec<f32>> {+ if self.vision_text.is_none() {+ self.vision_text = Some(siglip::Text::load(&self.files.sig_text, &self.files.sig_tokenizer)?);+ }+ self.vision_text.as_mut().unwrap().embed(texts)+ }++ /// CLAP on clips of 48 kHz sound given directly (a test against the reference, or a damaged clip)+ pub fn clap_clips(&mut self, clips: &[&[f32]]) -> Result<Vec<f32>> {+ self.clap.embed(clips)+ }+}++/// `$var`, else `rel` under the home folder+pub(crate) fn under(var: &str, rel: &str) -> PathBuf {+ match std::env::var_os(var) {+ Some(p) => p.into(),+ None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(rel),+ }+}++/// Rows scaled to unit length in place+pub(crate) fn normalise(v: &mut [f32], dim: usize) {+ for row in v.chunks_mut(dim) {+ let n = row.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);+ row.iter_mut().for_each(|x| *x /= n);+ }+}++#[cfg(test)]+mod tests;diff --git a/systems/columns/src/look.rs b/systems/columns/src/look.rsnew file mode 100644index 00000000..2f0fa470--- /dev/null+++ b/systems/columns/src/look.rs@@ -0,0 +1,50 @@+//! The look column: what SigLIP's pooled vector is built to ignore (FP0d: glow at half strength caught 0.20). Per+//! frame, on the 224 x 224 picture the encoder sees, all in 0..1 units: an 8-bin luminance histogram, mean and spread+//! of luminance, mean saturation, local contrast (mean distance from the 3 x 3 neighbourhood's mean), sharpness (the+//! Laplacian's spread), the share of near-black and near-white pixels, and the 5th-95th percentile range.++use crate::media::SIDE;++pub const LOOK: usize = 16;++/// One frame's look, LOOK values+pub fn look(rgb: &[u8]) -> [f32; LOOK] {+ let n = SIDE * SIDE;+ let mut y = vec![0f32; n];+ let mut sat = 0f64;+ for i in 0..n {+ let (r, g, b) = (rgb[i * 3] as f32 / 255.0, rgb[i * 3 + 1] as f32 / 255.0, rgb[i * 3 + 2] as f32 / 255.0);+ y[i] = 0.2126 * r + 0.7152 * g + 0.0722 * b;+ let (hi, lo) = (r.max(g).max(b), r.min(g).min(b));+ sat += if hi > 1e-3 { ((hi - lo) / hi) as f64 } else { 0.0 };+ }+ let mut o = [0f32; LOOK];+ for v in &y {+ o[((v * 8.0) as usize).min(7)] += 1.0 / n as f32;+ }+ let mean = y.iter().sum::<f32>() / n as f32;+ o[8] = mean;+ o[9] = (y.iter().map(|v| (v - mean).powi(2)).sum::<f32>() / n as f32).sqrt();+ o[10] = (sat / n as f64) as f32;+ let (mut local, mut lap, mut lap2, mut inner) = (0f64, 0f64, 0f64, 0f64);+ for r in 1..SIDE - 1 {+ for c in 1..SIDE - 1 {+ let i = r * SIDE + c;+ let around = [i - SIDE - 1, i - SIDE, i - SIDE + 1, i - 1, i + 1, i + SIDE - 1, i + SIDE, i + SIDE + 1];+ let box_mean = (around.iter().map(|&j| y[j]).sum::<f32>() + y[i]) / 9.0;+ local += (y[i] - box_mean).abs() as f64;+ let l = (y[i - SIDE] + y[i + SIDE] + y[i - 1] + y[i + 1] - 4.0 * y[i]) as f64;+ lap += l;+ lap2 += l * l;+ inner += 1.0;+ }+ }+ o[11] = (local / inner) as f32 * 10.0;+ o[12] = ((lap2 / inner - (lap / inner).powi(2)).max(0.0).sqrt()) as f32 * 10.0;+ o[13] = y.iter().filter(|v| **v < 0.1).count() as f32 / n as f32;+ o[14] = y.iter().filter(|v| **v > 0.9).count() as f32 / n as f32;+ let mut s = y;+ s.sort_by(f32::total_cmp);+ o[15] = s[n * 95 / 100] - s[n * 5 / 100];+ o+}diff --git a/systems/columns/src/media.rs b/systems/columns/src/media.rsnew file mode 100644index 00000000..f39d07f8--- /dev/null+++ b/systems/columns/src/media.rs@@ -0,0 +1,136 @@+//! A file's frames and sound the way the encoders read them: frames squashed to 224 x 224 RGB (as SigLIP's processor+//! does, bicubic), sound as mono floats at the encoder's rate (raea's band-limited resampler). Decoding goes through+//! the media plane's preferred backends (VideoToolbox on Apple, then the portable decoders, then the ffmpeg CLI).++use anyhow::{Result, anyhow};+use sha2::{Digest, Sha256};+use std::io::Read;+use std::path::Path;++pub const SIDE: usize = 224;+/// A frame as SIDE x SIDE RGB8, row-major+pub type Rgb = Vec<u8>;++/// A file's sha256, hex+pub fn sha256(file: &Path) -> Result<String> {+ let mut f = std::fs::File::open(file).map_err(|e| anyhow!("{}: {e}", file.display()))?;+ let mut h = Sha256::new();+ let mut buf = vec![0u8; 1 << 20];+ loop {+ let n = f.read(&mut buf)?;+ if n == 0 {+ break;+ }+ h.update(&buf[..n]);+ }+ Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())+}++fn video(file: &Path) -> Result<Box<dyn raea_io_media::VideoDecoder>> {+ let mut why = Vec::new();+ for b in raea_io_media::preferred() {+ match b.open_video(file) {+ Ok(d) => return Ok(d),+ Err(e) => why.push(format!("{}: {e}", b.name())),+ }+ }+ Err(anyhow!("{}: no decoder opened it ({})", file.display(), why.join("; ")))+}++/// How long the file is, seconds: its picture's length, or its sound's when it has no picture+pub fn duration(file: &Path) -> Result<f64> {+ match video(file) {+ Ok(d) => Ok(d.info().duration),+ Err(e) => {+ let s = sound(file, 16_000).map_err(|_| e)?;+ Ok(s.len() as f64 / 16_000.0)+ }+ }+}++/// Frames at `fps` from `start` for `dur` seconds (t = start + i / fps), each squashed to SIDE x SIDE. A file with no+/// picture gives none.+pub fn frames(file: &Path, fps: f64, start: f64, dur: f64) -> Result<Vec<Rgb>> {+ let Ok(mut d) = video(file) else { return Ok(Vec::new()) };+ let n = (dur * fps).floor().max(1.0) as usize;+ let end = d.info().duration;+ let mut out = Vec::with_capacity(n);+ for i in 0..n {+ let t = start + i as f64 / fps;+ if t >= end && i > 0 {+ break;+ }+ let f = d.frame_at(t.min((end - 1e-3).max(0.0))).map_err(|e| anyhow!("{}: frame at {t:.2} s: {e}", file.display()))?;+ out.push(squash(&f.rgba, f.width as usize, f.height as usize));+ }+ Ok(out)+}++/// RGBA8 at w x h to SIDE x SIDE RGB8, bicubic (Catmull-Rom)+pub fn squash(rgba: &[u8], w: usize, h: usize) -> Rgb {+ let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba.to_vec()) else { return vec![0; SIDE * SIDE * 3] };+ let small = image::imageops::resize(&img, SIDE as u32, SIDE as u32, image::imageops::FilterType::CatmullRom);+ small.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect()+}++/// The file's sound as mono at `rate`; empty when it has none+pub fn sound(file: &Path, rate: u32) -> Result<Vec<f32>> {+ for b in raea_io_media::preferred() {+ let Ok(a) = b.decode_audio(file) else { continue };+ if a.channels.is_empty() || a.len() == 0 {+ continue;+ }+ let n = a.len();+ let k = a.channels.len() as f32;+ // the channels' average+ let mut mono = vec![0f32; n];+ for c in &a.channels {+ for (m, x) in mono.iter_mut().zip(c) {+ *m += x / k;+ }+ }+ let m = raea_io_media::soft_resample(&raea_io_media::Audio { rate: a.rate, channels: vec![mono] }, rate);+ return Ok(m.channels.into_iter().next().unwrap_or_default());+ }+ Ok(Vec::new())+}++/// RMS level in dBFS per 0.1 s (-100 for digital silence)+pub fn levels(pcm: &[f32], rate: u32) -> Vec<f32> {+ let step = (rate / 10).max(1) as usize;+ pcm.chunks(step).map(|c| (10.0 * (c.iter().map(|x| x * x).sum::<f32>() / c.len() as f32).max(1e-10).log10()).max(-100.0)).collect()+}++/// A spectrogram of mono sound for the sheet: `cols` frames of 512-sample FFTs spread over the sound, each folded to+/// `bins` bands (log-spaced from 50 Hz), in dB; [cols][bins]+pub fn spectrogram(pcm: &[f32], rate: u32, cols: usize, bins: usize) -> Vec<f32> {+ const N: usize = 512;+ let fft = rustfft::FftPlanner::<f32>::new().plan_fft_forward(N);+ let mut out = vec![-100f32; cols * bins];+ if pcm.len() < N || cols == 0 {+ return out;+ }+ let (lo, hi) = (50f32.ln(), (rate as f32 / 2.0).ln());+ for c in 0..cols {+ let at = (pcm.len() - N) * c / cols.max(2).saturating_sub(1).max(1);+ let mut buf: Vec<rustfft::num_complex::Complex<f32>> = (0..N)+ .map(|i| {+ let hann = 0.5 - 0.5 * (2.0 * std::f32::consts::PI * i as f32 / N as f32).cos();+ rustfft::num_complex::Complex::new(pcm[at + i] * hann, 0.0)+ })+ .collect();+ fft.process(&mut buf);+ let mut band = vec![0f32; bins];+ for (k, z) in buf.iter().take(N / 2).enumerate().skip(1) {+ let hz = k as f32 * rate as f32 / N as f32;+ let b = (((hz.ln() - lo) / (hi - lo)) * bins as f32).floor();+ if (0.0..bins as f32).contains(&b) {+ band[b as usize] += z.norm_sqr();+ }+ }+ for (b, e) in band.iter().enumerate() {+ out[c * bins + b] = 10.0 * (e + 1e-10).log10();+ }+ }+ out+}diff --git a/systems/columns/src/models.rs b/systems/columns/src/models.rsnew file mode 100644index 00000000..18eb1b83--- /dev/null+++ b/systems/columns/src/models.rs@@ -0,0 +1,108 @@+//! Where the encoders' files are, and their pins. SigLIP 2 and YAMNet are read from perception's models folder+//! ($RAEA_MODELS, else ~/.local/share/raea-models) when they're there; CLAP (and SigLIP 2 on a machine without+//! perception's copy) is fetched once from Hugging Face into raea's model cache (raea-sys-ml models.rs). YAMNet has+//! no public ONNX source, so its column is made only where perception installed it.++use anyhow::{Context, Result};+use raea_sys_ml::models::{Spec, ensure};+use std::path::{Path, PathBuf};++const CLAP: Spec = Spec {+ name: "clap-htsat-unfused",+ files: &[+ ("Xenova/clap-htsat-unfused", "onnx/audio_model_quantized.onnx", "audio_q8.onnx"),+ ("Xenova/clap-htsat-unfused", "onnx/text_model_quantized.onnx", "text_q8.onnx"),+ ("Xenova/clap-htsat-unfused", "tokenizer.json", "tokenizer.json"),+ ],+};++/// CLAP at full precision, the default: its ONNX Runtime outputs match transformers.js's at cosine 1.00000 (FP1a),+/// where the q8 export's (RAEA_CLAP_DTYPE=q8: 34 MB and 127 MB) differ by runtime build, worst 0.998+const CLAP_FP32: Spec = Spec {+ name: "clap-htsat-unfused-fp32",+ files: &[+ ("Xenova/clap-htsat-unfused", "onnx/audio_model.onnx", "audio.onnx"),+ ("Xenova/clap-htsat-unfused", "onnx/text_model.onnx", "text.onnx"),+ ("Xenova/clap-htsat-unfused", "tokenizer.json", "tokenizer.json"),+ ],+};++const SIGLIP: Spec = Spec {+ name: "siglip2-base-p16-224",+ files: &[+ ("onnx-community/siglip2-base-patch16-224-ONNX", "onnx/vision_model.onnx", "vision_model.onnx"),+ ("onnx-community/siglip2-base-patch16-224-ONNX", "onnx/text_model_fp16.onnx", "text_model_fp16.onnx"),+ ("onnx-community/siglip2-base-patch16-224-ONNX", "tokenizer.json", "tokenizer.json"),+ ],+};++/// The encoders' files on this machine+#[derive(Clone, Debug)]+pub struct Files {+ pub sig_vision: PathBuf,+ pub sig_text: PathBuf,+ pub sig_tokenizer: PathBuf,+ pub clap_audio: PathBuf,+ pub clap_text: PathBuf,+ pub clap_tokenizer: PathBuf,+ pub yam: Option<PathBuf>,+}++/// perception's models folder+pub fn perception_dir() -> PathBuf {+ crate::under("RAEA_MODELS", ".local/share/raea-models")+}++fn say(file: &str, n: u64) {+ // a line each 32 MB (the fetch reports every 64 KB)+ if n % (32 << 20) < (1 << 16) && n > (1 << 16) {+ eprintln!("fetching {file}: {} MB", n >> 20);+ }+}++/// Every encoder's files, fetching what's missing+pub fn locate() -> Result<Files> {+ let p = perception_dir();+ let local = p.join("siglip2-base-p16-224");+ let (sig_vision, sig_text, sig_tokenizer) = if local.join("onnx/vision_model.onnx").is_file() {+ (local.join("onnx/vision_model.onnx"), local.join("onnx/text_model_fp16.onnx"), local.join("tokenizer.json"))+ } else {+ let d = ensure(&SIGLIP, &mut say).context("SigLIP 2")?;+ (d.join("vision_model.onnx"), d.join("text_model_fp16.onnx"), d.join("tokenizer.json"))+ };+ let fp32 = !std::env::var("RAEA_CLAP_DTYPE").is_ok_and(|v| v == "q8");+ let c = ensure(if fp32 { &CLAP_FP32 } else { &CLAP }, &mut say).context("CLAP")?;+ let (audio, text) = if fp32 { ("audio.onnx", "text.onnx") } else { ("audio_q8.onnx", "text_q8.onnx") };+ let yam = Some(p.join("yamnet/yamnet.onnx")).filter(|f| f.is_file());+ Ok(Files { sig_vision, sig_text, sig_tokenizer, clap_audio: c.join(audio), clap_text: c.join(text), clap_tokenizer: c.join("tokenizer.json"), yam })+}++impl Files {+ pub fn pins(&self) -> Vec<(String, String)> {+ let mut out = vec![+ ("siglip2-base-p16-224/vision_model.onnx".to_string(), pin(&self.sig_vision)),+ (format!("clap-htsat-unfused/{}", self.clap_audio.file_name().unwrap_or_default().to_string_lossy()), pin(&self.clap_audio)),+ ];+ if let Some(y) = &self.yam {+ out.push(("yamnet/yamnet.onnx".to_string(), pin(y)));+ }+ out+ }+}++/// A model file's sha256, worked out once and kept beside raea's columns cache, keyed by its size and time+pub fn pin(file: &Path) -> String {+ let Ok(meta) = std::fs::metadata(file) else { return "missing".into() };+ let stamp = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0);+ let key = format!("{}:{}:{stamp}", file.display(), meta.len());+ let book = crate::cache::root().join("pins.json");+ let mut pins: serde_json::Map<String, serde_json::Value> = std::fs::read(&book).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();+ if let Some(h) = pins.get(&key).and_then(|v| v.as_str()) {+ return h.to_string();+ }+ let h = crate::media::sha256(file).unwrap_or_else(|_| "unreadable".into());+ pins.insert(key, h.clone().into());+ let _ = std::fs::create_dir_all(crate::cache::root());+ let _ = std::fs::write(&book, serde_json::to_vec_pretty(&pins).unwrap_or_default());+ h+}diff --git a/systems/columns/src/siglip.rs b/systems/columns/src/siglip.rsnew file mode 100644index 00000000..3d3b344a--- /dev/null+++ b/systems/columns/src/siglip.rs@@ -0,0 +1,91 @@+//! SigLIP 2 base p16-224 on ONNX Runtime (fp32, CPU): the image tower's pooled vector and patch tokens per frame, and+//! the text tower for picture axes' words. Pixels are scaled to [-1, 1] (mean 0.5, std 0.5), as its processor does.++use crate::media::{Rgb, SIDE};+use anyhow::{Context, Result, anyhow};+use ort::session::{Session, SessionInputValue};+use ort::value::Tensor;+use std::borrow::Cow;+use std::path::Path;++const BATCH: usize = 16;+/// SigLIP's text is padded to 64 tokens, lower case+const TEXT_LEN: usize = 64;++/// One input in, the named outputs out as flat f32+pub(crate) fn run(s: &mut Session, input: (&str, Vec<i64>, Input), outs: &[&str]) -> Result<Vec<Vec<f32>>> {+ let (name, shape, data) = input;+ let v: SessionInputValue = match data {+ Input::F32(d) => Tensor::from_array((shape, d))?.into_dyn().into(),+ Input::I64(d) => Tensor::from_array((shape, d))?.into_dyn().into(),+ };+ let out = s.run(vec![(Cow::Owned(name.to_string()), v)])?;+ outs.iter()+ .map(|o| {+ let (_, d) = out.get(*o).ok_or_else(|| anyhow!("output {o} missing"))?.try_extract_tensor::<f32>()?;+ Ok(d.to_vec())+ })+ .collect()+}++pub(crate) enum Input {+ F32(Vec<f32>),+ I64(Vec<i64>),+}++/// The image tower's session+pub struct Vision(pub(crate) Session);++fn pixels(frames: &[Rgb]) -> Vec<f32> {+ let plane = SIDE * SIDE;+ let mut x = vec![0f32; frames.len() * 3 * plane];+ for (n, f) in frames.iter().enumerate() {+ for i in 0..plane {+ for c in 0..3 {+ x[n * 3 * plane + c * plane + i] = f[i * 3 + c] as f32 / 127.5 - 1.0;+ }+ }+ }+ x+}++impl Vision {+ /// Each frame's pooled vector, L2-normalised: [frames][768]. (Its 196 patch tokens, "last_hidden_state", come+ /// with FP12's heatmaps.)+ pub fn embed(&mut self, frames: &[Rgb]) -> Result<Vec<f32>> {+ let mut v = Vec::new();+ for b in frames.chunks(BATCH) {+ let shape = vec![b.len() as i64, 3, SIDE as i64, SIDE as i64];+ v.extend(run(&mut self.0, ("pixel_values", shape, Input::F32(pixels(b))), &["pooler_output"])?.remove(0));+ }+ crate::normalise(&mut v, crate::SIG);+ Ok(v)+ }+}++pub struct Text {+ s: Session,+ tok: tokenizers::Tokenizer,+ pad: i64,+}++impl Text {+ pub fn load(file: &Path, tokenizer: &Path) -> Result<Text> {+ let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("SigLIP 2's tokenizer: {e}"))?;+ let pad = tok.token_to_id("<pad>").unwrap_or(0) as i64;+ Ok(Text { s: raea_sys_ml::session(file).context("SigLIP 2's text tower")?, tok, pad })+ }++ /// Each text's pooled vector, L2-normalised+ pub fn embed(&mut self, texts: &[String]) -> Result<Vec<f32>> {+ let mut v = Vec::new();+ for t in texts {+ let e = self.tok.encode(t.to_lowercase(), true).map_err(|e| anyhow!("tokenizing {t:?}: {e}"))?;+ let mut ids: Vec<i64> = e.get_ids().iter().map(|&i| i as i64).take(TEXT_LEN).collect();+ ids.resize(TEXT_LEN, self.pad);+ v.extend(run(&mut self.s, ("input_ids", vec![1, TEXT_LEN as i64], Input::I64(ids)), &["pooler_output"])?.remove(0));+ }+ crate::normalise(&mut v, crate::SIG);+ Ok(v)+ }+}diff --git a/systems/columns/src/tests.rs b/systems/columns/src/tests.rsnew file mode 100644index 00000000..e73b0a90--- /dev/null+++ b/systems/columns/src/tests.rs@@ -0,0 +1,110 @@+//! FP1a's parity bar: the Rust columns against the 11-12 spike's references (~/films/fingerprint-spike, or+//! $FP_SPIKE), at cosine 0.999 or better. The references are on Shane's machine, not in git (client footage), so+//! these tests are ignored by default: `cargo test -p raea-sys-columns -- --ignored`.++use super::*;+use std::path::PathBuf;++fn spike() -> PathBuf {+ std::env::var_os("FP_SPIKE").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap()).join("films/fingerprint-spike"))+}++fn cos(a: &[f32], b: &[f32]) -> f32 {+ let d: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();+ d / (a.iter().map(|x| x * x).sum::<f32>().sqrt() * b.iter().map(|x| x * x).sum::<f32>().sqrt()).max(1e-9)+}++fn f32s(p: &std::path::Path) -> Vec<f32> {+ std::fs::read(p).unwrap().as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()+}++fn reference(dtype: &str) -> Vec<serde_json::Value> {+ let text = std::fs::read_to_string(spike().join(format!("clap/vectors-{dtype}.jsonl"))).unwrap();+ text.lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect()+}++/// The spike's CLAP vectors to compare with: RAEA_CLAP_DTYPE's (fp32 unless q8)+fn dtype() -> String {+ std::env::var("RAEA_CLAP_DTYPE").unwrap_or_else(|_| "fp32".into())+}++fn vec_of(v: &serde_json::Value) -> Vec<f32> {+ v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect()+}++#[test]+#[ignore]+fn clap_audio_matches_the_spike() {+ let mut e = Encoders::load().unwrap();+ let items: Vec<serde_json::Value> = serde_json::from_slice(&std::fs::read(spike().join("clap/items.json")).unwrap()).unwrap();+ let refs = reference(&dtype());+ let by: std::collections::HashMap<String, Vec<f32>> = refs.iter().skip(1).map(|r| (r["id"].as_str().unwrap().to_string(), vec_of(&r["vec"]))).collect();+ let mut worst = (1.0f32, String::new());+ let mut sum = 0.0;+ // every 5th clip (all five conditions of each window keyed in turn): the dev build's FFT is slow+ for (n, it) in items.iter().enumerate().filter(|(i, _)| (i / 5) % 5 == 0) {+ if n % 100 == 0 {+ eprintln!("clip {n} of {}", items.len());+ }+ let id = format!("{}/{}", it["key"].as_str().unwrap(), it["cond"].as_str().unwrap());+ let pcm = f32s(std::path::Path::new(it["pcm"].as_str().unwrap()));+ let v = e.clap_clips(&[&pcm]).unwrap();+ let c = cos(&v, &by[&id]);+ sum += c;+ if c < worst.0 {+ worst = (c, id);+ }+ }+ let seen = items.len().div_ceil(25) * 5;+ eprintln!("CLAP audio, Rust against transformers.js ({}): {seen} clips, mean cosine {:.5}, worst {:.5} ({})", dtype(), sum / seen as f32, worst.0, worst.1);+ assert!(worst.0 >= 0.999);+}++#[test]+#[ignore]+fn clap_text_matches_the_spike() {+ let mut e = Encoders::load().unwrap();+ let t = &reference(&dtype())[0];+ let names: Vec<String> = t["names"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect();+ let texts: Vec<String> = names+ .iter()+ .map(|n| n.split(':').collect::<Vec<_>>())+ .map(|p| p.last().unwrap().to_string())+ .collect();+ // the spike's prompts: its axis words are in its script, so only the vocabulary's words are rebuilt here+ let vocab: Vec<(usize, String)> = names.iter().enumerate().filter(|(_, n)| n.starts_with("vocab:")).map(|(i, _)| (i, format!("This is a sound of {}.", texts[i]))).collect();+ // transformers.js embedded the spike's 46 prompts as one batch padded to its longest (the export takes no mask, so+ // the pads reach the tower): the same here shows the tower and tokenizer match; raea embeds each text unpadded+ let axis_prompts = ["hiss and static noise over everything", "a noisy recording full of white noise", "the sound suddenly cutting out to silence", "audio dropping out for a moment", "harsh clipped distorted audio", "loud crackling digital distortion"];+ let tok = tokenizers::Tokenizer::from_file(models::locate().unwrap().clap_tokenizer).unwrap();+ let longest = axis_prompts.iter().map(|w| format!("This is a sound of {w}.")).chain(vocab.iter().map(|(_, s)| s.clone())).map(|s| tok.encode(s, true).unwrap().get_ids().len()).max().unwrap();+ let v = e.words_sound_padded(&vocab.iter().map(|(_, s)| s.clone()).collect::<Vec<_>>(), longest).unwrap();+ let worst = vocab.iter().enumerate().map(|(k, (i, _))| cos(&v[k * CLAP..(k + 1) * CLAP], &vec_of(&t["vecs"][*i]))).fold(1.0f32, f32::min);+ eprintln!("CLAP text, Rust against transformers.js ({}): {} descriptions, worst cosine {worst:.5}", dtype(), vocab.len());+ assert!(worst >= 0.999);+}++#[test]+#[ignore]+fn siglip_matches_onnx_fp32() {+ let mut e = Encoders::load().unwrap();+ let raw = std::fs::read(spike().join("ref/siglip_frames.u8")).unwrap();+ let frames: Vec<media::Rgb> = raw.chunks(media::SIDE * media::SIDE * 3).map(|c| c.to_vec()).collect();+ let mut want = f32s(&spike().join("ref/siglip_pooled.f32"));+ normalise(&mut want, SIG);+ let got = e.vision.embed(&frames).unwrap();+ let worst = (0..frames.len()).map(|i| cos(&got[i * SIG..(i + 1) * SIG], &want[i * SIG..(i + 1) * SIG])).fold(1.0f32, f32::min);+ eprintln!("SigLIP 2, Rust ort against Python onnxruntime (fp32, the same pixels): {} frames, worst cosine {worst:.6}", frames.len());+ assert!(worst >= 0.999);+}++#[test]+fn clap_bank_is_slaney() {+ let b = clap::bank();+ // every band has weight, and the bank is normalised so each band's area is about the same+ for m in 0..64 {+ assert!(b[m * 513..(m + 1) * 513].iter().any(|x| *x > 0.0), "band {m} empty");+ }+ let p = clap::padded(&[1.0; 96_000]);+ assert_eq!((p[383_999], p[384_000]), (1.0, 0.0), "four repeats of 2 s, then zeros (repeatpad)");+}diff --git a/systems/columns/src/window.rs b/systems/columns/src/window.rsnew file mode 100644index 00000000..6b7955ac--- /dev/null+++ b/systems/columns/src/window.rs@@ -0,0 +1,104 @@+//! A span's features from a file's columns, as the heads read them. Each axis reads its own modality only (FP0b: a+//! head given two modalities learns worse from a few labels):+//!+//! - picture: the frames' mean SigLIP vector, then the change (below): 771 values+//! - change: the frame-to-frame SigLIP distance's mean and largest step, and the vectors' spread: 3+//! - look: the frames' mean look and its largest frame-to-frame step per value: 32+//! - sound: the mean of the CLAP windows that start in the span (the nearest one when none does): 512+//! - events: YAMNet's mean over the span: 1024++use crate::look::LOOK;+use crate::{CLAP, CLAP_HOP, Columns, FPS, SIG, YAM, YAM_HOP};+use serde::{Deserialize, Serialize};++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]+#[serde(rename_all = "lowercase")]+pub enum Modality {+ Picture,+ Change,+ Look,+ Sound,+ Events,+}++impl Modality {+ pub const ALL: [Modality; 5] = [Modality::Picture, Modality::Change, Modality::Look, Modality::Sound, Modality::Events];+ pub fn dim(self) -> usize {+ match self {+ Modality::Picture => SIG + 3,+ Modality::Change => 3,+ Modality::Look => 2 * LOOK,+ Modality::Sound => CLAP,+ Modality::Events => YAM,+ }+ }+ pub fn name(self) -> &'static str {+ match self {+ Modality::Picture => "picture",+ Modality::Change => "change",+ Modality::Look => "look",+ Modality::Sound => "sound",+ Modality::Events => "events",+ }+ }+}++fn rows(v: &[f32], dim: usize, a: usize, b: usize) -> &[f32] {+ let n = v.len() / dim;+ if n == 0 {+ return &[];+ }+ let a = a.min(n - 1);+ let b = b.clamp(a + 1, n);+ &v[a * dim..b * dim]+}++/// The mean row of rows `dim` wide+pub fn mean(r: &[f32], dim: usize) -> Vec<f32> {+ let n = (r.len() / dim).max(1) as f32;+ let mut m = vec![0f32; dim];+ for row in r.chunks(dim) {+ m.iter_mut().zip(row).for_each(|(a, b)| *a += b / n);+ }+ m+}++fn change(s: &[f32]) -> [f32; 3] {+ let n = s.len() / SIG;+ if n < 2 {+ return [0.0; 3];+ }+ let d: Vec<f32> = (1..n).map(|i| s[i * SIG..(i + 1) * SIG].iter().zip(&s[(i - 1) * SIG..i * SIG]).map(|(a, b)| (a - b).powi(2)).sum::<f32>().sqrt()).collect();+ let m = mean(s, SIG);+ let spread = (0..SIG).map(|k| ((0..n).map(|i| (s[i * SIG + k] - m[k]).powi(2)).sum::<f32>() / n as f32).sqrt()).sum::<f32>() / SIG as f32;+ [d.iter().sum::<f32>() / d.len() as f32, d.iter().cloned().fold(0.0, f32::max), spread]+}++/// The span [a, b) seconds of `c` in modality `m`: m.dim() values (zeros where the column is missing)+pub fn features(c: &Columns, a: f64, b: f64, m: Modality) -> Vec<f32> {+ let (fa, fb) = ((a * FPS).floor() as usize, (b * FPS).ceil() as usize);+ let v = match m {+ Modality::Picture => {+ let s = rows(&c.sig, SIG, fa, fb);+ let mut v = mean(s, SIG);+ v.extend(change(s));+ v+ }+ Modality::Change => change(rows(&c.sig, SIG, fa, fb)).to_vec(),+ Modality::Look => {+ let l = rows(&c.look, LOOK, fa, fb);+ let mut v = mean(l, LOOK);+ let n = l.len() / LOOK;+ v.extend((0..LOOK).map(|k| (1..n).map(|i| (l[i * LOOK + k] - l[(i - 1) * LOOK + k]).abs()).fold(0.0, f32::max)));+ v+ }+ Modality::Sound => {+ let n = c.clap_windows();+ let first = ((a / CLAP_HOP).ceil() as usize).min(n.saturating_sub(1));+ let last = (((b - crate::CLAP_WIN) / CLAP_HOP).floor().max(first as f64) as usize + 1).min(n);+ mean(rows(&c.clap, CLAP, first, last), CLAP)+ }+ Modality::Events => mean(rows(&c.yam, YAM, (a / YAM_HOP) as usize, (b / YAM_HOP).ceil() as usize), YAM),+ };+ if v.len() == m.dim() { v } else { vec![0.0; m.dim()] }+}diff --git a/systems/columns/src/yamnet.rs b/systems/columns/src/yamnet.rsnew file mode 100644index 00000000..3d27ad05--- /dev/null+++ b/systems/columns/src/yamnet.rs@@ -0,0 +1,23 @@+//! YAMNet (Apache-2.0, AudioSet's 521 classes) on ONNX Runtime: its 1024-d embedding per 0.96 s patch every 0.48 s of+//! 16 kHz mono, the front end inside the graph. Perception's ONNX copy only (models.rs).++use crate::siglip::{Input, run};+use anyhow::Result;+use ort::session::Session;++/// The shortest waveform the graph takes (one patch)+const MIN: usize = 15_600;++/// YAMNet's session+pub struct Yamnet(pub(crate) Session);++impl Yamnet {+ /// [patches][1024]; a waveform under one patch is padded with silence+ pub fn embed(&mut self, pcm16: &[f32]) -> Result<Vec<f32>> {+ let mut w = pcm16.to_vec();+ if w.len() < MIN {+ w.resize(MIN, 0.0);+ }+ Ok(run(&mut self.0, ("waveform", vec![w.len() as i64], Input::F32(w)), &["embeddings"])?.remove(0))+ }+}diff --git a/systems/fingerprint/Cargo.toml b/systems/fingerprint/Cargo.tomlnew file mode 100644index 00000000..a96f1522--- /dev/null+++ b/systems/fingerprint/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-sys-fingerprint"+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"++[dependencies]+# the columns every head reads, the encoders that make them, and the damage the bootstrap puts in+raea-sys-columns = { path = "../columns" }+# evidence rows and word vectors are kept as fp16+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.rsnew file mode 100644index 00000000..5b3917a7--- /dev/null+++ b/systems/fingerprint/src/evidence.rs@@ -0,0 +1,137 @@+//! The evidence ledger (FP2c): one row per label, in evidence.jsonl, with the window's features for every modality in+//! evidence.f16 at the row's offset (about 4.7 KB a row). A row is a label on one axis, or with axis "*" a label on+//! every axis (an approval, or a clean window beside its damaged copies). Rows are the only thing a team shares+//! (FP8); heads are always retrained from them.++use anyhow::Result;+use half::f16;+use raea_sys_columns::window::Modality;+use serde::{Deserialize, Serialize};+use std::io::Write;+use std::path::Path;++/// Every modality's features, in Modality::ALL's order+pub fn width() -> usize {+ Modality::ALL.iter().map(|m| m.dim()).sum()+}++/// Where a modality's features sit in a row's vector+pub fn slice(m: Modality) -> std::ops::Range<usize> {+ let mut at = 0;+ for x in Modality::ALL {+ if x == m {+ return at..at + x.dim();+ }+ at += x.dim();+ }+ 0..0+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Row {+ /// the media's sha256 and the span, seconds+ pub media: String,+ pub a: f64,+ pub b: f64,+ /// the axis, or "*" for every axis+ pub axis: String,+ /// true: the axis's defect is there; false: it isn't+ pub bad: bool,+ #[serde(default = "one")]+ pub weight: f32,+ pub who: String,+ /// damage, cheat, teach, note, approval, pair, postmortem, eye:<name>+ pub source: String,+ /// what held-out scores hold out by (a project, or a source file in a bootstrap)+ pub project: String,+ /// the damage or cheat kind, for a bootstrap's rows+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub kind: Option<String>,+ /// a mark's box in 0-1 frame coordinates (FP11)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub region: Option<[f32; 4]>,+ /// the person's own words, when the label came with some+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub words: Option<String>,+ /// the row's index in evidence.f16+ pub at: u64,+}++fn one() -> f32 {+ 1.0+}++#[derive(Default)]+pub struct Ledger {+ pub rows: Vec<Row>,+ pub feats: Vec<f32>,+}++impl Ledger {+ pub fn features(&self, i: usize) -> &[f32] {+ let w = width();+ let at = self.rows[i].at as usize * w;+ &self.feats[at..at + w]+ }++ pub fn modality(&self, i: usize, m: Modality) -> &[f32] {+ &self.features(i)[slice(m)]+ }++ /// A new row with its features+ pub fn push(&mut self, mut r: Row, feats: &[f32]) {+ assert_eq!(feats.len(), width(), "a row carries every modality");+ r.at = (self.feats.len() / width()) as u64;+ self.feats.extend_from_slice(feats);+ self.rows.push(r);+ }++ pub fn read(dir: &Path) -> Result<Ledger> {+ let (j, f) = (dir.join("evidence.jsonl"), dir.join("evidence.f16"));+ if !j.is_file() {+ return Ok(Ledger::default());+ }+ let rows = std::fs::read_to_string(j)?.lines().filter(|l| !l.trim().is_empty()).map(serde_json::from_str).collect::<Result<Vec<Row>, _>>()?;+ let raw = std::fs::read(f).unwrap_or_default();+ let feats = raw.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect();+ Ok(Ledger { rows, feats })+ }++ pub fn write(&self, dir: &Path) -> Result<()> {+ std::fs::create_dir_all(dir)?;+ let mut j = Vec::new();+ for r in &self.rows {+ serde_json::to_writer(&mut j, r)?;+ j.push(b'\n');+ }+ std::fs::write(dir.join("evidence.jsonl"), j)?;+ let mut f = std::io::BufWriter::new(std::fs::File::create(dir.join("evidence.f16"))?);+ for x in &self.feats {+ f.write_all(&f16::from_f32(*x).to_le_bytes())?;+ }+ Ok(())+ }++ /// Only the rows `keep` says, their features moved up to match+ pub fn retain(&mut self, keep: impl Fn(&Row) -> bool) {+ let w = width();+ let old = std::mem::take(self);+ for r in old.rows.iter().filter(|r| keep(r)) {+ let at = r.at as usize * w;+ self.push(r.clone(), &old.feats[at..at + w]);+ }+ }++ /// Rows for training `axis`: its own labels (not cheats), and "*" rows that say it's clean+ pub 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))+ }).collect()+ }+}++/// A window's features for a row, every modality, from a file's columns+pub fn features(c: &raea_sys_columns::Columns, a: f64, b: f64) -> Vec<f32> {+ Modality::ALL.iter().flat_map(|m| raea_sys_columns::window::features(c, a, b, *m)).collect()+}diff --git a/systems/fingerprint/src/folder.rs b/systems/fingerprint/src/folder.rsnew file mode 100644index 00000000..789316d2--- /dev/null+++ b/systems/fingerprint/src/folder.rs@@ -0,0 +1,247 @@+//! A fingerprint's folder (FP2a): ~/.raea/fingerprints/NAME/ (a person's) or PROJECT/.raea/fingerprints/NAME/ (a+//! project's or team's), holding+//!+//! - fingerprint.ts: the axes, as `export default fingerprint({...})` from "raea/brief"; the person edits it+//! - fingerprint.json: what fingerprint.ts last evaluated to, so a host without a TS evaluator can still read it+//! - words.json and words.f16: the axes' words as vectors, and the background vocabulary (FP2e)+//! - heads.safetensors: each learned head's weights and scaler, its report in the metadata, the encoder pins+//! - evidence.jsonl and evidence.f16: the rows (evidence.rs)+//! - report.json: every head's held-out score, labels by source, cheats, gate state and limits (FP2d)++use crate::evidence::Ledger;+use crate::head::{Logistic, Scaler};+use crate::taxonomy::{Fingerprint, to_ts};+use crate::train::Trained;+use crate::words::Words;+use anyhow::{Context, Result, anyhow, bail};+use half::f16;+use raea_sys_columns::window::Modality;+use raea_sys_columns::{CLAP, SIG};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)+pub type Eval = fn(&Path) -> Result<String, String>;++/// Where a person's fingerprints live: $RAEA_FINGERPRINTS, else ~/.raea/fingerprints+pub fn root() -> PathBuf {+ match std::env::var_os("RAEA_FINGERPRINTS") {+ Some(p) => p.into(),+ None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(".raea/fingerprints"),+ }+}++pub struct Folder {+ pub dir: PathBuf,+}++/// words.json: what words.f16 holds, in order+#[derive(Serialize, Deserialize)]+struct WordsHead {+ axes: Vec<(String, Modality)>,+ sound_vocab: usize,+ picture_vocab: usize,+ made_from: Vec<String>,+ /// the vocabulary's words in order, so a reader (the feed's fingerprint map) can name what a direction points at+ #[serde(default)]+ sound_words: Vec<String>,+ #[serde(default)]+ picture_words: Vec<String>,+}++fn f16s(v: &[f32]) -> Vec<u8> {+ v.iter().flat_map(|x| f16::from_f32(*x).to_le_bytes()).collect()+}++fn f32s_of_f16(b: &[u8]) -> Vec<f32> {+ b.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect()+}++impl Folder {+ /// A person's fingerprint by name, or a folder given as a path+ pub fn named(name: &str) -> Folder {+ let p = Path::new(name);+ Folder { dir: if p.is_absolute() || name.contains('/') { p.to_path_buf() } else { root().join(name) } }+ }++ pub fn exists(&self) -> bool {+ self.dir.join("fingerprint.ts").is_file()+ }++ pub fn ts(&self) -> PathBuf {+ self.dir.join("fingerprint.ts")+ }++ /// A new fingerprint's folder: its fingerprint.ts; refused when one is there already+ pub fn create(&self, f: &Fingerprint) -> Result<()> {+ if self.exists() {+ bail!("{} has a fingerprint already", self.dir.display());+ }+ std::fs::create_dir_all(&self.dir)?;+ std::fs::write(self.ts(), to_ts(f))?;+ std::fs::write(self.dir.join("fingerprint.json"), serde_json::to_vec_pretty(f)?)?;+ Ok(())+ }++ /// The fingerprint as fingerprint.ts says, through `eval`; without one, as fingerprint.ts last evaluated+ pub fn read(&self, eval: Option<Eval>) -> Result<Fingerprint> {+ if !self.exists() {+ bail!("no fingerprint at {} (`raea fingerprint new NAME` makes one)", self.dir.display());+ }+ let json = match eval {+ Some(e) => e(&self.ts()).map_err(|e| anyhow!("{e}"))?,+ None => std::fs::read_to_string(self.dir.join("fingerprint.json")).context("fingerprint.json")?,+ };+ let f: Fingerprint = serde_json::from_str(&json).with_context(|| format!("{}: not a fingerprint", self.ts().display()))?;+ if eval.is_some() {+ std::fs::write(self.dir.join("fingerprint.json"), serde_json::to_vec_pretty(&f)?)?;+ }+ Ok(f)+ }++ /// fingerprint.ts rewritten from the fingerprint (after its encoders are pinned)+ pub fn rewrite(&self, f: &Fingerprint) -> Result<()> {+ std::fs::write(self.ts(), to_ts(f))?;+ std::fs::write(self.dir.join("fingerprint.json"), serde_json::to_vec_pretty(f)?)?;+ Ok(())+ }++ pub fn words(&self) -> Option<Words> {+ let head: WordsHead = serde_json::from_slice(&std::fs::read(self.dir.join("words.json")).ok()?).ok()?;+ let v = f32s_of_f16(&std::fs::read(self.dir.join("words.f16")).ok()?);+ let mut at = 0;+ let mut take = |n: usize| -> Option<Vec<f32>> {+ let r = v.get(at..at + n)?.to_vec();+ at += n;+ Some(r)+ };+ let mut axes = Vec::new();+ for (name, sp) in head.axes {+ let dim = if sp == Modality::Sound { CLAP } else { SIG };+ axes.push((name, sp, take(dim)?));+ }+ let sound_vocab = (0..head.sound_vocab).map(|_| take(CLAP)).collect::<Option<Vec<_>>>()?;+ let picture_vocab = (0..head.picture_vocab).map(|_| take(SIG)).collect::<Option<Vec<_>>>()?;+ Some(Words { axes, sound_vocab, picture_vocab, made_from: head.made_from })+ }++ pub fn write_words(&self, w: &Words) -> Result<()> {+ let head = WordsHead {+ axes: w.axes.iter().map(|(n, sp, _)| (n.clone(), *sp)).collect(),+ sound_vocab: w.sound_vocab.len(),+ picture_vocab: w.picture_vocab.len(),+ made_from: w.made_from.clone(),+ sound_words: crate::taxonomy::SOUND_VOCAB.iter().take(w.sound_vocab.len()).map(|s| s.to_string()).collect(),+ picture_words: crate::taxonomy::PICTURE_VOCAB.iter().take(w.picture_vocab.len()).map(|s| s.to_string()).collect(),+ };+ let v: Vec<f32> = w.axes.iter().map(|a| &a.2).chain(&w.sound_vocab).chain(&w.picture_vocab).flatten().copied().collect();+ std::fs::write(self.dir.join("words.json"), serde_json::to_vec_pretty(&head)?)?;+ std::fs::write(self.dir.join("words.f16"), f16s(&v))?;+ Ok(())+ }++ pub fn ledger(&self) -> Result<Ledger> {+ Ledger::read(&self.dir)+ }++ pub fn write_ledger(&self, l: &Ledger) -> Result<()> {+ l.write(&self.dir)+ }++ /// The trained heads and the encoders they were trained on; None before the first training+ pub fn trained(&self) -> Result<Option<(Trained, BTreeMap<String, String>)>> {+ let p = self.dir.join("heads.safetensors");+ if !p.is_file() {+ return Ok(None);+ }+ let (meta, tensors) = read_safetensors(&p)?;+ let mut t: Trained = serde_json::from_str(meta.get("trained").map(String::as_str).unwrap_or("{}"))?;+ let pins: BTreeMap<String, String> = serde_json::from_str(meta.get("encoders").map(String::as_str).unwrap_or("{}"))?;+ let head = |k: &str| -> Option<Logistic> {+ let get = |part: &str| tensors.get(&format!("{k}/{part}")).cloned();+ Some(Logistic { scaler: Scaler { mean: get("mean")?, std: get("std")? }, w: get("w")?, b: *get("b")?.first()? })+ };+ for h in &mut t.heads {+ h.head = head(&h.axis);+ }+ t.weighting = head("*weighting");+ Ok(Some((t, pins)))+ }++ pub fn write_trained(&self, t: &Trained, pins: &BTreeMap<String, String>) -> Result<()> {+ fn put<'a>(tensors: &mut Vec<(String, &'a [f32])>, k: &str, l: &'a Logistic) {+ let b = std::slice::from_ref(&l.b);+ for (part, v) in [("mean", &l.scaler.mean[..]), ("std", &l.scaler.std[..]), ("w", &l.w[..]), ("b", b)] {+ tensors.push((format!("{k}/{part}"), v));+ }+ }+ let mut tensors: Vec<(String, &[f32])> = Vec::new();+ for h in &t.heads {+ if let Some(l) = &h.head {+ put(&mut tensors, &h.axis, l);+ }+ }+ if let Some(l) = &t.weighting {+ put(&mut tensors, "*weighting", l);+ }+ let meta = BTreeMap::from([("trained".to_string(), serde_json::to_string(t)?), ("encoders".to_string(), serde_json::to_string(pins)?)]);+ write_safetensors(&self.dir.join("heads.safetensors"), &meta, &tensors)+ }++ pub fn write_report(&self, report: &serde_json::Value) -> Result<()> {+ std::fs::write(self.dir.join("report.json"), serde_json::to_vec_pretty(report)?)?;+ Ok(())+ }++ pub fn report(&self) -> Option<serde_json::Value> {+ serde_json::from_slice(&std::fs::read(self.dir.join("report.json")).ok()?).ok()+ }+}++/// safetensors: an 8-byte little-endian header length, the JSON header (padded with spaces to 8 bytes), then the data+fn write_safetensors(p: &Path, meta: &BTreeMap<String, String>, tensors: &[(String, &[f32])]) -> Result<()> {+ let mut head = serde_json::Map::new();+ head.insert("__metadata__".into(), serde_json::to_value(meta)?);+ let mut at = 0usize;+ for (k, v) in tensors {+ let end = at + 4 * v.len();+ head.insert(k.clone(), serde_json::json!({"dtype": "F32", "shape": [v.len()], "data_offsets": [at, end]}));+ at = end;+ }+ let mut h = serde_json::to_vec(&head)?;+ while h.len() % 8 != 0 {+ h.push(b' ');+ }+ let mut out = (h.len() as u64).to_le_bytes().to_vec();+ out.extend(h);+ for (_, v) in tensors {+ out.extend(v.iter().flat_map(|x| x.to_le_bytes()));+ }+ let tmp = p.with_extension("part");+ std::fs::write(&tmp, out)?;+ std::fs::rename(tmp, p)?;+ Ok(())+}++type Tensors = BTreeMap<String, Vec<f32>>;++fn read_safetensors(p: &Path) -> Result<(BTreeMap<String, String>, Tensors)> {+ let b = std::fs::read(p)?;+ let n = u64::from_le_bytes(b.get(..8).ok_or_else(|| anyhow!("{}: too short", p.display()))?.try_into()?) as usize;+ let head: serde_json::Map<String, serde_json::Value> = serde_json::from_slice(b.get(8..8 + n).ok_or_else(|| anyhow!("{}: header past the end", p.display()))?)?;+ let data = &b[8 + n..];+ let mut meta = BTreeMap::new();+ let mut tensors = BTreeMap::new();+ for (k, v) in head {+ if k == "__metadata__" {+ meta = serde_json::from_value(v)?;+ continue;+ }+ let o = v["data_offsets"].as_array().ok_or_else(|| anyhow!("{k}: no offsets"))?;+ let (a, e) = (o[0].as_u64().unwrap_or(0) as usize, o[1].as_u64().unwrap_or(0) as usize);+ let raw = data.get(a..e).ok_or_else(|| anyhow!("{k}: data past the end"))?;+ tensors.insert(k, raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect());+ }+ Ok((meta, tensors))+}diff --git a/systems/fingerprint/src/head.rs b/systems/fingerprint/src/head.rsnew file mode 100644index 00000000..2fde4498--- /dev/null+++ b/systems/fingerprint/src/head.rs@@ -0,0 +1,202 @@+//! A head (FP2c): logistic regression on one modality's standardised features, L2-regularised (C = 0.5) with balanced+//! class weights, fit by L-BFGS in milliseconds on the CPU; Bradley-Terry for pairs is the same fit on the pair's+//! difference with no intercept. Also the measures every report uses: AUC and the band thresholds.++use serde::{Deserialize, Serialize};++/// Feature statistics: the encoder's own, from unlabelled windows of the person's work (FP0b: unscaled, SigLIP hid+/// behind YAMNet's larger values)+#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Scaler {+ pub mean: Vec<f32>,+ pub std: Vec<f32>,+}++impl Scaler {+ pub fn fit(rows: &[&[f32]]) -> Scaler {+ let d = rows.first().map_or(0, |r| r.len());+ let n = rows.len().max(1) as f64;+ let mut mean = vec![0f64; d];+ let mut sq = vec![0f64; d];+ for r in rows {+ for (k, &x) in r.iter().enumerate() {+ mean[k] += x as f64 / n;+ sq[k] += (x as f64).powi(2) / n;+ }+ }+ let std = (0..d).map(|k| ((sq[k] - mean[k].powi(2)).max(0.0).sqrt() as f32).max(1e-6)).collect();+ Scaler { mean: mean.into_iter().map(|m| m as f32).collect(), std }+ }+ pub fn apply(&self, x: &[f32]) -> Vec<f64> {+ x.iter().zip(&self.mean).zip(&self.std).map(|((x, m), s)| ((x - m) / s) as f64).collect()+ }+}++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Logistic {+ pub scaler: Scaler,+ pub w: Vec<f32>,+ pub b: f32,+}++impl Logistic {+ /// The decision value (log-odds) for raw features+ pub fn score(&self, x: &[f32]) -> f32 {+ let z = self.scaler.apply(x);+ (z.iter().zip(&self.w).map(|(a, b)| a * *b as f64).sum::<f64>() + self.b as f64) as f32+ }++ /// Fit on raw rows (`y` true for the defect), with the given scaler; C as scikit-learn's+ pub fn fit(scaler: Scaler, x: &[&[f32]], y: &[bool], weights: Option<&[f32]>, c: f64, intercept: bool) -> Logistic {+ let z: Vec<Vec<f64>> = x.iter().map(|r| scaler.apply(r)).collect();+ let (pos, neg) = (y.iter().filter(|v| **v).count().max(1) as f64, y.iter().filter(|v| !**v).count().max(1) as f64);+ let n = y.len() as f64;+ // balanced: each class weighs n / (2 * its count), times the row's own weight+ let cw: Vec<f64> = y.iter().enumerate().map(|(i, &v)| (if v { n / (2.0 * pos) } else { n / (2.0 * neg) }) * weights.map_or(1.0, |w| w[i] as f64)).collect();+ let d = z.first().map_or(0, |r| r.len());+ let f = |p: &[f64], g: &mut [f64]| -> f64 {+ g.iter_mut().for_each(|v| *v = 0.0);+ let (w, b) = (&p[..d], if intercept { p[d] } else { 0.0 });+ let mut loss = 0.0;+ for (i, r) in z.iter().enumerate() {+ let s = r.iter().zip(w).map(|(a, b)| a * b).sum::<f64>() + b;+ let t = if y[i] { 1.0 } else { -1.0 };+ let m = t * s;+ loss += cw[i] * if m > 0.0 { (-m).exp().ln_1p() } else { -m + m.exp().ln_1p() };+ let dl = -cw[i] * t / (1.0 + m.exp());+ for k in 0..d {+ g[k] += dl * r[k];+ }+ if intercept {+ g[d] += dl;+ }+ }+ // the penalty: |w|^2 / 2, the data term times C (scikit-learn's form)+ for k in 0..d {+ g[k] = c * g[k] + w[k];+ }+ if intercept {+ g[d] *= c;+ }+ c * loss + 0.5 * w.iter().map(|v| v * v).sum::<f64>()+ };+ let p = lbfgs(vec![0.0; d + usize::from(intercept)], f, 300);+ Logistic { scaler, w: p[..d].iter().map(|v| *v as f32).collect(), b: if intercept { p[d] as f32 } else { 0.0 } }+ }+}++/// Limited-memory BFGS (10 pairs) with a backtracking line search+fn lbfgs(mut x: Vec<f64>, f: impl Fn(&[f64], &mut [f64]) -> f64, iters: usize) -> Vec<f64> {+ let n = x.len();+ let mut g = vec![0.0; n];+ let mut fx = f(&x, &mut g);+ let (mut s_hist, mut y_hist): (Vec<Vec<f64>>, Vec<Vec<f64>>) = (vec![], vec![]);+ let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| x * y).sum::<f64>();+ for _ in 0..iters {+ let gn = dot(&g, &g).sqrt();+ if gn < 1e-6 * (1.0 + fx.abs()) {+ break;+ }+ // two-loop recursion+ let mut q = g.clone();+ let mut alpha = vec![0.0; s_hist.len()];+ for i in (0..s_hist.len()).rev() {+ let rho = 1.0 / dot(&y_hist[i], &s_hist[i]);+ alpha[i] = rho * dot(&s_hist[i], &q);+ q.iter_mut().zip(&y_hist[i]).for_each(|(a, b)| *a -= alpha[i] * b);+ }+ if let (Some(s), Some(y)) = (s_hist.last(), y_hist.last()) {+ let gamma = dot(s, y) / dot(y, y);+ q.iter_mut().for_each(|v| *v *= gamma);+ } else {+ q.iter_mut().for_each(|v| *v /= gn.max(1.0));+ }+ for i in 0..s_hist.len() {+ let rho = 1.0 / dot(&y_hist[i], &s_hist[i]);+ let beta = rho * dot(&y_hist[i], &q);+ q.iter_mut().zip(&s_hist[i]).for_each(|(a, b)| *a += (alpha[i] - beta) * b);+ }+ let dir: Vec<f64> = q.iter().map(|v| -v).collect();+ let slope = dot(&g, &dir);+ if slope >= 0.0 {+ s_hist.clear();+ y_hist.clear();+ continue;+ }+ let mut step = 1.0;+ let mut g2 = vec![0.0; n];+ let mut x2;+ let mut f2;+ loop {+ x2 = x.iter().zip(&dir).map(|(a, b)| a + step * b).collect::<Vec<_>>();+ f2 = f(&x2, &mut g2);+ if f2 <= fx + 1e-4 * step * slope || step < 1e-10 {+ break;+ }+ step *= 0.5;+ }+ let s: Vec<f64> = x2.iter().zip(&x).map(|(a, b)| a - b).collect();+ let yv: Vec<f64> = g2.iter().zip(&g).map(|(a, b)| a - b).collect();+ if dot(&s, &yv) > 1e-12 {+ s_hist.push(s);+ y_hist.push(yv);+ if s_hist.len() > 10 {+ s_hist.remove(0);+ y_hist.remove(0);+ }+ }+ let done = (fx - f2).abs() < 1e-9 * (1.0 + fx.abs());+ x = x2;+ g = g2;+ fx = f2;+ if done {+ break;+ }+ }+ x+}++/// Area under the ROC curve: the chance a random defect scores above a random clean one (ties count half)+pub fn auc(pos: &[f32], neg: &[f32]) -> f64 {+ if pos.is_empty() || neg.is_empty() {+ return f64::NAN;+ }+ let mut all: Vec<(f32, bool)> = pos.iter().map(|&s| (s, true)).chain(neg.iter().map(|&s| (s, false))).collect();+ all.sort_by(|a, b| a.0.total_cmp(&b.0));+ let (mut rank_sum, mut i) = (0.0, 0);+ while i < all.len() {+ let mut j = i;+ while j < all.len() && all[j].0 == all[i].0 {+ j += 1;+ }+ let r = (i + j + 1) as f64 / 2.0;+ rank_sum += r * all[i..j].iter().filter(|x| x.1).count() as f64;+ i = j;+ }+ let (p, n) = (pos.len() as f64, neg.len() as f64);+ (rank_sum - p * (p + 1.0) / 2.0) / (p * n)+}++/// The score above which `q` of the clean scores fall (the threshold that flags 1 - q of clean work)+pub fn quantile(v: &[f32], q: f64) -> f32 {+ let mut s = v.to_vec();+ s.sort_by(f32::total_cmp);+ if s.is_empty() {+ return f32::INFINITY;+ }+ let x = q * (s.len() - 1) as f64;+ let (lo, hi) = (x.floor() as usize, x.ceil() as usize);+ s[lo] + (s[hi] - s[lo]) * (x - lo as f64) as f32+}++/// The lowest threshold at which a flag is right `precision` of the time on held-out scores (earshot's bands: strong+/// 0.9, plausible 0.7); None when no threshold reaches it+pub fn band(pos: &[f32], neg: &[f32], precision: f64) -> Option<f32> {+ let mut cands: Vec<f32> = pos.to_vec();+ cands.sort_by(f32::total_cmp);+ cands.into_iter().find(|&t| {+ let tp = pos.iter().filter(|s| **s >= t).count() as f64;+ let fp = neg.iter().filter(|s| **s >= t).count() as f64;+ tp >= 3.0 && tp / (tp + fp) >= precision+ })+}diff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rsnew file mode 100644index 00000000..496716f6--- /dev/null+++ b/systems/fingerprint/src/lib.rs@@ -0,0 +1,112 @@+//! 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.+//!+//! - taxonomy.rs: the axes and raea's base taxonomy (FP2b)+//! - folder.rs: the fingerprint's folder (FP2a)+//! - evidence.rs: the rows (FP2c)+//! - head.rs, train.rs: the heads, held-out scores, bands, cheats and the gate (FP2c, FP2d)+//! - words.rs: word heads from day one (FP2e)+//! - score.rs, sheet.rs: scoring a piece, its summary, timeline and sheet (FP3a, FP3c)++pub mod evidence;+pub mod folder;+pub mod head;+pub mod score;+pub mod sheet;+pub mod taxonomy;+pub mod train;+pub mod words;++use anyhow::Result;+use evidence::Ledger;+use folder::Folder;+use serde_json::json;+use std::collections::BTreeMap;+use taxonomy::Fingerprint;+use train::{GATE_AUC, GATE_CHEAT, GATE_LABELS, GATE_PROJECTS, Trained};+use words::Words;++/// What no head here can judge, whatever its evidence (earshot's LIMITS.md)+pub const LIMITS: [&str; 5] = [+ "whether the piece works as a whole, or for its audience: heads judge 2 s moments",+ "story, pace across shots and the cut's rhythm: no axis reads more than a window",+ "where in the frame a defect is, until marks teach patch heads (FP12)",+ "whether a stylised look or a held shot was meant: a word head reads it as the defect",+ "taste axes with only words: always advice, never a gate",+];++/// Every head retrained from the ledger, written with the report; the bootstrap's measures are kept from the last+/// report unless a new bootstrap gives its own+pub fn retrain(dir: &Folder, fp: &Fingerprint, w: &Words, l: &Ledger, bootstrap: Option<serde_json::Value>) -> Result<Trained> {+ let t = train::train(fp, l, w);+ dir.write_trained(&t, &fp.encoders)?;+ let kept = bootstrap.or_else(|| dir.report().and_then(|r| r.get("bootstrap").cloned()));+ dir.write_report(&report(fp, &t, l, kept))?;+ Ok(t)+}++/// report.json (FP2d): every head's held-out score, labels by source, cheat catch rates, gate state and limits+pub fn report(fp: &Fingerprint, t: &Trained, l: &Ledger, bootstrap: Option<serde_json::Value>) -> serde_json::Value {+ let mut by_source: BTreeMap<&str, usize> = BTreeMap::new();+ for r in &l.rows {+ *by_source.entry(r.source.as_str()).or_default() += 1;+ }+ let made = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ json!({+ "fingerprint": fp.name,+ "who": fp.who,+ "made_unix": made,+ "encoders": fp.encoders,+ "gate": {"labels_each": GATE_LABELS, "projects": GATE_PROJECTS, "held_out_auc": GATE_AUC, "cheat_caught": GATE_CHEAT},+ "evidence": {"rows": l.rows.len(), "by_source": by_source},+ "heads": t.heads,+ "gating": t.heads.iter().filter(|h| h.state == "gating").map(|h| h.axis.as_str()).collect::<Vec<_>>(),+ "weighting": t.weighting.is_some(),+ "bootstrap": bootstrap,+ "cannot_judge": LIMITS,+ })+}++/// report.json read back as lines for a person: each head's state, score, labels and cheats+pub fn report_text(r: &serde_json::Value) -> String {+ let mut out = format!("fingerprint {}: {} evidence rows\n", r["fingerprint"].as_str().unwrap_or("?"), r["evidence"]["rows"]);+ let f = |v: &serde_json::Value| v.as_f64().map_or("-".to_string(), |x| format!("{x:.2}"));+ for h in r["heads"].as_array().into_iter().flatten() {+ let labels: usize = h["labels"].as_object().map_or(0, |m| m.values().filter_map(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).sum::<u64>() as usize).sum());+ let cheats: Vec<String> = h["cheats"].as_object().map_or(Vec::new(), |m| m.iter().map(|(k, v)| format!("{k} {}", f(v))).collect());+ out += &format!(+ " {:16} {:7} held out {:>4} words {:>4} labels {:>5} {}{}\n",+ h["axis"].as_str().unwrap_or(""),+ h["state"].as_str().unwrap_or(""),+ f(&h["held_out"]),+ f(&h["words"]),+ labels,+ if cheats.is_empty() { String::new() } else { format!("cheats: {}; ", cheats.join(", ")) },+ h["why"].as_str().unwrap_or("")+ );+ }+ if let Some(b) = r["bootstrap"].as_object() {+ out += "bootstrap, held out by source (AUC at k = 4 / 16 / 32, FP0b's k = 32):\n";+ for c in b.get("curves").and_then(|c| c.as_array()).into_iter().flatten() {+ let k = |n: &str| f(&c["k"][n]);+ let holds = match c["holds"].as_bool() {+ Some(true) => "holds",+ Some(false) => "BELOW",+ None => "",+ };+ out += &format!(" {:8} {:8} {} / {} / {} {} {holds}\n", c["axis"].as_str().unwrap_or(""), c["modality"].as_str().unwrap_or(""), k("4"), k("16"), k("32"), f(&c["fp0b"]));+ }+ for w in b.get("words").and_then(|c| c.as_array()).into_iter().flatten() {+ out += &format!(" words {:8} AUC {} caught {} cheats {}\n", w["axis"].as_str().unwrap_or(""), f(&w["auc"]), f(&w["caught"]), w["cheats"]);+ }+ }+ out += "can't judge:\n";+ for l in r["cannot_judge"].as_array().into_iter().flatten() {+ out += &format!(" {}\n", l.as_str().unwrap_or(""));+ }+ out+}++#[cfg(test)]+mod tests;diff --git a/systems/fingerprint/src/score.rs b/systems/fingerprint/src/score.rsnew file mode 100644index 00000000..da5ba716--- /dev/null+++ b/systems/fingerprint/src/score.rs@@ -0,0 +1,210 @@+//! Scoring a piece (FP3a): every axis per 2 s window every 1 s, from the file's columns. An axis reads its learned+//! head once that beats its word head on held-out evidence, else its words (always advice). A window is flagged on an+//! 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_columns::Columns;+use raea_sys_columns::window::Modality;+use serde::Serialize;++pub const WIN: f64 = 2.0;+pub const HOP: f64 = 1.0;+/// A word head's flag before any clean evidence has set one: a z this far over the vocabulary+pub const WORD_FLAG: f32 = 2.5;++#[derive(Clone, Debug, Serialize)]+pub struct AxisScore {+ pub axis: String,+ pub value: f32,+ /// "head" or "words"+ pub by: &'static str,+ /// gating, advice or words+ pub state: String,+ /// strong, plausible or weak, for a learned head+ #[serde(skip_serializing_if = "Option::is_none")]+ pub band: Option<&'static str>,+ pub flagged: bool,+ pub gating: bool,+}++#[derive(Clone, Debug, Serialize)]+pub struct Window {+ pub a: f64,+ pub b: f64,+ pub axes: Vec<AxisScore>,+ /// the nearest of the vocabulary's descriptions: what is seen and heard+ pub seen: Option<&'static str>,+ pub heard: Option<&'static str>,+ /// the sound's mean level, dBFS+ pub level: f32,+ /// the person's weighting over the axes, once they've taught enough+ #[serde(skip_serializing_if = "Option::is_none")]+ pub overall: Option<f32>,+}++#[derive(Clone, Debug, Serialize)]+pub struct Moment {+ pub a: f64,+ pub b: f64,+ pub axis: String,+ /// the axis in the person's words (its first)+ pub words: String,+ pub by: &'static str,+ pub state: String,+ pub band: Option<&'static str>,+ pub gating: bool,+ pub peak: f32,+}++#[derive(Clone, Debug, Serialize)]+pub struct Scored {+ pub file: String,+ pub media: String,+ pub dur: f64,+ pub fingerprint: String,+ pub moments: Vec<Moment>,+ pub windows: Vec<Window>,+}++fn rank(b: Option<&str>) -> u8 {+ match b {+ Some("strong") => 3,+ Some("plausible") => 2,+ Some(_) => 1,+ None => 0,+ }+}++/// One axis on one window's features+fn one(h: Option<&AxisHead>, words: Option<&Words>, axis: &str, m: Modality, row: &[f32]) -> Option<AxisScore> {+ let learned = h.and_then(|h| h.head.as_ref().map(|f| (h, f))).filter(|(h, _)| match (h.held_out, h.words) {+ (Some(a), Some(w)) => a >= w,+ (None, Some(_)) => false,+ _ => true,+ });+ if let Some((h, f)) = learned {+ let v = f.score(&row[slice(m)]);+ let band = if h.strong.is_some_and(|t| v >= t) {+ "strong"+ } else if h.plausible.is_some_and(|t| v >= t) {+ "plausible"+ } else {+ "weak"+ };+ let flagged = h.flag.is_some_and(|t| v > t);+ let gating = flagged && h.state == "gating" && band == "strong";+ return Some(AxisScore { axis: axis.into(), value: v, by: "head", state: h.state.clone(), band: Some(band), flagged, gating });+ }+ let z = words?.z(axis, row)?;+ let flagged = z > h.and_then(|h| h.word_flag).unwrap_or(WORD_FLAG);+ Some(AxisScore { axis: axis.into(), value: z, by: "words", state: "words".into(), band: None, flagged, gating: false })+}++pub fn score(fp: &Fingerprint, words: Option<&Words>, trained: Option<&Trained>, c: &Columns, file: &str) -> Scored {+ let mut windows = Vec::new();+ let mut a = 0.0;+ loop {+ let b = (a + WIN).min(c.dur.max(0.25));+ let row = features(c, a, b);+ let head = |name: &str| trained.and_then(|t| t.heads.iter().find(|h| h.axis == name));+ let axes: Vec<AxisScore> = fp.axes.iter().filter_map(|ax| one(head(&ax.name), words, &ax.name, ax.modality, &row)).collect();+ let (l0, l1) = ((a * 10.0) as usize, ((b * 10.0) as usize).max((a * 10.0) as usize + 1));+ let lv = c.level.get(l0.min(c.level.len())..l1.min(c.level.len())).unwrap_or(&[]);+ let level = if lv.is_empty() { -100.0 } else { lv.iter().sum::<f32>() / lv.len() as f32 };+ let overall = trained.and_then(|t| t.weighting.as_ref().map(|w| w.score(&scores(&t.heads, &row))));+ windows.push(Window {+ a,+ b,+ axes,+ seen: words.and_then(|w| w.nearest(&row, Modality::Picture)),+ heard: words.and_then(|w| w.nearest(&row, Modality::Sound)),+ level,+ overall,+ });+ if a + HOP + WIN > c.dur + 1e-6 {+ break;+ }+ a += HOP;+ }+ let mut moments: Vec<Moment> = Vec::new();+ for ax in &fp.axes {+ let mut open: Option<Moment> = None;+ for w in &windows {+ match (w.axes.iter().find(|s| s.axis == ax.name && s.flagged), open.as_mut()) {+ (Some(s), Some(m)) if w.a <= m.b => {+ m.b = w.b;+ m.peak = m.peak.max(s.value);+ m.gating |= s.gating;+ if rank(s.band) > rank(m.band) {+ m.band = s.band;+ }+ }+ (Some(s), _) => {+ moments.extend(open.take());+ let words = ax.words.first().cloned().unwrap_or_default();+ open = Some(Moment { a: w.a, b: w.b, axis: ax.name.clone(), words, by: s.by, state: s.state.clone(), band: s.band, gating: s.gating, peak: s.value });+ }+ (None, _) => {}+ }+ }+ moments.extend(open);+ }+ moments.sort_by(|x, y| (y.gating, rank(y.band)).cmp(&(x.gating, rank(x.band))).then(x.a.total_cmp(&y.a)));+ Scored { file: file.into(), media: c.media.clone(), dur: c.dur, fingerprint: fp.name.clone(), moments, windows }+}++/// m:ss+pub fn clock(t: f64) -> String {+ let s = t.max(0.0).round() as u64;+ format!("{}:{:02}", s / 60, s % 60)+}++fn label(m: &Moment) -> String {+ match (m.gating, m.band) {+ (true, _) => "gating".into(),+ (false, Some(b)) => format!("{b}, {}", m.state),+ (false, None) => "words, advice".into(),+ }+}++/// The summary first: the moments the fingerprint expects a note on, gating ones first+pub fn summary(s: &Scored) -> String {+ let gating = s.moments.iter().filter(|m| m.gating).count();+ let mut out = format!(+ "{} ({}), fingerprint {}: {} moment{} to look at, {gating} gating\n",+ s.file,+ clock(s.dur),+ s.fingerprint,+ s.moments.len(),+ if s.moments.len() == 1 { "" } else { "s" }+ );+ for m in &s.moments {+ out += &format!(" {}-{} {}: \"{}\" ({})\n", clock(m.a), clock(m.b), m.axis, m.words, label(m));+ }+ if s.moments.is_empty() {+ out += " nothing flagged\n";+ }+ out+}++/// Second by second in words: what is seen, what is heard, which axes flag (earshot's timeline)+pub fn timeline(s: &Scored) -> String {+ let mut out = String::new();+ for w in &s.windows {+ let flags: Vec<String> = w.axes.iter().filter(|x| x.flagged).map(|x| format!("{} ({})", x.axis, if x.gating { "gating" } else { x.band.unwrap_or("words") })).collect();+ out += &format!(+ "{}-{} seen: {} · heard: {} · {:.0} dB{}\n",+ clock(w.a),+ clock(w.b),+ w.seen.unwrap_or("?"),+ w.heard.unwrap_or("?"),+ w.level,+ if flags.is_empty() { String::new() } else { format!(" · flags: {}", flags.join(", ")) }+ );+ }+ out+}diff --git a/systems/fingerprint/src/sheet.rs b/systems/fingerprint/src/sheet.rsnew file mode 100644index 00000000..13402271--- /dev/null+++ b/systems/fingerprint/src/sheet.rs@@ -0,0 +1,166 @@+//! The sheet (FP3c, earshot's `sheet`): the whole piece in one PNG an agent or a person can read at a glance. Frames+//! along the top (a red frame where a moment is flagged), a lane per axis (grey for advice, amber plausible, red+//! strong, a white edge for gating), the sound's level, its spectrogram with flagged sound moments boxed, and the+//! checks' findings as ticks. Patch heatmaps on the frames come with FP12.++use crate::score::{Scored, clock};+use anyhow::Result;+use image::{Rgb, RgbImage};+use raea_sys_columns::media::{Rgb as Frame, SIDE};+use raea_sys_columns::window::Modality;++const W: u32 = 1600;+const LEFT: u32 = 150;+const LANE: u32 = 14;+const THUMBS: u32 = 12;+const SPEC: u32 = 120;++/// 5 x 7 glyphs, a row a byte (low 5 bits, left bit first)+const FONT: [(char, [u8; 7]); 44] = [+ ('A', [14, 17, 17, 31, 17, 17, 17]), ('B', [30, 17, 17, 30, 17, 17, 30]), ('C', [14, 17, 16, 16, 16, 17, 14]),+ ('D', [30, 17, 17, 17, 17, 17, 30]), ('E', [31, 16, 16, 30, 16, 16, 31]), ('F', [31, 16, 16, 30, 16, 16, 16]),+ ('G', [14, 17, 16, 23, 17, 17, 15]), ('H', [17, 17, 17, 31, 17, 17, 17]), ('I', [14, 4, 4, 4, 4, 4, 14]),+ ('J', [7, 2, 2, 2, 2, 18, 12]), ('K', [17, 18, 20, 24, 20, 18, 17]), ('L', [16, 16, 16, 16, 16, 16, 31]),+ ('M', [17, 27, 21, 21, 17, 17, 17]), ('N', [17, 17, 25, 21, 19, 17, 17]), ('O', [14, 17, 17, 17, 17, 17, 14]),+ ('P', [30, 17, 17, 30, 16, 16, 16]), ('Q', [14, 17, 17, 17, 21, 18, 13]), ('R', [30, 17, 17, 30, 20, 18, 17]),+ ('S', [15, 16, 16, 14, 1, 1, 30]), ('T', [31, 4, 4, 4, 4, 4, 4]), ('U', [17, 17, 17, 17, 17, 17, 14]),+ ('V', [17, 17, 17, 17, 17, 10, 4]), ('W', [17, 17, 17, 21, 21, 21, 10]), ('X', [17, 17, 10, 4, 10, 17, 17]),+ ('Y', [17, 17, 10, 4, 4, 4, 4]), ('Z', [31, 1, 2, 4, 8, 16, 31]), ('0', [14, 17, 19, 21, 25, 17, 14]),+ ('1', [4, 12, 4, 4, 4, 4, 14]), ('2', [14, 17, 1, 2, 4, 8, 31]), ('3', [31, 2, 4, 2, 1, 17, 14]),+ ('4', [2, 6, 10, 18, 31, 2, 2]), ('5', [31, 16, 30, 1, 1, 17, 14]), ('6', [6, 8, 16, 30, 17, 17, 14]),+ ('7', [31, 1, 2, 4, 8, 8, 8]), ('8', [14, 17, 17, 14, 17, 17, 14]), ('9', [14, 17, 17, 15, 1, 2, 12]),+ (':', [0, 12, 12, 0, 12, 12, 0]), ('.', [0, 0, 0, 0, 0, 12, 12]), ('-', [0, 0, 0, 31, 0, 0, 0]),+ ('/', [1, 1, 2, 4, 8, 16, 16]), ('(', [2, 4, 8, 8, 8, 4, 2]), (')', [8, 4, 2, 2, 2, 4, 8]),+ (',', [0, 0, 0, 0, 12, 4, 8]), ('%', [24, 25, 2, 4, 8, 19, 3]),+];++const INK: Rgb<u8> = Rgb([225, 225, 225]);+const DIM: Rgb<u8> = Rgb([70, 70, 74]);+const RED: Rgb<u8> = Rgb([230, 60, 50]);+const AMBER: Rgb<u8> = Rgb([235, 160, 40]);+const ADVICE: Rgb<u8> = Rgb([120, 120, 130]);++fn text(img: &mut RgbImage, x: u32, y: u32, s: &str, c: Rgb<u8>) {+ for (n, ch) in s.to_uppercase().chars().enumerate() {+ let Some((_, g)) = FONT.iter().find(|(k, _)| *k == ch) else { continue };+ for (r, bits) in g.iter().enumerate() {+ for b in 0..5 {+ let (px, py) = (x + n as u32 * 6 + b, y + r as u32);+ if bits >> (4 - b) & 1 == 1 && px < img.width() && py < img.height() {+ img.put_pixel(px, py, c);+ }+ }+ }+ }+}++fn fill(img: &mut RgbImage, x0: u32, y0: u32, w: u32, h: u32, c: Rgb<u8>) {+ for y in y0..(y0 + h).min(img.height()) {+ for x in x0..(x0 + w).min(img.width()) {+ img.put_pixel(x, y, c);+ }+ }+}++fn outline(img: &mut RgbImage, x0: u32, y0: u32, w: u32, h: u32, c: Rgb<u8>) {+ fill(img, x0, y0, w, 1, c);+ fill(img, x0, y0 + h.saturating_sub(1), w, 1, c);+ fill(img, x0, y0, 1, h, c);+ fill(img, x0 + w.saturating_sub(1), y0, 1, h, c);+}++/// A check's finding drawn as a tick: where, and what+pub struct Tick {+ pub a: f64,+ pub b: f64,+ pub what: String,+}++/// The sheet for a scored piece: `frames` are THUMBS frames spread over it (224 x 224 RGB), `pcm16` its sound+pub fn sheet(s: &Scored, frames: &[Frame], pcm16: &[f32], ticks: &[Tick], modality: &dyn Fn(&str) -> Option<Modality>, out: &std::path::Path) -> Result<()> {+ let axes: Vec<&str> = s.windows.first().map(|w| w.axes.iter().map(|a| a.axis.as_str()).collect()).unwrap_or_default();+ let span = W - LEFT - 10;+ let thumb = span / THUMBS;+ let h = 30 + thumb + 20 + axes.len() as u32 * LANE + 10 + 40 + 10 + SPEC + 10 + 16 + ticks.len().min(12) as u32 * 10 + 20;+ let mut img = RgbImage::from_pixel(W, h, Rgb([18, 18, 20]));+ let x_at = |t: f64| LEFT + ((t / s.dur.max(1e-6)) * span as f64).clamp(0.0, span as f64) as u32;+ text(&mut img, 10, 10, &format!("{} ({}), fingerprint {}: {} moments", s.file.rsplit('/').next().unwrap_or(""), clock(s.dur), s.fingerprint, s.moments.len()), INK);+ // frames+ let mut y = 30;+ for (i, f) in frames.iter().take(THUMBS as usize).enumerate() {+ let x0 = LEFT + i as u32 * thumb;+ for ty in 0..thumb - 2 {+ for tx in 0..thumb - 2 {+ let (sx, sy) = (tx as usize * SIDE / (thumb - 2) as usize, ty as usize * SIDE / (thumb - 2) as usize);+ let p = (sy * SIDE + sx) * 3;+ img.put_pixel(x0 + tx, y + ty, Rgb([f[p], f[p + 1], f[p + 2]]));+ }+ }+ let t = s.dur * (i as f64 + 0.5) / THUMBS as f64;+ if s.moments.iter().any(|m| m.a <= t && t <= m.b && modality(&m.axis).is_some_and(|m| !matches!(m, Modality::Sound | Modality::Events))) {+ outline(&mut img, x0, y, thumb - 2, thumb - 2, RED);+ }+ }+ y += thumb + 4;+ for k in 0..=10 {+ let t = s.dur * k as f64 / 10.0;+ fill(&mut img, x_at(t), y, 1, 4, DIM);+ text(&mut img, x_at(t).saturating_sub(10).max(LEFT), y + 6, &clock(t), DIM);+ }+ y += 20;+ // lanes+ for name in &axes {+ text(&mut img, 10, y + 3, name, INK);+ fill(&mut img, LEFT, y + 1, span, LANE - 2, Rgb([30, 30, 34]));+ for w in &s.windows {+ let Some(a) = w.axes.iter().find(|a| a.axis == *name).filter(|a| a.flagged) else { continue };+ let c = match (a.state.as_str(), a.band) {+ ("gating", Some("strong")) => RED,+ (_, Some("strong")) | (_, Some("plausible")) => AMBER,+ _ => ADVICE,+ };+ let (x0, x1) = (x_at(w.a + 0.5), x_at(w.b - 0.5).max(x_at(w.a + 0.5) + 1));+ fill(&mut img, x0, y + 1, x1 - x0, LANE - 2, c);+ if a.gating {+ outline(&mut img, x0, y + 1, x1 - x0, LANE - 2, INK);+ }+ }+ y += LANE;+ }+ // level+ y += 10;+ text(&mut img, 10, y + 16, "LEVEL", INK);+ for w in &s.windows {+ let v = ((w.level + 60.0) / 60.0).clamp(0.0, 1.0);+ let bar = (v * 38.0) as u32;+ let (x0, x1) = (x_at(w.a + 0.5), x_at(w.b - 0.5).max(x_at(w.a + 0.5) + 1));+ fill(&mut img, x0, y + 40 - bar, x1 - x0, bar, Rgb([80, 150, 220]));+ }+ y += 50;+ // spectrogram, with flagged sound moments boxed+ text(&mut img, 10, y + SPEC / 2, "SPECTRUM", INK);+ let spec = raea_sys_columns::media::spectrogram(pcm16, 16_000, span as usize, SPEC as usize);+ for c in 0..span as usize {+ for b in 0..SPEC as usize {+ let v = ((spec[c * SPEC as usize + b] + 90.0) / 80.0).clamp(0.0, 1.0);+ img.put_pixel(LEFT + c as u32, y + SPEC - 1 - b as u32, Rgb([(255.0 * v.powf(0.8)) as u8, (200.0 * v.powi(2)) as u8, (120.0 * v.powi(4) + 30.0 * v) as u8]));+ }+ }+ for m in s.moments.iter().filter(|m| modality(&m.axis).is_some_and(|m| matches!(m, Modality::Sound | Modality::Events))) {+ let (x0, x1) = (x_at(m.a), x_at(m.b));+ outline(&mut img, x0, y, (x1 - x0).max(2), SPEC, if m.gating { RED } else { AMBER });+ }+ y += SPEC + 10;+ // checks+ text(&mut img, 10, y, "CHECKS", INK);+ if ticks.is_empty() {+ text(&mut img, LEFT, y, "no findings", DIM);+ }+ for (i, t) in ticks.iter().take(12).enumerate() {+ let (x0, x1) = (x_at(t.a), x_at(t.b).max(x_at(t.a) + 2));+ fill(&mut img, x0, y, x1 - x0, 6, RED);+ text(&mut img, (x1 + 4).min(W - 300), y + 8 + i as u32 * 10, &format!("{} {}", clock(t.a), t.what), INK);+ }+ img.save(out)?;+ Ok(())+}diff --git a/systems/fingerprint/src/taxonomy.rs b/systems/fingerprint/src/taxonomy.rsnew file mode 100644index 00000000..9b51ea3b--- /dev/null+++ b/systems/fingerprint/src/taxonomy.rs@@ -0,0 +1,147 @@+//! The taxonomy (FP2b): a fingerprint's axes, each with the words people use for it, the modality its head reads,+//! its scope, polarity and the check it maps to. It's written in fingerprint.ts (`fingerprint({...})` from+//! "raea/brief", sdk/raea/src/fingerprint.ts) and read here as the JSON its default export evaluates to. raea's base+//! taxonomy is drawn from Shane's notes (docs/fingerprint.md): glitch and continuity, sound, pace, camera, cut, light+//! and look, realism and detail, design and type. Creative directions are never axes.++use raea_sys_columns::window::Modality;+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Axis {+ pub name: String,+ /// what people say for it, best first; the word head (FP2e) reads these+ pub words: Vec<String>,+ pub modality: Modality,+ /// moment, shot or whole+ #[serde(default = "moment")]+ pub scope: String,+ /// "bad": a high score is the defect (most axes); "good": a high score is the quality+ #[serde(default = "bad")]+ pub polarity: String,+ /// the `raea check` rule that measures it exactly, when one does; the check wins over the head (FP4c)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub check: Option<String>,+ /// false where words can't find it (silence matches no description: FP0g)+ #[serde(default = "yes")]+ pub word_head: bool,+ /// the group in the base taxonomy+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub group: String,+}++fn moment() -> String {+ "moment".into()+}+fn bad() -> String {+ "bad".into()+}+fn yes() -> bool {+ true+}++#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Fingerprint {+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub who: Option<String>,+ /// one line: what it tracks and when it judges (docs/fingerprint.feature FP14a)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub about: Option<String>,+ /// the fingerprint it builds on, by name: it started from that one's axes+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub extends: Option<String>,+ /// which pieces it judges when a project or workspace holds more than one (FP14c)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub applies: Option<Applies>,+ pub axes: Vec<Axis>,+ /// each encoder's id and its file's sha256 (FP2a): heads trained on other encoders' columns are refused+ #[serde(default)]+ pub encoders: std::collections::BTreeMap<String, String>,+}++/// The kinds of piece (film, ad, game, playable, still, sound) and the project tags a fingerprint is for+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]+pub struct Applies {+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub kinds: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub tags: Vec<String>,+}++impl Fingerprint {+ pub fn axis(&self, name: &str) -> Option<&Axis> {+ let i = self.axes.iter().position(|a| a.name == name)?;+ self.axes.get(i)+ }+}++fn ax(group: &str, name: &str, m: Modality, words: &[&str], check: Option<&str>, word_head: bool) -> Axis {+ Axis {+ name: name.into(),+ words: words.iter().map(|w| w.to_string()).collect(),+ modality: m,+ scope: "moment".into(),+ polarity: "bad".into(),+ check: check.map(str::to_string),+ word_head,+ group: group.into(),+ }+}++/// raea's base taxonomy: the mechanical axes damage can bootstrap (FP4a), then taste axes that start from words+pub fn base(name: &str) -> Fingerprint {+ use Modality::*;+ let axes = vec![+ ax("light and look", "blur", Picture, &["a blurry, soft, low resolution picture", "an out of focus smeared image"], None, true),+ ax("light and look", "dark", Picture, &["a very dark, underexposed picture", "a murky image where nothing can be seen"], None, true),+ ax("light and look", "glow", Look, &["a hazy glow over everything", "a washed out picture with heavy bloom"], None, true),+ ax("glitch and continuity", "flash", Change, &["a single black frame flashing"], Some("flash-frame"), false),+ ax("pace", "freeze", Change, &["a frozen picture where nothing moves"], Some("frozen"), false),+ ax("sound", "noise", Sound, &["hiss and static noise over everything", "a noisy recording full of white noise"], None, true),+ ax("sound", "dropout", Sound, &["the sound suddenly cutting out to silence"], Some("dropout"), false),+ ax("sound", "clip", Sound, &["harsh clipped distorted audio", "loud crackling digital distortion"], Some("clipping"), true),+ ax("sound", "muffled voice", Sound, &["a muffled, distant voice that is hard to understand"], None, true),+ ax("sound", "harsh music", Sound, &["harsh, shrill music that hurts to listen to"], None, true),+ ax("glitch and continuity", "glitch", Picture, &["a rendering glitch with broken, torn geometry", "corrupted video with blocky artifacts"], None, true),+ ax("realism and detail", "fake", Picture, &["a fake, plastic looking computer generated scene", "a cheap video game render"], None, true),+ ax("realism and detail", "barren", Picture, &["an empty, barren scene with nothing in it", "a bare grey room with no detail"], None, true),+ ax("design and type", "unreadable text", Picture, &["small, cluttered text that is hard to read"], None, true),+ ax("camera", "shaky camera", Change, &["a shaky handheld camera"], None, false),+ ];+ Fingerprint { name: name.into(), who: None, about: None, extends: None, applies: None, axes, encoders: Default::default() }+}++/// The background vocabularies a word head is calibrated against (earshot's method: an axis's similarity as a z+/// against ordinary descriptions), sound and picture+pub const SOUND_VOCAB: [&str; 40] = [+ "a man talking", "a woman talking", "people chatting", "a crowd cheering", "calm electronic music", "a piano",+ "an acoustic guitar", "drums", "an orchestra", "a pop song", "hip hop beats", "ambient synth pads", "birds singing", "wind",+ "rain", "ocean waves", "a car passing", "footsteps", "a door closing", "typing on a keyboard", "a mouse click", "a phone ringing",+ "a dog barking", "water running", "a city street", "a quiet room", "an engine humming", "a whoosh", "a cinematic impact",+ "a bell", "laughter", "applause", "a fire crackling", "a sci-fi beep", "a swelling string section", "a bass drop",+ "a clean studio recording", "a voiceover", "a kitchen", "an airplane",+];++pub const PICTURE_VOCAB: [&str; 40] = [+ "a person talking to the camera", "a city street at night", "a forest", "an ocean", "a mountain landscape", "an office",+ "a kitchen", "a living room", "a car on a road", "a product on a table", "a phone screen", "a computer screen with an app",+ "a logo on a plain background", "text on a coloured background", "a crowd of people", "a close up of a face", "hands typing",+ "a dog", "a cat", "food on a plate", "a stage with lights", "a sunset sky", "clouds", "a cathedral interior", "a hallway",+ "a beach", "a desert", "snow", "a 3D animated character", "an illustration", "a chart", "a map", "a bedroom", "a garden",+ "a corridor with doors", "a painting", "a sports game", "a concert", "a train", "a bright clean studio shot",+];++/// The sentence a word or description is embedded as: CLAP was trained on captions of this form (perception H5)+pub fn prompt(m: Modality, words: &str) -> String {+ match m {+ Modality::Sound | Modality::Events => format!("This is a sound of {words}."),+ _ => format!("a photo of {words}"),+ }+}++/// fingerprint.ts for a fingerprint: what a person edits to add, remove or reword axes+pub fn to_ts(f: &Fingerprint) -> String {+ let body = serde_json::to_string_pretty(f).unwrap_or_default();+ format!("// A fingerprint: your sense of good work, as axes (docs/fingerprint.md). Add an axis, reword one, or remove one;\n// the next `raea fingerprint` command embeds the new words and retrains. `raea fingerprint report` says what each head has learned and what it can't judge.\nimport {{ fingerprint }} from \"raea/brief\";\n\nexport default fingerprint({body});\n")+}diff --git a/systems/fingerprint/src/tests.rs b/systems/fingerprint/src/tests.rsnew file mode 100644index 00000000..124ca1f8--- /dev/null+++ b/systems/fingerprint/src/tests.rs@@ -0,0 +1,133 @@+//! The crate's own checks, on small made-up rows: a head learns a separable axis and the AUC says so, the folder+//! keeps heads and words through a round trip, a ledger keeps its rows' features when it drops some, a moment is a+//! run of flagged windows, and a gate is earned only with labels from enough projects.++use crate::evidence::{Ledger, Row, width};+use crate::folder::Folder;+use crate::head::{Logistic, Scaler, auc, band, quantile};+use crate::taxonomy::base;+use crate::train::train;+use crate::words::Words;+use raea_sys_columns::window::Modality;++fn row(axis: &str, bad: bool, project: &str) -> Row {+ Row {+ media: "m".into(),+ a: 0.0,+ b: 2.0,+ axis: axis.into(),+ bad,+ weight: 1.0,+ who: "t".into(),+ source: "damage".into(),+ project: project.into(),+ kind: None,+ region: None,+ words: None,+ at: 0,+ }+}++/// A row's features: every value noise from a hash of (value, row), and the picture's first value `x`. (A plain+/// modular pattern won't do: it carries the row's parity, which is the label here.)+fn feats(x: f32, seed: usize) -> Vec<f32> {+ let hash = |i: usize| {+ let mut z = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (seed as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z ^= z >> 31;+ z = z.wrapping_mul(0x94D0_49BB_1331_11EB);+ ((z >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 0.1+ };+ let mut v: Vec<f32> = (0..width()).map(hash).collect();+ // the signal spread over the first 20 values, as an embedding spreads a quality+ v.iter_mut().take(20).for_each(|f| *f += 0.1 * x);+ v+}++#[test]+fn a_head_learns_a_separable_axis() {+ let x: Vec<Vec<f32>> = (0..40).map(|i| vec![if i < 20 { 1.0 } else { -1.0 }, (i % 7) as f32 * 0.01]).collect();+ let y: Vec<bool> = (0..40).map(|i| i < 20).collect();+ let xr: Vec<&[f32]> = x.iter().map(|v| v.as_slice()).collect();+ let h = Logistic::fit(Scaler::fit(&xr), &xr, &y, None, 0.5, true);+ let (p, n): (Vec<f32>, Vec<f32>) = (x[..20].iter().map(|v| h.score(v)).collect(), x[20..].iter().map(|v| h.score(v)).collect());+ assert_eq!(auc(&p, &n), 1.0);+ assert!(h.score(&[1.0, 0.0]) > 0.0 && h.score(&[-1.0, 0.0]) < 0.0);+ assert_eq!(auc(&[0.0], &[0.0]), 0.5);+ assert_eq!(quantile(&[1.0, 2.0, 3.0, 4.0, 5.0], 0.5), 3.0);+ assert!(band(&p, &n, 0.9).is_some());+}++#[test]+fn a_ledger_keeps_features_when_it_drops_rows() {+ let mut l = Ledger::default();+ for i in 0..4 {+ l.push(row("blur", i % 2 == 0, "p"), &feats(i as f32, i));+ }+ l.retain(|r| r.bad);+ assert_eq!(l.rows.len(), 2);+ assert_eq!((l.rows[0].at, l.rows[1].at), (0, 1));+ assert_eq!(l.features(1), feats(2.0, 2).as_slice(), "the third row's features moved up with it");+}++#[test]+fn the_folder_keeps_heads_words_and_evidence() {+ let dir = Folder { dir: std::env::temp_dir().join(format!("raea-fp-test-{}", std::process::id())) };+ let _ = std::fs::remove_dir_all(&dir.dir);+ let fp = base("t");+ dir.create(&fp).unwrap();+ assert!(dir.create(&fp).is_err(), "a second create is refused");+ let mut l = Ledger::default();+ for i in 0..60 {+ let p = format!("p{}", (i / 2) % 4);+ l.push(row(if i % 2 == 0 { "blur" } else { "*" }, i % 2 == 0, &p), &feats(if i % 2 == 0 { 1.0 } else { -1.0 }, i));+ }+ dir.write_ledger(&l).unwrap();+ let back = dir.ledger().unwrap();+ assert_eq!(back.rows.len(), 60);+ let w = Words { axes: vec![("noise".into(), Modality::Sound, vec![0.5; raea_sys_columns::CLAP])], sound_vocab: vec![vec![0.1; raea_sys_columns::CLAP]; 3], picture_vocab: vec![vec![0.2; raea_sys_columns::SIG]; 2], made_from: vec!["k".into()] };+ dir.write_words(&w).unwrap();+ let w2 = dir.words().unwrap();+ assert_eq!((w2.axes.len(), w2.sound_vocab.len(), w2.picture_vocab.len(), w2.made_from.clone()), (1, 3, 2, vec!["k".to_string()]));+ let t = train(&fp, &back, &w2);+ let blur = t.heads.iter().find(|h| h.axis == "blur").unwrap();+ assert_eq!(blur.held_out, Some(1.0), "{}", blur.why);+ assert_eq!(blur.state, "gating", "{}", blur.why);+ dir.write_trained(&t, &fp.encoders).unwrap();+ let (t2, _) = dir.trained().unwrap().unwrap();+ let b2 = t2.heads.iter().find(|h| h.axis == "blur").unwrap();+ let f = feats(1.0, 99);+ assert!((b2.head.as_ref().unwrap().score(&f[0..771]) - blur.head.as_ref().unwrap().score(&f[0..771])).abs() < 1e-4);+ assert!(b2.head.as_ref().unwrap().score(&f[0..771]) > 0.0, "a blurred row scores as blur");+ let _ = std::fs::remove_dir_all(&dir.dir);+}++#[test]+fn a_gate_needs_projects() {+ let mut l = Ledger::default();+ for i in 0..60 {+ l.push(row(if i % 2 == 0 { "dark" } else { "*" }, i % 2 == 0, if i < 30 { "a" } else { "b" }), &feats(if i % 2 == 0 { 1.0 } else { -1.0 }, i));+ }+ let t = train(&base("t"), &l, &Words::default());+ let dark = t.heads.iter().find(|h| h.axis == "dark").unwrap();+ assert_eq!(dark.state, "advice");+ assert!(dark.why.contains("2 projects"), "{}", dark.why);+}++/// FP14a: what a fingerprint is for, what it builds on and what it applies to survive fingerprint.ts, and a fingerprint+/// without them writes none of them+#[test]+fn about_extends_and_applies_round_trip() {+ use crate::taxonomy::{Applies, base, to_ts};+ let plain = serde_json::to_string(&base("me")).unwrap();+ assert!(!plain.contains("about") && !plain.contains("extends") && !plain.contains("applies"));+ let mut f = base("ads");+ f.about = Some("Short ads for one brand: pace, type on screen".into());+ f.extends = Some("me".into());+ f.applies = Some(Applies { kinds: vec!["ad".into()], tags: vec![] });+ let back: crate::taxonomy::Fingerprint = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();+ assert_eq!(back, f);+ let ts = to_ts(&f);+ assert!(ts.contains("\"about\": \"Short ads for one brand: pace, type on screen\"") && ts.contains("\"extends\": \"me\""));+ let old: crate::taxonomy::Fingerprint = serde_json::from_str(r#"{"name":"me","axes":[]}"#).unwrap();+ assert_eq!((old.about, old.extends, old.applies), (None, None, None));+}diff --git a/systems/fingerprint/src/train.rs b/systems/fingerprint/src/train.rsnew file mode 100644index 00000000..18132a98--- /dev/null+++ b/systems/fingerprint/src/train.rs@@ -0,0 +1,203 @@+//! Training (FP2c, FP2d): each axis's head from its evidence, its held-out by project score, its bands and its+//! cheats, and whether it has earned the right to gate; then the person's weighting over the axes. Runs after every+//! new row: milliseconds a head on the CPU.++use crate::evidence::{Ledger, slice};+use crate::head::{Logistic, Scaler, auc, band, quantile};+use crate::taxonomy::Fingerprint;+use crate::words::Words;+use raea_sys_columns::window::Modality;+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet};++pub const C: f64 = 0.5;+/// The gate (FP2d): labels of each polarity, projects, held-out AUC, and each cheat's catch rate+pub const GATE_LABELS: usize = 16;+pub const GATE_PROJECTS: usize = 3;+pub const GATE_AUC: f64 = 0.8;+pub const GATE_CHEAT: f64 = 0.8;++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct AxisHead {+ pub axis: String,+ pub modality: Option<Modality>,+ /// the learned head: kept in heads.safetensors, not in report.json+ #[serde(skip)]+ pub head: Option<Logistic>,+ /// labels by source: [defect, clean]+ pub labels: BTreeMap<String, [usize; 2]>,+ pub projects: usize,+ /// the learned head's AUC on projects it never saw+ pub held_out: Option<f64>,+ /// the word head's AUC on the same labels, with no training+ pub words: Option<f64>,+ /// the word score that flags 10% of clean windows+ pub word_flag: Option<f32>,+ /// each cheat's share caught at the threshold that flags 10% of clean held-out work+ pub cheats: BTreeMap<String, f64>,+ /// "gating", "advice" or "words" (only the word head)+ pub state: String,+ pub why: String,+ /// decision values above which a flag was right 0.9 (strong) and 0.7 (plausible) of the time, held out+ pub strong: Option<f32>,+ pub plausible: Option<f32>,+ /// the decision value that flags 10% of clean held-out work+ pub flag: Option<f32>,+ /// what this head can't judge (earshot's LIMITS.md)+ pub cannot: Vec<String>,+}++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Trained {+ pub heads: Vec<AxisHead>,+ /// the person's weighting over the axes' scores, once they've given 8 overall labels of each kind+ #[serde(skip)]+ pub weighting: Option<Logistic>,+}++/// The modality's scaler: unlabelled statistics over every row that isn't a cheat+fn scaler(l: &Ledger, rows: &[usize], m: Modality) -> Scaler {+ let x: Vec<&[f32]> = rows.iter().map(|&i| l.modality(i, m)).collect();+ Scaler::fit(&x)+}++/// The rows' labels and weights+fn labels(l: &Ledger, rows: &[usize]) -> (Vec<bool>, Vec<f32>) {+ let (mut y, mut w) = (Vec::with_capacity(rows.len()), Vec::with_capacity(rows.len()));+ for &i in rows {+ y.push(l.rows[i].bad);+ w.push(l.rows[i].weight);+ }+ (y, w)+}++/// How many of the rows say the defect is there, and how many say it isn't+fn counts(l: &Ledger, rows: &[usize]) -> (usize, usize) {+ let bad = rows.iter().filter(|&&i| l.rows[i].bad).count();+ (bad, rows.len() - bad)+}++fn fit(l: &Ledger, rows: &[usize], m: Modality, sc: Scaler) -> Logistic {+ let x: Vec<&[f32]> = rows.iter().map(|&i| l.modality(i, m)).collect();+ let (y, w) = labels(l, rows);+ Logistic::fit(sc, &x, &y, Some(&w), C, true)+}++/// Folds over projects (FP0b's: sorted, every fifth), or one project each when there are five or fewer+pub fn folds(projects: &BTreeSet<String>) -> Vec<Vec<String>> {+ let p: Vec<String> = projects.iter().cloned().collect();+ let k = p.len().min(5);+ (0..k).map(|i| p.iter().skip(i).step_by(k).cloned().collect()).collect()+}++fn limits(m: Modality) -> Vec<String> {+ let mut v = vec!["why a moment is wrong, beyond naming the axis".to_string(), "whether the piece works as a whole, or for its audience".to_string()];+ v.push(match m {+ Modality::Picture => "where in the frame (needs marks: FP12)".into(),+ Modality::Look => "whether a look was meant (a stylised grade reads as a defect)".into(),+ Modality::Change => "whether stillness or a cut was meant".into(),+ Modality::Sound | Modality::Events => "which sound in a mix it means, or whether it was meant".into(),+ });+ v+}++pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHead {+ let Some(ax) = fp.axis(name) else { return AxisHead { axis: name.into(), state: "none".into(), why: "not in the taxonomy".into(), ..Default::default() } };+ let m = ax.modality;+ let rows = l.for_axis(name);+ let mut h = AxisHead { axis: name.into(), modality: Some(m), cannot: limits(m), ..Default::default() };+ for &i in &rows {+ h.labels.entry(l.rows[i].source.clone()).or_default()[usize::from(!l.rows[i].bad)] += 1;+ }+ let (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 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();+ let (p, n): (Vec<f32>, Vec<f32>) = (s.iter().filter(|x| x.1).map(|x| x.0).collect(), s.iter().filter(|x| !x.1).map(|x| x.0).collect());+ h.words = Some(auc(&p, &n)).filter(|a| a.is_finite());+ h.word_flag = Some(quantile(&n, 0.9)).filter(|v| v.is_finite());+ }+ 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");+ return h;+ }+ h.head = Some(fit(l, &rows, m, scaler(l, &plain, m)));+ // held out by project+ let (mut hp, mut hn) = (Vec::new(), Vec::new());+ let mut caught: BTreeMap<String, (usize, usize)> = BTreeMap::new();+ if projects.len() >= 2 {+ for fold in folds(&projects) {+ let held = |i: usize| fold.contains(&l.rows[i].project);+ let (test, train): (Vec<usize>, Vec<usize>) = rows.iter().copied().partition(|&i| held(i));+ if matches!(counts(l, &train), (0, _) | (_, 0)) {+ continue;+ }+ let base: Vec<usize> = plain.iter().copied().filter(|&i| !held(i)).collect();+ let f = fit(l, &train, m, scaler(l, &base, m));+ let (mut fp_, mut fn_) = (Vec::new(), Vec::new());+ for &i in &test {+ let s = f.score(l.modality(i, m));+ if l.rows[i].bad { fp_.push(s) } else { fn_.push(s) }+ }+ let thr = quantile(&fn_, 0.9);+ for (i, r) in l.rows.iter().enumerate().filter(|(_, r)| r.source == "cheat" && r.axis == name && fold.contains(&r.project)) {+ let e = caught.entry(r.kind.clone().unwrap_or_default()).or_default();+ e.0 += usize::from(f.score(l.modality(i, m)) > thr);+ e.1 += 1;+ }+ hp.extend(fp_);+ hn.extend(fn_);+ }+ }+ h.held_out = Some(auc(&hp, &hn)).filter(|a| a.is_finite());+ h.cheats = caught.into_iter().map(|(k, (c, n))| (k, c as f64 / n.max(1) as f64)).collect();+ h.strong = band(&hp, &hn, 0.9);+ h.plausible = band(&hp, &hn, 0.7);+ h.flag = Some(quantile(&hn, 0.9)).filter(|v| v.is_finite());+ let mut why = Vec::new();+ if pos < GATE_LABELS || neg < GATE_LABELS {+ why.push(format!("{pos} defect and {neg} clean labels (needs {GATE_LABELS} of each)"));+ }+ if h.projects < GATE_PROJECTS {+ why.push(format!("labels from {} projects (needs {GATE_PROJECTS})", h.projects));+ }+ match h.held_out {+ Some(a) if a < GATE_AUC => why.push(format!("held-out AUC {a:.2} (needs {GATE_AUC})")),+ None => why.push("no held-out score yet".into()),+ _ => {}+ }+ for (k, c) in &h.cheats {+ if *c < GATE_CHEAT {+ why.push(format!("the {k} cheat is caught {c:.2} (needs {GATE_CHEAT})"));+ }+ }+ h.state = if why.is_empty() { "gating".into() } else { "advice".into() };+ h.why = if why.is_empty() { "earned: enough labels, held out by project, cheats caught".into() } else { why.join("; ") };+ h+}++/// Every axis's head, then the person's weighting+pub fn train(fp: &Fingerprint, l: &Ledger, words: &Words) -> Trained {+ let heads: Vec<AxisHead> = fp.axes.iter().map(|a| axis(fp, l, words, &a.name)).collect();+ // the weighting: overall labels the person gave (axis "*", their own sources), read through every head+ let overall: Vec<usize> = (0..l.rows.len()).filter(|&i| l.rows[i].axis == "*" && matches!(l.rows[i].source.as_str(), "teach" | "note" | "approval" | "postmortem")).collect();+ let (p, n) = counts(l, &overall);+ let weighting = (p >= 8 && n >= 8).then(|| {+ let x: Vec<Vec<f32>> = overall.iter().map(|&i| scores(&heads, l.features(i))).collect();+ let xr: Vec<&[f32]> = x.iter().map(|v| v.as_slice()).collect();+ Logistic::fit(Scaler::fit(&xr), &xr, &labels(l, &overall).0, None, C, true)+ });+ Trained { heads, weighting }+}++/// Each head's decision value on a row's features (0 for an axis without a learned head)+pub fn scores(heads: &[AxisHead], row: &[f32]) -> Vec<f32> {+ heads.iter().map(|h| match (&h.head, h.modality) {+ (Some(f), Some(m)) => f.score(&row[slice(m)]),+ _ => 0.0,+ }).collect()+}diff --git a/systems/fingerprint/src/words.rs b/systems/fingerprint/src/words.rsnew file mode 100644index 00000000..8a2c0be4--- /dev/null+++ b/systems/fingerprint/src/words.rs@@ -0,0 +1,92 @@+//! Word heads (FP2e): every axis scores from its words on day one. A window's similarity to the axis's words, as a z+//! against a background vocabulary of about 40 ordinary descriptions (earshot's calibration): sound axes in CLAP's+//! space, picture and look axes in SigLIP 2's. The words are embedded when they change and stored in the fingerprint+//! (words.json and words.f16); the text towers never run at score time. A word head is always advice (FP2d).++use crate::taxonomy::{Fingerprint, PICTURE_VOCAB, SOUND_VOCAB, prompt};+use anyhow::Result;+use raea_sys_columns::window::{Modality, mean};+use raea_sys_columns::{CLAP, Encoders, SIG};+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct Words {+ /// each axis with a word head: its name, the space (sound or picture), and the mean of its words' vectors+ pub axes: Vec<(String, Modality, Vec<f32>)>,+ pub sound_vocab: Vec<Vec<f32>>,+ pub picture_vocab: Vec<Vec<f32>>,+ /// the axis words the vectors were made from, so a change is seen+ pub made_from: Vec<String>,+}++/// The space an axis's words are read in, if any+pub fn space(m: Modality) -> Option<Modality> {+ match m {+ Modality::Sound | Modality::Events => Some(Modality::Sound),+ Modality::Picture | Modality::Look => Some(Modality::Picture),+ Modality::Change => None,+ }+}++fn unit(v: &[f32]) -> Vec<f32> {+ let n = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);+ v.iter().map(|x| x / n).collect()+}++/// What the words were made from: an axis's name, space and words+pub fn key(f: &Fingerprint) -> Vec<String> {+ f.axes.iter().filter(|a| a.word_head && space(a.modality).is_some()).map(|a| format!("{}|{:?}|{}", a.name, a.modality, a.words.join("|"))).collect()+}++impl Words {+ pub fn stale(&self, f: &Fingerprint) -> bool {+ self.made_from != key(f)+ }++ pub fn build(enc: &mut Encoders, f: &Fingerprint) -> Result<Words> {+ let sv: Vec<String> = SOUND_VOCAB.iter().map(|w| prompt(Modality::Sound, w)).collect();+ let pv: Vec<String> = PICTURE_VOCAB.iter().map(|w| prompt(Modality::Picture, w)).collect();+ let s = enc.words_sound(&sv)?;+ let p = enc.words_picture(&pv)?;+ let mut axes = Vec::new();+ for a in f.axes.iter().filter(|a| a.word_head) {+ let Some(sp) = space(a.modality) else { continue };+ let texts: Vec<String> = a.words.iter().map(|w| prompt(sp, w)).collect();+ let v = if sp == Modality::Sound { mean(&enc.words_sound(&texts)?, CLAP) } else { mean(&enc.words_picture(&texts)?, SIG) };+ axes.push((a.name.clone(), sp, v));+ }+ Ok(Words { axes, sound_vocab: s.chunks(CLAP).map(<[f32]>::to_vec).collect(), picture_vocab: p.chunks(SIG).map(<[f32]>::to_vec).collect(), made_from: key(f) })+ }++ /// The window's vector in the space of `sp`, from its row features (every modality)+ fn window(row: &[f32], sp: Modality) -> Vec<f32> {+ let r = &row[crate::evidence::slice(sp)];+ unit(if sp == Modality::Picture { &r[..SIG] } else { r })+ }++ /// The axis's word score for a window: its similarity to the words as a z against the vocabulary+ pub fn z(&self, axis: &str, row: &[f32]) -> Option<f32> {+ let (_, sp, v) = self.axes.iter().find(|a| a.0 == axis)?;+ let w = Self::window(row, *sp);+ if w.iter().all(|x| *x == 0.0) {+ return None;+ }+ let dot = |a: &[f32]| a.iter().zip(&w).map(|(x, y)| x * y).sum::<f32>();+ let bg: Vec<f32> = (if *sp == Modality::Sound { &self.sound_vocab } else { &self.picture_vocab }).iter().map(|b| dot(b)).collect();+ let m = bg.iter().sum::<f32>() / bg.len() as f32;+ let sd = (bg.iter().map(|x| (x - m).powi(2)).sum::<f32>() / bg.len() as f32).sqrt().max(1e-6);+ Some((dot(v) - m) / sd)+ }++ /// The description from the vocabulary a window is nearest: what is heard (sound) or seen (picture), for the+ /// timeline+ pub fn nearest(&self, row: &[f32], sp: Modality) -> Option<&'static str> {+ let w = Self::window(row, sp);+ if w.iter().all(|x| *x == 0.0) {+ return None;+ }+ let (vocab, names): (&Vec<Vec<f32>>, &[&'static str]) = if sp == Modality::Sound { (&self.sound_vocab, &SOUND_VOCAB) } else { (&self.picture_vocab, &PICTURE_VOCAB) };+ let best = vocab.iter().enumerate().map(|(i, b)| (i, b.iter().zip(&w).map(|(x, y)| x * y).sum::<f32>())).max_by(|a, b| a.1.total_cmp(&b.1))?;+ names.get(best.0).copied()+ }+}