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
FP12a: patch heads say where in the frame a picture defect is. raea fingerprint bootstrap also puts FP0f's local defects in a random box of up to 6 frames a source (a blurred patch, a black hole, heavy grain, flat grey, a local glow; one that changes its box by under 6 levels is left out) and fits a logistic on SigLIP 2's 196 patch tokens per axis. Held out by source from 8 frames on 27 real renders: barren 0.92, glitch 0.90, blur 0.88 (0.79 before the visible rule), glow 0.49; an axis says where only at 0.85. score gives a flagged moment its place and the layers under it, by name (raea-sys-layers reads names); --json has at, the sheet boxes it in amber
shinyobjectzc65baf2c8122
diff --git a/Cargo.lock b/Cargo.lockindex c688332a..83c8d7f6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15599,6 +15599,7 @@ name = "raea-sys-fingerprint-things"version = "0.1.0"dependencies = ["anyhow",+ "fastrand","image","raea-sys-columns","raea-sys-fingerprint-use",@@ -15612,6 +15613,7 @@ name = "raea-sys-fingerprint-use"version = "0.1.0"dependencies = ["anyhow",+ "fastrand","image","raea-sys-columns","raea-sys-fingerprint",diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rsindex 270d6aa1..f58d318d 100644--- a/apps/fingerprint/src/lib.rs+++ b/apps/fingerprint/src/lib.rs@@ -21,7 +21,7 @@ use std::path::Path;pub use serve::serve;-pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--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), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";+pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--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), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)pub type Eval = fn(&Path) -> Result<String, String>;diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rsindex a7a983f5..1aa48bc7 100644--- a/apps/fingerprint/src/verbs.rs+++ b/apps/fingerprint/src/verbs.rs@@ -147,7 +147,8 @@ fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dsay(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});+ let patches = raea_sys_fingerprint_things::located::bootstrap(enc, &dir.dir, &files, per, say)?;+ let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws, "patches": patches});retrain(&dir, &fp, &w, &l, Some(b))?;Ok((report_text(&dir.report().unwrap_or_default()), 0))}@@ -300,6 +301,7 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Resultlet mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());let found = checks(&file);arbitrate(&mut s, &fp, &found);+ raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;// FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fixlet fixes = match flag(args, "--was") {Some(old) => {diff --git a/docs/fingerprint.md b/docs/fingerprint.mdindex 47c0c642..b2139776 100644--- a/docs/fingerprint.md+++ b/docs/fingerprint.md@@ -100,8 +100,8 @@ Each axis uses the best head it has earned:2. **A learned head**: logistic on the axis's own modality columns, standardised with the encoder's shippedstatistics, plus Bradley-Terry when the axis has pairs. It takes over from the word head once it beats it onheld-out evidence.-3. **A patch head** (picture axes): logistic on SigLIP 2's patch tokens, trained from marks. It says *where* in the- frame.+3. **A patch head** (picture axes): logistic on SigLIP 2's patch tokens, trained from local defects (FP12a) and,+ once there are enough, marks (FP12b). It says *where* in the frame.An axis that a check measures exactly, such as dropout or loudness, reports the check, and its head only adds whatthe check can't see.diff --git a/docs/manual/guides/fingerprint.md b/docs/manual/guides/fingerprint.mdindex 4d6590a2..e6bad097 100644--- a/docs/manual/guides/fingerprint.md+++ b/docs/manual/guides/fingerprint.md@@ -40,6 +40,11 @@ difference, held out by source, so it can't learn a shortcut. Each axis also hasas a blur that was sharpened afterwards or a freeze hidden under a slow zoom. An axis that misses its disguises staysadvice.+The same run teaches picture axes where a defect sits. It blurs, punches a hole in, greys out or glows one patch of a+frame, and learns to find the patch. An axis that finds it 85 times in 100 on renders it didn't learn from says where:+`score` then gives the moment's place in the frame, such as "top right", and on a render with a layer pass the layers+there, such as "on Floor", and `--sheet` boxes it on the frame.+Your own reviewing teaches it the rest:```sh@@ -141,5 +146,5 @@ finds the media.## What it can't do yetAxes judge two-second moments, so a fingerprint can't say whether a piece works as a whole, or judge story and pace-across shots. It says when a moment is wrong, not where in the frame, until marks teach it to point. A stylised look-or a held shot can read as a defect. And taste axes with only words never hold a post back.+across shots. It can say where in the frame only for blur, glitches and flat, barren surfaces; glow it can only+flag. A stylised look or a held shot can read as a defect. And taste axes with only words never hold a post back.diff --git a/runtime/world/src/covers.rs b/runtime/world/src/covers.rsindex d7048053..4d26422c 100644--- a/runtime/world/src/covers.rs+++ b/runtime/world/src/covers.rs@@ -87,7 +87,7 @@ mod tests {let runs = mask.iter().map(|v| (*v, 1)).collect();let keys = ["bg.tsx:1:1", "bg.tsx:2:3", "bg.tsx:3:3", "bg.tsx:4:3"].map(String::from).to_vec();// the caption (2) is inside the background (1); the band (3) and the mesh (4) are its siblings- Masks { w: 4, h: 1, keys, kinds: ["element", "text", "element", "mesh"].map(String::from).to_vec(), parents: vec![None, Some(0), Some(0), None], frames: HashMap::from([(7, runs)]) }+ Masks { w: 4, h: 1, names: keys.clone(), keys, kinds: ["element", "text", "element", "mesh"].map(String::from).to_vec(), parents: vec![None, Some(0), Some(0), None], frames: HashMap::from([(7, runs)]) }}#[test]diff --git a/systems/columns/src/damage.rs b/systems/columns/src/damage.rsindex bffd180c..fe8ffde2 100644--- a/systems/columns/src/damage.rs+++ b/systems/columns/src/damage.rs@@ -89,6 +89,53 @@ pub fn picture(frames: &[Rgb], kind: &str) -> Vec<Rgb> {}}+/// FP0f's local defects, each in one box of the frame, with the picture axis it labels: a blurred patch, a black+/// hole, a flat grey surface, heavy grain (corrupted, as a glitch) and a local glow. FP12's patch heads learn where.+pub const LOCAL: [(&str, &str); 5] = [("blur_box", "blur"), ("hole", "glitch"), ("flat", "barren"), ("grain", "glitch"), ("glow_box", "glow")];++/// A box in a 224 x 224 frame: its left, top and side, in pixels+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Square {+ pub x: usize,+ pub y: usize,+ pub side: usize,+}++impl Square {+ /// A random box 64-80 px a side, wholly in the frame (FP0f's)+ pub fn random(rng: &mut fastrand::Rng) -> Square {+ let side = rng.usize(64..=80);+ Square { x: rng.usize(0..=SIDE - side), y: rng.usize(0..=SIDE - side), side }+ }+ /// The pixels inside it, as indices into a 224 x 224 frame+ pub fn pixels(&self) -> Vec<usize> {+ (self.y..self.y + self.side).flat_map(|y| (self.x..self.x + self.side).map(move |x| y * SIDE + x)).collect()+ }+}++/// A frame with a local defect put into one box; the rest of the frame is untouched+pub fn local(f: &Rgb, kind: &str, b: Square, noise: &mut Noise) -> Rgb {+ let whole: Rgb = match kind {+ "blur_box" => soft(f).into_raw(),+ "glow_box" => glow(f, 0.9),+ _ => f.clone(),+ };+ let inside = b.pixels();+ let grey = (inside.iter().map(|&i| f[i * 3..i * 3 + 3].iter().map(|&c| c as f32).sum::<f32>() / 3.0).sum::<f32>() / inside.len().max(1) as f32) as u8;+ let mut out = f.clone();+ for &i in &inside {+ for c in 0..3 {+ out[i * 3 + c] = match kind {+ "hole" => 0,+ "flat" => grey,+ "grain" => (f[i * 3 + c] as f32 + noise.normal() * 60.0).clamp(0.0, 255.0) as u8,+ _ => whole[i * 3 + c],+ };+ }+ }+ out+}+/// A seeded normal source (fastrand's, Box-Muller)pub struct Noise(fastrand::Rng);diff --git a/systems/columns/src/lib.rs b/systems/columns/src/lib.rsindex c1cf59fb..c47f5614 100644--- a/systems/columns/src/lib.rs+++ b/systems/columns/src/lib.rs@@ -140,6 +140,14 @@ impl Encoders {Ok((sig, frames.iter().flat_map(|f| look::look(f)).collect()))}+ /// Each frame's 196 patch tokens, L2-normalised (siglip.rs tower): FP12's patch heads read them. An export that+ /// gives another count (a class token first, another grid) is refused, since a patch's place would be wrong+ pub fn patches(&mut self, frames: &[media::Rgb]) -> Result<Vec<f32>> {+ let v = self.vision.tower(frames, "last_hidden_state")?;+ anyhow::ensure!(v.len() == frames.len() * 196 * SIG, "SigLIP 2 gave {} patch values for {} frames, not 196 x {SIG} each", v.len(), frames.len());+ Ok(v)+ }+/// 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 herepub fn sound(&mut self, pcm16: &[f32], pcm48: &[f32]) -> Result<(Vec<f32>, Vec<f32>)> {diff --git a/systems/columns/src/siglip.rs b/systems/columns/src/siglip.rsindex 3d3b344a..8cbb4ae9 100644--- a/systems/columns/src/siglip.rs+++ b/systems/columns/src/siglip.rs@@ -50,13 +50,18 @@ fn pixels(frames: &[Rgb]) -> Vec<f32> {}impl Vision {- /// Each frame's pooled vector, L2-normalised: [frames][768]. (Its 196 patch tokens, "last_hidden_state", come- /// with FP12's heatmaps.)+ /// Each frame's pooled vector, L2-normalised: [frames][768]pub fn embed(&mut self, frames: &[Rgb]) -> Result<Vec<f32>> {+ self.tower(frames, "pooler_output")+ }++ /// The image tower's output `out` for each frame, each row L2-normalised: "pooler_output" one row a frame, or+ /// "last_hidden_state" its 14 x 14 patch tokens row by row from the top left ([frames][196][768], FP12's patch heads)+ pub(crate) fn tower(&mut self, frames: &[Rgb], out: &str) -> 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));+ v.extend(run(&mut self.0, ("pixel_values", shape, Input::F32(pixels(b))), &[out])?.remove(0));}crate::normalise(&mut v, crate::SIG);Ok(v)diff --git a/systems/fingerprint-things/Cargo.toml b/systems/fingerprint-things/Cargo.tomlindex 6dbbf64e..d635f9e9 100644--- a/systems/fingerprint-things/Cargo.toml+++ b/systems/fingerprint-things/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "Fingerprint's things (docs/fingerprint.feature FP13a, FP13c): a piece's shots, its things with their depth and the ground under them, and the camera's path, from a render's layer and AOV passes or from marks followed by EdgeTAM and Depth Anything; and the geometry checks raea check reports from them"+description = "Fingerprint's things (docs/fingerprint.feature FP13a, FP13c): a piece's shots, its things with their depth and the ground under them, and the camera's path, from a render's layer and AOV passes or from marks followed by EdgeTAM and Depth Anything; and the geometry checks raea check reports from them; and where a picture flag is (FP12a): patch heads bootstrapped from local defects, and a moment placed in the frame and its layers"[dependencies]# a mark followed by EdgeTAM, raea-perceive found, the percentile (grow.rs, profile.rs)@@ -17,3 +17,5 @@ serde = { version = "1", features = ["derive"] }serde_json = "1"anyhow = "1"image = { version = "0.25", default-features = false, features = ["png"] }+# the boxes local defects go in, seeded (located.rs)+fastrand = "2"diff --git a/systems/fingerprint-things/src/lib.rs b/systems/fingerprint-things/src/lib.rsindex 0a15476f..34912361 100644--- a/systems/fingerprint-things/src/lib.rs+++ b/systems/fingerprint-things/src/lib.rs@@ -1,5 +1,7 @@//! Fingerprint's things (docs/fingerprint.feature FP13): things.rs finds a piece's shots, things and camera path;-//! geometry.rs measures what floats, passes through, lurches or is empty in them, as checks, never heads.+//! geometry.rs measures what floats, passes through, lurches or is empty in them, as checks, never heads; located.rs+//! says where a picture flag is in the frame and which layers it covers (FP12a).pub mod geometry;+pub mod located;pub mod things;diff --git a/systems/fingerprint-things/src/located.rs b/systems/fingerprint-things/src/located.rsnew file mode 100644index 00000000..a6d005d4--- /dev/null+++ b/systems/fingerprint-things/src/located.rs@@ -0,0 +1,128 @@+//! Where a picture flag is (docs/fingerprint.feature FP12a): patch heads bootstrapped from FP0f's local defects put+//! into frames of real work, and a scored piece's moments placed in the frame and read through its layer pass into+//! the layers they cover. Only a head that points held out (patch.rs POINTS) says where.++use anyhow::Result;+use raea_sys_columns::damage::{LOCAL, Noise, Square, local};+use raea_sys_columns::media::{self, SIDE};+use raea_sys_columns::{Encoders, FPS};+use raea_sys_fingerprint_use::patch::{self, CELLS, Frame, GRID, PatchHead};+use raea_sys_fingerprint_use::score::{Scored, Where};+use std::path::{Path, PathBuf};++/// The cells of the 14 x 14 grid a box in the 224 x 224 frame covers by half or more+fn cells(b: Square) -> Vec<bool> {+ let cell = SIDE / GRID;+ (0..CELLS)+ .map(|i| {+ let (x, y) = ((i % GRID) * cell, (i / GRID) * cell);+ let over = |a: usize, s: usize| (a + cell).min(s + b.side).saturating_sub(a.max(s));+ over(x, b.x) * over(y, b.y) * 2 >= cell * cell+ })+ .collect()+}++/// The mean change a defect has to make in its box, in levels of 255, to count as one+pub const VISIBLE: f64 = 6.0;++/// The mean change between two frames inside a box, in levels of 255+fn changed(a: &media::Rgb, b: &media::Rgb, s: Square) -> f64 {+ let px = s.pixels();+ px.iter().map(|&i| (0..3).map(|c| (a[i * 3 + c] as f64 - b[i * 3 + c] as f64).abs()).sum::<f64>() / 3.0).sum::<f64>() / px.len().max(1) as f64+}++/// `per` frames from each file, evenly through it: each clean, then with each of LOCAL's defects in a random box; a+/// defect that left its box looking the same (under VISIBLE, as blur on a clear sky) is no defect, and is left out+pub fn frames(enc: &mut Encoders, files: &[PathBuf], per: usize, seed: u64, say: &mut dyn FnMut(String)) -> Result<Vec<Frame>> {+ let (mut rng, mut noise, mut out) = (fastrand::Rng::with_seed(seed), Noise::new(seed), Vec::new());+ for (n, file) in files.iter().enumerate() {+ let dur = media::duration(file).unwrap_or(0.0);+ let source = file.display().to_string();+ for k in 0..per {+ let t = dur * (k as f64 + 0.5) / per as f64;+ let Some(f) = media::frames(file, FPS, t, 1.0 / FPS)?.into_iter().next() else { continue };+ let boxes: Vec<Square> = LOCAL.iter().map(|_| Square::random(&mut rng)).collect();+ let mut batch = vec![f.clone()];+ batch.extend(LOCAL.iter().zip(&boxes).map(|((kind, _), b)| local(&f, kind, *b, &mut noise)));+ let p = enc.patches(&batch)?;+ let one = CELLS * raea_sys_columns::SIG;+ out.push(Frame { source: source.clone(), axis: "*".into(), kind: "clean".into(), patches: p[..one].to_vec(), inside: vec![false; CELLS] });+ for (j, ((kind, axis), b)) in LOCAL.iter().zip(&boxes).enumerate().filter(|(j, (_, b))| changed(&f, &batch[j + 1], **b) >= VISIBLE) {+ out.push(Frame { source: source.clone(), axis: (*axis).into(), kind: (*kind).into(), patches: p[(j + 1) * one..(j + 2) * one].to_vec(), inside: cells(*b) });+ }+ }+ say(format!("patch heads: source {}/{} {}", n + 1, files.len(), file.display()));+ }+ Ok(out)+}++/// The frames a source gives the patch heads at most: each is six frames' patch tokens (2.4 MB) held until training+pub const PER: usize = 6;++/// `raea fingerprint bootstrap`'s patch heads: frames of each file with LOCAL's defects, a head for each axis held out+/// by source and then trained on all, kept in the fingerprint's folder (patch.rs FILE); what report.json says of them+pub fn bootstrap(enc: &mut Encoders, dir: &Path, files: &[PathBuf], per: usize, say: &mut dyn FnMut(String)) -> Result<serde_json::Value> {+ let heads = patch::train(&frames(enc, files, per.min(PER), 0, say)?, 0);+ patch::save(dir, &heads)?;+ Ok(heads.iter().map(|h| serde_json::json!({"axis": h.axis, "pointing": h.pointing, "by_kind": h.by_kind, "points": h.points(), "frames": h.frames})).collect())+}++/// The layers a box covers in a render's layer pass (NAME.layers beside it) at time t, by name, most of the box first;+/// a layer under a tenth of the box is left out+fn layers(file: &Path, t: f64, b: [f64; 4]) -> Vec<String> {+ let Ok(m) = raea_sys_layers::read::read(&file.with_extension("layers")) else { return Vec::new() };+ let fps = media::video(file).map(|d| d.info().fps).unwrap_or(30.0);+ let f = (t * fps).round() as i64;+ let Some(mask) = m.frames.keys().filter(|k| **k <= f).max().and_then(|k| m.mask(*k)) else { return Vec::new() };+ let (x0, y0, x1, y1) = ((b[0] * m.w as f64) as usize, (b[1] * m.h as f64) as usize, (b[2] * m.w as f64) as usize, (b[3] * m.h as f64) as usize);+ let mut count = vec![0usize; m.keys.len() + 1];+ for y in y0..y1.min(m.h) {+ for x in x0..x1.min(m.w) {+ count[mask[y * m.w + x] as usize] += 1;+ }+ }+ let all = ((x1 - x0) * (y1 - y0)).max(1);+ let mut by: Vec<(usize, usize)> = count.iter().enumerate().skip(1).filter(|(_, n)| **n * 10 >= all).map(|(v, n)| (v, *n)).collect();+ by.sort_by(|a, b| b.1.cmp(&a.1));+ by.into_iter().map(|(v, _)| Some(&m.names[v - 1]).filter(|n| !n.is_empty()).unwrap_or(&m.keys[v - 1]).clone()).collect()+}++/// Each moment whose axis has a patch head that points gets where it is, from its middle frame+pub fn locate(enc: &mut Encoders, file: &Path, heads: &[PatchHead], s: &mut Scored) -> Result<()> {+ for m in s.moments.iter_mut() {+ let Some(h) = heads.iter().find(|h| h.axis == m.axis && h.points()) else { continue };+ let t = (m.a + m.b) / 2.0;+ let Some(f) = media::frames(file, FPS, t, 1.0 / FPS)?.into_iter().next() else { continue };+ let region = patch::region(&patch::heat(&h.head, &enc.patches(&[f])?));+ m.at = Some(Where { t, region, layers: layers(file, t, region) });+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ /// `RAEA_PATCHES=LIST OUT=DIR cargo test --release -p raea-sys-fingerprint-things patch_heads_on -- --ignored+ /// --nocapture`: the bootstrap's patch heads on the renders LIST names (one path a line), held out by source+ #[test]+ #[ignore]+ fn patch_heads_on_this_machine() {+ let list = std::env::var("RAEA_PATCHES").expect("RAEA_PATCHES");+ let files: Vec<PathBuf> = std::fs::read_to_string(list).unwrap().lines().filter(|l| !l.is_empty()).map(PathBuf::from).collect();+ let out = PathBuf::from(std::env::var("OUT").expect("OUT"));+ std::fs::create_dir_all(&out).unwrap();+ let mut enc = Encoders::load().unwrap();+ let said = bootstrap(&mut enc, &out, &files, PER, &mut |s| eprintln!("{s}")).unwrap();+ eprintln!("{}", serde_json::to_string_pretty(&said).unwrap());+ }++ #[test]+ fn a_box_covers_the_cells_it_is_mostly_over() {+ // 64 px from (32, 48): cells 2..6 across (32 px is cell 2's left edge) and rows 3..7 (48 to 112)+ let c = cells(Square { x: 32, y: 48, side: 64 });+ let on: Vec<(usize, usize)> = (0..CELLS).filter(|i| c[*i]).map(|i| (i % GRID, i / GRID)).collect();+ assert_eq!(on.len(), 16);+ assert_eq!((on[0], on[15]), ((2, 3), (5, 6)));+ }+}diff --git a/systems/fingerprint-use/Cargo.toml b/systems/fingerprint-use/Cargo.tomlindex a2a340c5..36c7807c 100644--- a/systems/fingerprint-use/Cargo.toml+++ b/systems/fingerprint-use/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "Using a fingerprint (docs/fingerprint.feature FP3, FP6e, FP8b, FP14c): a piece scored per moment and drawn as a sheet, which fingerprint judges a piece, where two differ, and profiles of admired work"+description = "Using a fingerprint (docs/fingerprint.feature FP3, FP6e, FP8b, FP12a, FP14c): a piece scored per moment and drawn as a sheet, patch heads that say where, which fingerprint judges a piece, where two differ, and profiles of admired work"[dependencies]# the fingerprint: its taxonomy, folder, evidence, heads and words@@ -17,3 +17,5 @@ anyhow = "1"serde_json = "1"# the sheet (sheet.rs) is a PNG; a mark grown by EdgeTAM writes its frames and reads its mattes (grow.rs)image = { version = "0.25", default-features = false, features = ["png"] }+# a patch head's held-out folds pick their frames, seeded (patch.rs)+fastrand = "2"diff --git a/systems/fingerprint-use/src/lib.rs b/systems/fingerprint-use/src/lib.rsindex 79b60ed5..e4ca5140 100644--- a/systems/fingerprint-use/src/lib.rs+++ b/systems/fingerprint-use/src/lib.rs@@ -12,6 +12,7 @@pub mod diff;pub mod fixed;pub mod grow;+pub mod patch;pub mod postmortem;pub mod profile;pub mod realness;diff --git a/systems/fingerprint-use/src/patch.rs b/systems/fingerprint-use/src/patch.rsnew file mode 100644index 00000000..21ea8fcf--- /dev/null+++ b/systems/fingerprint-use/src/patch.rs@@ -0,0 +1,195 @@+//! Patch heads (docs/fingerprint.feature FP12a): a picture axis's head on SigLIP 2's 14 x 14 patch tokens, so a flag+//! says where in the frame, not only whether. Trained from region labels: a defect frame's patches inside its box+//! are positive, its patches outside and every other frame's negative. Held out by source, a head points when its top+//! patch falls in the box; it says where only at POINTS or better from FEW frames, as FP0f measured (0.85-0.96).++use raea_sys_columns::SIG;+use raea_sys_fingerprint::head::{Logistic, Scaler};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::path::Path;++pub const GRID: usize = 14;+pub const CELLS: usize = GRID * GRID;+/// Held out by source, how often the top patch must fall in the box for a head to say where (FP12a)+pub const POINTS: f64 = 0.85;+/// The defect frames a held-out fold trains on: FP0f's 8 marked frames+pub const FEW: usize = 8;+/// The head's C (as the axis heads')+const C: f64 = 1.0;+/// Where a fingerprint keeps its patch heads+pub const FILE: &str = "patches.json";++/// One frame's patch tokens, its source, and where its defect is (`axis` "*" for a clean frame)+#[derive(Clone, Debug)]+pub struct Frame {+ pub source: String,+ pub axis: String,+ /// the defect put in (damage.rs LOCAL), or "mark"+ pub kind: String,+ /// CELLS x SIG, row by row from the top left+ pub patches: Vec<f32>,+ pub inside: Vec<bool>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct PatchHead {+ pub axis: String,+ pub head: Logistic,+ /// held out by source from FEW frames: the share of the held-out source's frames whose top patch is in the box+ pub pointing: Option<f64>,+ /// the same for each kind of defect on this axis+ pub by_kind: BTreeMap<String, f64>,+ /// defect frames the head was trained on+ pub frames: usize,+}++impl PatchHead {+ /// Whether it may say where: pointing at POINTS or better, held out+ pub fn points(&self) -> bool {+ self.pointing.is_some_and(|p| p >= POINTS)+ }+}++fn fit(train: &[&Frame], axis: &str) -> Logistic {+ let (mut rows, mut y): (Vec<&[f32]>, Vec<bool>) = (Vec::new(), Vec::new());+ for f in train {+ for (i, p) in f.patches.chunks(SIG).enumerate() {+ rows.push(p);+ y.push(f.axis == axis && f.inside[i]);+ }+ }+ Logistic::fit(Scaler::fit(&rows), &rows, &y, None, C, true)+}++/// Each patch's score (log-odds), row by row from the top left+pub fn heat(h: &Logistic, patches: &[f32]) -> Vec<f32> {+ patches.chunks(SIG).map(|p| h.score(p)).collect()+}++fn top(heat: &[f32]) -> usize {+ (0..heat.len()).max_by(|a, b| heat[*a].total_cmp(&heat[*b])).unwrap_or(0)+}++fn pick<'a>(rng: &mut fastrand::Rng, v: &[&'a Frame], k: usize) -> Vec<&'a Frame> {+ let mut v = v.to_vec();+ rng.shuffle(&mut v);+ v.truncate(k);+ v+}++/// Held out by source: for each source in turn, a head trained on FEW of the axis's frames from the others (and as many+/// of their other frames, clean or another defect, times two) is tested on every frame of the axis from that source+pub fn pointing(frames: &[Frame], axis: &str, rng: &mut fastrand::Rng) -> (Option<f64>, BTreeMap<String, f64>) {+ let mut sources: Vec<&str> = frames.iter().filter(|f| f.axis == axis).map(|f| f.source.as_str()).collect();+ sources.sort();+ sources.dedup();+ if sources.len() < 2 {+ return (None, BTreeMap::new());+ }+ let mut kinds: BTreeMap<String, (usize, usize)> = BTreeMap::new();+ for s in &sources {+ let other: Vec<&Frame> = frames.iter().filter(|f| f.source != *s).collect();+ let on: Vec<&Frame> = other.iter().copied().filter(|f| f.axis == axis).collect();+ let off: Vec<&Frame> = other.iter().copied().filter(|f| f.axis != axis).collect();+ let train = [pick(rng, &on, FEW), pick(rng, &off, 2 * FEW)].concat();+ let h = fit(&train, axis);+ for f in frames.iter().filter(|f| f.source == *s && f.axis == axis) {+ let e = kinds.entry(f.kind.clone()).or_default();+ e.0 += usize::from(f.inside[top(&heat(&h, &f.patches))]);+ e.1 += 1;+ }+ }+ let rate = |(hit, n): (usize, usize)| hit as f64 / n.max(1) as f64;+ let all = kinds.values().fold((0, 0), |a, k| (a.0 + k.0, a.1 + k.1));+ (Some(rate(all)), kinds.into_iter().map(|(k, c)| (k, rate(c))).collect())+}++/// A patch head for each axis with defect frames: held out first, then trained on every frame+pub fn train(frames: &[Frame], seed: u64) -> Vec<PatchHead> {+ let mut rng = fastrand::Rng::with_seed(seed);+ let mut axes: Vec<&str> = frames.iter().map(|f| f.axis.as_str()).filter(|a| *a != "*").collect();+ axes.sort();+ axes.dedup();+ let all: Vec<&Frame> = frames.iter().collect();+ axes.into_iter()+ .map(|a| {+ let (pointing, by_kind) = pointing(frames, a, &mut rng);+ PatchHead { axis: a.into(), head: fit(&all, a), pointing, by_kind, frames: frames.iter().filter(|f| f.axis == a).count() }+ })+ .collect()+}++/// The box around the top patch and the patches joined to it that score within 1 of it (log-odds), as fractions of+/// the frame: [x0, y0, x1, y1]+pub fn region(heat: &[f32]) -> [f64; 4] {+ let t = top(heat);+ let (mut seen, mut todo) = (vec![false; heat.len()], vec![t]);+ let (mut x0, mut y0, mut x1, mut y1) = (GRID, GRID, 0, 0);+ while let Some(i) = todo.pop() {+ if seen[i] || heat[i] < heat[t] - 1.0 {+ continue;+ }+ seen[i] = true;+ let (x, y) = (i % GRID, i / GRID);+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));+ if x > 0 { todo.push(i - 1) }+ if x + 1 < GRID { todo.push(i + 1) }+ if y > 0 { todo.push(i - GRID) }+ if y + 1 < GRID { todo.push(i + GRID) }+ }+ [x0, y0, x1, y1].map(|v| v as f64 / GRID as f64)+}++/// Where a box sits, in words: top left, middle, bottom right...+pub fn place(b: [f64; 4]) -> &'static str {+ let (x, y) = ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);+ const NAMES: [[&str; 3]; 3] = [["top left", "top", "top right"], ["left", "middle", "right"], ["bottom left", "bottom", "bottom right"]];+ let third = |v: f64| (v * 3.0).min(2.0) as usize;+ NAMES[third(y)][third(x)]+}++pub fn save(dir: &Path, heads: &[PatchHead]) -> std::io::Result<()> {+ std::fs::write(dir.join(FILE), serde_json::to_vec(heads)?)+}++/// A fingerprint's patch heads; none before `raea fingerprint patches`+pub fn load(dir: &Path) -> Vec<PatchHead> {+ std::fs::read(dir.join(FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A frame whose patches carry `on` in their first value inside `b`'s cells, and seeded spread elsewhere+ fn frame(source: &str, axis: &str, b: Option<(usize, usize)>, seed: usize) -> Frame {+ let inside: Vec<bool> = (0..CELLS).map(|i| b.is_some_and(|(x, y)| (x..x + 4).contains(&(i % GRID)) && (y..y + 4).contains(&(i / GRID)))).collect();+ let patches = (0..CELLS * SIG).map(|j| if j % SIG == 0 && inside[j / SIG] { 1.0 } else { (((j * 31 + seed * 17) % 97) as f32 / 97.0 - 0.5) * 0.2 }).collect();+ Frame { source: source.into(), axis: axis.into(), kind: "blur_box".into(), patches, inside }+ }++ #[test]+ fn a_patch_head_points_at_its_box_held_out_by_source() {+ let mut v = Vec::new();+ for s in 0..3 {+ for k in 0..10 {+ v.push(frame(&format!("s{s}"), "blur", Some(((k * 3) % 10, (k * 7) % 10)), s * 100 + k));+ v.push(frame(&format!("s{s}"), "*", None, s * 100 + k + 50));+ }+ }+ let heads = train(&v, 1);+ assert_eq!(heads.len(), 1);+ assert!(heads[0].points(), "{:?}", heads[0].pointing);+ let f = &v[0];+ let r = region(&heat(&heads[0].head, &f.patches));+ assert_eq!(r, [0.0, 0.0, 4.0 / 14.0, 4.0 / 14.0]);+ assert_eq!(place(r), "top left");+ }++ #[test]+ fn one_source_is_not_held_out() {+ let v = vec![frame("s0", "blur", Some((2, 2)), 1), frame("s0", "*", None, 2)];+ assert_eq!(train(&v, 1)[0].pointing, None);+ }+}diff --git a/systems/fingerprint-use/src/score.rs b/systems/fingerprint-use/src/score.rsindex 44e3f2ca..1b224de3 100644--- a/systems/fingerprint-use/src/score.rs+++ b/systems/fingerprint-use/src/score.rs@@ -58,6 +58,18 @@ pub struct Moment {pub band: Option<&'static str>,pub gating: bool,pub peak: f32,+ /// where in the frame, once the axis has a patch head that points (FP12a)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub at: Option<Where>,+}++/// Where a moment's defect is: its box in the frame at time `t` (fractions, [x0, y0, x1, y1]) and the render's layers+/// under it, most of the box first+#[derive(Clone, Debug, Serialize)]+pub struct Where {+ pub t: f64,+ pub region: [f64; 4],+ pub layers: Vec<String>,}#[derive(Clone, Debug, Serialize)]@@ -148,7 +160,7 @@ pub fn score(fp: &Fingerprint, words: Option<&Words>, trained: Option<&Trained>,(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 });+ 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, at: None });}(None, _) => {}}@@ -185,7 +197,11 @@ pub fn summary(s: &Scored) -> String {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));+ let at = m.at.as_ref().map_or(String::new(), |w| {+ let on = if w.layers.is_empty() { String::new() } else { format!(" on {}", w.layers.join(", ")) };+ format!(", {}{on}", crate::patch::place(w.region))+ });+ out += &format!(" {}-{} {}: \"{}\" ({}){at}\n", clock(m.a), clock(m.b), m.axis, m.words, label(m));}if s.moments.is_empty() {out += " nothing flagged\n";diff --git a/systems/fingerprint-use/src/sheet.rs b/systems/fingerprint-use/src/sheet.rsindex 38913fc0..52ec0b4d 100644--- a/systems/fingerprint-use/src/sheet.rs+++ b/systems/fingerprint-use/src/sheet.rs@@ -1,7 +1,7 @@//! 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.+//! checks' findings as ticks. Where a patch head put a flagged moment's defect is boxed in amber on its frames (FP12a).use crate::score::{Scored, clock};use anyhow::Result;@@ -100,6 +100,13 @@ pub fn sheet(s: &Scored, frames: &[Frame], pcm16: &[f32], ticks: &[Tick], modaliif 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);}+ // where a patch head put the defect (FP12a), boxed in amber on the frame+ for m in &s.moments {+ let (Some(w), true) = (&m.at, (m.a..=m.b).contains(&t)) else { continue };+ let (r, side) = (w.region, (thumb - 2) as f64);+ let px = |v: f64| (v * side) as u32;+ outline(&mut img, x0 + px(r[0]), y + px(r[1]), px(r[2] - r[0]).max(2), px(r[3] - r[1]).max(2), AMBER);+ }}y += thumb + 4;for k in 0..=10 {diff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rsindex 81f84844..b208806d 100644--- a/systems/fingerprint/src/lib.rs+++ b/systems/fingerprint/src/lib.rs@@ -35,7 +35,7 @@ use words::Words;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)",+ "where in the frame a defect is, on an axis whose patch head doesn't point held out (glow, and any without one: FP12a)","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",];@@ -145,6 +145,12 @@ pub fn report_text(r: &serde_json::Value) -> String {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"]);}+ // FP12a: how often a patch head's top patch falls in the defect's box, held out by source+ for p in b.get("patches").and_then(|c| c.as_array()).into_iter().flatten() {+ let kinds: Vec<String> = p["by_kind"].as_object().into_iter().flatten().map(|(k, v)| format!("{k} {}", f(v))).collect();+ let says = if p["points"].as_bool() == Some(true) { "says where" } else { "doesn't say where" };+ out += &format!(" where {:8} points {} ({}), {says}\n", p["axis"].as_str().unwrap_or(""), f(&p["pointing"]), kinds.join(", "));+ }}out += "can't judge:\n";for l in r["cannot_judge"].as_array().into_iter().flatten() {diff --git a/systems/layers/src/read.rs b/systems/layers/src/read.rsindex 52b132db..d5f8abba 100644--- a/systems/layers/src/read.rs+++ b/systems/layers/src/read.rs@@ -13,6 +13,8 @@ pub struct Masks {pub w: usize,pub h: usize,pub keys: Vec<String>,+ /// what a person would call each layer (its component, its label), beside its key+ pub names: Vec<String>,pub kinds: Vec<String>,pub parents: Vec<Option<usize>>,pub frames: HashMap<i64, Vec<(u16, u16)>>,@@ -30,7 +32,7 @@ pub fn read(path: &Path) -> Result<Masks, String> {let head: Value = serde_json::from_slice(b.get(12..12 + n).ok_or_else(bad)?).map_err(|_| bad())?;let layers = head["layers"].as_array().cloned().unwrap_or_default();let field = |name: &str| -> Vec<String> { layers.iter().map(|l| l[name].as_str().unwrap_or_default().to_string()).collect() };- let (keys, kinds) = (field("key"), field("kind"));+ let (keys, names, kinds) = (field("key"), field("name"), field("kind"));let at: HashMap<&str, usize> = keys.iter().enumerate().map(|(i, k)| (k.as_str(), i)).collect();let parents = field("parent").iter().map(|p| at.get(p.as_str()).copied()).collect();let count = head["frames"].as_u64().unwrap_or(0) as i64;@@ -46,7 +48,7 @@ pub fn read(path: &Path) -> Result<Masks, String> {}frames.insert(f, before.clone());}- Ok(Masks { w: head["mask"]["w"].as_u64().unwrap_or(0) as usize, h: head["mask"]["h"].as_u64().unwrap_or(0) as usize, keys, kinds, parents, frames })+ Ok(Masks { w: head["mask"]["w"].as_u64().unwrap_or(0) as usize, h: head["mask"]["h"].as_u64().unwrap_or(0) as usize, keys, names, kinds, parents, frames })}impl Masks {