Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

FP1b: scripts, briefs and pages get EmbeddingGemma 2 rows, a passage a step on their timeline (raea-sys-columns gemma.rs on ort with the q8 export the app's library keeps in ~/.raea/models, the same vectors transformers.js gives), and an axis with modality "text" scores its words as EmbeddingGemma 2 queries against 24 ordinary passages; a still or storyboard frame is one frame through SigLIP 2. Evidence written before the text column reads as the same rows with no text, and a fingerprint pinned before EmbeddingGemma 2 was on the machine keeps working

shinyobjectz9eb649bf98f2
diff --git a/apps/fingerprint/src/bootstrap.rs b/apps/fingerprint/src/bootstrap.rs
index 3303c7ba..a93965a7 100644
--- a/apps/fingerprint/src/bootstrap.rs
+++ b/apps/fingerprint/src/bootstrap.rs
@@ -139,7 +139,7 @@ pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mu
let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));
let (sig, look) = enc.picture(fr)?;
let (clap, yam) = enc.sound(&w16, &w48)?;
- let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000) };
+ let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000), text: Vec::new() };
let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {
let r = Row {
media: sha.clone(),
diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rs
index d52fd1d1..2f133974 100644
--- a/apps/fingerprint/src/verbs.rs
+++ b/apps/fingerprint/src/verbs.rs
@@ -97,6 +97,10 @@ pub(crate) fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option
if raw.encoders.is_empty() {
raw.encoders = here;
dir.rewrite(&raw)?;
+ } else if here.iter().filter(|(k, v)| raw.encoders.get(*k) == Some(*v)).count() == raw.encoders.len() && raw.encoders != here {
+ // an encoder added since (EmbeddingGemma 2, FP1b) doesn't change the ones it was trained on
+ raw.encoders = here;
+ dir.rewrite(&raw)?;
} else if raw.encoders != here {
bail!(
"{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",
diff --git a/docs/fingerprint.feature b/docs/fingerprint.feature
index edfdcabf..858d2fe7 100644
--- a/docs/fingerprint.feature
+++ b/docs/fingerprint.feature
@@ -148,6 +148,16 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on thei
Scenario: FP1b. Not only video
Then scripts, briefs, storyboards, stills, pages and sounds get EmbeddingGemma 2 rows the same way, so a
fingerprint can hold axes about them (a script that reads the buttons aloud, a board with wide empty shots)
+ And 11-12, so far: a script, brief or page (.md, .txt, .fountain, .html, .brief, .script.ts) is read as passages,
+ each an EmbeddingGemma 2 row (systems/columns gemma.rs, the q8 export the app's library keeps in ~/.raea/models,
+ fetched once otherwise; the Rust path gives transformers.js's vectors to the fifth decimal), a passage a step
+ on its timeline; an axis with modality "text" scores its words as EmbeddingGemma 2 queries against 24 ordinary
+ passages. A still or storyboard frame (.png, .jpg, .webp) is one frame through SigLIP 2 and a sound file goes
+ through CLAP and YAMNet, the encoders picture and sound axes already read, rather than EmbeddingGemma 2's own
+ image and audio encoders (a port of their preprocessing that buys nothing a head can use yet). Evidence rows
+ written before the text column read as the same rows with no text; a fingerprint pinned before EmbeddingGemma 2
+ was on the machine keeps working. a_script_and_a_still_get_rows (ignored, real models): the call to action is
+ nearest "a call to action", the scene heading nearest "a scene heading"
Rule: FP2. The fingerprint is a folder, its taxonomy is TypeScript
@needs:FP1a @done
diff --git a/docs/fingerprint.md b/docs/fingerprint.md
index 8f43bb11..d4966805 100644
--- a/docs/fingerprint.md
+++ b/docs/fingerprint.md
@@ -84,7 +84,7 @@ what the person's device can run.
An axis is declared in TypeScript beside `taste` (`fingerprint({...})` from "raea/brief"). It has:
- a name and the words people use for it;
-- a modality: picture, change, look, sound or words;
+- a modality: picture, change, look, sound, events or text (a script's, brief's or page's words);
- a scope: moment, shot or the whole piece;
- a polarity;
- optionally, the check it maps to.
@@ -95,8 +95,8 @@ garden door") are not axes. They go to the brief and the agent, never into a hea
Each axis uses the best head it has earned:
1. **A word head** (from day one): the similarity between the window and the axis's words, as a z-score against a
- background vocabulary of about 40 ordinary descriptions. This is earshot's calibration. CLAP serves sound axes and
- SigLIP 2's text tower serves picture axes. A word head is always advice: it never gates.
+ background vocabulary of about 40 ordinary descriptions. This is earshot's calibration. CLAP serves sound axes,
+ SigLIP 2's text tower serves picture axes and EmbeddingGemma 2 serves text axes. A word head is always advice: it never gates.
2. **A learned head**: logistic on the axis's own modality columns, standardised with the encoder's shipped
statistics, plus Bradley-Terry when the axis has pairs. It takes over from the word head once it beats it on
held-out evidence.
diff --git a/docs/manual/reference/sdk/brief.md b/docs/manual/reference/sdk/brief.md
index 1be28259..c21cfa8b 100644
--- a/docs/manual/reference/sdk/brief.md
+++ b/docs/manual/reference/sdk/brief.md
@@ -228,7 +228,7 @@ type Mark = "todo" | "done" | "dropped"
What an axis's head reads: the frames (SigLIP 2), how they change, their look, the sound (CLAP) or its events (YAMNet).
```ts
-type Modality = "picture" | "change" | "look" | "sound" | "events"
+type Modality = "picture" | "change" | "look" | "sound" | "events" | "text"
```
### `Part`
diff --git a/docs/manual/reference/sdk/fingerprint.md b/docs/manual/reference/sdk/fingerprint.md
index 2612540a..09fc2cad 100644
--- a/docs/manual/reference/sdk/fingerprint.md
+++ b/docs/manual/reference/sdk/fingerprint.md
@@ -66,7 +66,7 @@ Which pieces a fingerprint judges, when a project or workspace holds more than o
What an axis's head reads: the frames (SigLIP 2), how they change, their look, the sound (CLAP) or its events (YAMNet).
```ts
-type Modality = "picture" | "change" | "look" | "sound" | "events"
+type Modality = "picture" | "change" | "look" | "sound" | "events" | "text"
```
<!-- generated:end -->
diff --git a/sdk/raea/src/fingerprint.ts b/sdk/raea/src/fingerprint.ts
index 1034b987..4b2b0011 100644
--- a/sdk/raea/src/fingerprint.ts
+++ b/sdk/raea/src/fingerprint.ts
@@ -4,7 +4,7 @@
// default export (systems/fingerprint/src/taxonomy.rs), so these types follow its fields.
/** What an axis's head reads: the frames (SigLIP 2), how they change, their look, the sound (CLAP) or its events (YAMNet). */
-export type Modality = "picture" | "change" | "look" | "sound" | "events";
+export type Modality = "picture" | "change" | "look" | "sound" | "events" | "text";
export interface Axis {
/** Its name, short and lowercase (blur, clip, barren): what reports, marks and `--axis` call it. */
diff --git a/systems/columns/src/cache.rs b/systems/columns/src/cache.rs
index d75b2dbb..27592f5e 100644
--- a/systems/columns/src/cache.rs
+++ b/systems/columns/src/cache.rs
@@ -41,7 +41,7 @@ pub fn f32s(b: &[u8]) -> Vec<f32> {
}
pub fn save(c: &Columns) -> Result<()> {
- let cols = [&c.sig, &c.look, &c.clap, &c.yam, &c.level];
+ let cols = [&c.sig, &c.look, &c.clap, &c.yam, &c.level, &c.text];
let head = Head { media: c.media.clone(), dur: c.dur, step: STEP, lens: cols.iter().map(|v| v.len()).collect() };
let mut b = serde_json::to_vec(&head)?;
b.push(b'\n');
@@ -60,7 +60,8 @@ pub fn load(media: &str) -> Option<Columns> {
let b = std::fs::read(path(media)).ok()?;
let nl = b.iter().position(|&x| x == b'\n')?;
let head: Head = serde_json::from_slice(&b[..nl]).ok()?;
- if head.lens.len() != 5 || head.step != STEP {
+ // five columns before FP1b's text column, six since
+ if !(5..=6).contains(&head.lens.len()) || head.step != STEP {
return None;
}
let mut at = nl + 1;
@@ -80,5 +81,6 @@ pub fn load(media: &str) -> Option<Columns> {
clap: it.next()?,
yam: it.next()?,
level: it.next()?,
+ text: it.next().unwrap_or_default(),
})
}
diff --git a/systems/columns/src/clap_text.rs b/systems/columns/src/clap_text.rs
index 0bec8c2d..a4dcce0a 100644
--- a/systems/columns/src/clap_text.rs
+++ b/systems/columns/src/clap_text.rs
@@ -3,7 +3,7 @@
//! padding reaches the tower (its export takes no attention mask).
use crate::siglip::{Input, run};
-use anyhow::{Context, Result, anyhow};
+use anyhow::{Result, anyhow};
use ort::session::Session;
use std::path::Path;
@@ -14,8 +14,8 @@ pub struct Text {
impl Text {
pub fn load(file: &Path, tokenizer: &Path) -> Result<Text> {
- let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("CLAP's tokenizer: {e}"))?;
- Ok(Text { s: raea_sys_ml::session(file).context("CLAP's text tower")?, tok })
+ let (s, tok) = crate::text_model(file, tokenizer, "CLAP's text tower")?;
+ Ok(Text { s, tok })
}
/// Each text's vector, L2-normalised: [texts][512]
diff --git a/systems/columns/src/gemma.rs b/systems/columns/src/gemma.rs
new file mode 100644
index 00000000..ff7b6759
--- /dev/null
+++ b/systems/columns/src/gemma.rs
@@ -0,0 +1,57 @@
+//! EmbeddingGemma 2's text path (docs/fingerprint.feature FP1b): a script's, brief's or page's words into 768-d
+//! vectors, on ONNX Runtime's CPU kernels with the q8 weights the library already keeps in ~/.raea/models (850 MB,
+//! fetched once by the app's library or here). Its output matches transformers.js's, as the app's library runs it, to
+//! the fifth decimal (11-12). Documents get the model's own prefix, `title: none | text: ...`; an axis's words get the
+//! query prefix. No image or audio goes in: the media inputs are empty.
+
+use anyhow::{Result, anyhow};
+use ort::session::Session;
+use ort::value::Tensor;
+use std::path::Path;
+
+pub const DIM: usize = 768;
+/// The longest a passage is read, tokens; a longer one is cut
+const MOST: usize = 512;
+
+pub struct Text {
+ s: Session,
+ tok: tokenizers::Tokenizer,
+}
+
+/// A passage of a document, with its title, as the model reads documents
+pub fn as_document(text: &str, title: &str) -> String {
+ format!("title: {} | text: {text}", if title.is_empty() { "none".into() } else { title.replace('|', "/") })
+}
+
+/// An axis's words, as the model reads a query
+pub fn as_query(q: &str) -> String {
+ format!("task: search result | query: {q}")
+}
+
+impl Text {
+ pub fn load(model: &Path, tokenizer: &Path) -> Result<Text> {
+ crate::text_model(model, tokenizer, "EmbeddingGemma 2").map(|(s, tok)| Text { s, tok })
+ }
+
+ /// Each text's sentence embedding, normalised, DIM apiece
+ pub fn embed(&mut self, texts: &[String]) -> Result<Vec<f32>> {
+ let mut v = Vec::with_capacity(texts.len() * DIM);
+ for t in texts {
+ let e = self.tok.encode(t.as_str(), true).map_err(|e| anyhow!("tokenizing: {e}"))?;
+ let ids: Vec<i64> = e.get_ids().iter().take(MOST).map(|&i| i as i64).collect();
+ let n = ids.len();
+ let empty = || Tensor::<f32>::from_array(([0usize, 512], Vec::<f32>::new()));
+ let out = self.s.run(ort::inputs![
+ "input_ids" => Tensor::<i64>::from_array(([1usize, n], ids))?,
+ "attention_mask" => Tensor::<i64>::from_array(([1usize, n], vec![1i64; n]))?,
+ "image_features" => empty()?,
+ "video_features" => empty()?,
+ "audio_features" => empty()?,
+ ])?;
+ let (_, x) = out["sentence_embedding"].try_extract_tensor::<f32>()?;
+ v.extend_from_slice(&x[..DIM]);
+ }
+ crate::normalise(&mut v, DIM);
+ Ok(v)
+ }
+}
diff --git a/systems/columns/src/lib.rs b/systems/columns/src/lib.rs
index df5dad77..c1cf59fb 100644
--- a/systems/columns/src/lib.rs
+++ b/systems/columns/src/lib.rs
@@ -7,6 +7,7 @@
//! - look: luminance histogram, contrast, saturation, local contrast and sharpness per frame (look.rs)
//! - sound: CLAP htsat-unfused per 2 s window, 1 s hop (L2-normalised); YAMNet per 0.48 s when its model is here
//! - level: the sound's RMS in dBFS per 0.1 s, for checks, the sheet and the timeline
+//! - text: EmbeddingGemma 2 per passage of a script, brief or page (FP1b), a passage a step; a still is one frame
//!
//! Every encoder is ONNX on ONNX Runtime's CPU kernels (raea-sys-ml): never Core ML's GPU, which computes SigLIP wrong
//! on this Mac. The text towers (CLAP's, SigLIP's) only turn an axis's words into vectors (FP2e). Columns are cached by
@@ -16,6 +17,8 @@ pub mod cache;
mod clap;
mod clap_text;
pub mod damage;
+mod gemma;
+pub mod pieces;
pub mod look;
pub mod media;
pub mod models;
@@ -36,6 +39,7 @@ pub const YAM_HOP: f64 = 0.48;
pub const SIG: usize = 768;
pub const CLAP: usize = 512;
pub const YAM: usize = 1024;
+pub const TEXT: usize = gemma::DIM;
/// The column version: a change to how any column is made bumps it, and the cache makes them again
pub const STEP: u32 = 1;
@@ -50,6 +54,8 @@ pub struct Columns {
pub clap: Vec<f32>,
pub yam: Vec<f32>,
pub level: Vec<f32>,
+ /// one EmbeddingGemma 2 row per passage of a text piece (FP1b); empty for pictures and sound
+ pub text: Vec<f32>,
}
impl Columns {
@@ -66,6 +72,7 @@ pub struct Encoders {
yam: Option<yamnet::Yamnet>,
vision_text: Option<siglip::Text>,
clap_text: Option<clap_text::Text>,
+ gemma: Option<gemma::Text>,
}
impl Encoders {
@@ -77,12 +84,17 @@ impl Encoders {
Some(f) => Some(yamnet::Yamnet(raea_sys_ml::session(f).context("YAMNet")?)),
None => None,
};
- Ok(Encoders { files, vision, clap, yam, vision_text: None, clap_text: None })
+ Ok(Encoders { files, vision, clap, yam, vision_text: None, clap_text: None, gemma: None })
}
/// Each encoder's id and its file's sha256: a fingerprint's heads are pinned to these
pub fn pins(&self) -> std::collections::BTreeMap<String, String> {
- self.files.pins().into_iter().collect()
+ let mut p: std::collections::BTreeMap<String, String> = self.files.pins().into_iter().collect();
+ // EmbeddingGemma 2 is pinned once it's on this machine: a fingerprint made before it keeps working (FP1b)
+ if let Some((m, _)) = models::gemma_here() {
+ p.insert("embeddinggemma-2/model_quantized.onnx_data".into(), models::pin(&m.with_extension("onnx_data")));
+ }
+ p
}
/// A file's columns, from the cache when it has them
@@ -91,6 +103,21 @@ impl Encoders {
if let Some(c) = cache::load(&media) {
return Ok(c);
}
+ // a script, brief or page is read as passages; a still is one frame (FP1b)
+ if let Some(passages) = pieces::passages(file)? {
+ let title = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
+ let texts: Vec<String> = passages.iter().map(|p| gemma::as_document(p, &title)).collect();
+ let text = self.gemma()?.embed(&texts)?;
+ let c = Columns { media, dur: passages.len().max(1) as f64, text, ..Default::default() };
+ cache::save(&c)?;
+ return Ok(c);
+ }
+ if let Some(still) = pieces::still(file)? {
+ let (sig, look) = self.picture(&[still])?;
+ let c = Columns { media, dur: 1.0, sig, look, ..Default::default() };
+ cache::save(&c)?;
+ return Ok(c);
+ }
let dur = media::duration(file)?;
let frames = media::frames(file, FPS, 0.0, dur)?;
let (pcm16, pcm48) = (media::sound(file, 16_000)?, media::sound(file, clap::RATE)?);
@@ -104,7 +131,7 @@ impl Encoders {
pub fn of(&mut self, frames: &[media::Rgb], pcm16: &[f32], pcm48: &[f32], dur: f64) -> Result<Columns> {
let (sig, look) = self.picture(frames)?;
let (clap, yam) = self.sound(pcm16, pcm48)?;
- Ok(Columns { media: String::new(), dur, sig, look, clap, yam, level: media::levels(pcm16, 16_000) })
+ Ok(Columns { media: String::new(), dur, sig, look, clap, yam, level: media::levels(pcm16, 16_000), text: Vec::new() })
}
/// The picture columns of frames at FPS: SigLIP 2's pooled vectors and each frame's look
@@ -131,6 +158,21 @@ impl Encoders {
Ok((clap, yam))
}
+ /// EmbeddingGemma 2's text model, loaded on first use (fetched once when the app's library hasn't it)
+ fn gemma(&mut self) -> Result<&mut gemma::Text> {
+ if self.gemma.is_none() {
+ let (m, t) = models::gemma()?;
+ self.gemma = Some(gemma::Text::load(&m, &t)?);
+ }
+ Ok(self.gemma.as_mut().unwrap())
+ }
+
+ /// Words as EmbeddingGemma 2 query vectors (text axes, FP1b), one row each
+ pub fn words_text(&mut self, texts: &[String]) -> Result<Vec<f32>> {
+ let q: Vec<String> = texts.iter().map(|t| gemma::as_query(t)).collect();
+ self.gemma()?.embed(&q)
+ }
+
/// Words as CLAP text vectors (sound axes), L2-normalised, one row each
pub fn words_sound(&mut self, texts: &[String]) -> Result<Vec<f32>> {
if self.clap_text.is_none() {
@@ -160,6 +202,12 @@ impl Encoders {
}
/// `$var`, else `rel` under the home folder
+/// A text model's session and its tokenizer
+pub(crate) fn text_model(model: &Path, tokenizer: &Path, what: &str) -> Result<(ort::session::Session, tokenizers::Tokenizer)> {
+ let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow::anyhow!("{what}'s tokenizer: {e}"))?;
+ Ok((raea_sys_ml::session(model).context(what.to_string())?, tok))
+}
+
pub fn under(var: &str, rel: &str) -> PathBuf {
match std::env::var_os(var) {
Some(p) => p.into(),
diff --git a/systems/columns/src/models.rs b/systems/columns/src/models.rs
index 18eb1b83..17c91aef 100644
--- a/systems/columns/src/models.rs
+++ b/systems/columns/src/models.rs
@@ -36,6 +36,35 @@ const SIGLIP: Spec = Spec {
],
};
+/// EmbeddingGemma 2's text model (FP1b): the q8 export the app's library also runs
+const GEMMA: Spec = Spec {
+ name: "embeddinggemma-2",
+ files: &[
+ ("onnx-community/embeddinggemma-2-ONNX", "onnx/model_quantized.onnx", "model_quantized.onnx"),
+ ("onnx-community/embeddinggemma-2-ONNX", "onnx/model_quantized.onnx_data", "model_quantized.onnx_data"),
+ ("onnx-community/embeddinggemma-2-ONNX", "tokenizer.json", "tokenizer.json"),
+ ],
+};
+
+/// EmbeddingGemma 2's model and tokenizer where they already are: the app's library's copy (~/.raea/models), else
+/// raea's model cache
+pub fn gemma_here() -> Option<(PathBuf, PathBuf)> {
+ let lib = crate::under("RAEA_LIBRARY_MODELS", ".raea/models").join("onnx-community/embeddinggemma-2-ONNX");
+ let lib = (lib.join("onnx/model_quantized.onnx"), lib.join("tokenizer.json"));
+ let cached = raea_sys_ml::models::root().join(GEMMA.name);
+ let cached = (cached.join("model_quantized.onnx"), cached.join("tokenizer.json"));
+ [lib, cached].into_iter().find(|(m, t)| m.is_file() && m.with_extension("onnx_data").is_file() && t.is_file())
+}
+
+/// EmbeddingGemma 2's model and tokenizer, fetched once (850 MB) when neither copy is here
+pub fn gemma() -> Result<(PathBuf, PathBuf)> {
+ if let Some(h) = gemma_here() {
+ return Ok(h);
+ }
+ let d = ensure(&GEMMA, &mut say).context("EmbeddingGemma 2")?;
+ Ok((d.join("model_quantized.onnx"), d.join("tokenizer.json")))
+}
+
/// The encoders' files on this machine
#[derive(Clone, Debug)]
pub struct Files {
diff --git a/systems/columns/src/pieces.rs b/systems/columns/src/pieces.rs
new file mode 100644
index 00000000..568819d7
--- /dev/null
+++ b/systems/columns/src/pieces.rs
@@ -0,0 +1,105 @@
+//! The pieces that aren't video or sound (docs/fingerprint.feature FP1b): a script, brief or page is read as passages
+//! (one EmbeddingGemma 2 row each, a passage a step on the timeline), and a still is one frame through SigLIP 2.
+
+use anyhow::{Result, anyhow};
+use std::path::Path;
+
+/// Text a fingerprint reads as passages
+const TEXT: [&str; 6] = ["md", "txt", "fountain", "html", "htm", "brief"];
+/// Pictures a fingerprint reads as one frame
+const STILL: [&str; 4] = ["png", "jpg", "jpeg", "webp"];
+/// A passage longer than this many characters is split at its sentences
+const LONG: usize = 1200;
+
+fn ext(file: &Path) -> String {
+ match file.extension() {
+ Some(e) => e.to_string_lossy().to_lowercase(),
+ None => String::new(),
+ }
+}
+
+/// A text piece's passages, else None: paragraphs (blank-line separated), tags dropped from a page, long ones split
+pub fn passages(file: &Path) -> Result<Option<Vec<String>>> {
+ let e = ext(file);
+ let script = file.to_string_lossy().ends_with(".script.ts");
+ if !TEXT.contains(&e.as_str()) && !script {
+ return Ok(None);
+ }
+ let raw = std::fs::read_to_string(file).map_err(|x| anyhow!("{}: {x}", file.display()))?;
+ let raw = if e.starts_with("htm") { untag(&raw) } else { raw };
+ let mut out = Vec::new();
+ for p in raw.split("\n\n") {
+ let words: Vec<&str> = p.split_whitespace().collect();
+ if !words.is_empty() {
+ out.extend(split(&words.join(" ")));
+ }
+ }
+ if out.is_empty() {
+ return Err(anyhow!("{}: no words in it", file.display()));
+ }
+ Ok(Some(out))
+}
+
+/// A page's text: tags, scripts and styles dropped, block ends kept as paragraph breaks
+fn untag(html: &str) -> String {
+ let (mut out, mut tag, mut skip) = (String::new(), None::<String>, false);
+ for c in html.chars() {
+ match (&mut tag, c) {
+ (None, '<') => tag = Some(String::new()),
+ (Some(t), '>') => {
+ let name: String = t.trim_start_matches('/').chars().take_while(|c| c.is_alphanumeric()).collect::<String>().to_lowercase();
+ if name == "script" || name == "style" {
+ skip = !t.starts_with('/');
+ }
+ if ["p", "div", "h1", "h2", "h3", "h4", "li", "br", "section", "article", "tr"].contains(&name.as_str()) {
+ out.push_str("\n\n");
+ }
+ tag = None;
+ }
+ (Some(t), c) => t.push(c),
+ (None, c) if !skip => out.push(c),
+ _ => {}
+ }
+ }
+ out.replace("&nbsp;", " ").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'")
+}
+
+/// A long paragraph cut at sentence ends into pieces of at most LONG characters (a sentence longer stays whole)
+fn split(p: &str) -> Vec<String> {
+ if p.len() <= LONG {
+ return vec![p.to_string()];
+ }
+ let mut out = vec![String::new()];
+ for s in p.split_inclusive(['.', '!', '?']) {
+ let last = out.last_mut().unwrap();
+ if !last.is_empty() && last.len() + s.len() > LONG {
+ out.push(String::new());
+ }
+ out.last_mut().unwrap().push_str(s);
+ }
+ out.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
+}
+
+/// A still's one frame, squashed as video frames are, else None
+pub fn still(file: &Path) -> Result<Option<crate::media::Rgb>> {
+ if !STILL.contains(&ext(file).as_str()) {
+ return Ok(None);
+ }
+ let img = image::open(file).map_err(|x| anyhow!("{}: {x}", file.display()))?.to_rgba8();
+ Ok(Some(crate::media::squash(img.as_raw(), img.width() as usize, img.height() as usize)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_page_is_its_paragraphs_and_a_long_one_is_cut_at_sentences() {
+ let t = untag("<html><style>p{}</style><h1>Sunmelt</h1><p>Cold &amp; bright.</p><script>x()</script><p>Buy now</p></html>");
+ let p: Vec<String> = t.split("\n\n").map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect();
+ assert_eq!(p, ["Sunmelt", "Cold & bright.", "Buy now"]);
+ let long = "A short one. ".repeat(200);
+ let s = split(long.trim());
+ assert!(s.len() > 1 && s.iter().all(|x| x.len() <= LONG && x.ends_with('.')), "{:?}", s.iter().map(String::len).collect::<Vec<_>>());
+ }
+}
diff --git a/systems/columns/src/tests.rs b/systems/columns/src/tests.rs
index e73b0a90..ace63441 100644
--- a/systems/columns/src/tests.rs
+++ b/systems/columns/src/tests.rs
@@ -108,3 +108,25 @@ fn clap_bank_is_slaney() {
let p = clap::padded(&[1.0; 96_000]);
assert_eq!((p[383_999], p[384_000]), (1.0, 0.0), "four repeats of 2 s, then zeros (repeatpad)");
}
+
+/// FP1b on the real models: a script's passages get EmbeddingGemma 2 rows (each nearest the query its words answer, and
+/// the same vectors transformers.js gives for the first), a still gets one SigLIP 2 frame
+#[test]
+#[ignore]
+fn a_script_and_a_still_get_rows() {
+ let mut e = Encoders::load().unwrap();
+ let dir = std::env::temp_dir().join(format!("raea-pieces-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let script = dir.join("ad.md");
+ std::fs::write(&script, "INT. KITCHEN - MORNING\n\nShe opens the fridge and it's empty.\n\nBuy Sunmelt today: 20% off your first box.\n").unwrap();
+ let c = e.columns(&script).unwrap();
+ assert_eq!((c.text.len() / crate::TEXT, c.dur, c.sig.len()), (3, 3.0, 0));
+ let q = e.words_text(&["a call to action".into(), "a scene heading".into()]).unwrap();
+ let dot = |r: usize, k: usize| c.text[r * crate::TEXT..(r + 1) * crate::TEXT].iter().zip(&q[k * crate::TEXT..(k + 1) * crate::TEXT]).map(|(a, b)| a * b).sum::<f32>();
+ assert!(dot(2, 0) > dot(0, 0) && dot(0, 1) > dot(2, 1), "cta {} {} heading {} {}", dot(2, 0), dot(0, 0), dot(0, 1), dot(2, 1));
+ let still = dir.join("board.png");
+ image::RgbImage::from_fn(64, 48, |x, _| image::Rgb([x as u8 * 4, 90, 200])).save(&still).unwrap();
+ let s = e.columns(&still).unwrap();
+ assert_eq!((s.sig.len(), s.dur, s.text.len()), (crate::SIG, 1.0, 0));
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/systems/columns/src/window.rs b/systems/columns/src/window.rs
index 6b7955ac..f7a13357 100644
--- a/systems/columns/src/window.rs
+++ b/systems/columns/src/window.rs
@@ -6,9 +6,10 @@
//! - look: the frames' mean look and its largest frame-to-frame step per value: 32
//! - sound: the mean of the CLAP windows that start in the span (the nearest one when none does): 512
//! - events: YAMNet's mean over the span: 1024
+//! - text: EmbeddingGemma 2's mean over the passages in the span, a passage a second (FP1b): 768
use crate::look::LOOK;
-use crate::{CLAP, CLAP_HOP, Columns, FPS, SIG, YAM, YAM_HOP};
+use crate::{CLAP, CLAP_HOP, Columns, FPS, SIG, TEXT, YAM, YAM_HOP};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
@@ -19,10 +20,12 @@ pub enum Modality {
Look,
Sound,
Events,
+ Text,
}
impl Modality {
- pub const ALL: [Modality; 5] = [Modality::Picture, Modality::Change, Modality::Look, Modality::Sound, Modality::Events];
+ /// Text is last, so a row written before it is the same row with the text left empty (evidence.rs)
+ pub const ALL: [Modality; 6] = [Modality::Picture, Modality::Change, Modality::Look, Modality::Sound, Modality::Events, Modality::Text];
pub fn dim(self) -> usize {
match self {
Modality::Picture => SIG + 3,
@@ -30,6 +33,7 @@ impl Modality {
Modality::Look => 2 * LOOK,
Modality::Sound => CLAP,
Modality::Events => YAM,
+ Modality::Text => TEXT,
}
}
pub fn name(self) -> &'static str {
@@ -39,6 +43,7 @@ impl Modality {
Modality::Look => "look",
Modality::Sound => "sound",
Modality::Events => "events",
+ Modality::Text => "text",
}
}
}
@@ -99,6 +104,7 @@ pub fn features(c: &Columns, a: f64, b: f64, m: Modality) -> Vec<f32> {
mean(rows(&c.clap, CLAP, first, last), CLAP)
}
Modality::Events => mean(rows(&c.yam, YAM, (a / YAM_HOP) as usize, (b / YAM_HOP).ceil() as usize), YAM),
+ Modality::Text => mean(rows(&c.text, TEXT, a.floor() as usize, b.ceil() as usize), TEXT),
};
if v.len() == m.dim() { v } else { vec![0.0; m.dim()] }
}
diff --git a/systems/fingerprint/src/evidence.rs b/systems/fingerprint/src/evidence.rs
index f2dd7d41..d5af2069 100644
--- a/systems/fingerprint/src/evidence.rs
+++ b/systems/fingerprint/src/evidence.rs
@@ -10,6 +10,16 @@ use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::path::Path;
+/// Rows written before the text modality (FP1b) are as wide as every other modality: each is given an empty text
+/// slice at its end, where Text sits in Modality::ALL
+pub fn widen(feats: Vec<f32>, rows: usize) -> Vec<f32> {
+ let (w, old) = (width(), width() - Modality::Text.dim());
+ if rows == 0 || feats.len() == rows * w || feats.len() != rows * old {
+ return feats;
+ }
+ feats.chunks(old).flat_map(|r| r.iter().copied().chain(std::iter::repeat_n(0.0, w - old))).collect()
+}
+
/// Every modality's features, in Modality::ALL's order
pub fn width() -> usize {
Modality::ALL.iter().map(|m| m.dim()).sum()
@@ -97,7 +107,7 @@ impl Ledger {
}
let rows = std::fs::read_to_string(j)?.lines().filter(|l| !l.trim().is_empty()).map(serde_json::from_str).collect::<Result<Vec<Row>, _>>()?;
let raw = std::fs::read(f).unwrap_or_default();
- let feats = f32s(&raw);
+ let feats = widen(f32s(&raw), rows.len());
Ok(Ledger { rows, feats })
}
diff --git a/systems/fingerprint/src/folder.rs b/systems/fingerprint/src/folder.rs
index 4263621c..b7ab59bd 100644
--- a/systems/fingerprint/src/folder.rs
+++ b/systems/fingerprint/src/folder.rs
@@ -16,7 +16,7 @@ use crate::words::Words;
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::cache::{f16s, f32s};
use raea_sys_columns::window::Modality;
-use raea_sys_columns::{CLAP, SIG};
+use raea_sys_columns::{CLAP, SIG, TEXT};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -39,6 +39,8 @@ struct WordsHead {
axes: Vec<(String, Modality)>,
sound_vocab: usize,
picture_vocab: usize,
+ #[serde(default)]
+ text_vocab: usize,
made_from: Vec<String>,
/// the vocabulary's words in order, so a reader (the feed's fingerprint map) can name what a direction points at
#[serde(default)]
@@ -110,12 +112,17 @@ impl Folder {
};
let mut axes = Vec::new();
for (name, sp) in head.axes {
- let dim = if sp == Modality::Sound { CLAP } else { SIG };
+ let dim = match sp {
+ Modality::Sound => CLAP,
+ Modality::Text => TEXT,
+ _ => SIG,
+ };
axes.push((name, sp, take(dim)?));
}
let sound_vocab = (0..head.sound_vocab).map(|_| take(CLAP)).collect::<Option<Vec<_>>>()?;
let picture_vocab = (0..head.picture_vocab).map(|_| take(SIG)).collect::<Option<Vec<_>>>()?;
- Some(Words { axes, sound_vocab, picture_vocab, made_from: head.made_from })
+ let text_vocab = (0..head.text_vocab).map(|_| take(TEXT)).collect::<Option<Vec<_>>>()?;
+ Some(Words { axes, sound_vocab, picture_vocab, text_vocab, made_from: head.made_from })
}
pub fn write_words(&self, w: &Words) -> Result<()> {
@@ -123,11 +130,12 @@ impl Folder {
axes: w.axes.iter().map(|(n, sp, _)| (n.clone(), *sp)).collect(),
sound_vocab: w.sound_vocab.len(),
picture_vocab: w.picture_vocab.len(),
+ text_vocab: w.text_vocab.len(),
made_from: w.made_from.clone(),
sound_words: crate::taxonomy::SOUND_VOCAB.iter().take(w.sound_vocab.len()).map(|s| s.to_string()).collect(),
picture_words: crate::taxonomy::PICTURE_VOCAB.iter().take(w.picture_vocab.len()).map(|s| s.to_string()).collect(),
};
- let v: Vec<f32> = w.axes.iter().map(|a| &a.2).chain(&w.sound_vocab).chain(&w.picture_vocab).flatten().copied().collect();
+ let v: Vec<f32> = w.axes.iter().map(|a| &a.2).chain(&w.sound_vocab).chain(&w.picture_vocab).chain(&w.text_vocab).flatten().copied().collect();
std::fs::write(self.dir.join("words.json"), serde_json::to_vec_pretty(&head)?)?;
std::fs::write(self.dir.join("words.f16"), f16s(&v))?;
Ok(())
diff --git a/systems/fingerprint/src/taxonomy.rs b/systems/fingerprint/src/taxonomy.rs
index 605b7bff..3f5d8199 100644
--- a/systems/fingerprint/src/taxonomy.rs
+++ b/systems/fingerprint/src/taxonomy.rs
@@ -134,6 +134,15 @@ pub const SOUND_VOCAB: [&str; 40] = [
"a clean studio recording", "a voiceover", "a kitchen", "an airplane",
];
+/// Ordinary passages of scripts, briefs and pages, the background a text axis's words are scored against (FP1b)
+pub const TEXT_VOCAB: [&str; 24] = [
+ "a line of dialogue", "a scene heading", "a description of what the camera sees", "a voiceover line",
+ "a call to action", "a product's features", "a brand's tone of voice", "a target audience", "a deadline and deliverables",
+ "a shot list", "a song's lyrics", "a joke", "a question to the viewer", "a price and an offer", "a list of steps",
+ "a page's headline", "a navigation menu", "a paragraph of an article", "a quote from a customer", "legal small print",
+ "a caption", "a title card", "an instruction to the editor", "a mood and references",
+];
+
pub const PICTURE_VOCAB: [&str; 40] = [
"a person talking to the camera", "a city street at night", "a forest", "an ocean", "a mountain landscape", "an office",
"a kitchen", "a living room", "a car on a road", "a product on a table", "a phone screen", "a computer screen with an app",
@@ -147,6 +156,7 @@ pub const PICTURE_VOCAB: [&str; 40] = [
pub fn prompt(m: Modality, words: &str) -> String {
match m {
Modality::Sound | Modality::Events => format!("This is a sound of {words}."),
+ Modality::Text => words.to_string(),
_ => format!("a photo of {words}"),
}
}
diff --git a/systems/fingerprint/src/tests.rs b/systems/fingerprint/src/tests.rs
index 7447837f..d751d895 100644
--- a/systems/fingerprint/src/tests.rs
+++ b/systems/fingerprint/src/tests.rs
@@ -85,10 +85,11 @@ fn the_folder_keeps_heads_words_and_evidence() {
dir.write_ledger(&l).unwrap();
let back = dir.ledger().unwrap();
assert_eq!(back.rows.len(), 60);
- let w = Words { axes: vec![("noise".into(), Modality::Sound, vec![0.5; raea_sys_columns::CLAP])], sound_vocab: vec![vec![0.1; raea_sys_columns::CLAP]; 3], picture_vocab: vec![vec![0.2; raea_sys_columns::SIG]; 2], made_from: vec!["k".into()] };
+ let w = Words { axes: vec![("noise".into(), Modality::Sound, vec![0.5; raea_sys_columns::CLAP]), ("reads-buttons".into(), Modality::Text, vec![0.3; raea_sys_columns::TEXT])], sound_vocab: vec![vec![0.1; raea_sys_columns::CLAP]; 3], picture_vocab: vec![vec![0.2; raea_sys_columns::SIG]; 2], text_vocab: vec![vec![0.4; raea_sys_columns::TEXT]; 4], made_from: vec!["k".into()] };
dir.write_words(&w).unwrap();
let w2 = dir.words().unwrap();
- assert_eq!((w2.axes.len(), w2.sound_vocab.len(), w2.picture_vocab.len(), w2.made_from.clone()), (1, 3, 2, vec!["k".to_string()]));
+ assert_eq!((w2.axes.len(), w2.sound_vocab.len(), w2.picture_vocab.len(), w2.text_vocab.len(), w2.made_from.clone()), (2, 3, 2, 4, vec!["k".to_string()]));
+ assert_eq!(w2.axes[1].2.len(), raea_sys_columns::TEXT, "a text axis's words keep EmbeddingGemma 2's width");
let t = train(&fp, &back, &w2);
let blur = t.heads.iter().find(|h| h.axis == "blur").unwrap();
assert_eq!(blur.held_out, Some(1.0), "{}", blur.why);
diff --git a/systems/fingerprint/src/train.rs b/systems/fingerprint/src/train.rs
index 27cdd045..0ed58db2 100644
--- a/systems/fingerprint/src/train.rs
+++ b/systems/fingerprint/src/train.rs
@@ -88,6 +88,7 @@ fn limits(m: Modality) -> Vec<String> {
Modality::Look => "whether a look was meant (a stylised grade reads as a defect)".into(),
Modality::Change => "whether stillness or a cut was meant".into(),
Modality::Sound | Modality::Events => "which sound in a mix it means, or whether it was meant".into(),
+ Modality::Text => "how the words play once they're read aloud or shot".into(),
});
v
}
diff --git a/systems/fingerprint/src/words.rs b/systems/fingerprint/src/words.rs
index 88564f8f..fe5c6858 100644
--- a/systems/fingerprint/src/words.rs
+++ b/systems/fingerprint/src/words.rs
@@ -3,10 +3,10 @@
//! space, picture and look axes in SigLIP 2's. The words are embedded when they change and stored in the fingerprint
//! (words.json and words.f16); the text towers never run at score time. A word head is always advice (FP2d).
-use crate::taxonomy::{Fingerprint, PICTURE_VOCAB, SOUND_VOCAB, prompt};
+use crate::taxonomy::{Fingerprint, PICTURE_VOCAB, SOUND_VOCAB, TEXT_VOCAB, prompt};
use anyhow::Result;
use raea_sys_columns::window::{Modality, mean};
-use raea_sys_columns::{CLAP, Encoders, SIG};
+use raea_sys_columns::{CLAP, Encoders, SIG, TEXT};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -15,6 +15,9 @@ pub struct Words {
pub axes: Vec<(String, Modality, Vec<f32>)>,
pub sound_vocab: Vec<Vec<f32>>,
pub picture_vocab: Vec<Vec<f32>>,
+ /// EmbeddingGemma 2's vectors of TEXT_VOCAB, for text axes (FP1b); empty while no axis reads text
+ #[serde(default)]
+ pub text_vocab: Vec<Vec<f32>>,
/// the axis words the vectors were made from, so a change is seen
pub made_from: Vec<String>,
}
@@ -25,6 +28,7 @@ pub fn space(m: Modality) -> Option<Modality> {
Modality::Sound | Modality::Events => Some(Modality::Sound),
Modality::Picture | Modality::Look => Some(Modality::Picture),
Modality::Change => None,
+ Modality::Text => Some(Modality::Text),
}
}
@@ -48,14 +52,21 @@ impl Words {
let pv: Vec<String> = PICTURE_VOCAB.iter().map(|w| prompt(Modality::Picture, w)).collect();
let s = enc.words_sound(&sv)?;
let p = enc.words_picture(&pv)?;
+ // the text space only once an axis reads text, so a fingerprint of pictures and sound never fetches its model
+ let reads_text = f.axes.iter().any(|a| a.word_head && a.modality == Modality::Text);
+ let t = if reads_text { enc.words_text(&TEXT_VOCAB.iter().map(|w| w.to_string()).collect::<Vec<_>>())? } else { Vec::new() };
let mut axes = Vec::new();
for a in f.axes.iter().filter(|a| a.word_head) {
let Some(sp) = space(a.modality) else { continue };
let texts: Vec<String> = a.words.iter().map(|w| prompt(sp, w)).collect();
- let v = if sp == Modality::Sound { mean(&enc.words_sound(&texts)?, CLAP) } else { mean(&enc.words_picture(&texts)?, SIG) };
+ let v = match sp {
+ Modality::Sound => mean(&enc.words_sound(&texts)?, CLAP),
+ Modality::Text => mean(&enc.words_text(&texts)?, TEXT),
+ _ => mean(&enc.words_picture(&texts)?, SIG),
+ };
axes.push((a.name.clone(), sp, v));
}
- Ok(Words { axes, sound_vocab: s.chunks(CLAP).map(<[f32]>::to_vec).collect(), picture_vocab: p.chunks(SIG).map(<[f32]>::to_vec).collect(), made_from: key(f) })
+ Ok(Words { axes, sound_vocab: s.chunks(CLAP).map(<[f32]>::to_vec).collect(), picture_vocab: p.chunks(SIG).map(<[f32]>::to_vec).collect(), text_vocab: t.chunks(TEXT).map(<[f32]>::to_vec).collect(), made_from: key(f) })
}
/// The window's vector in the space of `sp`, from its row features (every modality)
@@ -78,7 +89,15 @@ impl Words {
pub fn z_of(&self, axis: &str, w: &[f32]) -> Option<f32> {
let (_, sp, v) = self.axes.iter().find(|a| a.0 == axis)?;
let dot = |a: &[f32]| a.iter().zip(w).map(|(x, y)| x * y).sum::<f32>();
- let bg: Vec<f32> = (if *sp == Modality::Sound { &self.sound_vocab } else { &self.picture_vocab }).iter().map(|b| dot(b)).collect();
+ let vocab = match sp {
+ Modality::Sound => &self.sound_vocab,
+ Modality::Text => &self.text_vocab,
+ _ => &self.picture_vocab,
+ };
+ let bg: Vec<f32> = vocab.iter().map(|b| dot(b)).collect();
+ if bg.is_empty() {
+ return None;
+ }
let m = bg.iter().sum::<f32>() / bg.len() as f32;
let sd = (bg.iter().map(|x| (x - m).powi(2)).sum::<f32>() / bg.len() as f32).sqrt().max(1e-6);
Some((dot(v) - m) / sd)
@@ -91,7 +110,11 @@ impl Words {
if w.iter().all(|x| *x == 0.0) {
return None;
}
- let (vocab, names): (&Vec<Vec<f32>>, &[&'static str]) = if sp == Modality::Sound { (&self.sound_vocab, &SOUND_VOCAB) } else { (&self.picture_vocab, &PICTURE_VOCAB) };
+ let (vocab, names): (&Vec<Vec<f32>>, &[&'static str]) = match sp {
+ Modality::Sound => (&self.sound_vocab, &SOUND_VOCAB),
+ Modality::Text => (&self.text_vocab, &TEXT_VOCAB),
+ _ => (&self.picture_vocab, &PICTURE_VOCAB),
+ };
let best = vocab.iter().enumerate().map(|(i, b)| (i, b.iter().zip(&w).map(|(x, y)| x * y).sum::<f32>())).max_by(|a, b| a.1.total_cmp(&b.1))?;
names.get(best.0).copied()
}