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.

DR28: text-read, raea's reading check. A render now gives each text an Ocr (what Apple Vision reads in its box on that frame, and the share of its words), from frames decoded once in order (runtime/world pixels.rs), which also measure each text's contrast without an ffmpeg call a text a frame. OCR reads a box fast first, then the text's line across the frame and the box accurately where fast misses a word (a lone short word reads as well upside down), and a crop that holds still but for a video's coding noise isn't read again: the manual's title example checks in 2.5 s from no record. text-read gives each text on, visible (in the frame, at an opacity, size and contrast that read, covered by no layer past a share) and read; holds its reading time (0.3 s a word, at least a second, none for a caption said as it shows) to visible, saying which frames were lost and why; and calls text that can be read where OCR doesn't read it broken (an error past 3 frames; read on under half: a warn). raea check runs it on every composition's newest render as raea's own rule, where it holds the floor's reading rule; what it couldn't measure (OCR off the Mac, covers without --layers) is a note. A word is matched by one key everywhere (core/facts word_key: letters and digits, lower case), which the floor's caption-against-voice rule now shares. bench/direction/read: a caption and five cheats, all as expected. The scenario's plan now gives pixels.rs 240 lines and read.rs 270 (planned 170 and 230): the fast and accurate reads, the still-frame reuse and saying lost frames in groups took more than planned.

shinyobjectz060380ead5b2
diff --git a/Cargo.lock b/Cargo.lock
index d2fef105..45c02a2e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15138,8 +15138,10 @@ version = "0.1.0"
dependencies = [
"bevy",
"flate2",
+ "image",
"raea-core-facts",
"raea-core-scene",
+ "raea-io-media",
"raea-runtime-bake",
"raea-runtime-bundle",
"raea-runtime-page",
@@ -15147,6 +15149,7 @@ dependencies = [
"raea-runtime-scene",
"raea-sys-layers",
"raea-sys-measure",
+ "raea-sys-vision",
"serde_json",
"sha2 0.10.9",
]
diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs
index debd10f5..4ffee128 100644
--- a/apps/check/src/lib.rs
+++ b/apps/check/src/lib.rs
@@ -127,9 +127,12 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
/// raea's floor on a video (`args` as raea check takes them) as Findings, printed and kept nowhere: `raea check
/// EDIT.tsx` runs it on the composition's newest render beside its other checks (apps/direction, DR4). `held`: the
/// rules of the named checks it measures on the video itself (loudness, still-max), each its form, value and line.
-pub fn floor(args: &[String], held: &[(&'static str, f64, String)]) -> R<Vec<Finding>> {
+/// `without`: its own rules that a named check holds there instead (`reading`, which text-read holds against when
+/// a text can be read, not when it's on: DR28).
+pub fn floor(args: &[String], held: &[(&'static str, f64, String)], without: &[&str]) -> R<Vec<Finding>> {
let held = held.iter().map(|(form, value, line)| Taste { form: *form, value: *value, line: line.clone() }).collect();
- let (_, issues, _, fps) = measured(args, held)?;
+ let (_, mut issues, _, fps) = measured(args, held)?;
+ issues.retain(|i| without.iter().all(|w| *w != i.rule));
Ok(findings_of(issues, Vec::new(), fps))
}
diff --git a/apps/check/src/text.rs b/apps/check/src/text.rs
index cd23a72d..966cc156 100644
--- a/apps/check/src/text.rs
+++ b/apps/check/src/text.rs
@@ -232,9 +232,7 @@ pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
Ok(raea_core_facts::transcript_words(&v, fps))
}
-pub(crate) fn norm(s: &str) -> String {
- s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
-}
+pub(crate) use raea_core_facts::word_key as norm;
pub(crate) const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rs
index 32dd6c74..2a9b0b03 100644
--- a/apps/direction/src/check.rs
+++ b/apps/direction/src/check.rs
@@ -77,7 +77,9 @@ enum How {
/// Every rule `project` is held to (`given`: `--taste`'s files), and a finding for each file of rules raea couldn't
/// read.
fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
- let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea")];
+ // raea's own: the floor, and the reading check (DR28: its findings keep their own levels, so no rule level)
+ let read = Rule { level: None, ..Rule::named("text-read", "text can be read for as long as it needs, and OCR reads it", Default::default(), Level::Warn, "raea") };
+ let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea"), read];
let mut bad = Vec::new();
let name = |f: &Path| f.strip_prefix(project).unwrap_or(f).display().to_string();
for f in tastes(project, given, host) {
@@ -164,7 +166,10 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
asked.sort();
asked.dedup();
// the render joins the first frame (what it is, or that there is none) and where a TS check needs it
- let join_all = hows.iter().any(|(_, h)| matches!(h, How::File(m) if m.render && m.frames.whole()));
+ let join_all = hows.iter().any(|(_, h)| match h {
+ How::File(m) => m.render && m.frames.whole(),
+ How::Named(n) => n.render && n.frames.whole(),
+ });
let join_on = (!join_all).then(|| hows.iter().flat_map(|(_, h)| match h { How::File(m) if m.render => if let Frames::At(v) = &m.frames { v.clone() } else { vec![] }, _ => vec![] }).chain([0]).collect());
let render_how = match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
(Some(o), _) => Render::From(o.into()),
@@ -195,6 +200,8 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
held.push((n.name, r.number("value").unwrap_or(if n.name == "loudness" { -14.0 } else { 3.0 }), r.text.clone()));
bys.push(r.by.clone());
}
+ "text-read" if rendered.is_none() => needs(&mut waits, r),
+ "text-read" => found.extend(crate::read::read(r, &worlds)),
_ => found.extend(systems::text(r, &worlds)),
}
}
@@ -202,7 +209,9 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
match &rendered {
Some(r) if is_video(r["out"].as_str().unwrap_or("")) => {
let a = [r["out"].as_str().unwrap_or("").to_string(), "--manifest".into(), r["manifest"].as_str().unwrap_or("").to_string()];
- for mut f in raea_app_check::floor(&a, &held)? {
+ // where text-read runs, the floor's own reading rule (held against when a text is on) is its
+ let without: &[&str] = if hows.iter().any(|(_, h)| matches!(h, How::Named(n) if n.name == "text-read")) { &["reading"] } else { &[] };
+ for mut f in raea_app_check::floor(&a, &held, without)? {
match held.iter().position(|h| h.0 == f.check) {
Some(k) => f.by = bys[k].clone(),
None if !floor => continue,
@@ -211,8 +220,8 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
found.push(f);
}
}
- Some(_) => waits.extend(hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render)).map(|(r, _)| (r.id.clone(), "a video render (its render is stills)".to_string()))),
- None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render)).for_each(|(r, _)| needs(&mut waits, r)),
+ Some(_) => waits.extend(hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).map(|(r, _)| (r.id.clone(), "a video render (its render is stills)".to_string()))),
+ None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
}
}
// the project's own checks, in one run
diff --git a/apps/direction/src/lib.rs b/apps/direction/src/lib.rs
index 19fc533c..349d0789 100644
--- a/apps/direction/src/lib.rs
+++ b/apps/direction/src/lib.rs
@@ -15,3 +15,5 @@ pub mod findings;
pub mod check;
pub mod systems;
pub mod ts;
+// text-read: each text's reading time held to when it can be read, and what OCR reads of it (DR28)
+pub mod read;
diff --git a/apps/direction/src/read.rs b/apps/direction/src/read.rs
new file mode 100644
index 00000000..8047ebc0
--- /dev/null
+++ b/apps/direction/src/read.rs
@@ -0,0 +1,243 @@
+//! `text-read`, raea's reading check (docs/direction.feature DR28). Each text on screen is given three times: the
+//! frames it is in the world (`on`), the frames it can be read on (`visible`: in the frame, at an opacity, size and
+//! contrast against what is behind it that can be read, and covered by no other layer past a share), and the frames
+//! OCR reads its words on (`read`, the render's Ocr). Its reading time is held against `visible`, not `on`: a text
+//! faded in over half its time, or behind a part for some of it, has less time to be read than it is up, and the
+//! finding says which frames were lost and why. A text that can be read where OCR doesn't read it is broken. raea
+//! check runs it on every composition's newest render with no rule asking for it, as raea's own, beside the floor.
+
+use std::collections::BTreeMap;
+
+use raea_core_facts::{Contrast, Covers, Facts, Finding, Layer, Level, Line, Ocr, Rule, Text, word_key as norm};
+
+use crate::systems::{ident, quote};
+
+/// Frames OCR may miss inside what it reads before that's a fault (a word dropped for a frame or two, as textread's
+/// GAP allows).
+const GAP: usize = 3;
+
+/// What the check holds a text to, each a value its rule may change: seconds a word (`word`) and at least (`least`),
+/// as the floor's reading rule; the least opacity, letter height (px at 1080 on the short side) and contrast that can
+/// be read; the most of it another layer may cover; the share of its words OCR must read.
+struct Limits {
+ word: f64,
+ least: f64,
+ opacity: f64,
+ size: f64,
+ contrast: f64,
+ covered: f64,
+ share: f64,
+}
+
+impl Limits {
+ fn of(rule: &Rule) -> Limits {
+ let v = |n: &str, d: f64| rule.number(n).unwrap_or(d);
+ Limits { word: v("word", 0.3), least: v("least", 1.0), opacity: v("opacity", 0.5), size: v("size", 24.0), contrast: v("contrast", 3.0), covered: v("covered", 0.5), share: v("share", 0.5) }
+ }
+}
+
+/// One frame a text is on: why it can't be read there (None: it can), whether OCR read it (None: OCR didn't run),
+/// and what OCR read.
+struct Seen {
+ frame: i64,
+ lost: Option<String>,
+ read: Option<bool>,
+ ocr: String,
+}
+
+/// A text across the frames: its words, its layer key, the largest it's set, and each frame it's on.
+struct Track {
+ words: String,
+ key: Option<String>,
+ size: f64,
+ seen: Vec<Seen>,
+}
+
+/// An entity's opacity: its own layer's, else its nearest parent's.
+fn opacity(w: &Facts, mut e: u32) -> f64 {
+ loop {
+ if let Some(l) = w.get::<Layer>(e) {
+ return l.opacity;
+ }
+ match w.entities.get(e as usize).and_then(|x| x.parent) {
+ Some(p) => e = p,
+ None => return 1.0,
+ }
+ }
+}
+
+/// Why a text can't be read on this frame (`covered`: the most of it one layer covers), or None.
+fn lost(w: &Facts, e: u32, t: &Text, l: &Limits, covered: f64) -> Option<String> {
+ if let Some(b) = t.box_ {
+ let inside = |a: f64, z: f64| (z.min(1.0) - a.max(0.0)).max(0.0);
+ let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1e-9);
+ if inside(b[0], b[2]) * inside(b[1], b[3]) / area < 0.9 {
+ return Some("partly off the frame".into());
+ }
+ }
+ let o = opacity(w, e);
+ if o < l.opacity {
+ return Some(format!("at {:.0}% opacity", o * 100.0));
+ }
+ if let Some(s) = t.size.filter(|s| *s < l.size) {
+ return Some(format!("{s:.0} px high"));
+ }
+ // covered before contrast: what covers it is what its pixels then measure against
+ if covered > l.covered {
+ return Some(format!("{:.0}% covered", covered * 100.0));
+ }
+ w.get::<Contrast>(e).filter(|c| c.ratio < l.contrast).map(|c| format!("{:.1}:1 against what's behind it", c.ratio))
+}
+
+/// The words said or sung over the piece, each with its start in seconds.
+fn said(worlds: &[Facts]) -> Vec<(String, f64)> {
+ let Some(w) = worlds.iter().find(|w| !w.find(&["Line"]).is_empty()) else { return Vec::new() };
+ w.find(&["Line"]).iter().filter_map(|e| w.get::<Line>(e.id)).flat_map(|l| l.words).map(|x| (norm(&x.text), x.start)).collect()
+}
+
+/// Runs of frames one after another in `frames` (sorted), each [first, the frame after its last).
+fn runs(frames: impl IntoIterator<Item = i64>) -> Vec<[i64; 2]> {
+ let mut out: Vec<[i64; 2]> = Vec::new();
+ for f in frames {
+ match out.last_mut() {
+ Some(r) if r[1] == f => r[1] = f + 1,
+ _ => out.push([f, f + 1]),
+ }
+ }
+ out
+}
+
+/// Runs closer than `gap` frames to the one before, joined.
+fn joined(runs: Vec<[i64; 2]>, gap: i64) -> Vec<[i64; 2]> {
+ let mut out: Vec<[i64; 2]> = Vec::new();
+ for r in runs {
+ match out.last_mut() {
+ Some(p) if r[0] - p[1] < gap => p[1] = r[1],
+ _ => out.push(r),
+ }
+ }
+ out
+}
+
+/// A number of frames as a person reads it: "2 frames" under a tenth of a second, else seconds.
+fn span(frames: i64, fps: f64) -> String {
+ match frames {
+ 1 => "1 frame".into(),
+ n if (n as f64) < 0.1 * fps => format!("{n} frames"),
+ n => format!("{:.1} s", n as f64 / fps),
+ }
+}
+
+/// "frames 10-22 at 20% opacity; frames 30-41 60% covered": the frames of [from, to) lost, grouped by why (three
+/// groups at most); a frame it isn't drawn on is "not shown".
+fn why_lost(from: i64, to: i64, seen: &[&Seen]) -> String {
+ let mut groups: Vec<([i64; 2], &str)> = Vec::new();
+ for f in from..to {
+ let why = match seen.iter().find(|s| s.frame == f) {
+ Some(s) => match s.lost.as_deref() {
+ Some(w) => w,
+ None => continue,
+ },
+ None => "not shown",
+ };
+ match groups.last_mut() {
+ Some((r, w)) if r[1] == f && *w == why => r[1] = f + 1,
+ _ => groups.push(([f, f + 1], why)),
+ }
+ }
+ let shown: Vec<String> = groups.iter().take(3).map(|([a, b], w)| if b - a == 1 { format!("frame {a} {w}") } else { format!("frames {a}-{} {w}", b - 1) }).collect();
+ let more = groups.len().saturating_sub(3);
+ format!("{}{}", shown.join("; "), if more > 0 { format!("; and {more} more") } else { String::new() })
+}
+
+/// The check's findings over `worlds` (every frame of the composition, in order, with its render joined).
+pub fn read(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {
+ let l = Limits::of(rule);
+ let Some(fps) = worlds.first().map(|w| w.fps) else { return Vec::new() };
+ let lvl = |d: Level| rule.level.unwrap_or(d);
+ let mut tracks: BTreeMap<String, Track> = BTreeMap::new();
+ // what wasn't measured, and what it waits for
+ let mut waits: BTreeMap<String, String> = BTreeMap::new();
+ for w in worlds {
+ for c in ["Ocr", "Covers"] {
+ if let Some(why) = w.resources.get("Waits").and_then(|v| v.get(c)).and_then(|v| v.as_str()) {
+ waits.entry(c.to_string()).or_insert_with(|| why.to_string());
+ }
+ }
+ // the most of each layer one other layer covers
+ let mut covered: BTreeMap<u32, f64> = BTreeMap::new();
+ for e in w.find(&["Covers"]) {
+ for c in w.get::<Covers>(e.id).map(|c| c.0).unwrap_or_default() {
+ let s = covered.entry(c.layer).or_default();
+ *s = s.max(c.share);
+ }
+ }
+ for e in w.find(&["Text"]) {
+ let Some(t) = w.get::<Text>(e.id) else { continue };
+ let (id, key) = ident(w, e.id, &t);
+ let lost = lost(w, e.id, &t, &l, covered.get(&e.id).copied().unwrap_or(0.0));
+ let ocr = w.get::<Ocr>(e.id);
+ let tr = tracks.entry(id).or_insert_with(|| Track { words: t.words.clone(), key, size: 0.0, seen: Vec::new() });
+ // a text laid out with no size known is held as a caption
+ tr.size = tr.size.max(t.size.unwrap_or(f64::INFINITY));
+ tr.seen.push(Seen { frame: w.frame, lost, read: ocr.as_ref().map(|o| o.share >= l.share), ocr: ocr.map(|o| o.words).unwrap_or_default() });
+ }
+ }
+ let said = said(worlds);
+ let mut out = Vec::new();
+ // a text that leaves and comes back within half a second is one text that blinks, not two
+ let blink = (0.5 * fps).round() as i64;
+ for tr in tracks.values().filter(|t| t.size >= l.size) {
+ for [from, to] in joined(runs(tr.seen.iter().map(|s| s.frame)), blink) {
+ let seen: Vec<&Seen> = tr.seen.iter().filter(|s| (from..to).contains(&s.frame)).collect();
+ let at = |f: Finding| f.about(tr.words.clone(), tr.key.clone());
+ let q = quote(&tr.words);
+ // the time it needs to be read, against the time it can be: a caption the voice says as it shows needs none
+ let n = tr.words.split_whitespace().count();
+ let need = (l.word * n as f64).max(l.least);
+ let can_frames = seen.iter().filter(|s| s.lost.is_none()).count() as i64;
+ let can = can_frames as f64 / fps;
+ let (a, b) = (from as f64 / fps, to as f64 / fps);
+ let tokens: Vec<String> = tr.words.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
+ let spoken = !tokens.is_empty() && tokens.iter().all(|t| said.iter().any(|(w, s)| w == t && *s >= a - 0.3 && *s <= b + 0.1));
+ if can + 0.05 < need && !spoken {
+ let says = if can_frames == 0 {
+ format!("{q} is up {} but can't be read on any frame of it ({}); {n} words need {need:.1} s", span(to - from, fps), why_lost(from, to, &seen))
+ } else if can_frames < to - from {
+ format!("{q} is up {} but can be read for {} ({}); {n} words need {need:.1} s", span(to - from, fps), span(can_frames, fps), why_lost(from, to, &seen))
+ } else {
+ format!("{q} is on for {}; {n} words need {need:.1} s", span(to - from, fps))
+ };
+ out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("readable", (can * 10.0).round() / 10.0, "s", Some((need * 10.0).round() / 10.0)));
+ }
+ // what can be read and OCR doesn't read is broken; a word with fewer than two letters or digits isn't held
+ if norm(&tr.words).chars().count() < 2 {
+ continue;
+ }
+ let judged: Vec<&&Seen> = seen.iter().filter(|s| s.lost.is_none() && s.read.is_some()).collect();
+ let unread: Vec<[i64; 2]> = runs(judged.iter().filter(|s| s.read == Some(false)).map(|s| s.frame)).into_iter().filter(|[a, b]| (b - a) as usize > GAP).collect();
+ for [ua, ub] in &unread {
+ let got = judged.iter().find(|s| s.frame == *ua).map_or("", |s| s.ocr.as_str());
+ let heard = if got.trim().is_empty() { "OCR reads nothing in its box".to_string() } else { format!("OCR reads {} in its box", quote(got)) };
+ let says = format!("{q} can be read on frames {ua}-{} and OCR doesn't read it there ({heard}): it's broken", ub - 1);
+ out.push(at(Finding::new(&rule.id, lvl(Level::Error), says, &rule.by)).frames(*ua, *ub).fix("set it so it reads: a face, weight, size or treatment OCR reads, and nothing drawn through it"));
+ }
+ let read = judged.iter().filter(|s| s.read == Some(true)).count();
+ if unread.is_empty() && !judged.is_empty() && read * 2 < judged.len() {
+ let says = format!("{q} is read by OCR on {read} of the {} frames it can be read on", judged.len());
+ out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("read", read as f64, "frames", Some(judged.len() as f64 / 2.0)));
+ }
+ }
+ }
+ // what it didn't see, said
+ if let Some(why) = waits.get("Ocr") {
+ out.push(Finding::new(&rule.id, Level::Note, format!("no text was held to what OCR reads: OCR waits for {why}"), &rule.by));
+ }
+ if let Some(why) = waits.get("Covers") {
+ out.push(Finding::new(&rule.id, Level::Note, format!("what covers each text wasn't counted: it waits for {why}"), &rule.by));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/direction/src/read/tests.rs b/apps/direction/src/read/tests.rs
new file mode 100644
index 00000000..1107bfc5
--- /dev/null
+++ b/apps/direction/src/read/tests.rs
@@ -0,0 +1,98 @@
+use super::*;
+use raea_core_facts::{Medium, Waits, Word};
+
+/// A caption of `words` on 60 frames at 30 fps: frame f at `opacity(f)`, read by OCR at `share(f)` (None: OCR
+/// didn't run), 40 px high in the middle of the frame, 7:1 against its ground.
+fn caption(words: &str, opacity: impl Fn(i64) -> f64, share: impl Fn(i64) -> Option<f64>) -> Vec<Facts> {
+ (0..60)
+ .map(|f| {
+ let mut w = Facts::new(f, 1080, 1920, 30.0);
+ let e = w.spawn(None);
+ w.put(e, &Text { words: words.into(), font: None, size: Some(40.0), box_: Some([0.1, 0.45, 0.9, 0.5]), extruded: 0.0, lines: Some(1), needs: None });
+ w.put(e, &Layer { medium: Medium::Type2d, order: 1, opacity: opacity(f), blend: None });
+ w.put(e, &Contrast { ratio: 7.0 });
+ match share(f) {
+ Some(s) => w.put(e, &Ocr { words: if s > 0.0 { words.into() } else { String::new() }, share: s }),
+ None => w.set(&Waits([("Ocr".to_string(), "OCR (on the Mac)".to_string())].into())),
+ }
+ w
+ })
+ .collect()
+}
+
+fn rule() -> Rule {
+ Rule { level: None, ..Rule::named("text-read", "", Default::default(), Level::Warn, "raea") }
+}
+
+#[test]
+fn a_caption_up_long_enough_that_ocr_reads_holds() {
+ assert!(read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0))).is_empty());
+ // OCR dropping it for a frame or two isn't a fault
+ let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f == 20 || f == 21 { 0.0 } else { 1.0 })));
+ assert!(found.is_empty(), "{found:?}");
+}
+
+#[test]
+fn reading_time_is_held_to_the_frames_it_can_be_read_on() {
+ // up 2 s, but under half opacity for its first 40 frames: 0.7 s to read seven words
+ let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0)));
+ assert_eq!(found.len(), 1, "{found:?}");
+ assert_eq!((found[0].level, found[0].frames), (Level::Warn, Some([0, 60])));
+ assert!(found[0].says.contains("is up 2.0 s but can be read for 0.7 s (frames 0-39 at 20% opacity); 7 words need 2.1 s"), "{}", found[0].says);
+ // the frames it couldn't be read on aren't held to OCR
+ let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |f| Some(if f < 40 { 0.0 } else { 1.0 })));
+ assert_eq!(found.len(), 1, "{found:?}");
+}
+
+#[test]
+fn a_caption_said_as_it_shows_needs_no_reading_time() {
+ let mut worlds = caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0));
+ for w in &mut worlds {
+ let l = w.spawn(None);
+ let words = "one two three four five six seven".split(' ').enumerate().map(|(i, t)| Word { text: t.into(), start: 0.2 * i as f64, end: 0.2 * i as f64 + 0.15 }).collect();
+ w.put(l, &Line { text: "one two three four five six seven".into(), from: 0.0, to: Some(2.0), words, needs: None });
+ }
+ assert!(read(&rule(), &worlds).is_empty());
+}
+
+#[test]
+fn text_that_can_be_read_and_that_ocr_doesnt_read_is_broken() {
+ let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(0.0)));
+ assert_eq!(found.len(), 1, "{found:?}");
+ assert_eq!((found[0].level, found[0].frames), (Level::Error, Some([0, 60])));
+ assert!(found[0].says.contains("can be read on frames 0-59 and OCR doesn't read it there (OCR reads nothing in its box): it's broken"), "{}", found[0].says);
+ // read on a frame here and there, never long enough to be a broken run: a warn
+ let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f % 3 == 0 { 1.0 } else { 0.0 })));
+ assert_eq!(found.len(), 1, "{found:?}");
+ assert_eq!(found[0].level, Level::Warn);
+ assert!(found[0].says.contains("is read by OCR on 20 of the 60 frames it can be read on"), "{}", found[0].says);
+}
+
+#[test]
+fn what_it_did_not_measure_it_says() {
+ let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| None));
+ assert_eq!(found.len(), 1, "{found:?}");
+ assert_eq!(found[0].level, Level::Note);
+ assert!(found[0].says.contains("OCR waits for OCR (on the Mac)"), "{}", found[0].says);
+}
+
+#[test]
+fn small_type_and_a_lone_mark_arent_held() {
+ let mut worlds = caption("x", |_| 1.0, |_| Some(0.0));
+ assert!(read(&rule(), &worlds).is_empty(), "one letter: nothing for OCR to read, and a second is enough");
+ for w in &mut worlds {
+ w.put(0, &Text { words: "a label in the corner".into(), font: None, size: Some(12.0), box_: Some([0.0, 0.0, 0.2, 0.02]), extruded: 0.0, lines: Some(1), needs: None });
+ }
+ assert!(read(&rule(), &worlds).is_empty(), "under 24 px: not a caption");
+}
+
+#[test]
+fn a_text_that_blinks_is_one_text_up_the_whole_time() {
+ // drawn on one frame in ten: one finding over all of it, its frames off said as not shown
+ let worlds: Vec<Facts> = caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0)).into_iter().map(|w| if w.frame % 10 == 0 { w } else { Facts::new(w.frame, 1080, 1920, 30.0) }).collect();
+ let found = read(&rule(), &worlds);
+ assert_eq!(found.len(), 1, "{found:?}");
+ assert_eq!(found[0].frames, Some([0, 51]));
+ let says = "is up 1.7 s but can be read for 0.2 s (frames 1-9 not shown; frames 11-19 not shown; frames 21-29 not shown; and 2 more); 4 words need 1.2 s";
+ assert!(found[0].says.contains(says), "{}", found[0].says);
+}
diff --git a/apps/direction/src/systems.rs b/apps/direction/src/systems.rs
index 4c46a1e9..4ee6b042 100644
--- a/apps/direction/src/systems.rs
+++ b/apps/direction/src/systems.rs
@@ -78,11 +78,12 @@ pub fn named() -> Vec<Named> {
n("loudness", true, Frames::Once, "the mix is at its loudness"),
n("still-max", true, Frames::Once, "the picture is never still for too long"),
n("floor", true, Frames::Once, "raea's floor: what every finished piece must meet"),
+ n("text-read", true, Frames::All, "text on screen can be read for as long as it needs, and OCR reads what can be read (read.rs)"),
]
}
/// A text's identity across frames: its layer key, else its words.
-fn ident(f: &Facts, e: u32, t: &Text) -> (String, Option<String>) {
+pub(crate) fn ident(f: &Facts, e: u32, t: &Text) -> (String, Option<String>) {
let key = f.get::<Source>(e).and_then(|s| s.key);
(key.clone().unwrap_or_else(|| t.words.clone()), key)
}
@@ -127,7 +128,7 @@ fn runs(worlds: &[Facts], bad: impl Fn(&Facts, &Text) -> Option<f64>, worse: fn(
done
}
-fn quote(s: &str) -> String {
+pub(crate) fn quote(s: &str) -> String {
let s: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
if s.chars().count() > 40 { format!("\"{}…\"", s.chars().take(39).collect::<String>()) } else { format!("\"{s}\"") }
}
diff --git a/bench/direction/read/broken.tsx b/bench/direction/read/broken.tsx
new file mode 100644
index 00000000..1f04fe24
--- /dev/null
+++ b/bench/direction/read/broken.tsx
@@ -0,0 +1,13 @@
+// DR28's proof, text that's there and can be seen but can't be read: the caption mirrored. It's up for 3 s at full
+// opacity, large and dark on light, so it passes every measure but OCR, and text-read must call it broken.
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+
+function Broken() {
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#222", transform: "scaleX(-1)" }}>Fresh bread every morning</div>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="broken" component={Broken} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/read/camo.tsx b/bench/direction/read/camo.tsx
new file mode 100644
index 00000000..2439e9af
--- /dev/null
+++ b/bench/direction/read/camo.tsx
@@ -0,0 +1,13 @@
+// DR28's proof, a cheat: the caption is up for its full 3 s, set in nearly the colour of the ground behind it.
+// text-read must fail it: against its pixels it can't be read.
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+
+function Camo() {
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#e9dcc8" }}>Fresh bread every morning</div>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="camo" component={Camo} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/read/covered.tsx b/bench/direction/read/covered.tsx
new file mode 100644
index 00000000..5426c191
--- /dev/null
+++ b/bench/direction/read/covered.tsx
@@ -0,0 +1,15 @@
+// DR28's proof, a cheat: the caption is up for its full 3 s, but a panel sits over it for the first 2.5 s. text-read
+// must fail it (rendered with --layers, so what covers it is counted): it can be read for half a second.
+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
+
+function Covered() {
+ const frame = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#222" }}>Fresh bread every morning</div>
+ {frame < 75 ? <div style={{ position: "absolute", left: 40, top: 400, width: 460, height: 160, background: "#3b6e8f" }} /> : null}
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="covered" component={Covered} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/read/faded.tsx b/bench/direction/read/faded.tsx
new file mode 100644
index 00000000..a12bb1fe
--- /dev/null
+++ b/bench/direction/read/faded.tsx
@@ -0,0 +1,13 @@
+// DR28's proof, a cheat: the caption is up for its full 3 s, but at an opacity no one can read. text-read must fail
+// it: the time it can be read is none of the time it's on.
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+
+function Faded() {
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#222", opacity: 0.12 }}>Fresh bread every morning</div>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="faded" component={Faded} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/read/flicker.tsx b/bench/direction/read/flicker.tsx
new file mode 100644
index 00000000..3e98a218
--- /dev/null
+++ b/bench/direction/read/flicker.tsx
@@ -0,0 +1,14 @@
+// DR28's proof, a cheat: the caption is in the piece for its full 3 s, but shows on one frame in ten. text-read must
+// fail it: nine frames are not enough to read four words.
+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
+
+function Flicker() {
+ const frame = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#222", opacity: frame % 10 === 0 ? 1 : 0 }}>Fresh bread every morning</div>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="flicker" component={Flicker} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/read/proof.sh b/bench/direction/read/proof.sh
new file mode 100644
index 00000000..fddfd3bf
--- /dev/null
+++ b/bench/direction/read/proof.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# DR28's proof (docs/direction.feature): raea's reading check, text-read, on a caption that holds it and on the
+# scenario's cheats, each of which must fail it: the reading time met at an opacity no one can read (faded), the
+# text the colour of what's behind it (camo), the text behind something for most of its time (covered), the text
+# shown on a frame here and there (flicker); and text that can be seen but that OCR can't read (broken, mirrored),
+# which is an error. Each piece is rendered with --layers, so what covers a text is counted, and a case passes only
+# when text-read measured everything it holds (no note saying what it waits for). Every case runs in a copy.
+#
+# RAEA_BIN=path/to/raea bash bench/direction/read/proof.sh
+set -uo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+raea=${RAEA_BIN:-raea}
+work=$(mktemp -d "${TMPDIR:-/tmp}/raea-dr28-proof.XXXXXX")
+# KEEP=1 keeps the copy (its renders, logs and record) and says where
+if [ -n "${KEEP:-}" ]; then trap 'echo "proof: kept $work"' EXIT; else trap 'rm -rf "$work"' EXIT; fi
+cp -R "$here/." "$work/"
+mkdir -p "$work/.raea" "$work/out"
+: >"$work/.raea/project"
+cd "$work" || exit 2
+
+bad=0
+# PIECE WANT: render it, then `raea check PIECE.tsx --only text-read`: WANT none finds nothing, warn finds a warn
+# and no error, error finds an error; every finding is shown
+case_() {
+ local p=$1 want=$2 out code
+ if ! "$raea" render "$p.tsx" -o "out/$p.mp4" --layers >"out/$p.render.log" 2>&1; then
+ echo "FAIL $p: raea render failed: $(tail -3 "out/$p.render.log")"
+ bad=$((bad + 1))
+ return
+ fi
+ out=$("$raea" check "$p.tsx" --only text-read --json 2>"out/$p.err")
+ code=$?
+ if [ $code -eq 2 ] || ! jq -e .compositions >/dev/null 2>&1 <<<"$out"; then
+ echo "FAIL $p: raea check couldn't check it (exit $code): $(tail -3 "out/$p.err") $(head -c 300 <<<"$out")"
+ bad=$((bad + 1))
+ return
+ fi
+ local n e w notes waits ok=1
+ n=$(jq '[.compositions[].findings[]] | length' <<<"$out")
+ e=$(jq '[.compositions[].findings[] | select(.level == "error")] | length' <<<"$out")
+ w=$(jq '[.compositions[].findings[] | select(.level == "warn")] | length' <<<"$out")
+ notes=$(jq '[.compositions[].findings[] | select(.level == "note")] | length' <<<"$out")
+ waits=$(jq -r '[.compositions[].waits[] | "\(.rule) waits for \(.for)"] | join("; ")' <<<"$out")
+ case $want in
+ none) [ "$n" -eq 0 ] || ok=0 ;;
+ warn) { [ "$w" -gt 0 ] && [ "$e" -eq 0 ]; } || ok=0 ;;
+ error) [ "$e" -gt 0 ] || ok=0 ;;
+ esac
+ { [ "$notes" -ne 0 ] || [ -n "$waits" ]; } && ok=0
+ [ $ok -eq 1 ] || bad=$((bad + 1))
+ printf '%s %s (want %s): %s error, %s warn, %s note%s\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$p" "$want" "$e" "$w" "$notes" "${waits:+, $waits}"
+ jq -r '.compositions[].findings[] | " \(.level) \(.frames // "" | tostring): \(.says)"' <<<"$out"
+}
+
+case_ read none
+case_ faded warn
+case_ camo warn
+case_ covered warn
+case_ flicker warn
+case_ broken error
+
+if [ $bad -eq 0 ]; then echo "proof: every case as expected"; else echo "proof: $bad case(s) wrong"; fi
+exit $((bad > 0))
diff --git a/bench/direction/read/read.tsx b/bench/direction/read/read.tsx
new file mode 100644
index 00000000..1daf51db
--- /dev/null
+++ b/bench/direction/read/read.tsx
@@ -0,0 +1,13 @@
+// DR28's proof, the caption as it should be: dark on a light ground, up for 3 s, nothing over it. text-read finds
+// nothing: it can be read on every frame it's on, for longer than its four words need, and OCR reads it.
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+
+function Read() {
+ return (
+ <AbsoluteFill style={{ background: "#f4e9d8" }}>
+ <div style={{ position: "absolute", left: 60, top: 420, width: 420, fontSize: 44, fontWeight: 700, color: "#222" }}>Fresh bread every morning</div>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => <Composition id="read" component={Read} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/core/facts/src/components.rs b/core/facts/src/components.rs
index d40852bf..28c2b5f8 100644
--- a/core/facts/src/components.rs
+++ b/core/facts/src/components.rs
@@ -243,7 +243,7 @@ pub fn declarations() -> Vec<String> {
let cfg = Config::default().with_large_int("number");
macro_rules! decls { ($($t:ty),*) => { vec![$(format!("export {}", <$t as TS>::decl(&cfg))),*] }; }
use crate::rendered::*;
- decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, Contrast, Picture, Onset, Covered, Covers, Mix, Rendered, Waits, crate::Level, crate::About, crate::Measure, crate::Finding)
+ decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, Contrast, Ocr, Picture, Onset, Covered, Covers, Mix, Rendered, Waits, crate::Level, crate::About, crate::Measure, crate::Finding)
}
#[cfg(test)]
diff --git a/core/facts/src/lib.rs b/core/facts/src/lib.rs
index c95930dd..b70c66dc 100644
--- a/core/facts/src/lib.rs
+++ b/core/facts/src/lib.rs
@@ -7,7 +7,7 @@ pub mod components;
pub use components::*;
pub mod words;
-pub use words::transcript_words;
+pub use words::{transcript_words, word_key};
pub mod finding;
pub use finding::{About, Finding, Level, Measure};
diff --git a/core/facts/src/rendered.rs b/core/facts/src/rendered.rs
index c4f20adb..7e4da24d 100644
--- a/core/facts/src/rendered.rs
+++ b/core/facts/src/rendered.rs
@@ -12,6 +12,14 @@ pub struct Contrast {
pub ratio: f64,
}
+/// What OCR reads in a text's box on this frame of the render (DR28: Apple Vision's text recognition, on the Mac): the
+/// words it read there, and the share of the text's own words among them (0 to 1).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Ocr {
+ pub words: String,
+ pub share: f64,
+}
+
/// The picture's light and movement: its mean luma (0 to 1) and the mean change from the frame before (0 to 1; None
/// with no frame before it rendered). As a resource, this frame's; on a Shot, the mean over its frames rendered,
/// counted in `frames`.
@@ -65,4 +73,4 @@ pub struct Rendered {
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
pub struct Waits(pub BTreeMap<String, String>);
-crate::components::component!(Contrast, Picture, Onset, Covers, Mix, Rendered, Waits);
+crate::components::component!(Contrast, Ocr, Picture, Onset, Covers, Mix, Rendered, Waits);
diff --git a/core/facts/src/words.rs b/core/facts/src/words.rs
index 3cb3e0cb..6204872e 100644
--- a/core/facts/src/words.rs
+++ b/core/facts/src/words.rs
@@ -22,6 +22,12 @@ pub fn transcript_words(v: &Value, fps: f64) -> Vec<Word> {
.collect()
}
+/// A word as raea matches words (a caption's against what is said, what OCR read against a text's): its letters and
+/// digits, lower case.
+pub fn word_key(s: &str) -> String {
+ s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/docs/direction.feature b/docs/direction.feature
index f4606ed7..4f85e938 100644
--- a/docs/direction.feature
+++ b/docs/direction.feature
@@ -653,8 +653,37 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
And `raea stage review sound` posts the mix with its cues marked on a waveform under the strip
And every post an agent makes ends with what it did not watch in motion and did not hear
- @needs:DR2,DR4
+ @needs:DR2,DR4 @done
Scenario: DR28. Text on screen is timed by when it can be read, and text that can't be read is broken
+ # Status 11-10: built. A render's frames are read once, in order (runtime/world pixels.rs: a video by raea's own
+ # decoders, a still by its file), and each Text on each frame gets its Contrast and an Ocr (core/facts
+ # rendered.rs: the words Apple Vision reads in its box, and the share of its own words among them). OCR reads the
+ # box fast first; where that misses a word, it reads the text's line across the frame accurately, then the box
+ # (a short word alone reads as well upside down: the manual's title example's "you" was "nof"). What it read is
+ # kept in the render's manifest, so a second check reads nothing again, and a crop that is the picture last read
+ # in its place but for coding noise (2 of 255 between still frames of an H.264 render) isn't read again.
+ # text-read (apps/direction read.rs) runs on every composition's newest render as one of raea's own rules, holds
+ # each text's reading time to the frames it can be read on, says which were lost and why (off the frame, opacity,
+ # size, covered, contrast, not shown), and calls more than 3 frames in a row that can be read and that OCR
+ # doesn't read broken: an error. A text OCR reads on under half its frames is a warn; what it couldn't measure
+ # is a note.
+ # The proof, bench/direction/read/proof.sh (release binary, M5 Pro; nothing downloaded): a caption that holds (0
+ # findings) and five cheats, each 540x960 and 3 s, rendered with --layers. Faded (12% opacity): "can't be read on
+ # any frame of it (frames 0-89 at 12% opacity)". Camo (the colour of its ground): "1.1:1 against what's behind
+ # it". Covered (a panel over it until frame 75): "can be read for 0.5 s (frames 0-74 100% covered)". Flicker (on
+ # one frame in ten): one warn, "is up 2.7 s but can be read for 0.3 s". Broken (mirrored): the error, "OCR reads
+ # "pnimnom" in its box". Six cases, all as expected. The manual's title and hello examples check clean, in 2.5 s
+ # and 1.8 s from no record (212 and 88 OCR reads).
+ # Found and fixed on the way: the title's lone "you" (above); a covered text blamed on its contrast (covers are
+ # judged first now); a flicker said as nine findings of "0.0 s" (runs a blink apart are one text).
+ # Proved by tests in raea-app-direction (16), raea-runtime-world (15), raea-core-facts (11: the generated TS
+ # types match), raea-app-check (27), raea-sys-vision (2), and the proof.
+ # Not seen, or left: of the proof I looked at a contact sheet of each case's frames; none was watched in motion,
+ # and nothing here has sound. Off the Mac, OCR waits and the report says so (Open, below). 3D type has no box in
+ # the world yet, so its OCR reads the whole frame. What covers a text is known only from a render made with
+ # --layers; without one, covers aren't judged and that is a note. The first checks of the title took 28-36 s
+ # while other work was running on the Mac; I couldn't make that happen again (2.5 s each time since, including
+ # the first check after a new build), so its cause isn't known.
# Shane, 11-10, verbatim: "also q coupel notes we need to maintain too. we need to automatically measure reading
# time of text on screen and note how long its actually visible including chekcign if its visible in OCR. if
# text exists and is visible and has no ocr its broken."
@@ -663,7 +692,12 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
# it while it is visible; (4) text that is there and visible but that OCR doesn't read is an error; (5) these
# are kept: they run on every render, every round. Not asked: a new reading speed (craft/floor.md's 0.3 s a
# word, a second at least, stays the check's value), a change to any piece's text, or a check of spelling.
- Given a render (every render has its manifest and findings, DR2 and DR3), of 2D or 3D text (Text, either medium)
+ Given the plan
+ | crate | file | lines | job |
+ | raea-core-facts | core/facts/src/rendered.rs | 90 | Ocr: what OCR reads in a text's box on a frame of the render, and the share of its words |
+ | raea-runtime-world | runtime/world/src/pixels.rs | 240 | the render's frames decoded once, in order: a text's contrast, and what OCR reads in its box |
+ | raea-app-direction | apps/direction/src/read.rs | 270 | text-read: on, visible and read for each text; reading time against visible; visible and unread is broken |
+ And a render (every render has its manifest and findings, DR2 and DR3), of 2D or 3D text (Text, either medium)
Then each Text is given three times, in seconds: `on` (the frames it is in the world: today's "held"), `visible`
(the frames it is in the frame, at an opacity, size and contrast against what is behind it that can be
read, and covered by no other layer past a share, DR2's Covers) and `read` (the frames on which OCR reads its
@@ -676,6 +710,12 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Source and the frames; a run OCR reads on less than half its visible frames is a warn (OCR drops a word for a
frame or two, as textread's GAP allows)
And it is a named raea check (DR4) run on every render with no flag, so it holds every round (DR7)
+ # Fixed in the code (DR28): "run on every render" is `raea check` running text-read on each composition's newest
+ # render as one of raea's own rules, beside the floor, with no rule or flag asking; `raea render` itself doesn't
+ # OCR its frames. A render's own findings are what its drawing knows (clipping, exposure), and every harness render
+ # (P26's rows, a review's tiles) would pay for OCR it never reads. DR7 runs `raea check` with every round, which is
+ # what makes it hold every round. Where text-read runs, the floor's own reading rule (held against `on`) is its,
+ # so one line isn't said twice by two measures; `raea check VIDEO.mp4`, with no composition, keeps the floor's.
And its cheats fail it: the reading time met by holding the text at an opacity no one can read; the text the
colour of what's behind it; the text behind a part for most of its time; the text visible only on a frame
here and there
diff --git a/docs/manual/reference/cli/check.md b/docs/manual/reference/cli/check.md
index f6d20f11..f9272f9b 100644
--- a/docs/manual/reference/cli/check.md
+++ b/docs/manual/reference/cli/check.md
@@ -32,6 +32,12 @@ composition: raea's floor on its newest render, your taste's measurable lines, a
the project's controllers. A rule is a controller field of type `rule`: its words, and the check that holds it,
either one of raea's by name with its values or a `.ts` check of your own.
+raea's reading check, `text-read`, runs on the newest render too, with nothing asking for it. Each text's reading
+time (0.3 s a word, at least a second) is held to the frames it can be read on (in the frame, at an opacity, size and
+contrast that read, and not covered), not the frames it's on, and the finding says which frames were lost and why.
+Text that can be read where OCR doesn't read it is an error: it's broken. Render with `--layers` so what covers a
+text is counted.
+
```ts
// controllers/rules.ts
{ label: "Captions clear the button band", type: "rule", check: "../checks/caption.ts", values: { band: 0.8 } }
diff --git a/docs/manual/reference/sdk/check.md b/docs/manual/reference/sdk/check.md
index 1dcd2a4e..ed5e1814 100644
--- a/docs/manual/reference/sdk/check.md
+++ b/docs/manual/reference/sdk/check.md
@@ -11,8 +11,8 @@ components, so one check reads the same for any of them. It finds entities, meas
thing that breaks its line; it never prints. A rule in a project's controller names it by its path, with its values,
and [`raea check`](../cli/check.md) runs it on every composition, on the frames it says it ranges over. A check that
reads what only a render has (`needs: "render"`) waits for one, and says so. raea's own checks are the same thing
-written in Rust, under the names `text-hold`, `text-above`, `text-below`, `text-margin`, `loudness`, `still-max` and
-`floor`.
+written in Rust, under the names `text-hold`, `text-above`, `text-below`, `text-margin`, `loudness`, `still-max`,
+`text-read` and `floor`.
```ts
// controllers/rules.ts holds the rule:
@@ -37,7 +37,7 @@ export default check({ id: "caption", text: "a caption clears the platform's but
import { check, declared, found, runChecks } from "raea/check"
```
-`raea/check` exports 5 functions, 1 class, 31 types. Source: [sdk/raea/src/check.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/check.ts).
+`raea/check` exports 5 functions, 1 class, 32 types. Source: [sdk/raea/src/check.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/check.ts).
## Functions
@@ -272,6 +272,12 @@ type Medium = "2d-type" | "2d-graphic" | "3d" | "footage" | "page"
type Mix = { lufs?: number, peak?: number, }
```
+### `Ocr`
+
+```ts
+type Ocr = { words: string, share: number, }
+```
+
### `Onset`
```ts
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index 4d5bbe08..5c5aeed5 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -92,7 +92,7 @@ Checks, lints and a headless App you can drive.
| Import | What it's for | Exports |
| --- | --- | --- |
-| [`raea/check`](check.md) | A check written as a system over a composition's world: what `raea check` runs for a rule a controller holds. | 5 functions, 1 class, 31 types |
+| [`raea/check`](check.md) | A check written as a system over a composition's world: what `raea check` runs for a rule a controller holds. | 5 functions, 1 class, 32 types |
| [`raea/dev_tools`](dev_tools.md) | Checks and lints you can run from code: a motion performance's lint report. | 2 functions, 3 types |
| [`raea/remote`](remote.md) | A headless Bevy App you open, step and query from TypeScript, through Bevy's remote protocol. | 1 class, 1 type |
diff --git a/runtime/world/Cargo.toml b/runtime/world/Cargo.toml
index 9b6a35b3..daa8c192 100644
--- a/runtime/world/Cargo.toml
+++ b/runtime/world/Cargo.toml
@@ -18,6 +18,10 @@ raea-runtime-page = { path = "../page" }
raea-sys-layers = { path = "../../systems/layers" }
# what a render's output measures, joined to the world (DR2), and its layers file read
raea-sys-measure = { path = "../../systems/measure" }
+# the render's frames decoded once (a text's contrast, what OCR reads: DR28), its stills read, and OCR itself
+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"
diff --git a/runtime/world/src/lib.rs b/runtime/world/src/lib.rs
index 7b2b1d15..df649e62 100644
--- a/runtime/world/src/lib.rs
+++ b/runtime/world/src/lib.rs
@@ -5,6 +5,7 @@
mod covers;
mod page;
+mod pixels;
mod renders;
mod scene;
mod source;
diff --git a/runtime/world/src/pixels.rs b/runtime/world/src/pixels.rs
new file mode 100644
index 00000000..c59ce091
--- /dev/null
+++ b/runtime/world/src/pixels.rs
@@ -0,0 +1,217 @@
+//! The render's frames as pixels (docs/direction.feature DR28), decoded once and in order as the worlds are read, for
+//! what is measured in a text's box: its contrast against what is behind it (raea-sys-measure's ratio, as `raea check`
+//! takes it), and what OCR reads there (Apple Vision's text recognition, systems/vision text_lines). A crop the same
+//! as one read before isn't read again, nor one that is the picture last read in its place but for a video's coding
+//! noise, so a text that holds still over a still ground is read once for all its frames. Off the Mac, OCR waits: the
+//! portable OCR fetches its models, and that download is asked for first.
+
+use std::collections::HashMap;
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::path::Path;
+
+use raea_core_facts::Ocr;
+use raea_io_media::{Frame, VideoDecoder};
+use raea_sys_measure as measure;
+
+/// What OCR waits for where it can't run.
+#[cfg(not(target_vendor = "apple"))]
+pub(crate) const OCR_OFF: &str = "OCR (Apple Vision on the Mac; elsewhere the portable OCR's models, asked for once)";
+
+/// A line OCR read, with its box (0 to 1 of the crop: x, y, w, h).
+type Line = (String, [f64; 4]);
+
+/// How far apart two pictures of one still thing can be, in any channel, and be the same picture: a video's coding
+/// noise is up to 2 of 255 between frames that hold still (measured on an H.264 render of a settled title).
+const NOISE: u8 = 4;
+
+/// A render's pictures: a video's decoder, opened when first asked, or its still files; the last frame decoded; what
+/// OCR read in each crop it was given, by the crop's pixels; and the pixels each place was last read from (by its crop
+/// and how it was read), with the last frame it was asked for on.
+#[derive(Default)]
+pub(crate) struct Pixels {
+ video: Option<Box<dyn VideoDecoder>>,
+ last: Option<(usize, Frame)>,
+ read: HashMap<u64, Vec<Line>>,
+ held: HashMap<([u32; 4], bool), (usize, Vec<u8>, Vec<Line>)>,
+}
+
+/// Whether two crops' pixels are one picture, but for coding noise.
+fn same(a: &[u8], b: &[u8]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= NOISE)
+}
+
+/// A text's words as OCR is held to them: letters and digits, lower case, one word each.
+pub(crate) fn words_of(s: &str) -> Vec<String> {
+ s.split_whitespace().map(raea_core_facts::word_key).filter(|w| !w.is_empty()).collect()
+}
+
+/// The share of `words` that OCR's `lines` hold (two words OCR ran together still count).
+pub(crate) fn share(words: &str, lines: &[String]) -> f64 {
+ let want = words_of(words);
+ if want.is_empty() {
+ return 0.0;
+ }
+ let got: String = lines.iter().flat_map(|l| words_of(l)).collect::<Vec<_>>().join(" ");
+ let joined: String = got.split(' ').collect();
+ let has = |w: &String| got.split(' ').any(|g| g == w) || joined.contains(w.as_str());
+ want.iter().filter(|w| has(w)).count() as f64 / want.len() as f64
+}
+
+/// `bx` (0 to 1 of the frame: x0, y0, x1, y1) in a `w`x`h` frame's pixels, grown by `pad` of its height on each side
+/// (at least `least` px) and kept inside the frame: x, y, w, h. None when nothing of it is in the frame.
+pub(crate) fn crop_of(bx: [f64; 4], w: u32, h: u32, pad: f64, least: f64) -> Option<[u32; 4]> {
+ let (fw, fh) = (w as f64, h as f64);
+ let m = ((bx[3] - bx[1]) * fh * pad).max(least);
+ let x0 = (bx[0] * fw - m).max(0.0).floor();
+ let y0 = (bx[1] * fh - m).max(0.0).floor();
+ let x1 = (bx[2] * fw + m).min(fw).ceil();
+ let y1 = (bx[3] * fh + m).min(fh).ceil();
+ (x1 - x0 >= 2.0 && y1 - y0 >= 2.0).then(|| [x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32])
+}
+
+/// The RGBA pixels of `c` (x, y, w, h) in `f`.
+fn cut(f: &Frame, c: [u32; 4]) -> Vec<u8> {
+ let [x, y, w, h] = c.map(|v| v as usize);
+ let stride = f.width as usize * 4;
+ (y..y + h).flat_map(|row| f.rgba[row * stride + x * 4..row * stride + (x + w) * 4].iter().copied()).collect()
+}
+
+impl Pixels {
+ /// The `k`th frame drawn: a video's at `sec`, or the still at `file`.
+ fn frame(&mut self, k: usize, file: &Path, sec: f64, video: bool) -> Result<&Frame, String> {
+ if self.last.as_ref().is_none_or(|(at, _)| *at != k) {
+ let f = if video {
+ if self.video.is_none() {
+ let mut why = Vec::new();
+ for b in raea_io_media::preferred() {
+ match b.open_video(file) {
+ Ok(d) => {
+ self.video = Some(d);
+ break;
+ }
+ Err(e) => why.push(format!("{}: {e}", b.name())),
+ }
+ }
+ self.video.as_ref().ok_or_else(|| format!("{} can't be decoded ({})", file.display(), why.join("; ")))?;
+ }
+ self.video.as_mut().map(|d| d.frame_at(sec)).ok_or("no decoder")??
+ } else {
+ let img = image::open(file).map_err(|e| format!("{}: {e}", file.display()))?.to_rgba8();
+ Frame { pts: 0.0, width: img.width(), height: img.height(), rgba: img.into_raw() }
+ };
+ self.last = Some((k, f));
+ }
+ Ok(&self.last.as_ref().ok_or("no frame")?.1)
+ }
+
+ /// The contrast of the text of colour `color` drawn in `crop` (x, y, w, h in the composition's `size`) on the
+ /// `k`th frame, against what is behind it.
+ pub(crate) fn contrast(&mut self, (k, file, sec, video): (usize, &Path, f64, bool), crop: [f64; 4], size: (u32, u32), color: &str) -> Option<f64> {
+ let f = self.frame(k, file, sec, video).ok()?;
+ let (sx, sy) = (f.width as f64 / size.0 as f64, f.height as f64 / size.1 as f64);
+ let bx = [crop[0] * sx / f.width as f64, crop[1] * sy / f.height as f64, (crop[0] + crop[2]) * sx / f.width as f64, (crop[1] + crop[3]) * sy / f.height as f64];
+ let c = crop_of(bx, f.width, f.height, 0.0, 0.0)?;
+ let rgb: Vec<u8> = cut(f, c).chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
+ measure::ratio_behind(&rgb, measure::lum(measure::rgb_of(color)))
+ }
+
+ /// What OCR reads in `bx` (0 to 1 of the frame: x0, y0, x1, y1) on the `k`th frame, held to `words`; with no box
+ /// (3D type, which has none in the world yet), in the whole frame. Its box is read fast first; where that doesn't
+ /// read every word, its line is read accurately across the frame and what lies over it kept (a short word alone
+ /// reads as well upside down to OCR, "you" as "nof", and the words beside it set which way up it is), then its box
+ /// accurately. The best of them is what OCR read.
+ pub(crate) fn ocr(&mut self, at: (usize, &Path, f64, bool), bx: Option<[f64; 4]>, words: &str) -> Result<Option<Ocr>, String> {
+ let (w, h) = self.frame(at.0, at.1, at.2, at.3).map(|f| (f.width, f.height))?;
+ // a quarter of its height around it, so no letter is cut
+ let Some(c) = (match bx {
+ Some(b) => crop_of(b, w, h, 0.25, 6.0),
+ None => Some([0, 0, w, h]),
+ }) else {
+ return Ok(None);
+ };
+ let mut got: Vec<String> = self.lines_in(at, c, true)?.into_iter().map(|l| l.0).collect();
+ if let (Some(b), true) = (bx, share(words, &got) < 1.0) {
+ if let Some(band) = crop_of([0.0, b[1], 1.0, b[3]], w, h, 0.25, 6.0) {
+ // the band is the frame's width, so a line's x is the frame's: those over at least half of the text
+ let over = |l: &[f64; 4]| (l[0] + l[2]).min(b[2]) - l[0].max(b[0]) >= 0.5 * (b[2] - b[0]);
+ let wide: Vec<String> = self.lines_in(at, band, false)?.into_iter().filter(|l| over(&l.1)).map(|l| l.0).collect();
+ if share(words, &wide) > share(words, &got) {
+ got = wide;
+ }
+ }
+ }
+ if share(words, &got) < 1.0 {
+ // on a tie the accurate read is kept: what it says it read shows a person what is wrong with the text
+ let close: Vec<String> = self.lines_in(at, c, false)?.into_iter().map(|l| l.0).collect();
+ if share(words, &close) >= share(words, &got) {
+ got = close;
+ }
+ }
+ Ok(Some(Ocr { words: got.join(" "), share: (share(words, &got) * 100.0).round() / 100.0 }))
+ }
+
+ /// The lines OCR reads in crop `c` of the `k`th frame (fast, or accurately), each with its box, read once for each
+ /// crop's pixels, and not again while the picture in its place holds still.
+ fn lines_in(&mut self, (k, file, sec, video): (usize, &Path, f64, bool), c: [u32; 4], fast: bool) -> Result<Vec<Line>, String> {
+ let px = cut(self.frame(k, file, sec, video)?, c);
+ // a place not asked for on the frame before has stopped holding still
+ self.held.retain(|_, h| h.0 + 1 >= k);
+ if let Some(h) = self.held.get_mut(&(c, fast))
+ && same(&h.1, &px)
+ {
+ h.0 = k;
+ return Ok(h.2.clone());
+ }
+ let mut h = DefaultHasher::new();
+ (c[2], c[3], fast, &px).hash(&mut h);
+ let key = h.finish();
+ let got = match self.read.get(&key) {
+ Some(got) => got.clone(),
+ None => {
+ let got = lines(&px, c[2] as usize, c[3] as usize, fast)?;
+ self.read.insert(key, got.clone());
+ got
+ }
+ };
+ self.held.insert((c, fast), (k, px, got.clone()));
+ Ok(got)
+ }
+}
+
+#[cfg(target_vendor = "apple")]
+fn lines(rgba: &[u8], w: usize, h: usize, fast: bool) -> Result<Vec<Line>, String> {
+ Ok(raea_sys_vision::vision::text_lines_at(rgba, w, h, fast)?.into_iter().map(|(t, _, b)| (t, b)).collect())
+}
+
+#[cfg(not(target_vendor = "apple"))]
+fn lines(_: &[u8], _: usize, _: usize, _: bool) -> Result<Vec<Line>, String> {
+ Err(OCR_OFF.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_texts_words_are_read_when_ocr_holds_them_even_run_together() {
+ assert_eq!(share("Fresh bread, every morning", &["FRESH BREAD".into(), "everymorning".into()]), 1.0);
+ assert_eq!(share("Fresh bread, every morning", &["Fresh".into()]), 0.25);
+ assert_eq!(share("Fresh bread", &[]), 0.0);
+ assert_eq!(share("--", &["--".into()]), 0.0, "no word to read");
+ }
+
+ #[test]
+ fn a_crop_grows_round_its_box_and_stays_in_the_frame() {
+ // 0.1 of 1000 px high: a quarter of it, 25 px, each side
+ assert_eq!(crop_of([0.1, 0.5, 0.5, 0.6], 1000, 1000, 0.25, 6.0), Some([75, 475, 450, 150]));
+ assert_eq!(crop_of([0.9, 0.95, 1.2, 1.0], 100, 100, 0.0, 0.0), Some([90, 95, 10, 5]));
+ assert_eq!(crop_of([1.2, 0.5, 1.4, 0.6], 100, 100, 0.0, 0.0), None);
+ }
+
+ #[test]
+ fn a_picture_is_the_same_but_for_coding_noise() {
+ assert!(same(&[10, 200, 30, 255], &[12, 197, 30, 255]));
+ assert!(!same(&[10, 200, 30, 255], &[10, 190, 30, 255]), "a fade's step is a new picture");
+ assert!(!same(&[10, 200], &[10, 200, 0, 0]));
+ }
+}
diff --git a/runtime/world/src/renders.rs b/runtime/world/src/renders.rs
index f2beb922..3812fd95 100644
--- a/runtime/world/src/renders.rs
+++ b/runtime/world/src/renders.rs
@@ -2,14 +2,15 @@
//! its manifest beside its output (render.json: what each frame showed, as laid out); the world takes the newest of
//! the composition's renders in its project's record, or one it's given, and adds what only that render holds: each
//! text's contrast against its pixels, the frame's and each shot's light and movement, the mix's loudness, when each
-//! cue is heard, and, from a render with --layers, which layers cover which (covers.rs). Each is measured on the
-//! output when first asked for and kept in the manifest's "measured", so asking again reads it back. A world with no
-//! render, or a frame the render didn't draw, says what waits for one (`Waits`).
+//! cue is heard, what OCR reads in each text's box (DR28, pixels.rs), and, from a render with --layers, which layers
+//! cover which (covers.rs). Each is measured on the output when first asked for and kept in the manifest's
+//! "measured", so asking again reads it back. A world with no render, or a frame the render didn't draw, says what
+//! waits for one (`Waits`).
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
-use raea_core_facts::{record, Contrast, Cue, Facts, Mix, Onset, Picture, Rendered, Shot, Source, Text, Waits};
+use raea_core_facts::{record, Contrast, Cue, Facts, Mix, Ocr, Onset, Picture, Rendered, Shot, Source, Text, Waits};
use raea_sys_measure as measure;
use serde_json::{json, Value};
@@ -27,7 +28,7 @@ pub enum Render {
}
/// The components a render adds, and what each waits for when there is none.
-const FROM_A_RENDER: [&str; 5] = ["Contrast", "Picture", "Mix", "Onset", "Covers"];
+const FROM_A_RENDER: [&str; 6] = ["Contrast", "Ocr", "Picture", "Mix", "Onset", "Covers"];
/// A render found: its output, its manifest, its record entry, whether the composition changed after it, and each
/// frame's place among the frames it drew.
@@ -42,6 +43,8 @@ pub(crate) struct Found {
dirty: bool,
env: Option<Vec<f32>>,
masks: Option<Option<crate::covers::Masks>>,
+ /// its frames, decoded once as they're asked for (a text's contrast, what OCR reads)
+ pixels: crate::pixels::Pixels,
}
fn secs(p: &Path) -> u64 {
@@ -73,7 +76,7 @@ pub(crate) fn find(how: &Render, tsx: &Path, size: (u32, u32, f64)) -> Option<Fo
// another composition of the file draws another size or rate
let same = m["width"] == size.0 && m["height"] == size.1 && m["fps"].as_f64() == Some(size.2);
let at = m["frames"].as_array()?.iter().enumerate().filter_map(|(k, f)| Some((f["frame"].as_i64()?, k))).collect();
- (same && out.exists()).then(|| Found { stale: secs(tsx) > made, out, path, m, record, at, dirty: false, env: None, masks: None })
+ (same && out.exists()).then(|| Found { stale: secs(tsx) > made, out, path, m, record, at, dirty: false, env: None, masks: None, pixels: Default::default() })
})
}
@@ -97,15 +100,32 @@ impl Found {
return v.clone();
}
let v = make(self);
+ self.keep_as(name, key, v.clone());
+ v
+ }
+
+ fn keep_as(&mut self, name: &str, key: &str, v: Value) {
if !self.m["measured"].is_object() {
self.m["measured"] = json!({});
}
if !self.m["measured"][name].is_object() {
self.m["measured"][name] = json!({});
}
- self.m["measured"][name][key] = v.clone();
+ self.m["measured"][name][key] = v;
self.dirty = true;
- v
+ }
+
+ /// What OCR reads of a text on the `k`th frame (`id`: the frame and the text), kept once read; where OCR can't
+ /// run, what it waits for, and nothing kept.
+ fn ocr(&mut self, k: usize, id: &str, bx: Option<[f64; 4]>, words: &str) -> Result<Option<Ocr>, String> {
+ if let Some(v) = self.m["measured"]["ocr"].get(id) {
+ return Ok(serde_json::from_value(v.clone()).ok());
+ }
+ let (file, sec) = self.picture_at(k);
+ let video = self.video();
+ let got = self.pixels.ocr((k, &file, sec, video), bx, words)?;
+ self.keep_as("ocr", id, json!(got));
+ Ok(got)
}
/// The `k`th frame's light and movement.
@@ -182,17 +202,27 @@ pub(crate) fn join(facts: &mut Facts, found: Option<&mut Found>, tree: &[El]) {
shots(facts, r);
let laid = r.m["frames"][k].clone();
let mut boxed = Vec::new();
+ let (size, video, (file, sec)) = ((facts.width, facts.height), r.video(), r.picture_at(k));
for e in facts.find(&["Text"]).iter().map(|e| e.id).collect::<Vec<_>>() {
let (Some(t), key) = (facts.get::<Text>(e), facts.get::<Source>(e).and_then(|s| s.key)) else { continue };
+ let id = format!("{}|{}", facts.frame, key.clone().unwrap_or_else(|| t.words.clone()));
+ // what OCR reads in its box (DR28)
+ match r.ocr(k, &id, t.box_, &t.words) {
+ Ok(Some(o)) => facts.put(e, &o),
+ Ok(None) => {}
+ Err(why) => {
+ waits.insert("Ocr".into(), why);
+ }
+ }
// its own entry by its layer key, else the one with its words
let texts = || laid["text"].as_array().into_iter().flatten();
let entry = texts().find(|x| key.is_some() && key_of(x) == key).or_else(|| texts().find(|x| x["text"].as_str() == Some(t.words.as_str())));
let (Some(x), Some(bx)) = (entry, t.box_) else { continue };
let b: Vec<f64> = x["box"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
- let (file, sec) = r.picture_at(k);
- let id = format!("{}|{}", facts.frame, key.clone().unwrap_or_else(|| t.words.clone()));
- let crop = (b.len() == 4).then(|| [b[0], b[1], b[2], b[3]].map(|v| v.max(0.0) as u32));
- let ratio = r.kept("contrast", &id, |_| json!(crop.and_then(|c| measure::contrast(&file, sec, c, x["color"].as_str().unwrap_or("")))));
+ let crop = (b.len() == 4).then(|| [b[0], b[1], b[2], b[3]].map(|v| v.max(0.0)));
+ let color = x["color"].as_str().unwrap_or("").to_string();
+ // measured on the frame as decoded once for every text on it (raea check's ratio, raea-sys-measure)
+ let ratio = r.kept("contrast", &id, |r| json!(crop.and_then(|c| r.pixels.contrast((k, &file, sec, video), c, size, &color))));
if let Some(ratio) = ratio.as_f64() {
facts.put(e, &Contrast { ratio: (ratio * 10.0).round() / 10.0 });
}
diff --git a/runtime/world/src/renders/tests.rs b/runtime/world/src/renders/tests.rs
index b9663356..cddb526d 100644
--- a/runtime/world/src/renders/tests.rs
+++ b/runtime/world/src/renders/tests.rs
@@ -61,13 +61,14 @@ fn world(f: i64) -> Facts {
#[test]
fn a_render_adds_what_it_measured_and_what_it_did_not_draw_waits() {
let (dir, tsx) = project("join");
- let measured = json!({"picture": {"all": [[0.5, null], [0.25, 0.125]]}, "mix": {"all": [-14.2, -1.3]}, "onsets": {"0.500": 0.51}, "contrast": {"1|piece.tsx:3:5": 4.54}});
+ let measured = json!({"picture": {"all": [[0.5, null], [0.25, 0.125]]}, "mix": {"all": [-14.2, -1.3]}, "onsets": {"0.500": 0.51}, "contrast": {"1|piece.tsx:3:5": 4.54}, "ocr": {"1|piece.tsx:3:5": {"words": "SALE", "share": 1.0}}});
rendered(&tsx, &dir.join("v.mp4"), (1920, 1080, 30.0), &[0, 1], measured, "20261110-110000");
let mut r = find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap();
let mut w = world(1);
join(&mut w, Some(&mut r), &[]);
let get = |w: &Facts, c: &str| w.find(&[c]).first().map(|e| e.components[c].clone());
assert_eq!(get(&w, "Contrast"), Some(json!({"ratio": 4.5})));
+ assert_eq!(get(&w, "Ocr"), Some(json!({"words": "SALE", "share": 1.0})), "what OCR read, kept");
assert_eq!(w.resources["Picture"], json!({"luma": 0.25, "motion": 0.125, "frames": null}));
assert_eq!(get(&w, "Picture"), Some(json!({"luma": 0.375, "motion": 0.125, "frames": 2})), "the shot's mean over the frames drawn");
assert_eq!(w.resources["Mix"], json!({"lufs": -14.2, "peak": -1.3}));
@@ -87,10 +88,10 @@ fn a_render_adds_what_it_measured_and_what_it_did_not_draw_waits() {
assert_eq!(far.resources["Waits"]["Contrast"], "a render of frame 20");
// what was read is kept; nothing new to write back
assert!(!r.dirty);
- // no render: all five wait for one
+ // no render: all six wait for one
let mut none = world(1);
join(&mut none, None, &[]);
- assert_eq!(none.resources["Waits"].as_object().map(|o| o.len()), Some(5));
+ assert_eq!(none.resources["Waits"].as_object().map(|o| o.len()), Some(6));
assert!(none.find(&["Onset"]).is_empty(), "a cue isn't heard because it was placed");
}
@@ -105,4 +106,7 @@ fn a_still_has_no_mix_to_measure() {
assert_eq!(w.resources["Waits"]["Mix"], "a video render");
assert_eq!(w.resources["Waits"]["Onset"], "a video render");
assert_eq!(w.find(&["Contrast"])[0].components["Contrast"]["ratio"], 1.2, "a low contrast is said as measured");
+ // a still that can't be read: OCR says what it waits for, and keeps nothing
+ assert!(w.resources["Waits"]["Ocr"].as_str().is_some_and(|w| w.contains("s.png")), "{}", w.resources["Waits"]);
+ assert!(w.find(&["Ocr"]).is_empty() && r.m["measured"].get("ocr").is_none());
}
diff --git a/sdk/guides/craft/floor.md b/sdk/guides/craft/floor.md
index c23ebb92..7e93c92b 100644
--- a/sdk/guides/craft/floor.md
+++ b/sdk/guides/craft/floor.md
@@ -25,8 +25,9 @@ Before you say a piece is done, every line here is true of the last render, not
- **Every name the voice says is on screen when it says it.** If the narration says "the brief", the brief is visible.
- **Nothing stands still for three seconds** unless the stillness is the point. A held frame needs a reason the viewer
can feel.
-- **Reading time.** About 0.3 s a word, and at least a second for anything that has to be read. A number gets time
- to land before the next thing replaces it.
+- **Reading time.** About 0.3 s a word, and at least a second for anything that has to be read, counted while it can
+ be read: faded, covered or lost against its ground doesn't count, and `raea check` says which frames were lost. A
+ number gets time to land before the next thing replaces it.
- **The mix.** -14 LUFS integrated (±1), true peak at or below -1 dBTP, and the voice clear over everything.
Changing the target needs the person's say-so.
- **Names are spelled right.** People, products and places are spelled as the brief has them, never as the
diff --git a/sdk/raea/src/facts.gen.ts b/sdk/raea/src/facts.gen.ts
index a7c5b108..94a7b9bd 100644
--- a/sdk/raea/src/facts.gen.ts
+++ b/sdk/raea/src/facts.gen.ts
@@ -101,6 +101,8 @@ export type Line = { text: string, from: number, to?: number, words: Array<Word>
export type Contrast = { ratio: number, };
+export type Ocr = { words: string, share: number, };
+
export type Picture = { luma: number, motion?: number, frames?: number, };
export type Onset = { at?: number, late_ms?: number, };
diff --git a/systems/vision/src/apple_vision.rs b/systems/vision/src/apple_vision.rs
index 513bb1ce..93c956ce 100644
--- a/systems/vision/src/apple_vision.rs
+++ b/systems/vision/src/apple_vision.rs
@@ -276,9 +276,15 @@ impl Vision for AppleVision {
/// of the frame, from the top left, unrounded): no language correction (captions aren't prose), lines at least 1.5% of
/// the frame high.
pub fn text_lines(rgba: &[u8], w: usize, h: usize) -> Result<Vec<(String, f32, [f64; 4])>, String> {
+ text_lines_at(rgba, w, h, false)
+}
+
+/// text_lines, or with Vision's fast recognition (`fast`): a tenth of the time, for a crop that holds one line of
+/// clean type, where reading it at all is the question (DR28's reading check reads fast first, accurately after).
+pub fn text_lines_at(rgba: &[u8], w: usize, h: usize, fast: bool) -> Result<Vec<(String, f32, [f64; 4])>, String> {
let image = cg_image(rgba, w, h)?;
let text = VNRecognizeTextRequest::new();
- text.setRecognitionLevel(VNRequestTextRecognitionLevel::Accurate);
+ text.setRecognitionLevel(if fast { VNRequestTextRecognitionLevel::Fast } else { VNRequestTextRecognitionLevel::Accurate });
text.setUsesLanguageCorrection(false);
text.setMinimumTextHeight(0.015);
let handler = unsafe { VNImageRequestHandler::initWithCGImage_options(VNImageRequestHandler::alloc(), &image, &NSDictionary::new()) };
diff --git a/systems/vision/src/vision.rs b/systems/vision/src/vision.rs
index 2aad4ae4..e4abbd3c 100644
--- a/systems/vision/src/vision.rs
+++ b/systems/vision/src/vision.rs
@@ -68,7 +68,7 @@ pub struct Read {
// Apple Vision's implementation (apple_vision.rs), named here as before
#[cfg(target_vendor = "apple")]
-pub use crate::apple_vision::{AppleVision, text_lines};
+pub use crate::apple_vision::{AppleVision, text_lines, text_lines_at};
/// The layout reader's grey copy: the picture 240 px wide, luma, averaged down then sampled bilinearly.
pub fn grey(rgba: &[u8], w: usize, h: usize) -> raea_sys_layout::layout::Grey {