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
FP13a, FP13c, FP10a: `raea fingerprint things FILE` finds a piece's shots, its things with their depth and the ground under them every half second and a SigLIP 2 vector each (a render's things from its layer pass, NAME.layers, and its depth from its AOV pass when beside it, with no model run; footage's from the marks on its notes, followed by EdgeTAM, on Depth Anything 3 Small), and the camera's path (Lucas-Kanade flow); geometry.rs measures floating, passing through, a camera that changes speed mid-move and an empty frame, each with red-team cases, and `raea check --things` reports them as findings, never heads. The layers file reader moves from runtime/world into raea-sys-layers so both read it, and raea-perceive depth-values takes many frames to one model load. report names the axes stuck under the gate with 300 labels or more, the only ones that may try another encoder or an adapter
shinyobjectz677ca278ba6b
diff --git a/Cargo.lock b/Cargo.lockindex ef82b54a..bbc33376 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15305,7 +15305,6 @@ name = "raea-runtime-world"version = "0.1.0"dependencies = ["bevy",- "flate2","image","raea-core-facts","raea-core-scene",@@ -15486,6 +15485,7 @@ dependencies = ["image","raea-sys-columns","raea-sys-fingerprint",+ "raea-sys-layers","serde","serde_json",]diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rsindex fe30c6c8..36a9dce2 100644--- a/apps/check/src/lib.rs+++ b/apps/check/src/lib.rs@@ -1,4 +1,4 @@-//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]+//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone://! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing@@ -70,7 +70,7 @@ 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 const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";+pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.#[derive(Clone, Debug, PartialEq)]@@ -119,7 +119,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is}/// the flags `raea check` takes, each with a value-const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];+const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;@@ -161,6 +161,9 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<Stflash_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(p) = flag(args, "--things") {+ things(p, &mut issues, &mut passed)?;+ }if let Some(manifest) = &manifest {let runs = text_runs(manifest);let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));@@ -178,6 +181,22 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<StOk((video, issues, passed, fps))}+/// What `raea fingerprint things FILE --json` found (docs/fingerprint.feature FP13c): a thing floating, two passing+/// through each other, the camera lurching mid-move, an empty frame; measured there, from depth, masks and the camera's+/// path, never by a head+fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {+ let v: Value = serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?;+ let before = issues.len();+ for i in v["issues"].as_array().into_iter().flatten() {+ let Some(rule) = ["floating", "passing-through", "camera-speed", "empty-frame"].into_iter().find(|r| i["rule"] == *r) else { continue };+ issues.push(Issue { rule, p: i["p"].as_u64().unwrap_or(2).min(3) as u8, at: i["at"].as_f64(), says: i["says"].as_str().unwrap_or_default().into() });+ }+ if issues.len() == before {+ passed.push("things: nothing floats, passes through, lurches or is empty".into());+ }+ Ok(())+}+/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at/// `fps`), with `more` (a render's own), worst first then by time.fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {diff --git a/apps/check/src/tests.rs b/apps/check/src/tests.rsindex bd58fc7f..9782530c 100644--- a/apps/check/src/tests.rs+++ b/apps/check/src/tests.rs@@ -398,3 +398,17 @@ fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {white[10] = 1.0;assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);}++#[test]+fn things_found_are_findings_and_an_unknown_rule_is_not() {+ let p = std::env::temp_dir().join(format!("raea-check-things-{}.json", std::process::id()));+ let found = r#"{"issues": [{"rule": "floating", "p": 2, "at": 1.5, "to": 3.0, "says": "cup floats"}, {"rule": "made-up", "p": 0, "at": 0.0, "says": "x"}]}"#;+ std::fs::write(&p, found).unwrap();+ let (mut issues, mut passed) = (Vec::new(), Vec::new());+ things(p.to_str().unwrap(), &mut issues, &mut passed).unwrap();+ assert_eq!(issues.iter().map(|i| (i.rule, i.p, i.at)).collect::<Vec<_>>(), [("floating", 2, Some(1.5))]);+ std::fs::write(&p, r#"{"issues": []}"#).unwrap();+ things(p.to_str().unwrap(), &mut Vec::new(), &mut passed).unwrap();+ let _ = std::fs::remove_file(&p);+ assert_eq!(passed.len(), 1, "nothing found is a pass");+}diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rsindex dd5e21b5..270d6aa1 100644--- a/apps/fingerprint/src/lib.rs+++ b/apps/fingerprint/src/lib.rs@@ -14,13 +14,14 @@ mod postmortem;mod profiles;mod reembed;mod serve;+mod things;mod verbs;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 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)";+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)";/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)pub type Eval = fn(&Path) -> Result<String, String>;@@ -133,7 +134,7 @@ pub fn cli(args: &[String], eval: Eval) -> i32 {"readings" => notes::readings_here(&args[1..], &std::env::current_dir().unwrap_or_default()),"share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),"use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),- "new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "reembed" | "profile" | "score" | "stop" => {+ "new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "things" | "reembed" | "profile" | "score" | "stop" => {let cwd = std::env::current_dir().unwrap_or_default();let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };diff --git a/apps/fingerprint/src/notes.rs b/apps/fingerprint/src/notes.rsindex 948c2041..8f33bbaa 100644--- a/apps/fingerprint/src/notes.rs+++ b/apps/fingerprint/src/notes.rs@@ -46,28 +46,6 @@ pub struct Reading {pub region: Option<[f32; 4]>,}-/// How far a click reaches around its point, as a region, until a click is grown into its thing (FP11b, EdgeTAM)-const CLICK: f32 = 0.05;--/// The region a note's marks name: the box around its marks, boxes and lassos (a click as a small square around it).-/// Arrows and strikes are instructions for the agent, never a region-pub fn region(pin: &Value) -> Option<[f32; 4]> {- let mut r: Option<[f32; 4]> = None;- for m in pin["marks"].as_array().into_iter().flatten() {- let reach = match m["kind"].as_str() {- Some("mark") => CLICK,- Some("box" | "lasso") => 0.0,- _ => continue,- };- for p in m["points"].as_array().into_iter().flatten() {- let (Some(x), Some(y)) = (p[0].as_f64(), p[1].as_f64()) else { continue };- let (x, y) = (x as f32, y as f32);- let b = [(x - reach).max(0.0), (y - reach).max(0.0), (x + reach).min(1.0), (y + reach).min(1.0)];- r = Some(raea_sys_fingerprint_use::grow::union(r, b));- }- }- r.filter(|a| a[2] > a[0] && a[3] > a[1])-}/// A post's video on this machine: the renders library, else the project's own folderfn media(project: &Path, m: &Value) -> Option<PathBuf> {@@ -104,7 +82,7 @@ pub fn pinned(project: &Path) -> Vec<Reading> {continue;}let to = n["pin"]["to"].as_f64().filter(|&to| to > t);- out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: region(&n["pin"]), ..Default::default() });+ out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: raea_sys_fingerprint_use::grow::marked(&n["pin"]), ..Default::default() });}}out@@ -344,19 +322,6 @@ pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mutmod tests {use super::*;- #[test]- fn marks_name_a_region_and_arrows_dont() {- let pin = json!({"kind": "place", "x": 0.5, "y": 0.5, "marks": [- {"kind": "box", "points": [[0.6, 0.7], [0.2, 0.3]]},- {"kind": "mark", "points": [[0.9, 0.1]]},- {"kind": "arrow", "points": [[0.0, 0.0], [1.0, 1.0]]}- ]});- let r = region(&pin).unwrap();- let near = |a: f32, b: f32| (a - b).abs() < 1e-5;- assert!(near(r[0], 0.2) && near(r[1], 0.05) && near(r[2], 0.95) && near(r[3], 0.7), "{r:?}");- assert_eq!(region(&json!({"marks": [{"kind": "strike", "points": [[0.1, 0.1], [0.9, 0.9]]}]})), None, "a strike is for the agent");- assert_eq!(region(&json!({"kind": "place", "x": 0.5, "y": 0.5})), None, "a pin is never a mark");- }#[test]fn a_reading_keeps_only_kinds_and_axes_it_knows() {diff --git a/apps/fingerprint/src/things.rs b/apps/fingerprint/src/things.rsnew file mode 100644index 00000000..20c8d7d2--- /dev/null+++ b/apps/fingerprint/src/things.rs@@ -0,0 +1,31 @@+//! `raea fingerprint things FILE [--project P] [--json]` (docs/fingerprint.feature FP13a, FP13c): a piece's shots,+//! their things (a render's layers, and every mark a person drew on a note of it in P's feed, P the folder it runs in+//! by default) and the camera's path, with what floats, passes through, lurches or is empty+//! (raea-sys-fingerprint-use things.rs and geometry.rs). `--json` prints it all for `raea check --things`.++use crate::{flag, has};+use anyhow::Result;+use raea_sys_columns::Encoders;+use raea_sys_fingerprint_use::things::{Mark, things};+use std::path::{Path, PathBuf};++pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path) -> Result<(String, i32)> {+ let file = cwd.join(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("things FILE"))?);+ let project = flag(args, "--project").map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p));+ let me = file.canonicalize().ok();+ let marks: Vec<Mark> = crate::notes::pinned(&project)+ .into_iter()+ .filter(|r| r.media.canonicalize().ok() == me)+ .filter_map(|r| Some(Mark { name: r.text.chars().take(40).collect(), t: r.t, a: (r.t - 1.0).max(0.0), b: r.to.unwrap_or(r.t + 1.0), region: r.region? }))+ .collect();+ let t = things(enc, &file, &marks)?;+ if has(args, "--json") {+ return Ok((serde_json::to_string_pretty(&t)?, 0));+ }+ let n: usize = t.shots.iter().map(|s| s.things.len()).sum();+ let mut out = format!("{}: {} shots, {n} things seen ({} marked), {} findings\n", PathBuf::from(&t.file).display(), t.shots.len(), marks.len(), t.issues.len());+ for i in &t.issues {+ out += &format!(" {:>6.1} s {} {}\n", i.at, i.rule, i.says);+ }+ Ok((out, 0))+}diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rsindex 2f133974..a7a983f5 100644--- a/apps/fingerprint/src/verbs.rs+++ b/apps/fingerprint/src/verbs.rs@@ -30,6 +30,7 @@ pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, s"learn-notes" => learned(enc, rest, cwd, eval),"move" => moved(enc, rest, eval),"postmortem" => crate::postmortem::run(enc, rest, cwd, eval),+ "things" => crate::things::run(enc, rest, cwd),"profile" => {let dir = crate::pick::chosen(rest, None).0;crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))diff --git a/docs/fingerprint.feature b/docs/fingerprint.featureindex 858d2fe7..26b683ec 100644--- a/docs/fingerprint.feature+++ b/docs/fingerprint.feature@@ -584,6 +584,15 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theipatch tokens pooled in its mask)And on raea's renders the same things come from the layer pass, the depth and motion passes and the scene'scamera, with no model run+ And 11-12, so far: `raea fingerprint things FILE [--json]` (raea-sys-fingerprint-use things.rs): the shots+ (raea-perceive cuts), each thing's box, the median 1/depth of it, of its base and of the ground under it every+ half second, and one SigLIP 2 vector on its box where it's largest (the box pooled, until FP12a's patch tokens);+ and the camera's path (raea-perceive flow, Lucas-Kanade at 512: Vision's flow read a pan over plain ground at a+ quarter of its speed). A thing comes from each mark drawn on the piece's notes, followed by EdgeTAM (grow.rs+ follow), or on a render from NAME.layers beside it (the reader moved from runtime/world into raea-sys-layers+ read.rs, both use it). Depth is the render's own reverse Z when NAME.aov (`raea render EDIT --aov -o NAME.aov`)+ is beside it, else Depth Anything 3 Small (depth-values now takes many frames to one model load). The scene's+ camera isn't read yet: a render's path is the flow's too@needs:FP13a,FP5aScenario: FP13b. A note's words find its thing (the test that decides whether a grounder ships)@@ -597,6 +606,16 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theiThen floating (a gap under a thing that should rest), passing through (two things' masks and depths crossing),a camera that changes speed mid-move, and a frame with nothing on it are measured from depth, masks and thecamera's path as `raea check` findings, each with red-team cases, and never trained as heads+ And 11-12, so far: geometry.rs measures the four on things.rs's output and `raea check --things T.json` reports+ them (floating and a camera that changes speed as warns, passing through and an empty frame as errors); each has+ red-team cases offline (a resting thing, a base out of frame, one bad depth; one thing walking in front of+ another, two that part and come back; a steady pan, an ease, a start; a fade at either end, a dark frame with+ something in it), and on four renders made for it (scratch geom.tsx, 960 x 540, 3 s each) passing through,+ the camera tripling its speed at 1.5 s and a blank second are found where they are, with nothing found on the+ clean things in those scenes; with the floating scene's AOV pass beside it, the hanging box floats from 0 s and+ neither the resting box nor the 12 posts do. Floating needs true depth: on Depth Anything's the hanging box's+ base and the floor under it read 0.71 and 0.73 (the floor is about 30% farther), so on footage it's found only+ where the model sees the gapRule: FP10. A fine-tuned or other device-sized encoder, only on evidence@needs:FP4b@@ -609,3 +628,7 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on theieither, since a head is a logistic fit by L-BFGS in plain Rust (head.rs) in millisecondsAnd either is kept only if it raises that axis's held-out by project AUC by 0.05 or more, at a cost the person'sdevice can pay, and the result is recorded here with the date+ And 11-12, so far: report.json and `raea fingerprint report` name the stuck axes (raea-sys-fingerprint+ `stuck`: 300 labels or more, cheats not counted, and a held-out score under the gate's 0.8), the only axes that+ may try an adapter or another encoder. On this machine's fingerprints one is: glow in "me" (580 labels, all+ bootstrap damage; held out 0.79)diff --git a/docs/manual/reference/cli/check.md b/docs/manual/reference/cli/check.mdindex 8033af27..33bd904e 100644--- a/docs/manual/reference/cli/check.md+++ b/docs/manual/reference/cli/check.md@@ -73,7 +73,7 @@ last change is still joined, with a note that what it measured may have moved.```shraea 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)raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)-raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)+raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)```Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.@@ -93,6 +93,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b| `--render` | `OUT` | Join this render instead of the composition's newest in the project's record. || `--shape` | `S` | The delivery's aspect ratio, for its safe areas. || `--taste` | `T` | The person's taste files: the rules in them that carry a `check` are applied too. |+| `--things` | `T.json` | what `raea fingerprint things FILE --json` found in the video (a thing floating or passing through another, the camera lurching mid-move, an empty frame), as findings || `--words` | `W.json` | The transcript, to check cues against their words and the voice against the music. || `-o` | `check.json` | Write the findings as JSON, for a later review or for `raea next`. |diff --git a/docs/manual/reference/cli/fingerprint.md b/docs/manual/reference/cli/fingerprint.mdindex d69241a6..8c1998ef 100644--- a/docs/manual/reference/cli/fingerprint.md+++ b/docs/manual/reference/cli/fingerprint.md@@ -27,7 +27,7 @@ raea fingerprint report## Usage```sh-raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--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 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)+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)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.diff --git a/runtime/world/Cargo.toml b/runtime/world/Cargo.tomlindex daa8c192..cd3805a3 100644--- a/runtime/world/Cargo.toml+++ b/runtime/world/Cargo.toml@@ -22,7 +22,6 @@ raea-sys-measure = { path = "../../systems/measure" }raea-io-media = { path = "../../io/media", default-features = false, features = ["apple"] }image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }raea-sys-vision = { path = "../../systems/vision" }-flate2 = "1"bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }serde_json = "1"# a clip's file's identity (its SHA-256, as raea's asset store names files)diff --git a/runtime/world/src/covers.rs b/runtime/world/src/covers.rsindex c3d9a67b..d7048053 100644--- a/runtime/world/src/covers.rs+++ b/runtime/world/src/covers.rs@@ -5,72 +5,21 @@//! what the page hides of a part the file doesn't keep (only the frontmost layer of each pixel), so no part is covered.use std::collections::HashMap;-use std::io::Read;-use std::path::Path;use raea_core_facts::{Covered, Covers, Facts, Source};-use serde_json::Value;-/// NAME.layers read: the mask's size and each frame's runs, the table's keys, kinds and parents, and which frame-/// each recorded mask is.-pub(crate) struct Masks {- w: usize,- h: usize,- keys: Vec<String>,- kinds: Vec<String>,- parents: Vec<Option<usize>>,- frames: HashMap<i64, Vec<(u16, u16)>>,-}+pub(crate) use raea_sys_layers::read::{Masks, read};-pub(crate) fn read(path: &Path) -> Result<Masks, String> {- let mut b = Vec::new();- flate2::read::GzDecoder::new(std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?).read_to_end(&mut b).map_err(|e| format!("{}: {e}", path.display()))?;- let bad = || format!("{}: not a layers file", path.display());- let u32_at = |i: usize| b.get(i..i + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]) as usize);- if !b.starts_with(b"RAEALAYR") {- return Err(bad());- }- let n = u32_at(8).ok_or_else(bad)?;- 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 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;- let which: Vec<i64> = head["at"].as_array().map(|a| a.iter().filter_map(Value::as_i64).collect()).unwrap_or_else(|| (0..count).collect());- let (mut frames, mut i, mut before) = (HashMap::new(), 12 + n, Vec::new());- for f in which {- let runs = u32_at(i).ok_or_else(bad)?;- i += 4;- if runs > 0 {- let body = b.get(i..i + runs * 4).ok_or_else(bad)?;- before = body.chunks_exact(4).map(|r| (u16::from_le_bytes([r[0], r[1]]), u16::from_le_bytes([r[2], r[3]]))).collect();- i += runs * 4;- }- 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 })+/// What covers what, on a layers file read back+pub(crate) trait Over {+ fn over(&self, f: i64, key: &str, bx: [f64; 4], order: &HashMap<String, usize>) -> Vec<(String, f64)>;}-impl Masks {- /// Whether layer `a` is `b` or inside it.- fn within(&self, mut a: usize, b: usize) -> bool {- for _ in 0..self.keys.len() {- if a == b {- return true;- }- let Some(p) = self.parents[a] else { return false };- a = p;- }- false- }-+impl Over for Masks {/// Frame `f`'s layers drawn over the one keyed `key` inside `bx` (x0, y0, x1, y1, each 0 to 1), each with the/// share of the box it covers, by `order` (each key's place in the page's document order).- pub(crate) fn over(&self, f: i64, key: &str, bx: [f64; 4], order: &HashMap<String, usize>) -> Vec<(String, f64)> {- let (Some(runs), Some(me), Some(&mine)) = (self.frames.get(&f), self.keys.iter().position(|k| k == key), order.get(key)) else { return Vec::new() };- let mask: Vec<u16> = runs.iter().flat_map(|(v, n)| std::iter::repeat_n(*v, *n as usize)).collect();+ fn over(&self, f: i64, key: &str, bx: [f64; 4], order: &HashMap<String, usize>) -> Vec<(String, f64)> {+ let (Some(mask), Some(me), Some(&mine)) = (self.mask(f), self.keys.iter().position(|k| k == key), order.get(key)) else { return Vec::new() };let span = |a: f64, b: f64, n: usize| ((a * n as f64).floor().max(0.0) as usize, ((b * n as f64).ceil() as usize).min(n));let ((x0, x1), (y0, y1)) = (span(bx[0], bx[2], self.w), span(bx[1], bx[3], self.h));let mut seen: HashMap<u16, usize> = HashMap::new();diff --git a/systems/fingerprint-use/Cargo.toml b/systems/fingerprint-use/Cargo.tomlindex a2a340c5..29cfaec5 100644--- a/systems/fingerprint-use/Cargo.toml+++ b/systems/fingerprint-use/Cargo.toml@@ -11,6 +11,8 @@ description = "Using a fingerprint (docs/fingerprint.feature FP3, FP6e, FP8b, FPraea-sys-fingerprint = { path = "../fingerprint" }# a piece's columns, and the frames and sound the sheet drawsraea-sys-columns = { path = "../columns" }+# a render's layer pass read back: its things' masks with no model run (things.rs)+raea-sys-layers = { path = "../layers" }serde = { version = "1", features = ["derive"] }anyhow = "1"# a postmortem's asks kept beside the fingerprint, and the answers read from the inbox (postmortem.rs)diff --git a/systems/fingerprint-use/src/geometry.rs b/systems/fingerprint-use/src/geometry.rsnew file mode 100644index 00000000..9f13bb35--- /dev/null+++ b/systems/fingerprint-use/src/geometry.rs@@ -0,0 +1,250 @@+//! Geometry axes are checks, not heads (docs/fingerprint.feature FP13c): from a shot's things (things.rs), its depth+//! and its camera's path, four measures that `raea check --things` reports as findings, each with red-team cases+//! below, and none ever trained as a head.+//!+//! - floating: the ground right under a thing is farther than the thing's own base, for a second or more, while the+//! thing's base is in the frame+//! - passing through: two things overlap and swap which is nearer while they still overlap, so one went through the other+//! - a camera that changes speed mid-move: inside a move, away from its first and last half second, the camera's+//! speed doubles or halves from one half second to the next+//! - a frame with nothing on it: no detail, away from the piece's first and last quarter second (its depth is the+//! model's guess at a blank picture, so it isn't asked)++use serde::{Deserialize, Serialize};++/// The ground under a base this much farther (in inverse depth, relative) is a gap+const GAP: f32 = 0.15;+/// A gap this long is floating, seconds+const FLOATS: f64 = 1.0;+/// Two boxes overlapping by this much of the smaller are touching+const TOUCH: f32 = 0.2;+/// Two depths this far apart (relative) are an order; nearer, they're level+const ORDER: f32 = 0.05;+/// The camera moving at this much of the frame a second or more is a move+const MOVING: f32 = 0.01;+/// The ease at each end of a move a speed change is allowed in, seconds+const EASE: f64 = 0.5;+/// A speed this many times the half second before's (or a fraction of it) is a change+const JUMP: f32 = 2.0;+/// A frame's grey spread under this has nothing on it+const BLANK: f32 = 0.02;+/// A blank frame this near the piece's start or end is a fade, seconds+const FADE: f64 = 0.25;++/// A thing at a moment: its box (x0,y0,x1,y1 in 0-1), its base's inverse depth (bigger is nearer) and the ground's+/// right under its box, None when its box reaches the frame's foot+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Seen {+ pub t: f64,+ pub b: [f32; 4],+ pub near: f32,+ pub base: f32,+ pub under: Option<f32>,+}++/// The camera between two frames: its pan in frames a second and its zoom a second (0 is none, above 0 in)+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Move {+ pub t: f64,+ pub dx: f32,+ pub dy: f32,+ pub zoom: f32,+}++/// A frame's detail: its grey's spread and its depth's, 0-1+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Frame {+ pub t: f64,+ pub detail: f32,+ pub depth: Option<f32>,+}++/// A finding for `raea check` (its Issue: a rule, a rank, a time, the words)+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct Issue {+ pub rule: String,+ pub p: u8,+ pub at: f64,+ pub to: f64,+ pub says: String,+}++fn issue(rule: &str, p: u8, at: f64, to: f64, says: String) -> Issue {+ Issue { rule: rule.into(), p, at, to, says }+}++/// Each run as an issue of `rule`, in its words+fn each(rule: &str, p: u8, found: Vec<(f64, f64)>, says: impl Fn(f64, f64) -> String) -> Vec<Issue> {+ let mut out = Vec::new();+ for (a, b) in found {+ out.push(issue(rule, p, a, b, says(a, b)));+ }+ out+}++/// Runs where `bad` holds of consecutive seens, at least `long` seconds, as (first, last)+fn runs<T>(xs: &[T], t: impl Fn(&T) -> f64, bad: impl Fn(&T) -> bool, long: f64) -> Vec<(f64, f64)> {+ let mut out = Vec::new();+ let mut from: Option<f64> = None;+ let mut last = 0.0;+ for x in xs {+ if bad(x) {+ from.get_or_insert(t(x));+ last = t(x);+ } else if let Some(f) = from.take() {+ if last - f >= long {+ out.push((f, last));+ }+ }+ }+ if let Some(f) = from.filter(|f| last - f >= long) {+ out.push((f, last));+ }+ out+}++/// A thing whose ground is farther than its base for FLOATS or longer+pub fn floating(name: &str, seen: &[Seen]) -> Vec<Issue> {+ let gap = |s: &Seen| s.under.is_some_and(|u| u < s.base * (1.0 - GAP));+ each("floating", 2, runs(seen, |s| s.t, gap, FLOATS), |a, b| format!("{name} floats: there's a gap under it from {a:.1} s to {b:.1} s"))+}++fn overlap(a: &[f32; 4], b: &[f32; 4]) -> f32 {+ let w = (a[2].min(b[2]) - a[0].max(b[0])).max(0.0);+ let h = (a[3].min(b[3]) - a[1].max(b[1])).max(0.0);+ let area = |r: &[f32; 4]| ((r[2] - r[0]) * (r[3] - r[1])).max(1e-6);+ w * h / area(a).min(area(b))+}++/// Two things that swap which is nearer while they overlap: the order before and after a stretch of touching+pub fn passing(a: (&str, &[Seen]), b: (&str, &[Seen])) -> Vec<Issue> {+ let mut out = Vec::new();+ // which is nearer while touching: +1 a, -1 b, 0 level; reset when they part+ let mut was: Option<(i8, f64)> = None;+ for x in a.1 {+ let Some(y) = b.1.iter().find(|y| (y.t - x.t).abs() < 1e-3) else { continue };+ if overlap(&x.b, &y.b) < TOUCH {+ was = None;+ continue;+ }+ let d = (x.near - y.near) / x.near.max(y.near).max(1e-6);+ let now = if d > ORDER { 1 } else if d < -ORDER { -1 } else { 0 };+ match was {+ Some((o, t)) if o != 0 && now == -o => {+ out.push(issue("passing-through", 1, t, x.t, format!("{} and {} pass through each other between {t:.1} s and {:.1} s", a.0, b.0, x.t)));+ was = Some((now, x.t));+ }+ _ if now != 0 => was = Some((now, x.t)),+ _ => {}+ }+ }+ out+}++/// The camera's speed, frames a second (a zoom of 10% a second counts as a tenth of a frame)+fn speed(m: &Move) -> f32 {+ (m.dx * m.dx + m.dy * m.dy).sqrt() + m.zoom.abs()+}++/// Mean speed of the moves in [a, b)+fn mean_speed(ms: &[Move], a: f64, b: f64) -> Option<f32> {+ let (mut n, mut sum) = (0usize, 0.0f32);+ for m in ms {+ if m.t >= a && m.t < b {+ n += 1;+ sum += speed(m);+ }+ }+ (n > 0).then(|| sum / n as f32)+}++/// Inside each move of one shot (a run moving at MOVING or more), away from its eases, a half second whose speed is+/// JUMP times the one before's, or that fraction of it+pub fn speed_change(ms: &[Move]) -> Vec<Issue> {+ let mut out = Vec::new();+ for (a, b) in runs(ms, |m| m.t, |m| speed(m) >= MOVING, 2.0 * EASE + 1.0) {+ let mut t = a + EASE;+ while t + 1.0 <= b - EASE + 1e-6 {+ if let (Some(s0), Some(s1)) = (mean_speed(ms, t, t + 0.5), mean_speed(ms, t + 0.5, t + 1.0)) {+ let r = s1 / s0.max(1e-6);+ if r >= JUMP || r <= 1.0 / JUMP {+ out.push(issue("camera-speed", 2, t + 0.5, t + 1.0, format!("the camera {} mid-move at {:.1} s", if r > 1.0 { "lurches faster" } else { "suddenly slows" }, t + 0.5)));+ t += 0.5;+ }+ }+ t += 0.5;+ }+ }+ out+}++/// Frames with nothing on them, not at the piece's very start or end (`dur`)+pub fn empty(frames: &[Frame], dur: f64) -> Vec<Issue> {+ let blank = |f: &Frame| f.detail < BLANK && f.t > FADE && f.t < dur - FADE;+ each("empty-frame", 1, runs(frames, |f| f.t, blank, 0.0), |a, b| format!("nothing is on screen from {a:.1} s to {b:.1} s"))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(t: f64, b: [f32; 4], near: f32, base: f32, under: Option<f32>) -> Seen {+ Seen { t, b, near, base, under }+ }++ #[test]+ fn floating_is_a_lasting_gap_under_a_base_in_frame() {+ let on_ground: Vec<Seen> = (0..12).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.6, 0.8], 0.5, 0.6, Some(0.59))).collect();+ assert_eq!(floating("cup", &on_ground), [], "resting: the ground under it is as near as its base");+ let cropped: Vec<Seen> = (0..12).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.6, 1.0], 0.5, 0.6, None)).collect();+ assert_eq!(floating("cup", &cropped), [], "its base is out of frame");+ let blip: Vec<Seen> = (0..12).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.6, 0.8], 0.5, 0.6, Some(if i == 5 { 0.2 } else { 0.6 }))).collect();+ assert_eq!(floating("cup", &blip), [], "one bad depth isn't a gap");+ let floats: Vec<Seen> = (0..12).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.6, 0.8], 0.5, 0.6, Some(0.3))).collect();+ assert_eq!(floating("cup", &floats).len(), 1);+ }++ #[test]+ fn passing_through_is_a_swap_while_touching() {+ let a: Vec<Seen> = (0..8).map(|i| at(i as f64 * 0.25, [0.2 + i as f32 * 0.05, 0.3, 0.5 + i as f32 * 0.05, 0.8], 0.8, 0.8, None)).collect();+ let b: Vec<Seen> = (0..8).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.7, 0.8], 0.4, 0.4, None)).collect();+ assert_eq!(passing(("a", &a), ("b", &b)), [], "a walks in front of b: always nearer");+ let through: Vec<Seen> = (0..8).map(|i| at(i as f64 * 0.25, [0.4, 0.3, 0.7, 0.8], if i < 4 { 0.6 } else { 0.2 }, 0.4, None)).collect();+ assert_eq!(passing(("a", &through), ("b", &b)).len(), 1, "a goes from in front of b to behind it while overlapping");+ let parted: Vec<Seen> = (0..8).map(|i| at(i as f64 * 0.25, if (3..5).contains(&i) { [0.0, 0.0, 0.1, 0.1] } else { [0.4, 0.3, 0.7, 0.8] }, if i < 4 { 0.6 } else { 0.2 }, 0.4, None)).collect();+ assert_eq!(passing(("a", &parted), ("b", &b)), [], "they part, then come back the other way round");+ }++ fn pan(t: f64, dx: f32) -> Move {+ Move { t, dx, dy: 0.0, zoom: 0.0 }+ }++ #[test]+ fn a_speed_change_is_inside_a_move_not_its_ease() {+ let steady: Vec<Move> = (0..32).map(|i| pan(i as f64 / 8.0, 0.2)).collect();+ assert_eq!(speed_change(&steady), []);+ // eases in and out over a second each end: half-second steps never double past the ease+ let eased: Vec<Move> = (0..48).map(|i| {+ let t = i as f64 / 8.0;+ pan(t, 0.2 * (t.min(6.0 - t).clamp(0.0, 1.0) as f32).max(0.15))+ }).collect();+ assert_eq!(speed_change(&eased), [], "a gentle ease isn't a lurch");+ let lurch: Vec<Move> = (0..32).map(|i| pan(i as f64 / 8.0, if i >= 16 { 0.6 } else { 0.2 })).collect();+ let c = speed_change(&lurch);+ assert_eq!(c.len(), 1, "{c:?}");+ assert!((c[0].at - 2.0).abs() < 0.01);+ let still_then_pan: Vec<Move> = (0..32).map(|i| pan(i as f64 / 8.0, if i >= 16 { 0.3 } else { 0.0 })).collect();+ assert_eq!(speed_change(&still_then_pan), [], "starting to move isn't a change mid-move");+ }++ #[test]+ fn an_empty_frame_is_mid_piece_with_no_detail() {+ let f = |t: f64, detail: f32| Frame { t, detail, depth: Some(detail) };+ let fade: Vec<Frame> = [f(0.0, 0.0), f(0.5, 0.3), f(1.0, 0.3), f(1.9, 0.0)].into();+ assert_eq!(empty(&fade, 2.0), [], "fading in and out at the ends");+ let dark = [f(0.5, 0.03), f(1.0, 0.04)];+ assert_eq!(empty(&dark, 2.0), [], "a dark frame with something in it");+ let black = [f(0.5, 0.3), f(1.0, 0.001), f(1.25, 0.002), f(1.5, 0.3)];+ assert_eq!(empty(&black, 2.0).len(), 1);+ }+}diff --git a/systems/fingerprint-use/src/grow.rs b/systems/fingerprint-use/src/grow.rsindex 89b95552..0424cf5d 100644--- a/systems/fingerprint-use/src/grow.rs+++ b/systems/fingerprint-use/src/grow.rs@@ -12,6 +12,8 @@ const FPS: f64 = 4.0;const SIDE: u32 = 512;/// Less of the frame than this, and EdgeTAM has lost the thingconst LOST: f64 = 0.0005;+/// A click marks this far around it, of the frame+const CLICK: f32 = 0.05;#[derive(Clone, Debug, PartialEq)]pub struct Grown {@@ -59,69 +61,113 @@ pub fn union(a: Option<[f32; 4]>, b: [f32; 4]) -> [f32; 4] {u}-/// The note's frames from `from` toward `to` (either way), the first at `from`, as PNGs in `dir`-fn frames(media: &Path, from: f64, to: f64, dir: &Path) -> Result<Vec<PathBuf>> {+/// A matte EdgeTAM drew: w x h, a pixel on at 128 or more+#[derive(Clone, Debug, PartialEq)]+pub struct Matte {+ pub w: usize,+ pub h: usize,+ pub px: Vec<u8>,+}++/// The note's frames from `from` toward `to` (either way) at `fps`, the first at `from`, as PNGs in `dir`, with their times+fn frames(media: &Path, from: f64, to: f64, fps: f64, dir: &Path) -> Result<Vec<(f64, PathBuf)>> {let mut d = raea_sys_columns::media::video(media)?;let end = (d.info().duration - 1e-3).max(0.0);- let n = ((to - from).abs() * FPS).floor() as usize + 1;- let step = if to >= from { 1.0 / FPS } else { -1.0 / FPS };+ let n = ((to - from).abs() * fps).floor() as usize + 1;+ let step = if to >= from { 1.0 / fps } else { -1.0 / fps };std::fs::create_dir_all(dir)?;let mut out = Vec::new();for i in 0..n {let t = (from + i as f64 * step).clamp(0.0, end);let f = d.frame_at(t).map_err(|e| anyhow!("{}: frame at {t:.2} s: {e}", media.display()))?;- let img = image::RgbaImage::from_raw(f.width, f.height, f.rgba).ok_or_else(|| anyhow!("frame size"))?;- let s = SIDE as f32 / f.width.max(f.height) as f32;- let small = image::imageops::resize(&img, ((f.width as f32 * s) as u32).max(1), ((f.height as f32 * s) as u32).max(1), image::imageops::FilterType::Triangle);let p = dir.join(format!("f{i:03}.png"));- small.save(&p)?;- out.push(p);+ small(f.rgba, f.width, f.height)?.save(&p)?;+ out.push((t, p));}Ok(out)}-/// One run of EdgeTAM from `seed` on the first of `imgs`: each frame's box, None where it lost the thing-fn track(bin: &Path, seed: [f32; 4], imgs: &[PathBuf], out: &Path) -> Result<Vec<Option<[f32; 4]>>> {+/// A frame at SIDE on its longest side+pub fn small(rgba: Vec<u8>, w: u32, h: u32) -> Result<image::RgbaImage> {+ let img = image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| anyhow!("frame size"))?;+ let s = SIDE as f32 / w.max(h) as f32;+ Ok(image::imageops::resize(&img, ((w as f32 * s) as u32).max(1), ((h as f32 * s) as u32).max(1), image::imageops::FilterType::Triangle))+}++/// One run of EdgeTAM from `seed` on the first of `imgs`: each frame's matte, None where it lost the thing+fn track(bin: &Path, seed: [f32; 4], imgs: &[PathBuf], out: &Path) -> Result<Vec<Option<Matte>>> {let b = format!("{},{},{},{}", seed[0], seed[1], (seed[2] - seed[0]).max(0.001), (seed[3] - seed[1]).max(0.001));let run = std::process::Command::new(bin).arg("track").arg(out).arg(&b).args(imgs).output()?;if !run.status.success() {return Err(anyhow!("raea-perceive track: {}", String::from_utf8_lossy(&run.stderr).trim()));}- let mut boxes = Vec::new();+ let mut mattes = Vec::new();for p in imgs {let m = image::open(out.join(p.file_name().unwrap_or_default()))?.to_luma8();- boxes.push(bounds(m.as_raw(), m.width() as usize, m.height() as usize));+ let m = Matte { w: m.width() as usize, h: m.height() as usize, px: m.into_raw() };+ mattes.push(bounds(&m.px, m.w, m.h).is_some().then_some(m));}- Ok(boxes)+ Ok(mattes)}-/// The mark's region tracked over a..b from the note's moment `t`; Ok(None) without raea-perceive-pub fn grow(media: &Path, t: f64, a: f64, b: f64, seed: [f32; 4]) -> Result<Option<Grown>> {+/// The mark's thing followed over a..b at `fps` from the note's moment `t`, forward then back: each frame's time and+/// matte (None where EdgeTAM lost it); Ok(None) without raea-perceive+pub fn follow(media: &Path, t: f64, a: f64, b: f64, seed: [f32; 4], fps: f64) -> Result<Option<Vec<(f64, Option<Matte>)>>> {let Some(bin) = perceive() else { return Ok(None) };- let tmp = std::env::temp_dir().join(format!("raea-fingerprint-grow-{}", std::process::id()));- let ran = (|| -> Result<Grown> {- let mut g = Grown { region: seed, kept: 0, lost: 0 };- let mut region = None;+ let tmp = std::env::temp_dir().join(format!("raea-fingerprint-follow-{}-{}", std::process::id(), (t * 1000.0) as i64));+ let ran = (|| -> Result<Vec<(f64, Option<Matte>)>> {+ let mut out = Vec::new();for (i, end) in [b, a].into_iter().enumerate() {- if (end - t).abs() * FPS < 1.0 && i == 1 {+ if (end - t).abs() * fps < 1.0 && i == 1 {continue;}let dir = tmp.join(format!("{i}"));- let imgs = frames(media, t, end, &dir.join("in"))?;- for x in track(&bin, seed, &imgs, &dir.join("out"))? {- match x {- Some(r) => (region, g.kept) = (Some(union(region, r)), g.kept + 1),- None => g.lost += 1,- }- }+ let imgs = frames(media, t, end, fps, &dir.join("in"))?;+ let paths: Vec<PathBuf> = imgs.iter().map(|x| x.1.clone()).collect();+ // the note's own frame is the first of both runs: kept once+ out.extend(imgs.iter().map(|x| x.0).zip(track(&bin, seed, &paths, &dir.join("out"))?).skip(i));}- g.region = region.unwrap_or(seed);- Ok(g)+ out.sort_by(|x, y| x.0.total_cmp(&y.0));+ Ok(out)})();let _ = std::fs::remove_dir_all(&tmp);ran.map(Some)}+/// The mark's region tracked over a..b from the note's moment `t`; Ok(None) without raea-perceive+pub fn grow(media: &Path, t: f64, a: f64, b: f64, seed: [f32; 4]) -> Result<Option<Grown>> {+ let Some(seen) = follow(media, t, a, b, seed, FPS)? else { return Ok(None) };+ let mut g = Grown { region: seed, kept: 0, lost: 0 };+ let mut region = None;+ for (_, m) in &seen {+ match m.as_ref().and_then(|m| bounds(&m.px, m.w, m.h)) {+ Some(r) => (region, g.kept) = (Some(union(region, r)), g.kept + 1),+ None => g.lost += 1,+ }+ }+ g.region = region.unwrap_or(seed);+ Ok(Some(g))+}++/// The region a note's marks name: the box around its marks, boxes and lassos (a click as a small square around it).+/// Arrows and strikes are instructions for the agent, never a region+pub fn marked(pin: &serde_json::Value) -> Option<[f32; 4]> {+ let mut r: Option<[f32; 4]> = None;+ for m in pin["marks"].as_array().into_iter().flatten() {+ let reach = match m["kind"].as_str() {+ Some("mark") => CLICK,+ Some("box" | "lasso") => 0.0,+ _ => continue,+ };+ for p in m["points"].as_array().into_iter().flatten() {+ let (Some(x), Some(y)) = (p[0].as_f64(), p[1].as_f64()) else { continue };+ let (x, y) = (x as f32, y as f32);+ r = Some(union(r, [(x - reach).max(0.0), (y - reach).max(0.0), (x + reach).min(1.0), (y + reach).min(1.0)]));+ }+ }+ r.filter(|a| a[2] > a[0] && a[3] > a[1])+}+#[cfg(test)]mod tests {use super::*;@@ -139,6 +185,21 @@ mod tests {assert_eq!(bounds(&vec![0u8; w * h], w, h), None, "nothing on is a lost frame");assert_eq!(union(Some([0.1, 0.5, 0.2, 0.6]), [0.6, 0.2, 0.9, 0.5]), [0.1, 0.2, 0.9, 0.6]);}++ #[test]+ fn marks_name_a_region_and_arrows_dont() {+ use serde_json::json;+ let pin = json!({"kind": "place", "x": 0.5, "y": 0.5, "marks": [+ {"kind": "box", "points": [[0.6, 0.7], [0.2, 0.3]]},+ {"kind": "mark", "points": [[0.9, 0.1]]},+ {"kind": "arrow", "points": [[0.0, 0.0], [1.0, 1.0]]}+ ]});+ let r = marked(&pin).unwrap();+ let near = |a: f32, b: f32| (a - b).abs() < 1e-5;+ assert!(near(r[0], 0.2) && near(r[1], 0.05) && near(r[2], 0.95) && near(r[3], 0.7), "{r:?}");+ assert_eq!(marked(&json!({"marks": [{"kind": "strike", "points": [[0.1, 0.1], [0.9, 0.9]]}]})), None, "a strike is for the agent");+ assert_eq!(marked(&json!({"kind": "place", "x": 0.5, "y": 0.5})), None, "a pin is never a mark");+ }}#[cfg(test)]diff --git a/systems/fingerprint-use/src/lib.rs b/systems/fingerprint-use/src/lib.rsindex 7215d82a..51ddf85c 100644--- a/systems/fingerprint-use/src/lib.rs+++ b/systems/fingerprint-use/src/lib.rs@@ -11,11 +11,13 @@pub mod diff;pub mod fixed;+pub mod geometry;pub mod grow;pub mod postmortem;pub mod profile;pub mod score;pub mod sheet;+pub mod things;pub mod which;#[cfg(test)]diff --git a/systems/fingerprint-use/src/profile.rs b/systems/fingerprint-use/src/profile.rsindex f46cbeff..352aac2a 100644--- a/systems/fingerprint-use/src/profile.rs+++ b/systems/fingerprint-use/src/profile.rs@@ -28,7 +28,7 @@ fn mean(v: &[f32]) -> f32 {v.iter().sum::<f32>() / v.len().max(1) as f32}-fn pct(v: &[f32], q: f32) -> f32 {+pub(crate) fn pct(v: &[f32], q: f32) -> f32 {let mut s = v.to_vec();s.sort_by(f32::total_cmp);s.get(((s.len().max(1) - 1) as f32 * q) as usize).copied().unwrap_or(0.0)diff --git a/systems/fingerprint-use/src/things.rs b/systems/fingerprint-use/src/things.rsnew file mode 100644index 00000000..54456635--- /dev/null+++ b/systems/fingerprint-use/src/things.rs@@ -0,0 +1,312 @@+//! A shot's things (docs/fingerprint.feature FP13a): per shot, its things, each with its box, its depth and the ground+//! under it at every half second, and one SigLIP 2 vector; the camera's path; and each frame's detail. A thing comes+//! from a person's mark, followed by EdgeTAM (grow.rs), or on a raea render from its layer pass (NAME.layers beside+//! the video), with no model run for its masks. Depth is the render's own when its AOV pass is beside it (NAME.aov,+//! `raea render EDIT --aov -o NAME.aov`), else Depth Anything 3 Small's (raea-perceive depth-values), the+//! camera's path Vision's optical flow (raea-perceive flow), the shots raea-perceive cuts'. geometry.rs measures them.++use crate::geometry::{self, Frame, Issue, Move, Seen};+use crate::grow::{self, Matte, bounds, perceive};+use anyhow::{Result, anyhow};+use raea_sys_columns::Encoders;+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};++/// Samples a second: depth, things and detail+pub const FPS: f64 = 2.0;+/// Pairs a second the camera's path is read at+const FLOW_FPS: f64 = 8.0;+/// A layer covering less of the frame than this, or more (a background), isn't a thing+const SMALLEST: f32 = 0.002;+const LARGEST: f32 = 0.6;+/// The strip under a thing's box the ground is read in, of the frame's height+const STRIP: f32 = 0.05;+/// A box this near the frame's foot has its base out of frame+const FOOT: f32 = 0.97;++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Thing {+ pub name: String,+ /// "mark" (EdgeTAM from a person's mark) or "layer" (a render's layer pass)+ pub from: String,+ pub seen: Vec<Seen>,+ /// SigLIP 2 on the thing's box where it's largest+ pub embed: Vec<f32>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Shot {+ pub a: f64,+ pub b: f64,+ pub camera: Vec<Move>,+ pub things: Vec<Thing>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Things {+ pub file: String,+ pub dur: f64,+ pub shots: Vec<Shot>,+ pub frames: Vec<Frame>,+ /// geometry.rs's findings, for `raea check --things`+ pub issues: Vec<Issue>,+}++/// A mark to follow: its words, its moment, its label's span and its region+pub struct Mark {+ pub name: String,+ pub t: f64,+ pub a: f64,+ pub b: f64,+ pub region: [f32; 4],+}++/// A frame's 1/depth, w x h, each value over the frame's 99th percentile (1 is the nearest)+struct Depth {+ w: usize,+ h: usize,+ v: Vec<f32>,+}++fn median(mut v: Vec<f32>) -> Option<f32> {+ if v.is_empty() {+ return None;+ }+ v.sort_by(f32::total_cmp);+ Some(v[v.len() / 2])+}++fn quantile(v: &[f32], q: f64) -> f32 {+ crate::profile::pct(v, q as f32)+}++/// A frame's 1/depth over its 99th percentile, clamped to 0-1+fn scaled(w: usize, h: usize, v: Vec<f32>) -> Depth {+ let top = quantile(&v, 0.99).max(1e-6);+ let v = v.into_iter().map(|x| (x / top).clamp(0.0, 1.0)).collect();+ Depth { w, h, v }+}++/// Every frame pair's camera move from raea-perceive flow, per second+fn camera(bin: &Path, file: &Path) -> Vec<Move> {+ // pyramidal Lucas-Kanade at 512: Vision's flow flattens a pan over plain ground to a quarter of it (11-12, a render)+ let Ok(o) = std::process::Command::new(bin).arg("flow").arg(file).args(["--fps", &FLOW_FPS.to_string(), "--side", "512", "--backend", "lk"]).output() else { return Vec::new() };+ let f = FLOW_FPS as f32;+ String::from_utf8_lossy(&o.stdout)+ .lines()+ .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())+ .map(|v| {+ let g = |k: &str| v[k].as_f64().unwrap_or(0.0) as f32;+ Move { t: v["t"].as_f64().unwrap_or(0.0), dx: g("dx") * f, dy: g("dy") * f, zoom: g("zoom") * f }+ })+ .collect()+}++/// The visible cuts, from raea-perceive cuts; none where it can't read them+fn cuts(bin: &Path, file: &Path) -> Vec<f64> {+ let Ok(o) = std::process::Command::new(bin).arg("cuts").arg(file).output() else { return Vec::new() };+ serde_json::from_slice::<serde_json::Value>(&o.stdout).ok().and_then(|v| v["cuts"].as_array().map(|c| c.iter().filter_map(serde_json::Value::as_f64).collect())).unwrap_or_default()+}++/// Each frame's depth, the model loaded once for them all+fn depths(bin: &Path, imgs: &[PathBuf]) -> Result<Vec<Depth>> {+ let outs: Vec<PathBuf> = imgs.iter().map(|p| p.with_extension("f32")).collect();+ let mut cmd = std::process::Command::new(bin);+ cmd.arg("depth-values");+ for (i, o) in imgs.iter().zip(&outs) {+ cmd.arg(i).arg(o);+ }+ let run = cmd.output()?;+ if !run.status.success() {+ return Err(anyhow!("raea-perceive depth-values: {}", String::from_utf8_lossy(&run.stderr).trim()));+ }+ let sizes: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).collect();+ outs.iter()+ .zip(sizes)+ .map(|(o, s)| {+ let v: Vec<f32> = std::fs::read(o)?.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();+ Ok(scaled(s["width"].as_u64().unwrap_or(0) as usize, s["height"].as_u64().unwrap_or(0) as usize, v))+ })+ .collect()+}++/// A render's own depth at each time, from the AOV pass rendered beside it (`raea render EDIT --aov -o NAME.aov`):+/// reverse Z, 1/depth as the model's is, with no model run; None when any frame's is missing+fn rendered(file: &Path, times: &[f64], (w, h): (u32, u32), fps: f64) -> Option<Vec<Depth>> {+ let dir = file.with_extension("aov").join("depth");+ times+ .iter()+ .map(|t| {+ let b = std::fs::read(dir.join(format!("frame-{:05}.f32", (t * fps).round() as i64))).ok()?;+ let v: Vec<f32> = b.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();+ // the prepass is the frame's size times RAEA_SS+ let dw = ((v.len() as f64 * w as f64 / h as f64).sqrt().round() as usize).max(1);+ Some(scaled(dw, v.len() / dw, v))+ })+ .collect()+}++/// A thing at `t` from its matte on that frame's depth+fn seen(t: f64, m: &Matte, d: &Depth) -> Option<Seen> {+ let b = bounds(&m.px, m.w, m.h)?;+ let at = |x: f32, y: f32| d.v.get(((y * d.h as f32) as usize).min(d.h.saturating_sub(1)) * d.w + ((x * d.w as f32) as usize).min(d.w.saturating_sub(1))).copied();+ let mut all: Vec<(usize, f32)> = Vec::new();+ for y in 0..m.h {+ for x in 0..m.w {+ if m.px[y * m.w + x] > 127 {+ all.push((y, at((x as f32 + 0.5) / m.w as f32, (y as f32 + 0.5) / m.h as f32)?));+ }+ }+ }+ // its base: its lowest tenth of rows, a row at least+ let (top, low) = (all.iter().map(|x| x.0).min()?, all.iter().map(|x| x.0).max()?);+ let rows = ((low - top + 1) as f32 * 0.1).ceil() as usize;+ let base: Vec<f32> = all.iter().filter(|x| x.0 + rows > low).map(|x| x.1).collect();+ let all: Vec<f32> = all.into_iter().map(|x| x.1).collect();+ let under = (b[3] < FOOT).then(|| {+ let mut v = Vec::new();+ for i in 0..8 {+ for j in 0..8 {+ v.extend(at(b[0] + (b[2] - b[0]) * (i as f32 + 0.5) / 8.0, b[3] + STRIP * (j as f32 + 0.5) / 8.0));+ }+ }+ median(v)+ });+ Some(Seen { t, b, near: median(all)?, base: median(base)?, under: under.flatten() })+}++/// A render's layers as things' mattes at each sample (NAME.layers beside it), keyed by layer+fn layered(file: &Path, times: &[f64]) -> Vec<(String, Vec<(f64, Matte)>)> {+ let Ok(m) = raea_sys_layers::read::read(&file.with_extension("layers")) else { return Vec::new() };+ let fps = raea_sys_columns::media::video(file).map(|d| d.info().fps).unwrap_or(30.0);+ let mut out: Vec<(String, Vec<(f64, Matte)>)> = Vec::new();+ for &t in times {+ // the recorded mask at or before this frame+ 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 { continue };+ for (j, key) in m.keys.iter().enumerate().filter(|(j, _)| m.kinds[*j] != "text") {+ let px: Vec<u8> = mask.iter().map(|v| if *v as usize == j + 1 { 255 } else { 0 }).collect();+ let share = px.iter().filter(|p| **p > 0).count() as f32 / px.len().max(1) as f32;+ if !(SMALLEST..=LARGEST).contains(&share) {+ continue;+ }+ let matte = Matte { w: m.w, h: m.h, px };+ match out.iter_mut().find(|x| &x.0 == key) {+ Some(x) => x.1.push((t, matte)),+ None => out.push((key.clone(), vec![(t, matte)])),+ }+ }+ }+ out+}++/// The piece's shots, things and camera, and what geometry.rs finds in them+pub fn things(enc: &mut Encoders, file: &Path, marks: &[Mark]) -> Result<Things> {+ let bin = perceive().ok_or_else(|| anyhow!("raea-perceive isn't beside raea or on PATH (RAEA_PERCEIVE): depth, masks and the camera's path come from it"))?;+ let mut v = raea_sys_columns::media::video(file)?;+ let dur = v.info().duration;+ let tmp = std::env::temp_dir().join(format!("raea-fingerprint-things-{}", std::process::id()));+ std::fs::create_dir_all(&tmp)?;+ let ran = (|| -> Result<Things> {+ let times: Vec<f64> = (0..((dur * FPS).floor() as usize).max(1)).map(|i| i as f64 / FPS).collect();+ let (mut small, mut imgs, mut frames) = (Vec::new(), Vec::new(), Vec::new());+ for (i, &t) in times.iter().enumerate() {+ let f = v.frame_at(t.min((dur - 1e-3).max(0.0))).map_err(|e| anyhow!("{}: frame at {t:.2} s: {e}", file.display()))?;+ let s = grow::small(f.rgba, f.width, f.height)?;+ let grey: Vec<f32> = s.pixels().map(|p| (0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32) / 255.0).collect();+ let mean = grey.iter().sum::<f32>() / grey.len().max(1) as f32;+ let detail = (grey.iter().map(|g| (g - mean).powi(2)).sum::<f32>() / grey.len().max(1) as f32).sqrt();+ let p = tmp.join(format!("f{i:04}.png"));+ s.save(&p)?;+ imgs.push(p);+ small.push(s);+ frames.push(Frame { t, detail, depth: None });+ }+ let info = v.info();+ let depth = match rendered(file, ×, (info.width, info.height), info.fps) {+ Some(d) => d,+ None => depths(&bin, &imgs)?,+ };+ for (f, d) in frames.iter_mut().zip(&depth) {+ f.depth = Some(quantile(&d.v, 0.95) - quantile(&d.v, 0.05));+ }+ let near = |t: f64| ((t * FPS).round() as usize).min(times.len() - 1);+ // the things: a render's layers, then each mark followed+ let mut found: Vec<(String, String, Vec<(f64, Matte)>)> = layered(file, ×).into_iter().map(|(k, m)| (k, "layer".to_string(), m)).collect();+ for m in marks {+ let t = near(m.t) as f64 / FPS;+ if let Some(f) = grow::follow(file, t, m.a, m.b, m.region, FPS)? {+ found.push((m.name.clone(), "mark".into(), f.into_iter().filter_map(|(t, x)| Some((t, x?))).collect()));+ }+ }+ let mut all = Vec::new();+ for (name, from, mattes) in found {+ let seen: Vec<Seen> = mattes.iter().filter_map(|(t, m)| seen(*t, m, &depth[near(*t)])).collect();+ let Some(big) = seen.iter().max_by(|a, b| ((a.b[2] - a.b[0]) * (a.b[3] - a.b[1])).total_cmp(&((b.b[2] - b.b[0]) * (b.b[3] - b.b[1])))) else { continue };+ let s = &small[near(big.t)];+ let (w, h) = (s.width() as f32, s.height() as f32);+ let crop = image::imageops::crop_imm(s, (big.b[0] * w) as u32, (big.b[1] * h) as u32, (((big.b[2] - big.b[0]) * w) as u32).max(1), (((big.b[3] - big.b[1]) * h) as u32).max(1)).to_image();+ let embed = enc.picture(&[raea_sys_columns::media::squash(crop.as_raw(), crop.width() as usize, crop.height() as usize)])?.0;+ all.push(Thing { name, from, seen, embed });+ }+ let cam = camera(&bin, file);+ let mut edges = vec![0.0];+ for c in cuts(&bin, file) {+ if c > 0.0 && c < dur {+ edges.push(c);+ }+ }+ edges.push(dur);+ let mut shots = Vec::new();+ let mut issues = geometry::empty(&frames, dur);+ for w in edges.windows(2) {+ let (a, b) = (w[0], w[1]);+ let inside = |t: f64| t >= a && t < b;+ let camera: Vec<Move> = cam.iter().filter(|m| inside(m.t)).cloned().collect();+ let things: Vec<Thing> = all.iter().map(|x| Thing { seen: x.seen.iter().filter(|s| inside(s.t)).cloned().collect(), ..x.clone() }).filter(|x| !x.seen.is_empty()).collect();+ issues.extend(geometry::speed_change(&camera));+ for (i, x) in things.iter().enumerate() {+ issues.extend(geometry::floating(&x.name, &x.seen));+ for y in &things[i + 1..] {+ issues.extend(geometry::passing((&x.name, &x.seen), (&y.name, &y.seen)));+ }+ }+ shots.push(Shot { a, b, camera, things });+ }+ issues.sort_by(|x, y| x.at.total_cmp(&y.at));+ Ok(Things { file: file.display().to_string(), dur, shots, frames, issues })+ })();+ let _ = std::fs::remove_dir_all(&tmp);+ ran+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_things_base_and_the_ground_under_it() {+ // a 10 x 10 depth: the floor nearer toward the foot, a box standing on it, and one hanging over far wall+ let mut v = vec![0.0f32; 100];+ for y in 0..10 {+ for x in 0..10 {+ v[y * 10 + x] = 0.1 * y as f32;+ }+ }+ let d = Depth { w: 10, h: 10, v };+ let mut px = vec![0u8; 100];+ for y in 4..7 {+ for x in 3..6 {+ px[y * 10 + x] = 255;+ }+ }+ let m = Matte { w: 10, h: 10, px };+ let s = seen(1.0, &m, &d).unwrap();+ assert_eq!(s.b, [0.3, 0.4, 0.6, 0.7]);+ assert!((s.base - 0.6).abs() < 1e-5 && s.under.is_some_and(|u| (u - 0.7).abs() < 1e-5), "{s:?}");+ let mut foot = vec![0u8; 100];+ foot[95] = 255;+ foot[85] = 255;+ assert_eq!(seen(1.0, &Matte { w: 10, h: 10, px: foot }, &d).unwrap().under, None, "its base is at the frame's foot");+ }+}diff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rsindex 93cdaec4..81f84844 100644--- a/systems/fingerprint/src/lib.rs+++ b/systems/fingerprint/src/lib.rs@@ -65,6 +65,23 @@ pub fn retrain(dir: &Folder, fp: &Fingerprint, w: &Words, l: &Ledger, bootstrap:Ok(t)}+/// An axis this many labels deep and still under the held-out bar is stuck (FP10a)+pub const STUCK_LABELS: usize = 300;++/// The axes stuck under their bar with STUCK_LABELS or more labels on their own columns (docs/fingerprint.feature+/// FP10a): only these may try an adapter on SigLIP 2 or another encoder, kept only if it lifts held out by 0.05+pub fn stuck(t: &Trained) -> Vec<(String, usize, f64)> {+ t.heads+ .iter()+ .filter_map(|h| {+ // a cheat is a test of the head, not a label of its axis+ let n: usize = h.labels.iter().filter(|(s, _)| s.as_str() != "cheat").map(|(_, [a, b])| a + b).sum();+ let auc = h.held_out?;+ (n >= STUCK_LABELS && auc < GATE_AUC).then(|| (h.axis.clone(), n, auc))+ })+ .collect()+}+/// report.json (FP2d): every head's held-out score, labels by source, cheat catch rates, gate state and limitspub 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();@@ -82,6 +99,7 @@ pub fn report(fp: &Fingerprint, t: &Trained, l: &Ledger, bootstrap: Option<serde"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(),+ "stuck": stuck(t).into_iter().map(|(axis, labels, held_out)| json!({"axis": axis, "labels": labels, "held_out": held_out})).collect::<Vec<_>>(),"bootstrap": bootstrap,"cannot_judge": LIMITS,})@@ -105,6 +123,14 @@ pub fn report_text(r: &serde_json::Value) -> String {h["why"].as_str().unwrap_or(""));}+ let stuck = r["stuck"].as_array().cloned().unwrap_or_default();+ out += &match stuck.is_empty() {+ true => format!("stuck: none (an axis {STUCK_LABELS} labels deep under held out {GATE_AUC} may try an adapter or another encoder)\n"),+ false => format!(+ "stuck, so each may try an adapter on SigLIP 2 or another encoder, kept only at 0.05 better held out: {}\n",+ stuck.iter().map(|x| format!("{} ({} labels, held out {})", x["axis"].as_str().unwrap_or(""), x["labels"], f(&x["held_out"]))).collect::<Vec<_>>().join(", ")+ ),+ };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() {diff --git a/systems/fingerprint/src/tests.rs b/systems/fingerprint/src/tests.rsindex d751d895..c9148315 100644--- a/systems/fingerprint/src/tests.rs+++ b/systems/fingerprint/src/tests.rs@@ -291,3 +291,29 @@ fn pairs_alone_rank() {let head = h.head.unwrap();assert!(head.score(&feats(1.0, 999)[crate::evidence::slice(raea_sys_columns::window::Modality::Picture)]) > head.score(&feats(-1.0, 998)[crate::evidence::slice(raea_sys_columns::window::Modality::Picture)]));}++#[test]+fn an_axis_is_stuck_only_deep_in_labels_and_under_its_bar() {+ use crate::train::AxisHead;+ let head = |axis: &str, n: usize, auc: Option<f64>| AxisHead { axis: axis.into(), labels: [("note".to_string(), [n / 2, n - n / 2]), ("cheat".to_string(), [500, 0])].into(), held_out: auc, ..Default::default() };+ let t = crate::train::Trained { heads: vec![head("pace", 320, Some(0.7)), head("glow", 120, Some(0.6)), head("blur", 400, Some(0.9)), head("cut", 350, None)], weighting: None };+ assert_eq!(crate::stuck(&t), [("pace".to_string(), 320, 0.7)], "glow is too few labels in, blur is over its bar, cut has no held-out score; cheats aren't labels");+}++/// FP10a's first try on a stuck axis, on this machine's "me" fingerprint (ignored: real evidence): glow, stuck on its+/// look columns, trained on the same labels through SigLIP 2's picture columns instead, held out by project as ever+#[test]+#[ignore]+fn a_stuck_axis_on_another_encoder() {+ let dir = Folder::named("me");+ let (mut fp, l) = (dir.read(None).unwrap(), dir.ledger().unwrap());+ let w = dir.words().unwrap();+ let auc = |fp: &crate::taxonomy::Fingerprint| crate::train::train(fp, &l, &w).heads.into_iter().find(|h| h.axis == "glow").and_then(|h| h.held_out);+ let was = auc(&fp);+ let mut out = format!("glow on look {was:?}");+ for m in [Modality::Picture, Modality::Change] {+ fp.axes.iter_mut().filter(|a| a.name == "glow").for_each(|a| a.modality = m);+ out += &format!(", on {} {:?}", m.name(), auc(&fp));+ }+ eprintln!("{out}");+}diff --git a/systems/layers/src/lib.rs b/systems/layers/src/lib.rsindex f5275988..e1ec4aa8 100644--- a/systems/layers/src/lib.rs+++ b/systems/layers/src/lib.rs@@ -8,6 +8,7 @@ mod file;mod hide;mod names;mod raster;+pub mod read;#[cfg(feature = "page")]mod page;#[cfg(feature = "page")]diff --git a/systems/layers/src/read.rs b/systems/layers/src/read.rsnew file mode 100644index 00000000..52b132db--- /dev/null+++ b/systems/layers/src/read.rs@@ -0,0 +1,69 @@+//! NAME.layers read back (file.rs writes it): a world's covers (runtime/world covers.rs) and a fingerprint's things+//! on a render (docs/fingerprint.feature FP13a) both read it.++use std::collections::HashMap;+use std::io::Read;+use std::path::Path;++use serde_json::Value;++/// NAME.layers read: the mask's size and each frame's runs, the table's keys, kinds and parents, and which frame+/// each recorded mask is.+pub struct Masks {+ pub w: usize,+ pub h: usize,+ pub keys: Vec<String>,+ pub kinds: Vec<String>,+ pub parents: Vec<Option<usize>>,+ pub frames: HashMap<i64, Vec<(u16, u16)>>,+}++pub fn read(path: &Path) -> Result<Masks, String> {+ let mut b = Vec::new();+ flate2::read::GzDecoder::new(std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?).read_to_end(&mut b).map_err(|e| format!("{}: {e}", path.display()))?;+ let bad = || format!("{}: not a layers file", path.display());+ let u32_at = |i: usize| b.get(i..i + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]) as usize);+ if !b.starts_with(b"RAEALAYR") {+ return Err(bad());+ }+ let n = u32_at(8).ok_or_else(bad)?;+ 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 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;+ let which: Vec<i64> = head["at"].as_array().map(|a| a.iter().filter_map(Value::as_i64).collect()).unwrap_or_else(|| (0..count).collect());+ let (mut frames, mut i, mut before) = (HashMap::new(), 12 + n, Vec::new());+ for f in which {+ let runs = u32_at(i).ok_or_else(bad)?;+ i += 4;+ if runs > 0 {+ let body = b.get(i..i + runs * 4).ok_or_else(bad)?;+ before = body.chunks_exact(4).map(|r| (u16::from_le_bytes([r[0], r[1]]), u16::from_le_bytes([r[2], r[3]]))).collect();+ i += runs * 4;+ }+ 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 })+}++impl Masks {+ /// Whether layer `a` is `b` or inside it.+ pub fn within(&self, mut a: usize, b: usize) -> bool {+ for _ in 0..self.keys.len() {+ if a == b {+ return true;+ }+ let Some(p) = self.parents[a] else { return false };+ a = p;+ }+ false+ }++ /// Frame `f`'s mask, w x h layer values (0 none, v the layer keys[v - 1]); None when the frame wasn't recorded+ pub fn mask(&self, f: i64) -> Option<Vec<u16>> {+ Some(self.frames.get(&f)?.iter().flat_map(|(v, n)| std::iter::repeat_n(*v, *n as usize)).collect())+ }+}diff --git a/tools/perceive/src/main.rs b/tools/perceive/src/main.rsindex 617b191a..283740b0 100644--- a/tools/perceive/src/main.rs+++ b/tools/perceive/src/main.rs@@ -29,7 +29,7 @@//! raea-perceive flow VIDEO [--fps 8] [--side 256] optical flow per frame pair (Vision): a 3x3 grid, pan, zoom//! raea-perceive track OUTDIR X,Y,W,H IMAGE... an object tracked from a box (EdgeTAM): a matte per frame//! raea-perceive hands IMAGE... each picture's hands through Core ML, one JSON line each-//! raea-perceive depth-values IMAGE OUT.f32 1/depth through Core ML, as `ugc-perceive depth-values` writes it+//! raea-perceive depth-values IMAGE OUT.f32 [IMAGE OUT.f32...] 1/depth through Core ML, as `ugc-perceive depth-values` writes it//! raea-perceive performance INPUTS.json Looks from the logged meshes, and the performance, from//! `ugc-perceive performance VIDEO --inputs`@@ -113,12 +113,19 @@ fn main() {}#[cfg(target_vendor = "apple")]Some("depth-values") => {- let (img, out) = (args.get(1).ok_or("depth-values IMAGE OUT.f32")?, args.get(2).ok_or("depth-values IMAGE OUT.f32")?);- let rgba = image::open(img).map_err(|e| format!("{img}: {e}"))?.to_rgba8();- let (w, h) = (rgba.width() as usize, rgba.height() as usize);- let (v, ww, hh) = raea_sys_vision::depth::inverse_depth(&raea_sys_vision::depth::model()?, rgba.as_raw(), w, h)?;- std::fs::write(out, v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()).map_err(|e| e.to_string())?;- println!("{}", json!({"width": ww, "height": hh}));+ // IMAGE OUT.f32 [IMAGE OUT.f32...]: the model loaded once for every pair, a size line each+ let pairs = &args[1..];+ if pairs.is_empty() || pairs.len() % 2 != 0 {+ return Err("depth-values IMAGE OUT.f32 [IMAGE OUT.f32...]".into());+ }+ let m = raea_sys_vision::depth::model()?;+ for p in pairs.chunks(2) {+ let rgba = image::open(&p[0]).map_err(|e| format!("{}: {e}", p[0]))?.to_rgba8();+ let (w, h) = (rgba.width() as usize, rgba.height() as usize);+ let (v, ww, hh) = raea_sys_vision::depth::inverse_depth(&m, rgba.as_raw(), w, h)?;+ std::fs::write(&p[1], v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()).map_err(|e| e.to_string())?;+ println!("{}", json!({"width": ww, "height": hh}));+ }Ok(())}#[cfg(target_vendor = "apple")]