LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Faces: YuNet face detection and one-click model downloads, with nothing bundled
Daniel Voshart20a801d6d202
diff --git a/Cargo.lock b/Cargo.lockindex d4adff9dd..12e7c651c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2883,6 +2883,7 @@ dependencies = ["lightcraft-color","lightcraft-develop","lightcraft-faces",+ "lightcraft-fetch","lightcraft-geom","lightcraft-gpu","lightcraft-merge",diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex cef805f6d..7a6ab4394 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -36,6 +36,10 @@ harfrust = { version = "0.12", default-features = false, features = ["std"] }unicode-segmentation = "1.13"lightcraft-segment = { workspace = true, optional = true }+# model downloads run natively only (the web build fetches no models)+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+lightcraft-fetch = { workspace = true }+[features]# AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds.sam = ["dep:lightcraft-segment"]diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rsnew file mode 100644index 000000000..9235a10aa--- /dev/null+++ b/crates/engine/src/cmd/face_detect.rs@@ -0,0 +1,176 @@+//! `faces.detect`: find faces with the YuNet detector the user has downloaded (Settings > Faces).+//!+//! The photo is rendered upright and uncropped with default settings (so edits, crops and rotations you have+//! made do not matter), the detector runs on it, and the faces come back as fractions of the photo's width+//! and height, the same frame face regions from XMP use. Unless `apply` is false, they are added to the photo as+//! unnamed face regions in one undoable step; earlier detections are replaced, and regions that came from XMP (or+//! that you drew or named) are never touched. Like every region edit it is catalog-only: no sidecar is written.++use std::path::PathBuf;+use std::sync::{Arc, Mutex, PoisonError};+use std::time::Instant;++use lightcraft_catalog::Op;+use lightcraft_develop::DevelopSettings;+use lightcraft_faces::known::YUNET_ID;+use lightcraft_faces::yunet::{Detector, Face, Options};+use lightcraft_meta::{Region, RegionKind};+use serde_json::{Value, json};++use super::{CommandSpec, bad, cmd, has_selection};+use crate::{Result, Session};++const C: &str = "faces.detect";+/// Regions made by this command say so in their description; only those are replaced on a new run.+const MARK: &str = "Detected by ";+const LABEL: &str = "YuNet 2023mar";+/// Long edge of the picture the detector looks at (it shrinks it to its own 640 anyway).+const LOOK_EDGE: usize = 1280;+/// YuNet is 232 KB; a file this much larger in its folder is not it.+const MAX_MODEL_BYTES: u64 = 8 << 20;+/// How much a detection must overlap a region the photo already has to count as the same face.+const EXISTING_IOU: f64 = 0.3;++/// What to tell someone who has not downloaded the detector yet.+const NOT_INSTALLED: &str = "finding faces needs the YuNet face detector (232 KB, MIT): download it in Settings > Faces";++/// The installed YuNet, loaded once and kept (a new one is loaded when the model folder changes).+fn detector(s: &Session) -> std::result::Result<Arc<Detector>, String> {+ static LOADED: Mutex<Option<(PathBuf, Arc<Detector>)>> = Mutex::new(None);+ let home = s.face_models_dir.as_deref().ok_or("this build has nowhere to keep face models (the desktop app does)")?.join(YUNET_ID);+ let path = home.join("model.onnx");+ // installing writes the manifest last, so a folder without one is not (yet) a model+ if !path.is_file() || !home.join("face-model.json").is_file() {+ return Err(NOT_INSTALLED.into());+ }+ let mut loaded = LOADED.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some((p, d)) = loaded.as_ref()+ && *p == path+ {+ return Ok(d.clone());+ }+ let len = std::fs::metadata(&path).map_err(|e| format!("could not read the detector: {e}"))?.len();+ if len > MAX_MODEL_BYTES {+ return Err("the detector's file is far bigger than YuNet: remove it in Settings > Faces and download it again".into());+ }+ let bytes = std::fs::read(&path).map_err(|e| format!("could not read the detector: {e}"))?;+ let d = Arc::new(Detector::new(&bytes).map_err(|e| format!("{e}: remove the detector in Settings > Faces and download it again"))?);+ *loaded = Some((path, d.clone()));+ Ok(d)+}++fn face_json(f: &Face) -> Value {+ json!({+ "rect": {"x0": f.x0, "y0": f.y0, "x1": f.x1, "y1": f.y1},+ "score": f.score,+ "landmarks": f.landmarks.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>(),+ })+}++/// A detected face that lies on a region the photo already has (from XMP, drawn or named) is that region, not a new face.+fn overlaps_existing(f: &Face, regions: &[Region]) -> bool {+ regions.iter().any(|r| {+ let (w, h) = (+ (r.rect.x1.min(f64::from(f.x1)) - r.rect.x0.max(f64::from(f.x0))).max(0.0),+ (r.rect.y1.min(f64::from(f.y1)) - r.rect.y0.max(f64::from(f.y0))).max(0.0),+ );+ let inter = w * h;+ let union = (r.rect.x1 - r.rect.x0) * (r.rect.y1 - r.rect.y0) + f64::from((f.x1 - f.x0) * (f.y1 - f.y0)) - inter;+ union > 0.0 && inter / union >= EXISTING_IOU+ })+}++fn is_detected(r: &Region) -> bool {+ r.description.as_deref().is_some_and(|d| d.starts_with(MARK))+}++fn detect(s: &mut Session, p: &Value) -> Result<Value> {+ let apply = p.get("apply").and_then(Value::as_bool).unwrap_or(true);+ let defaults = Options::default();+ let opts = Options {+ score: p.get("score").and_then(Value::as_f64).map_or(defaults.score, |v| v as f32),+ nms_iou: p.get("nmsIou").and_then(Value::as_f64).map_or(defaults.nms_iou, |v| v as f32),+ max_faces: p.get("maxFaces").and_then(Value::as_u64).map_or(defaults.max_faces, |v| usize::try_from(v).unwrap_or(defaults.max_faces)),+ };+ let detector = detector(s).map_err(|e| bad(C, e))?;+ let started = Instant::now();+ let (mut results, mut ops) = (Vec::new(), Vec::new());+ for id in s.targets(p) {+ let settings = DevelopSettings::default();+ let Some(job) = s.preview_job(id, LOOK_EDGE, LOOK_EDGE, false, &settings) else { continue };+ let rendered = match job.run().rendered {+ Ok(r) => r.image,+ Err(e) => {+ results.push(json!({"id": id.0, "error": e}));+ continue;+ }+ };+ let rgb: Vec<u8> = rendered.data.iter().flat_map(|px| [px[0], px[1], px[2]]).collect();+ let faces = match detector.detect(&rgb, rendered.width, rendered.height, &opts) {+ Ok(f) => f,+ Err(e) => {+ results.push(json!({"id": id.0, "error": e.to_string()}));+ continue;+ }+ };+ if apply && let Some(photo) = s.catalog.photo(id) {+ let mut meta = photo.meta.clone();+ meta.regions.retain(|r| !is_detected(r));+ let fresh: Vec<&Face> = faces.iter().filter(|f| !overlaps_existing(f, &meta.regions)).collect();+ for f in fresh {+ meta.regions.push(Region {+ rect: lightcraft_geom::Rect { x0: f64::from(f.x0), y0: f64::from(f.y0), x1: f64::from(f.x1), y1: f64::from(f.y1) },+ kind: RegionKind::Face,+ name: None,+ description: Some(format!("{MARK}{LABEL}")),+ });+ }+ ops.push(Op::SetMeta { id, meta: Box::new(meta) });+ }+ results.push(json!({"id": id.0, "faces": faces.iter().map(face_json).collect::<Vec<_>>()}));+ }+ let applied = !ops.is_empty();+ if applied {+ s.commit("Detect Faces", Op::Batch { ops })?;+ // regions are not written to XMP, so a sidecar must not be rewritten for this+ s.skip_auto_write = true;+ }+ Ok(json!({"detector": LABEL, "applied": applied, "photos": results, "ms": started.elapsed().as_secs_f64() * 1000.0}))+}++pub fn specs() -> Vec<CommandSpec> {+ vec![cmd!(+ "faces.detect",+ "Detect Faces",+ ["Photo"],+ None,+ "{ids?, apply?: bool (default true), score?: 0.6, nmsIou?: 0.3, maxFaces?} → {photos: [{id, faces: [{rect, score, landmarks}]}]}. Finds faces with the YuNet detector (download it first: `faces.models.download {id: \"yunet-2023mar\"}`) and, unless `apply` is false, adds them as unnamed face regions (one undo step), replacing earlier detections but never regions from XMP or ones you named; the sidecar is not touched",+ has_selection,+ detect+ )]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn face(x0: f32, y0: f32, x1: f32, y1: f32) -> Face {+ Face { x0, y0, x1, y1, score: 0.9, landmarks: [(0.0, 0.0); 5] }+ }+ fn region(x0: f64, y0: f64, x1: f64, y1: f64) -> Region {+ Region { rect: lightcraft_geom::Rect { x0, y0, x1, y1 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }+ }++ #[test]+ fn a_detection_on_an_existing_region_is_not_a_new_face() {+ let existing = [region(0.40, 0.20, 0.60, 0.50), region(0.10, 0.10, 0.20, 0.20)];+ // the same face, a bit larger or shifted (a Lightroom box is not YuNet's box)+ assert!(overlaps_existing(&face(0.38, 0.18, 0.64, 0.54), &existing));+ assert!(overlaps_existing(&face(0.42, 0.22, 0.58, 0.48), &existing));+ // another face, a sliver of overlap, and no regions at all+ assert!(!overlaps_existing(&face(0.70, 0.20, 0.90, 0.50), &existing));+ assert!(!overlaps_existing(&face(0.59, 0.49, 0.80, 0.80), &existing));+ assert!(!overlaps_existing(&face(0.0, 0.0, 0.0, 0.0), &existing), "an empty box overlaps nothing");+ assert!(!overlaps_existing(&face(0.4, 0.2, 0.6, 0.5), &[]));+ }+}diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rsindex 1ba0db0f4..8ffdf0681 100644--- a/crates/engine/src/cmd/face_models.rs+++ b/crates/engine/src/cmd/face_models.rs@@ -17,6 +17,7 @@ use serde::{Deserialize, Serialize};use serde_json::{Value, json};use super::{CommandSpec, always, bad, cmd, str_param};+use crate::face_download::{self, State};use crate::{EngineError, Result, Session};#[derive(Default, Serialize, Deserialize)]@@ -98,6 +99,8 @@ fn row(m: &ModelManifest, installed: bool, selected: bool, accepted: &Value) ->"sizeBytes": m.size_bytes,"sha256": m.sha256,"known": known::all().iter().any(|k| k.id == m.id),+ // a pinned address LightCraft can fetch it from (the user presses Download), and which site that is+ "downloadHost": known::download(&m.id).map(|d| d.host()),"installed": installed,"selected": selected,"accepted": accepted,@@ -111,7 +114,9 @@ struct Inspection {suggestion: Suggestion,}-fn inspect_file(path: &str, cmd: &str) -> Result<Inspection> {+/// Look at a model file. `known_sha` is its SHA-256 when something already checked it (a finished download), so a+/// file of hundreds of megabytes is not read again just to be hashed.+fn inspect_file(path: &str, cmd: &str, known_sha: Option<&str>) -> Result<Inspection> {let p = Path::new(path);let meta = std::fs::metadata(p).map_err(|e| bad(cmd, format!("cannot read `{path}`: {e}")))?;if !meta.is_file() {@@ -120,7 +125,10 @@ fn inspect_file(path: &str, cmd: &str) -> Result<Inspection> {if meta.len() == 0 || meta.len() > MAX_MODEL_BYTES {return Err(bad(cmd, "a model file must be between 1 byte and 4 GiB"));}- let sha256 = sha256_file(p).map_err(|e| fail(&format!("could not read {path}"), e))?;+ let sha256 = match known_sha {+ Some(h) => h.to_string(),+ None => sha256_file(p).map_err(|e| fail(&format!("could not read {path}"), e))?,+ };let file_name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let suggestion = match onnx::probe_path(p) {Ok(info) => suggest(&info, &sha256, meta.len(), &file_name),@@ -159,7 +167,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {fn inspect(s: &mut Session, p: &Value) -> Result<Value> {const C: &str = "faces.models.inspect";let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;- let ins = inspect_file(path, C)?;+ let ins = inspect_file(path, C, None)?;let installed = s.face_models_dir.as_deref().map(installed_models).unwrap_or_default();let (kind, model, assumptions, reason) = match &ins.suggestion {Suggestion::Known(m) => ("known", Some(m), Vec::new(), None),@@ -184,38 +192,126 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {const C: &str = "faces.models.install";let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;let acknowledged = p.get("acknowledged").and_then(Value::as_bool).unwrap_or(false);- let dir = models_dir(s, C)?;- let ins = inspect_file(path, C)?;+ let ins = inspect_file(path, C, None)?;+ install_file(s, C, Path::new(path), ins, acknowledged, false)+}++/// Install the inspected model file `src`. `verified` is for a download that was already checked against its recorded+/// hash: it is moved into place instead of being copied and read again.+fn install_file(s: &mut Session, c: &str, src: &Path, ins: Inspection, acknowledged: bool, verified: bool) -> Result<Value> {+ let dir = models_dir(s, c)?;let m = match ins.suggestion {Suggestion::Known(m) | Suggestion::Draft { manifest: m, .. } => m,- Suggestion::Unsupported(why) => return Err(bad(C, format!("this model cannot be used yet: {why}"))),+ Suggestion::Unsupported(why) => return Err(bad(c, format!("this model cannot be used yet: {why}"))),};- if m.role != Role::Embedder {- return Err(bad(C, "only face recognition models can be installed for now"));+ if !matches!(m.role, Role::Embedder | Role::Detector) {+ return Err(bad(c, "only face detection and recognition models can be installed"));}- manifest::validate(&m).map_err(|e| bad(C, e.to_string()))?;+ manifest::validate(&m).map_err(|e| bad(c, e.to_string()))?;if !acknowledged {- return Err(bad(C, "the licence has not been accepted: show the user its terms and pass `acknowledged: true` once they agree"));+ return Err(bad(c, "the licence has not been accepted: show the user its terms and pass `acknowledged: true` once they agree"));}let home = dir.join(&m.id);std::fs::create_dir_all(&home).map_err(|e| fail("could not create the model's folder", e))?;let (part, final_path) = (home.join("model.onnx.part"), home.join("model.onnx"));- let copied =- std::fs::copy(path, &part).map_err(|e| fail("could not copy the model (is the disk full?)", e)).and_then(|_| match sha256_file(&part) {+ let moved = verified && std::fs::rename(src, &part).is_ok();+ let placed = if moved {+ Ok(())+ } else {+ std::fs::copy(src, &part).map_err(|e| fail("could not copy the model (is the disk full?)", e)).and_then(|_| match sha256_file(&part) {Ok(h) if h == ins.sha256 => Ok(()),Ok(_) => Err(EngineError::Other("the copy does not match the original (the file changed while copying?)".into())),Err(e) => Err(fail("could not check the copy", e)),- });- if let Err(e) = copied.and_then(|_| std::fs::rename(&part, &final_path).map_err(|e| fail("could not finish the copy", e))) {+ })+ };+ if let Err(e) = placed.and_then(|_| std::fs::rename(&part, &final_path).map_err(|e| fail("could not finish the copy", e))) {let _ = std::fs::remove_file(&part);return Err(e);}write_atomic(&home.join("face-model.json"), &serde_json::to_vec_pretty(&m).map_err(|e| fail("manifest", e))?)?;let accepted = json!({"acceptedAt": (s.clock)(), "licence": m.licence.name, "commercial": m.licence.commercial, "fileName": ins.file_name});write_atomic(&home.join("installed.json"), &serde_json::to_vec_pretty(&accepted).map_err(|e| fail("record", e))?)?;+ // a file that was downloaded and waited in the staging folder has served: the installed copy is the model now+ if src.parent() == Some(dir.join(face_download::STAGING).as_path()) {+ let _ = std::fs::remove_file(src);+ s.face_downloads.staged_file_used(src);+ }Ok(json!({"installed": row(&m, true, false, &accepted)}))}+/// What an error says, without the command it came from (for a line shown to the user).+fn plain(e: &EngineError) -> String {+ match e {+ EngineError::BadParams { msg, .. } => msg.clone(),+ other => other.to_string(),+ }+}++/// Install every download that has arrived: each was accepted when it was started, so it is installed without another+/// question. Called by `faces.models.downloads`, which the UI asks for every frame while it watches a download.+fn finish_downloads(s: &mut Session) {+ const C: &str = "faces.models.download";+ for (id, path, sha) in s.face_downloads.finished() {+ let outcome = inspect_file(&path.to_string_lossy(), C, Some(&sha)).and_then(|ins| install_file(s, C, &path, ins, true, true));+ match outcome {+ Ok(_) => s.face_downloads.set_outcome(&id, State::Installed),+ Err(e) => {+ // a file that cannot be installed is of no use to anyone: throw it away, say why+ let _ = std::fs::remove_file(&path);+ s.face_downloads.set_outcome(&id, State::Failed(plain(&e)));+ }+ }+ }+}++/// `faces.models.download {id, acknowledged: true}`: fetch a model LightCraft knows an address for, in the background;+/// when it has arrived and checked out it is installed.+fn download(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "faces.models.download";+ let id = str_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;+ let dir = models_dir(s, C)?;+ let spec = known::download(id).ok_or_else(|| bad(C, "LightCraft has no download for that model: get the file from its page, then add it"))?;+ if cfg!(target_arch = "wasm32") {+ return Err(bad(C, "the web build downloads no models"));+ }+ if p.get("acknowledged").and_then(Value::as_bool) != Some(true) {+ return Err(bad(+ C,+ "the licence has not been accepted: show the user the model's terms (see `faces.models.list`) and pass `acknowledged: true` once they agree",+ ));+ }+ if installed_models(&dir).iter().any(|i| i.manifest.id == spec.id) {+ return Err(bad(C, "that model is already installed"));+ }+ s.face_downloads.start(spec, &dir).map_err(|e| bad(C, e))?;+ Ok(json!({"started": id, "from": spec.host()}))+}++fn download_row(id: &str, state: &State) -> Value {+ let from = known::download(id).map(|d| d.host());+ match state {+ State::Running { bytes, total } => json!({"id": id, "state": "running", "bytes": bytes, "total": total, "from": from}),+ State::Done { path, .. } => json!({"id": id, "state": "done", "path": path.display().to_string(), "from": from}),+ State::Installed => json!({"id": id, "state": "installed", "from": from}),+ State::Failed(why) => json!({"id": id, "state": "failed", "error": why, "from": from}),+ State::Cancelled => json!({"id": id, "state": "cancelled", "from": from}),+ }+}++/// `faces.models.downloads`: where each download stands (a finished one is installed first).+fn downloads(s: &mut Session, _: &Value) -> Result<Value> {+ finish_downloads(s);+ let all: Vec<Value> = s.face_downloads.snapshot().iter().map(|(id, st)| download_row(id, st)).collect();+ Ok(json!({"running": s.face_downloads.running(), "downloads": all}))+}++/// `faces.models.downloadCancel {id}`: stop a download, or clear a finished one (a staged file is deleted).+fn download_cancel(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "faces.models.downloadCancel";+ let id = str_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;+ Ok(json!({"discarded": s.face_downloads.discard(id)}))+}+fn remove(s: &mut Session, p: &Value) -> Result<Value> {const C: &str = "faces.models.remove";let id = str_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;@@ -268,7 +364,10 @@ pub fn specs() -> Vec<CommandSpec> {vec![cmd!(query "faces.models.list", "Face Models", [], None, "{} → {dir, enabled, embedder, runtime, models: [{id, name, role, licence{name, commercial, url, notice}, provenance, source, sizeBytes, known, installed, selected}]}", always, list),cmd!(query "faces.models.inspect", "Inspect Face Model File", [], None, "{path} → what a .onnx file is: {kind: known | draft | unsupported, model, assumptions, reason, alreadyInstalled}; installs nothing", always, inspect),- cmd!(query "faces.models.install", "Install Face Model", [], None, "{path, acknowledged: true} — copy a .onnx face recognition model into the models folder. `acknowledged` must be true: the user has been shown its licence (see inspect) and accepted it", always, install),+ cmd!(query "faces.models.install", "Install Face Model", [], None, "{path, acknowledged: true} — copy a .onnx face model (the detector or a recogniser) into the models folder. `acknowledged` must be true: the user has been shown its licence (see inspect) and accepted it", always, install),+ cmd!(query "faces.models.download", "Download Face Model", [], None, "{id, acknowledged: true} → {started, from} — fetch a model LightCraft has a pinned address for (see `downloadHost` in the list), in the background over https. `acknowledged` must be true: the user has been shown the model's terms and accepted them. It is checked against its size and SHA-256, then installed by itself; `faces.models.downloads` shows how far it is", always, download),+ cmd!(query "faces.models.downloads", "Face Model Downloads", [], None, "{} → {running, downloads: [{id, state: running | done | installed | failed | cancelled, bytes, total, error, from}]} — also installs any download that has arrived; `installed` stays listed until `faces.models.downloadCancel` clears it", always, downloads),+ cmd!(query "faces.models.downloadCancel", "Cancel Face Model Download", [], None, "{id} → {discarded} — stop a download, or clear a finished one", always, download_cancel),cmd!(query "faces.models.remove", "Remove Face Model", [], None, "{id} — delete an installed model", always, remove),cmd!(query "faces.models.select", "Choose Face Recognition Model", [], None, "{id: installed recogniser | null}", always, select),cmd!(query "faces.enable", "Face Recognition On/Off", [], None, "{enabled?: bool} (toggles when omitted)", always, enable),diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 730fb8110..b5909202f 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -13,6 +13,7 @@ pub mod curves;mod develop;mod edit;mod export;+mod face_detect;mod face_models;pub mod filters;pub mod keywords;@@ -142,6 +143,7 @@ pub fn command_specs() -> &'static [CommandSpec] {v.extend(metadata::specs());v.extend(filters::specs());v.extend(face_models::specs());+ v.extend(face_detect::specs());v})}diff --git a/crates/engine/src/face_download.rs b/crates/engine/src/face_download.rsnew file mode 100644index 000000000..cac1b2e64--- /dev/null+++ b/crates/engine/src/face_download.rs@@ -0,0 +1,375 @@+//! Downloading a face model the user asked for (Settings ▸ Faces ▸ Download).+//!+//! The transfer is [`lightcraft_fetch`] (pure-Rust HTTPS with resume, size and SHA-256 checks), on a background thread,+//! so the UI never waits for the network. Only a model listed in [`lightcraft_faces::known::download`] can be fetched:+//! the address is a pinned constant, never something typed or passed in, and no token is ever sent with it. What arrives+//! matches the model's recorded size and SHA-256 or it is thrown away; it then waits in a staging folder until the model+//! is installed (`faces.models.install`, or by itself once the user has accepted the model's terms in the download).+//!+//! Failure is a message, never a panic: no network, a stalled or truncated transfer, a full disk, a file that is not the+//! one expected, and a panic inside the thread itself all end as [`State::Failed`].++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, PoisonError};+use std::time::Duration;++use lightcraft_faces::known::Download;++/// The folder inside the models folder where a downloaded file waits to be installed. Its name starts with a dot, so it+/// can never be a model's own folder (ids start with a letter or digit).+pub const STAGING: &str = ".downloads";++/// Where a download stands.+#[derive(Clone, Debug, PartialEq)]+pub enum State {+ /// Fetching (`bytes` of `total` so far); the file is checked as the last step.+ Running {+ bytes: u64,+ total: u64,+ },+ /// Fetched and verified (its SHA-256 is `sha256`), waiting in the staging folder at `path` to be installed.+ Done {+ path: PathBuf,+ sha256: String,+ },+ /// Installed and in use: nothing more to do but tell the user.+ Installed,+ Failed(String),+ Cancelled,+}++struct Shared {+ state: Mutex<State>,+ cancel: AtomicBool,+}++impl Shared {+ fn new(total: u64) -> Self {+ Shared { state: Mutex::new(State::Running { bytes: 0, total }), cancel: AtomicBool::new(false) }+ }++ fn set(&self, s: State) {+ *self.state.lock().unwrap_or_else(PoisonError::into_inner) = s;+ }++ fn get(&self) -> State {+ self.state.lock().unwrap_or_else(PoisonError::into_inner).clone()+ }+}++/// The downloads of one session, by model id.+#[derive(Default)]+pub struct Downloads {+ jobs: HashMap<String, Arc<Shared>>,+}++impl Downloads {+ /// Start fetching `spec` into `<models dir>/.downloads/`. Different models can download side by side; the same+ /// one is started once.+ pub fn start(&mut self, spec: Download, models_dir: &Path) -> Result<(), String> {+ if self.jobs.get(spec.id).is_some_and(|j| matches!(j.get(), State::Running { .. })) {+ return Err("that model is already downloading".into());+ }+ let staging = models_dir.join(STAGING);+ std::fs::create_dir_all(&staging).map_err(|e| format!("could not create the download folder: {e}"))?;+ let shared = Arc::new(Shared::new(spec.size_bytes));+ let worker = shared.clone();+ std::thread::Builder::new()+ .name("face-model-download".into())+ .spawn(move || {+ let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&spec, spec.base(), &staging, &worker)));+ if outcome.is_err() {+ worker.set(State::Failed("the download stopped unexpectedly".into()));+ }+ })+ .map_err(|e| format!("could not start the download: {e}"))?;+ self.jobs.insert(spec.id.to_string(), shared);+ Ok(())+ }++ /// A download that has arrived and been checked, as if the transfer had just ended (tests of installing).+ #[cfg(test)]+ pub(crate) fn arrived(&mut self, id: &str, path: PathBuf, sha256: &str) {+ let j = Shared::new(0);+ j.set(State::Done { path, sha256: sha256.to_string() });+ self.jobs.insert(id.to_string(), Arc::new(j));+ }++ /// Every download this session has started and not discarded, by model id.+ pub fn snapshot(&self) -> Vec<(String, State)> {+ let mut all: Vec<_> = self.jobs.iter().map(|(id, j)| (id.clone(), j.get())).filter(|(_, s)| *s != State::Cancelled).collect();+ all.sort_by(|a, b| a.0.cmp(&b.0));+ all+ }++ pub fn running(&self) -> bool {+ self.jobs.values().any(|j| matches!(j.get(), State::Running { .. }))+ }++ /// Stop a running download, or discard a finished one (its staged file is deleted). `true` if there was one.+ pub fn discard(&mut self, id: &str) -> bool {+ let Some(job) = self.jobs.get(id) else { return false };+ job.cancel.store(true, Ordering::Relaxed);+ match job.get() {+ // the thread notices, deletes the partial file and marks itself cancelled+ State::Running { .. } => {}+ State::Done { path, .. } => {+ let _ = std::fs::remove_file(path);+ self.jobs.remove(id);+ }+ State::Installed | State::Failed(_) | State::Cancelled => {+ self.jobs.remove(id);+ }+ }+ true+ }++ /// The staged file at `path` has been installed (its copy is the model now) or is no longer wanted.+ pub fn staged_file_used(&mut self, path: &Path) {+ self.jobs.retain(|_, j| !matches!(j.get(), State::Done { path: p, .. } if p == path));+ }++ /// Downloads that have arrived and been checked, ready to install: (model id, staged file, its SHA-256).+ pub fn finished(&self) -> Vec<(String, PathBuf, String)> {+ let mut out: Vec<_> = self+ .jobs+ .iter()+ .filter_map(|(id, j)| match j.get() {+ State::Done { path, sha256 } => Some((id.clone(), path, sha256)),+ _ => None,+ })+ .collect();+ out.sort_by(|a, b| a.0.cmp(&b.0));+ out+ }++ /// Record how installing a finished download went (`Installed` or `Failed`).+ pub fn set_outcome(&mut self, id: &str, state: State) {+ match self.jobs.get(id) {+ Some(j) => j.set(state),+ None => {+ let j = Shared::new(0);+ j.set(state);+ self.jobs.insert(id.to_string(), Arc::new(j));+ }+ }+ }+}++impl Drop for Downloads {+ /// Quitting while a download runs stops it instead of leaving it behind.+ fn drop(&mut self) {+ for job in self.jobs.values() {+ job.cancel.store(true, Ordering::Relaxed);+ }+ let started = std::time::Instant::now();+ while self.running() && started.elapsed() < Duration::from_secs(1) {+ std::thread::sleep(Duration::from_millis(10));+ }+ }+}++/// What went wrong, in words the user can act on.+#[cfg(not(target_arch = "wasm32"))]+fn explain(e: &lightcraft_fetch::DownloadError) -> String {+ use lightcraft_fetch::DownloadError;+ match e {+ DownloadError::AllMirrorsFailed { errors, .. } => {+ let detail: String = errors.join("; ").chars().take(300).collect();+ format!("could not download the model ({detail}): check the internet connection, or get the file from its page and add it yourself")+ }+ other => other.to_string(),+ }+}++/// Fetch `spec` from `mirror` (the address without the file name) into `staging`, check it and leave it there.+#[cfg(not(target_arch = "wasm32"))]+fn fetch(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) -> Result<(), lightcraft_fetch::DownloadError> {+ let file = lightcraft_fetch::FileSpec { name: spec.file_name, size: Some(spec.size_bytes), sha256: Some(spec.sha256), max: spec.size_bytes };+ lightcraft_fetch::download(&[file], &[mirror.to_string()], staging, &lightcraft_fetch::Options::default(), &shared.cancel, &mut |p| {+ shared.set(State::Running { bytes: p.done.min(spec.size_bytes), total: spec.size_bytes });+ })+}++#[cfg(target_arch = "wasm32")]+fn fetch(_: &Download, _: &str, _: &Path, _: &Shared) -> Result<(), String> {+ Err("the web build downloads no models".into())+}++/// The whole job: reuse a verified earlier copy, else fetch, check and stage. Always ends in a final [`State`].+fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) {+ let target = staging.join(spec.file_name);+ let part = staging.join(format!("{}.part", spec.file_name));+ match fetch(spec, mirror, staging, shared) {+ Ok(()) => shared.set(State::Done { path: target, sha256: spec.sha256.to_string() }),+ #[cfg(not(target_arch = "wasm32"))]+ Err(lightcraft_fetch::DownloadError::Cancelled) => {+ let _ = std::fs::remove_file(&part);+ shared.set(State::Cancelled);+ }+ #[cfg(not(target_arch = "wasm32"))]+ Err(e) => {+ let _ = std::fs::remove_file(&part);+ shared.set(State::Failed(explain(&e)));+ }+ #[cfg(target_arch = "wasm32")]+ Err(e) => {+ let _ = std::fs::remove_file(&part);+ shared.set(State::Failed(e));+ }+ }+}++#[cfg(all(test, not(target_arch = "wasm32")))]+mod tests {+ use super::*;+ use lightcraft_faces::hash::sha256_hex;+ use std::io::{BufRead, BufReader, Write};+ use std::net::TcpListener;++ fn scratch(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("lc-face-dl-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+ }++ fn leak(s: String) -> &'static str {+ Box::leak(s.into_boxed_str())+ }++ fn spec_for(bytes: &[u8]) -> Download {+ Download {+ id: "test-model",+ url: "https://example.invalid/m/test-model.onnx",+ file_name: "test-model.onnx",+ size_bytes: bytes.len() as u64,+ sha256: leak(sha256_hex(bytes)),+ }+ }++ /// A local server that answers every request with `status` and `body` (the whole file, no ranges).+ fn serve(status: &'static str, body: Vec<u8>) -> String {+ let l = TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://{}/m", l.local_addr().unwrap());+ std::thread::spawn(move || {+ for mut s in l.incoming().flatten() {+ let mut r = BufReader::new(s.try_clone().unwrap());+ loop {+ let mut line = String::new();+ if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() {+ break;+ }+ }+ let _ = s.write_all(format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes());+ let _ = s.write_all(&body);+ }+ });+ base+ }++ #[test]+ fn fetches_checks_and_stages_a_file() {+ let dir = scratch("ok");+ let bytes: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();+ let (staging, spec) = (dir.join(STAGING), spec_for(&bytes));+ std::fs::create_dir_all(&staging).unwrap();+ let mirror = serve("200 OK", bytes.clone());+ let shared = Shared::new(spec.size_bytes);+ run(&spec, &mirror, &staging, &shared);+ let State::Done { path, sha256 } = shared.get() else { panic!("{:?}", shared.get()) };+ assert_eq!((std::fs::read(&path).unwrap(), sha256), (bytes, spec.sha256.to_string()));+ assert!(!staging.join("test-model.onnx.part").exists());+ // asked again with the copy still staged: no fetch needed (nothing listens there)+ let again = Shared::new(spec.size_bytes);+ run(&spec, "http://127.0.0.1:1/m", &staging, &again);+ assert!(matches!(again.get(), State::Done { .. }), "{:?}", again.get());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_file_that_does_not_match_is_thrown_away() {+ let dir = scratch("bad");+ let staging = dir.join(STAGING);+ std::fs::create_dir_all(&staging).unwrap();+ // the right size and the wrong content+ let spec = spec_for(&[7u8; 5000]);+ let shared = Shared::new(spec.size_bytes);+ run(&spec, &serve("200 OK", vec![8u8; 5000]), &staging, &shared);+ assert!(matches!(shared.get(), State::Failed(_)), "{:?}", shared.get());+ // nothing is left behind: not the file, not a partial one+ assert_eq!(std::fs::read_dir(&staging).unwrap().count(), 0);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn an_unreachable_or_refusing_server_is_a_message() {+ let dir = scratch("down");+ let staging = dir.join(STAGING);+ std::fs::create_dir_all(&staging).unwrap();+ let spec = spec_for(b"abc");+ for mirror in ["http://127.0.0.1:1/m".to_string(), serve("404 Not Found", b"not found".to_vec())] {+ let shared = Shared::new(3);+ run(&spec, &mirror, &staging, &shared);+ let State::Failed(why) = shared.get() else { panic!("{:?}", shared.get()) };+ assert!(why.contains("internet connection"), "{why}");+ }+ assert_eq!(std::fs::read_dir(&staging).unwrap().count(), 0);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_cancelled_download_leaves_nothing() {+ let dir = scratch("cancel");+ let staging = dir.join(STAGING);+ std::fs::create_dir_all(&staging).unwrap();+ let spec = spec_for(b"abc");+ let shared = Shared::new(3);+ shared.cancel.store(true, Ordering::Relaxed);+ run(&spec, &serve("200 OK", b"abc".to_vec()), &staging, &shared);+ assert_eq!(shared.get(), State::Cancelled);+ assert_eq!(std::fs::read_dir(&staging).unwrap().count(), 0);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn dropping_the_session_stops_a_running_download() {+ let shared = Arc::new(Shared::new(10));+ // a stand-in for the download thread: notices the cancel flag the way the downloader does+ let worker = shared.clone();+ let handle = std::thread::spawn(move || {+ while !worker.cancel.load(Ordering::Relaxed) {+ std::thread::sleep(Duration::from_millis(5));+ }+ worker.set(State::Cancelled);+ });+ let mut d = Downloads::default();+ d.jobs.insert("m".into(), shared.clone());+ assert!(d.running());+ let started = std::time::Instant::now();+ drop(d);+ assert!(started.elapsed() < Duration::from_millis(900), "quitting must not wait for a transfer to finish");+ assert_eq!(shared.get(), State::Cancelled);+ handle.join().unwrap();+ }++ #[test]+ fn discarding_a_finished_download_deletes_its_file() {+ let dir = scratch("discard");+ let file = dir.join("staged.onnx");+ std::fs::write(&file, b"x").unwrap();+ let mut d = Downloads::default();+ let shared = Arc::new(Shared::new(1));+ shared.set(State::Done { path: file.clone(), sha256: String::new() });+ d.jobs.insert("m".into(), shared);+ assert_eq!(d.snapshot().len(), 1);+ assert!(!d.running());+ assert!(d.discard("m"));+ assert!(!file.exists());+ assert!(d.snapshot().is_empty());+ assert!(!d.discard("m"), "nothing left to discard");+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex f656709e0..93e41e132 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -20,6 +20,7 @@ pub mod crs_masks;pub mod demo;pub mod devices;pub mod export;+pub mod face_download;pub mod files;pub mod fonts;pub mod guard;@@ -160,6 +161,8 @@ pub struct Session {pub(crate) skip_auto_write: bool,/// Where the host keeps face models (one folder each); `None` where there is no file system (the web).pub face_models_dir: Option<std::path::PathBuf>,+ /// Face model downloads started this session (the staged files wait in `<face_models_dir>/.downloads`).+ pub face_downloads: face_download::Downloads,/// Copied develop settings (partial JSON) for Paste.pub clipboard: Option<Value>,/// The folder on disk the [`LibrarySource::Folder`] view browses.@@ -267,6 +270,7 @@ impl Session {interaction: None,skip_auto_write: false,face_models_dir: None,+ face_downloads: Default::default(),clipboard: None,meta_clipboard: None,browse: None,diff --git a/crates/engine/src/tests_face_models.rs b/crates/engine/src/tests_face_models.rsindex e002b5c62..5fcf9e575 100644--- a/crates/engine/src/tests_face_models.rs+++ b/crates/engine/src/tests_face_models.rs@@ -170,3 +170,191 @@ fn hostile_ids_unsupported_models_and_odd_folders_are_handled() {assert!(s.execute("faces.models.select", &json!({"id": ""})).is_err());let _ = std::fs::remove_dir_all(&d);}++/// A demo session with the real YuNet installed, for the tests that need it: `LC_YUNET_MODEL=<the .onnx file>` (what+/// Settings > Faces downloads; nothing is committed). Without it those tests say so and pass.+fn demo_with_yunet() -> Option<Session> {+ let Some(file) = std::env::var_os("LC_YUNET_MODEL") else {+ eprintln!("LC_YUNET_MODEL is not set: skipping");+ return None;+ };+ let dir = temp("yunet");+ let mut s = Session::with_demo();+ s.face_models_dir = Some(dir.join("models"));+ let r = s.execute("faces.models.install", &json!({"path": file.to_string_lossy(), "acknowledged": true}));+ assert!(r.is_ok(), "{r:?}");+ Some(s)+}++#[test]+fn detect_without_the_model_says_where_to_get_it() {+ let d = temp("nodetector");+ let mut s = Session::with_demo();+ // no folder for models at all, then a folder that has none yet+ assert!(s.execute("faces.detect", &json!({})).is_err());+ s.face_models_dir = Some(d.join("models"));+ let e = s.execute("faces.detect", &json!({})).unwrap_err().to_string();+ assert!(e.contains("Settings > Faces"), "{e}");+ let _ = std::fs::remove_dir_all(&d);+}++#[test]+fn the_detector_and_the_recognisers_can_be_downloaded_and_the_download_is_refused_otherwise() {+ let d = temp("dl-refusals");+ let mut s = session(&d);+ let l = s.execute("faces.models.list", &json!({})).unwrap();+ for (id, host) in [("yunet-2023mar", "github.com"), ("sface-2021dec", "github.com"), ("auraface-v1", "huggingface.co")] {+ assert_eq!(find(&l, id)["downloadHost"], host, "{id}");+ }+ // without the user's acceptance, for an id nobody knows, and without a folder: nothing starts+ assert!(s.execute("faces.models.download", &json!({"id": "yunet-2023mar"})).is_err());+ assert!(s.execute("faces.models.download", &json!({"id": "yunet-2023mar", "acknowledged": false})).is_err());+ for id in ["nope", "", "../yunet-2023mar"] {+ assert!(s.execute("faces.models.download", &json!({"id": id, "acknowledged": true})).is_err(), "{id}");+ }+ assert!(Session::new().execute("faces.models.download", &json!({"id": "yunet-2023mar", "acknowledged": true})).is_err());+ assert_eq!(s.execute("faces.models.downloads", &json!({})).unwrap()["downloads"], json!([]));+ assert!(!d.join("models").join(".downloads").exists(), "a refused download touches nothing");+ let _ = std::fs::remove_dir_all(&d);+}++#[test]+fn a_download_that_has_arrived_is_installed_by_itself_and_its_staged_file_goes() {+ let d = temp("dl-arrived");+ let mut s = session(&d);+ let staging = d.join("models").join(".downloads");+ std::fs::create_dir_all(&staging).unwrap();+ let staged = staging.join("model.onnx");+ std::fs::write(&staged, lightcraft_faces::synthetic::embedder_model(512)).unwrap();+ let sha = lightcraft_faces::hash::sha256_file(&staged).unwrap();+ s.face_downloads.arrived("my-model", staged.clone(), &sha);++ let r = s.execute("faces.models.downloads", &json!({})).unwrap();+ let row = &r["downloads"][0];+ assert_eq!((row["id"].as_str(), row["state"].as_str()), (Some("my-model"), Some("installed")), "{r}");+ assert!(!staged.exists(), "the staged file was moved into the model's folder");+ let l = s.execute("faces.models.list", &json!({})).unwrap();+ assert_eq!(l["models"].as_array().unwrap().iter().filter(|m| m["installed"] == true).count(), 1);+ // announced once, cleared on request+ assert_eq!(s.execute("faces.models.downloadCancel", &json!({"id": "my-model"})).unwrap()["discarded"], true);+ assert_eq!(s.execute("faces.models.downloads", &json!({})).unwrap()["downloads"], json!([]));+ assert_eq!(s.execute("faces.models.downloadCancel", &json!({"id": "my-model"})).unwrap()["discarded"], false);++ // a file that cannot be installed is thrown away with a reason+ std::fs::write(&staged, b"this is not a model").unwrap();+ let sha = lightcraft_faces::hash::sha256_file(&staged).unwrap();+ s.face_downloads.arrived("bad", staged.clone(), &sha);+ let r = s.execute("faces.models.downloads", &json!({})).unwrap();+ assert_eq!(r["downloads"][0]["state"], "failed", "{r}");+ assert!(!staged.exists());+ let _ = std::fs::remove_dir_all(&d);+}++/// `faces.detect` on photos without faces: it reports nothing, and a new run replaces earlier detections but+/// never regions that came from XMP or were named; one undo step restores everything.+#[test]+fn detect_replaces_only_earlier_detections_and_is_one_undo_step() {+ use lightcraft_catalog::Op;+ use lightcraft_meta::{Region, RegionKind};+ let region = |name: Option<&str>, description: Option<&str>, x: f64| Region {+ rect: lightcraft_geom::Rect { x0: x, y0: 0.2, x1: x + 0.2, y1: 0.5 },+ kind: RegionKind::Face,+ name: name.map(str::to_string),+ description: description.map(str::to_string),+ };+ let Some(mut s) = demo_with_yunet() else { return };+ let id = s.active().unwrap();+ let mut meta = s.catalog.photo(id).unwrap().meta.clone();+ meta.regions =+ vec![region(Some("Jane Doe"), None, 0.1), region(None, Some("Detected by YuNet 2023mar"), 0.5), region(None, Some("Drawn by hand"), 0.7)];+ s.commit("setup", Op::SetMeta { id, meta: Box::new(meta) }).unwrap();+ let undo_before = s.undo.len();++ // a dry run reports and changes nothing+ let r = s.execute("faces.detect", &json!({"apply": false})).unwrap();+ assert_eq!(r["applied"], false);+ assert_eq!(s.catalog.photo(id).unwrap().meta.regions.len(), 3);+ assert_eq!(s.undo.len(), undo_before);++ // a real run (the default) drops the earlier detection (the demo has no faces) and keeps the others+ let r = s.execute("faces.detect", &json!({})).unwrap();+ assert_eq!(r["applied"], true);+ assert_eq!(r["detector"], "YuNet 2023mar");+ let photo = r["photos"].as_array().unwrap().iter().find(|p| p["id"] == id.0).unwrap();+ assert_eq!(photo["faces"].as_array().unwrap().len(), 0, "the procedural demo photos have no faces");+ let names: Vec<_> = s.catalog.photo(id).unwrap().meta.regions.iter().map(|r| (r.name.clone(), r.description.clone())).collect();+ assert_eq!(names, vec![(Some("Jane Doe".to_string()), None), (None, Some("Drawn by hand".to_string()))]);+ assert_eq!(s.undo.len(), undo_before + 1, "one undo step for the whole run");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.catalog.photo(id).unwrap().meta.regions.len(), 3, "undo brings the detection back");++ // odd parameters are tolerated, and nothing is detected without a selection+ for p in [json!({"score": 5}), json!({"score": -1}), json!({"nmsIou": 99}), json!({"maxFaces": 0}), json!({"score": "x"})] {+ assert!(s.execute("faces.detect", &p).is_ok(), "{p}");+ }+ let mut empty = Session::new();+ assert!(empty.execute("faces.detect", &json!({})).is_err());+}++/// Opt-in, needs the internet: `cargo test -p lightcraft-engine real_download -- --ignored --nocapture`. Downloads YuNet+/// from its pinned address the way the app does, waits for it to be installed, then finds faces with it.+#[test]+#[ignore = "downloads from github.com"]+fn real_download_of_yunet_installs_it_and_detects() {+ let d = temp("real-download");+ let mut s = Session::with_demo();+ s.face_models_dir = Some(d.join("models"));+ let started = s.execute("faces.models.download", &json!({"id": "yunet-2023mar", "acknowledged": true})).unwrap();+ assert_eq!(started["from"], "github.com");+ let t0 = std::time::Instant::now();+ loop {+ let r = s.execute("faces.models.downloads", &json!({})).unwrap();+ let row = r["downloads"][0].clone();+ match row["state"].as_str() {+ Some("installed") => break,+ Some("running") | Some("done") => {}+ _ => panic!("{r}"),+ }+ assert!(t0.elapsed() < std::time::Duration::from_secs(120), "{r}");+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ println!("downloaded and installed in {:?}", t0.elapsed());+ let l = s.execute("faces.models.list", &json!({})).unwrap();+ assert_eq!(find(&l, "yunet-2023mar")["installed"], true);+ let r = s.execute("faces.detect", &json!({"apply": false})).unwrap();+ assert_eq!(r["detector"], "YuNet 2023mar");+ // asking again once installed is refused+ assert!(s.execute("faces.models.download", &json!({"id": "yunet-2023mar", "acknowledged": true})).is_err());+ let _ = std::fs::remove_dir_all(&d);+}++/// Opt-in, needs the internet: the recognisers are big, so this only checks that bytes start to arrive (through the+/// hosts' redirects) and that cancelling leaves nothing behind.+#[test]+#[ignore = "downloads from github.com and huggingface.co"]+fn real_downloads_of_the_recognisers_start_and_can_be_cancelled() {+ let d = temp("real-start");+ let mut s = Session::with_demo();+ s.face_models_dir = Some(d.join("models"));+ for id in ["sface-2021dec", "auraface-v1"] {+ s.execute("faces.models.download", &json!({"id": id, "acknowledged": true})).unwrap();+ let t0 = std::time::Instant::now();+ loop {+ let r = s.execute("faces.models.downloads", &json!({})).unwrap();+ let row = r["downloads"].as_array().unwrap().iter().find(|x| x["id"] == id).unwrap().clone();+ if row["state"] == "running" && row["bytes"].as_u64().unwrap_or(0) > 100_000 {+ println!("{id}: {} of {} bytes after {:?}", row["bytes"], row["total"], t0.elapsed());+ break;+ }+ assert!(row["state"] == "running", "{r}");+ assert!(t0.elapsed() < std::time::Duration::from_secs(60), "{r}");+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ s.execute("faces.models.downloadCancel", &json!({"id": id})).unwrap();+ }+ drop(s);+ let staging = d.join("models").join(".downloads");+ let left: Vec<_> = std::fs::read_dir(&staging).map(|r| r.flatten().map(|e| e.file_name()).collect()).unwrap_or_default();+ println!("left in staging: {left:?}");+ let _ = std::fs::remove_dir_all(&d);+}diff --git a/crates/faces/src/graph.rs b/crates/faces/src/graph.rsnew file mode 100644index 000000000..4ef4ec8d7--- /dev/null+++ b/crates/faces/src/graph.rs@@ -0,0 +1,342 @@+//! A full, bounded read of a small ONNX model: its nodes, attributes and weights.+//!+//! This is for the detector that ships inside LightCraft (a few hundred kilobytes), which [`crate::net`]+//! runs itself. Bigger models are never loaded this way. The bytes are still treated as hostile: the+//! number of nodes, weight tensors and elements is capped, every length is checked against its parent,+//! and a weight blob whose size disagrees with its shape is an error.++use std::collections::HashMap;+use std::io::Cursor;++use crate::onnx::{ProbeError, Walker, Wire};++type Result<T> = std::result::Result<T, ProbeError>;++const MAX_NODES: usize = 20_000;+const MAX_TENSORS: usize = 20_000;+/// Elements across all weight tensors (4 bytes each as float32).+const MAX_ELEMENTS: usize = 64 * 1024 * 1024;+const MAX_NAME: usize = 4096;+const MAX_LIST: usize = 1_000_000;++#[derive(Clone, Debug, PartialEq)]+pub enum Attr {+ Int(i64),+ Float(f32),+ Str(String),+ Ints(Vec<i64>),+ Floats(Vec<f32>),+ /// A kind we do not read (a tensor, a sub-graph…).+ Other,+}++#[derive(Clone, Debug)]+pub struct Node {+ pub op: String,+ pub inputs: Vec<String>,+ pub outputs: Vec<String>,+ pub attrs: HashMap<String, Attr>,+}++impl Node {+ pub fn int(&self, name: &str) -> Option<i64> {+ match self.attrs.get(name) {+ Some(Attr::Int(v)) => Some(*v),+ _ => None,+ }+ }+ pub fn ints(&self, name: &str) -> Option<&[i64]> {+ match self.attrs.get(name) {+ Some(Attr::Ints(v)) => Some(v),+ _ => None,+ }+ }+ pub fn string(&self, name: &str) -> Option<&str> {+ match self.attrs.get(name) {+ Some(Attr::Str(v)) => Some(v),+ _ => None,+ }+ }+}++#[derive(Clone, Debug, PartialEq)]+pub enum Data {+ F32(Vec<f32>),+ I64(Vec<i64>),+}++/// A weight tensor.+#[derive(Clone, Debug, PartialEq)]+pub struct Weight {+ pub dims: Vec<usize>,+ pub data: Data,+}++#[derive(Clone, Debug)]+pub struct Graph {+ pub nodes: Vec<Node>,+ pub weights: HashMap<String, Weight>,+ /// The inputs the caller feeds (weights some exporters also list as inputs are left out), and their shapes+ /// (0 for a dynamic size).+ pub inputs: Vec<(String, Vec<usize>)>,+ pub outputs: Vec<String>,+}++fn malformed<T>(why: &'static str) -> Result<T> {+ Err(ProbeError::Malformed(why))+}++fn f32s(raw: &[u8]) -> Vec<f32> {+ raw.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()+}++fn i64s(raw: &[u8]) -> Vec<i64> {+ raw.as_chunks::<8>().0.iter().map(|b| i64::from_le_bytes(*b)).collect()+}++/// A list of varints in a packed field (`start..end`), appended to `out`.+fn packed_varints(w: &mut Walker<Cursor<&[u8]>>, end: u64, out: &mut Vec<u64>) -> Result<()> {+ while w.pos()? < end {+ if out.len() >= MAX_LIST {+ return malformed("a list is too long");+ }+ out.push(w.varint()?);+ }+ Ok(())+}++fn attribute(w: &mut Walker<Cursor<&[u8]>>, end: u64) -> Result<(String, Attr)> {+ let (mut name, mut kind) = (String::new(), 0u64);+ let (mut i, mut f, mut s) = (0i64, 0f32, String::new());+ let (mut ints, mut floats): (Vec<u64>, Vec<f32>) = (Vec::new(), Vec::new());+ while let Some((n, f_)) = w.next(end)? {+ match (n, f_) {+ (1, Wire::Len { start, end: e }) => {+ name = w.string(start, e)?;+ w.seek_to(e)?;+ }+ (2, Wire::Fixed32(v)) => f = f32::from_bits(v),+ (3, Wire::Varint(v)) => i = v as i64,+ (4, Wire::Len { start, end: e }) => {+ s = w.string(start, e)?;+ w.seek_to(e)?;+ }+ (7, Wire::Len { end: e, .. }) => {+ // packed floats+ let at = w.pos()?;+ let raw = w.bytes(at, e, (MAX_LIST * 4) as u64)?;+ floats.extend(f32s(&raw));+ }+ (7, Wire::Fixed32(v)) => floats.push(f32::from_bits(v)),+ (8, Wire::Len { end: e, .. }) => {+ packed_varints(w, e, &mut ints)?;+ w.seek_to(e)?;+ }+ (8, Wire::Varint(v)) => {+ if ints.len() >= MAX_LIST {+ return malformed("a list is too long");+ }+ ints.push(v);+ }+ (20, Wire::Varint(v)) => kind = v,+ (_, Wire::Len { end: e, .. }) => w.seek_to(e)?,+ _ => {}+ }+ }+ let ints = ints.into_iter().map(|v| v as i64).collect();+ let value = match kind {+ 1 => Attr::Float(f),+ 2 => Attr::Int(i),+ 3 => Attr::Str(s),+ 6 => Attr::Floats(floats),+ 7 => Attr::Ints(ints),+ _ => Attr::Other,+ };+ Ok((name, value))+}++fn node(w: &mut Walker<Cursor<&[u8]>>, end: u64) -> Result<Node> {+ let mut n = Node { op: String::new(), inputs: Vec::new(), outputs: Vec::new(), attrs: HashMap::new() };+ while let Some((num, f)) = w.next(end)? {+ match (num, f) {+ (1, Wire::Len { start, end: e }) => {+ n.inputs.push(w.string(start, e)?);+ w.seek_to(e)?;+ }+ (2, Wire::Len { start, end: e }) => {+ n.outputs.push(w.string(start, e)?);+ w.seek_to(e)?;+ }+ (4, Wire::Len { start, end: e }) => {+ n.op = w.string(start, e)?;+ w.seek_to(e)?;+ }+ (5, Wire::Len { end: e, .. }) => {+ let (k, v) = attribute(w, e)?;+ n.attrs.insert(k, v);+ w.seek_to(e)?;+ }+ (_, Wire::Len { end: e, .. }) => w.seek_to(e)?,+ _ => {}+ }+ if n.inputs.len() > 64 || n.outputs.len() > 64 || n.attrs.len() > 64 {+ return malformed("a node is too large");+ }+ }+ Ok(n)+}++/// A weight tensor (`TensorProto`): its name, shape and float32 or int64 values.+fn tensor(w: &mut Walker<Cursor<&[u8]>>, end: u64, budget: &mut usize) -> Result<(String, Option<Weight>)> {+ let (mut name, mut dtype) = (String::new(), 0u64);+ let mut dims: Vec<u64> = Vec::new();+ let (mut raw, mut float_data, mut int_data): (Vec<u8>, Vec<f32>, Vec<u64>) = (Vec::new(), Vec::new(), Vec::new());+ let max_bytes = (*budget as u64).saturating_mul(8);+ while let Some((n, f)) = w.next(end)? {+ match (n, f) {+ (1, Wire::Len { end: e, .. }) => {+ packed_varints(w, e, &mut dims)?;+ w.seek_to(e)?;+ }+ (1, Wire::Varint(v)) => dims.push(v),+ (2, Wire::Varint(v)) => dtype = v,+ (4, Wire::Len { end: e, .. }) => {+ let at = w.pos()?;+ let bytes = w.bytes(at, e, max_bytes)?;+ float_data.extend(f32s(&bytes));+ }+ (7, Wire::Len { end: e, .. }) => {+ packed_varints(w, e, &mut int_data)?;+ w.seek_to(e)?;+ }+ (8, Wire::Len { start, end: e }) => {+ name = w.string(start, e)?;+ w.seek_to(e)?;+ }+ (9, Wire::Len { start, end: e }) => {+ raw = w.bytes(start, e, max_bytes)?;+ }+ (_, Wire::Len { end: e, .. }) => w.seek_to(e)?,+ _ => {}+ }+ if dims.len() > 8 {+ return malformed("a tensor has too many dimensions");+ }+ }+ let mut elements: usize = 1;+ let mut shape = Vec::new();+ for d in &dims {+ let d = usize::try_from(*d).map_err(|_| ProbeError::Malformed("a tensor dimension is too large"))?;+ elements = elements.checked_mul(d).ok_or(ProbeError::Malformed("a tensor is too large"))?;+ shape.push(d);+ }+ if elements > *budget {+ return malformed("the weights are too large");+ }+ *budget -= elements;+ let data = match dtype {+ 1 => {+ let v = if raw.is_empty() { float_data } else { f32s(&raw) };+ if v.len() != elements {+ return malformed("a weight tensor's size disagrees with its shape");+ }+ Some(Data::F32(v))+ }+ 7 => {+ let v = if raw.is_empty() { int_data.into_iter().map(|v| v as i64).collect() } else { i64s(&raw) };+ if v.len() != elements {+ return malformed("a weight tensor's size disagrees with its shape");+ }+ Some(Data::I64(v))+ }+ _ => None,+ };+ Ok((name, data.map(|data| Weight { dims: shape, data })))+}++fn value_info(w: &mut Walker<Cursor<&[u8]>>, end: u64) -> Result<(String, Vec<usize>)> {+ let (mut name, mut shape) = (String::new(), Vec::new());+ while let Some((n, f)) = w.next(end)? {+ match (n, f) {+ (1, Wire::Len { start, end: e }) => {+ name = w.string(start, e)?;+ w.seek_to(e)?;+ }+ (2, Wire::Len { end: e, .. }) => {+ // TypeProto > tensor_type (1) > shape (2) > dim (1) > dim_value (1)+ let mut info = crate::onnx::TensorInfo { name: String::new(), elem_type: 0, shape: Vec::new() };+ crate::onnx::type_proto(w, e, &mut info)?;+ shape = info.shape.iter().map(|d| if let crate::onnx::Dim::Fixed(v) = d { usize::try_from(*v).unwrap_or(0) } else { 0 }).collect();+ w.seek_to(e)?;+ }+ (_, Wire::Len { end: e, .. }) => w.seek_to(e)?,+ _ => {}+ }+ }+ if name.len() > MAX_NAME {+ return malformed("a name is too long");+ }+ Ok((name, shape))+}++/// Read a whole (small) ONNX model.+pub fn load(bytes: &[u8]) -> Result<Graph> {+ let total = bytes.len() as u64;+ if total == 0 {+ return malformed("the file is empty");+ }+ let mut cursor = Cursor::new(bytes);+ let mut w = Walker { r: &mut cursor, total, fields: 0 };+ let (mut nodes, mut weights, mut inputs, mut outputs) = (Vec::new(), HashMap::new(), Vec::new(), Vec::new());+ let mut budget = MAX_ELEMENTS;+ let mut saw_graph = false;+ while let Some((n, f)) = w.next(total)? {+ match (n, f) {+ (7, Wire::Len { end, .. }) => {+ saw_graph = true;+ while let Some((gn, gf)) = w.next(end)? {+ match (gn, gf) {+ (1, Wire::Len { end: e, .. }) => {+ if nodes.len() >= MAX_NODES {+ return malformed("too many nodes");+ }+ nodes.push(node(&mut w, e)?);+ w.seek_to(e)?;+ }+ (5, Wire::Len { end: e, .. }) => {+ if weights.len() >= MAX_TENSORS {+ return malformed("too many weight tensors");+ }+ let (name, wt) = tensor(&mut w, e, &mut budget)?;+ if let Some(wt) = wt {+ weights.insert(name, wt);+ }+ w.seek_to(e)?;+ }+ (11, Wire::Len { end: e, .. }) => {+ inputs.push(value_info(&mut w, e)?);+ w.seek_to(e)?;+ }+ (12, Wire::Len { end: e, .. }) => {+ outputs.push(value_info(&mut w, e)?.0);+ w.seek_to(e)?;+ }+ (_, Wire::Len { end: e, .. }) => w.seek_to(e)?,+ _ => {}+ }+ }+ w.seek_to(end)?;+ }+ (_, Wire::Len { end, .. }) => w.seek_to(end)?,+ _ => {}+ }+ }+ if !saw_graph || nodes.is_empty() {+ return malformed("no graph");+ }+ inputs.retain(|(name, _)| !weights.contains_key(name));+ if inputs.is_empty() || outputs.is_empty() {+ return malformed("the graph has no inputs or no outputs");+ }+ Ok(Graph { nodes, weights, inputs, outputs })+}diff --git a/crates/faces/src/known.rs b/crates/faces/src/known.rsindex b5c73d5fc..973d6d494 100644--- a/crates/faces/src/known.rs+++ b/crates/faces/src/known.rs@@ -8,6 +8,8 @@ use crate::manifest::{Colour, Commercial, InputSpec, Licence, ModelManifest, Out/// Detector output decoders built into LightCraft.pub const DECODERS: &[&str] = &["yunet-v2"];+/// The id of the face detector LightCraft runs (see [`yunet`]).+pub const YUNET_ID: &str = "yunet-2023mar";pub const YUNET_SHA256: &str = "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4";pub const SFACE_SHA256: &str = "0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79";pub const AURAFACE_SHA256: &str = "a7933ea5330113b01c9b60351d8f4c33003f145d8470ac5f0e52ee2effe25c60";@@ -19,7 +21,7 @@ fn licence(name: &str, commercial: Commercial, url: &str, notice: &str) -> Licen/// YuNet 2023mar (OpenCV Zoo): a small face detector.pub fn yunet() -> ModelManifest {ModelManifest {- id: "yunet-2023mar".into(),+ id: YUNET_ID.into(),name: "YuNet (face detector)".into(),version: "2023mar".into(),role: Role::Detector,@@ -32,9 +34,8 @@ pub fn yunet() -> ModelManifest {source: Some("https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet".into()),sha256: Some(YUNET_SHA256.into()),size_bytes: Some(232_589),- provenance:- "Trained on WIDER FACE, whose terms are not settled by the weights' MIT licence. A detector: it finds faces, it does not identify anyone."- .into(),+ provenance: "WIDER FACE, whose terms are not settled by the weights' MIT licence. A detector: it finds faces, it does not identify anyone."+ .into(),input: InputSpec { width: 640, height: 640, colour: Colour::Bgr, mean: [0.0; 3], std: [1.0; 3], resize: Resize::Letterbox },output: OutputSpec::Detector { decoder: "yunet-v2".into() },thresholds: Thresholds { match_cosine: None, score: Some(0.6), nms_iou: Some(0.3) },@@ -87,6 +88,61 @@ pub fn auraface() -> ModelManifest {}}+/// Where LightCraft can fetch a model from when the user asks: an address pinned to a commit of the model's own+/// repository, and the exact size and SHA-256 of the file (checked after the download, so the address is never+/// trusted on its own). The file is the last segment of the address, which is what the downloader needs: it fetches+/// `<mirror>/<file name>`, and here the mirror is everything before it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Download {+ pub id: &'static str,+ pub url: &'static str,+ pub file_name: &'static str,+ pub size_bytes: u64,+ pub sha256: &'static str,+}++impl Download {+ /// The address without the file name (the downloader's "mirror").+ pub fn base(&self) -> &'static str {+ self.url.strip_suffix(self.file_name).map_or(self.url, |b| b.trim_end_matches('/'))+ }++ /// "github.com": which site the file comes from, as the user is told.+ pub fn host(&self) -> &'static str {+ self.url.strip_prefix("https://").and_then(|r| r.split('/').next()).unwrap_or("")+ }+}++/// Models LightCraft offers to download. A model marked non-commercial is never here: the user brings that file.+pub const SOURCES: &[Download] = &[+ Download {+ id: YUNET_ID,+ url: "https://github.com/opencv/opencv_zoo/raw/25f423d0e04c31a17254620e58febd7386da523b/models/face_detection_yunet/face_detection_yunet_2023mar.onnx",+ file_name: "face_detection_yunet_2023mar.onnx",+ size_bytes: 232_589,+ sha256: YUNET_SHA256,+ },+ Download {+ id: "sface-2021dec",+ url: "https://github.com/opencv/opencv_zoo/raw/25f423d0e04c31a17254620e58febd7386da523b/models/face_recognition_sface/face_recognition_sface_2021dec.onnx",+ file_name: "face_recognition_sface_2021dec.onnx",+ size_bytes: 38_696_353,+ sha256: SFACE_SHA256,+ },+ Download {+ id: "auraface-v1",+ url: "https://huggingface.co/fal/AuraFace-v1/resolve/af6d057c9b0ec4071d4c49c80e3539258798b609/glintr100.onnx",+ file_name: "glintr100.onnx",+ size_bytes: 260_694_151,+ sha256: AURAFACE_SHA256,+ },+];++/// How to download the model with this id, if LightCraft offers to.+pub fn download(id: &str) -> Option<Download> {+ SOURCES.iter().find(|d| d.id == id).copied()+}+/// Every model we know by hash.pub fn all() -> Vec<ModelManifest> {vec![yunet(), sface(), auraface()]@@ -126,6 +182,25 @@ mod tests {assert!(lookup("").is_none());}+ #[test]+ fn downloads_are_pinned_checked_and_only_for_models_we_may_point_at() {+ for d in SOURCES {+ let m = all().into_iter().find(|m| m.id == d.id).unwrap_or_else(|| panic!("{} is not a known model", d.id));+ assert!(d.url.starts_with("https://"), "{}: https only", d.id);+ assert!(!d.url.contains("/main/") && !d.url.contains("/master/"), "{}: pinned to a commit, not a branch", d.id);+ assert!(d.file_name.ends_with(".onnx") && !d.file_name.contains(['/', '\\']), "{}", d.file_name);+ assert!(d.url.ends_with(&format!("/{}", d.file_name)), "{}: the address ends in the file's name", d.id);+ assert!(d.base().starts_with("https://") && !d.base().ends_with('/') && !d.base().ends_with(".onnx"), "{}", d.base());+ assert_eq!((Some(d.size_bytes), Some(d.sha256)), (m.size_bytes, m.sha256.as_deref()), "{}", d.id);+ assert!(m.licence.commercial != Commercial::No, "{} is non-commercial and must not be offered", d.id);+ }+ assert_eq!(download("yunet-2023mar").map(|d| d.host()), Some("github.com"));+ assert_eq!(download("auraface-v1").map(|d| d.host()), Some("huggingface.co"));+ for id in ["nope", "", "../sface-2021dec", "SFACE-2021DEC"] {+ assert!(download(id).is_none(), "{id}");+ }+ }+#[test]fn unresolved_models_say_so() {assert_eq!(sface().licence.commercial, Commercial::Unknown);diff --git a/crates/faces/src/lib.rs b/crates/faces/src/lib.rsindex 3a6298872..aace35754 100644--- a/crates/faces/src/lib.rs+++ b/crates/faces/src/lib.rs@@ -9,11 +9,14 @@#![forbid(unsafe_code)]#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]+pub mod graph;pub mod hash;pub mod known;pub mod manifest;+pub mod net;pub mod onnx;pub mod suggest;pub mod synthetic;+pub mod yunet;pub use manifest::{Colour, Commercial, InputSpec, Licence, ManifestError, ModelManifest, OutputSpec, Resize, Role, Thresholds};diff --git a/crates/faces/src/net.rs b/crates/faces/src/net.rsnew file mode 100644index 000000000..2b6c3342c--- /dev/null+++ b/crates/faces/src/net.rs@@ -0,0 +1,579 @@+//! A small CPU interpreter for the convolutional networks LightCraft bundles (the YuNet face detector).+//!+//! It runs exactly the operators such a network uses (Conv, Relu, Sigmoid, MaxPool, Resize by whole-number+//! nearest-neighbour scales, Add, Transpose, Reshape) on float32 NCHW tensors with a batch of one, and refuses+//! anything else with an error, so an unknown model fails to load rather than computing nonsense. It is pure+//! Rust with no dependencies, and the inner loops are row-wise multiply-adds over slices that the compiler can+//! vectorise. Every shape, stride and size comes from the file, so all of them are checked.+//!+//! This is not a general runtime: models users install run on `tract` (see the plan), not here.++use std::collections::HashMap;+use std::rc::Rc;++use crate::graph::{Data, Graph, Node};++/// Elements of any one tensor the interpreter will allocate.+const MAX_TENSOR: usize = 64 * 1024 * 1024;++#[derive(Debug, thiserror::Error, PartialEq)]+pub enum NetError {+ #[error("this model uses something the built-in runtime does not support: {0}")]+ Unsupported(String),+ #[error("the model does not fit together: {0}")]+ Shape(String),+}++type Result<T> = std::result::Result<T, NetError>;++fn shape_err<T>(why: impl Into<String>) -> Result<T> {+ Err(NetError::Shape(why.into()))+}++fn unsupported<T>(why: impl Into<String>) -> Result<T> {+ Err(NetError::Unsupported(why.into()))+}++#[derive(Clone, Debug, PartialEq)]+pub struct Tensor {+ pub shape: Vec<usize>,+ pub data: Vec<f32>,+}++impl Tensor {+ pub fn new(shape: Vec<usize>, data: Vec<f32>) -> Result<Tensor> {+ let n = shape.iter().try_fold(1usize, |a, d| a.checked_mul(*d));+ if n != Some(data.len()) {+ return shape_err(format!("{} values do not fill the shape {shape:?}", data.len()));+ }+ Ok(Tensor { shape, data })+ }++ fn zeros(shape: Vec<usize>) -> Result<Tensor> {+ match shape.iter().try_fold(1usize, |a, d| a.checked_mul(*d)) {+ Some(n) if n <= MAX_TENSOR => Ok(Tensor { shape, data: vec![0.0; n] }),+ _ => shape_err("a tensor would be too large"),+ }+ }+}++/// A loaded network, ready to run.+pub struct Net {+ graph: Graph,+}++/// Which operators and attribute combinations are supported, checked once when the network is built.+fn check(node: &Node, g: &Graph) -> Result<()> {+ let weight = |i: usize| node.inputs.get(i).and_then(|n| g.weights.get(n));+ match node.op.as_str() {+ "Conv" => {+ let Some(w) = weight(1) else { return unsupported("a Conv without constant weights") };+ if w.dims.len() != 4 || !matches!(w.data, Data::F32(_)) {+ return unsupported("a Conv that is not a 2-D float convolution");+ }+ if node.ints("dilations").is_some_and(|d| d.iter().any(|v| *v != 1)) {+ return unsupported("a dilated Conv");+ }+ if node.string("auto_pad").is_some_and(|s| s != "NOTSET") {+ return unsupported("a Conv with auto_pad");+ }+ if node.inputs.get(2).is_some_and(|b| !b.is_empty() && !g.weights.contains_key(b)) {+ return unsupported("a Conv with a computed bias");+ }+ }+ "Relu" | "Sigmoid" | "Add" => {}+ "MaxPool" => {+ if node.int("ceil_mode").unwrap_or(0) != 0 || node.ints("kernel_shape").is_none_or(|k| k.len() != 2) {+ return unsupported("this MaxPool");+ }+ if node.ints("dilations").is_some_and(|d| d.iter().any(|v| *v != 1)) {+ return unsupported("a dilated MaxPool");+ }+ }+ "Resize" => {+ if node.string("mode").unwrap_or("nearest") != "nearest" {+ return unsupported("a Resize that is not nearest-neighbour");+ }+ if !node.inputs.get(2).is_some_and(|s| g.weights.contains_key(s)) {+ return unsupported("a Resize without constant scales");+ }+ }+ "Transpose" => {+ if node.ints("perm").is_none() {+ return unsupported("a Transpose without a permutation");+ }+ }+ "Reshape" => {+ if !node.inputs.get(1).is_some_and(|s| matches!(g.weights.get(s).map(|w| &w.data), Some(Data::I64(_)))) {+ return unsupported("a Reshape with a computed shape");+ }+ }+ other => return unsupported(format!("the operator `{other}`")),+ }+ Ok(())+}++impl Net {+ pub fn new(graph: Graph) -> Result<Net> {+ for n in &graph.nodes {+ check(n, &graph)?;+ }+ Ok(Net { graph })+ }++ /// The shape the model declares for its input (0 for a dynamic size).+ pub fn input_shape(&self) -> Option<&[usize]> {+ self.graph.inputs.first().map(|(_, s)| s.as_slice())+ }++ /// Run the network on `input` (its single input); returns each output by name.+ pub fn run(&self, input: Tensor) -> Result<Vec<(String, Tensor)>> {+ let g = &self.graph;+ let Some((input_name, _)) = g.inputs.first() else { return shape_err("the model has no input") };+ // when each value is last read, so big intermediates are dropped as soon as nothing needs them+ let mut last_use: HashMap<&str, usize> = HashMap::new();+ for (i, n) in g.nodes.iter().enumerate() {+ for name in &n.inputs {+ last_use.insert(name.as_str(), i);+ }+ }+ for o in &g.outputs {+ last_use.insert(o.as_str(), usize::MAX);+ }+ let mut values: HashMap<String, Rc<Tensor>> = HashMap::new();+ values.insert(input_name.clone(), Rc::new(input));+ for (i, node) in g.nodes.iter().enumerate() {+ let get = |idx: usize| -> Result<Rc<Tensor>> {+ let name = node.inputs.get(idx).ok_or_else(|| NetError::Shape(format!("{} is missing an input", node.op)))?;+ values.get(name).cloned().ok_or_else(|| NetError::Shape(format!("`{name}` is read before it is computed")))+ };+ let out = match node.op.as_str() {+ "Conv" => conv(node, &*get(0)?, g)?,+ "Relu" => map(&*get(0)?, |v| v.max(0.0)),+ "Sigmoid" => map(&*get(0)?, |v| 1.0 / (1.0 + (-v).exp())),+ "Add" => add(&*get(0)?, &*get(1)?)?,+ "MaxPool" => max_pool(node, &*get(0)?)?,+ "Resize" => resize(node, &*get(0)?, g)?,+ "Transpose" => transpose(node, &*get(0)?)?,+ "Reshape" => reshape(node, &*get(0)?, g)?,+ other => return unsupported(format!("the operator `{other}`")),+ };+ let Some(name) = node.outputs.first() else { return shape_err("a node has no output") };+ values.insert(name.clone(), Rc::new(out));+ for name in &node.inputs {+ if last_use.get(name.as_str()) == Some(&i) {+ values.remove(name);+ }+ }+ }+ g.outputs+ .iter()+ .map(|name| {+ let t = values.get(name).ok_or_else(|| NetError::Shape(format!("output `{name}` was never computed")))?;+ Ok((name.clone(), (**t).clone()))+ })+ .collect()+ }+}++fn map(x: &Tensor, f: impl Fn(f32) -> f32) -> Tensor {+ Tensor { shape: x.shape.clone(), data: x.data.iter().map(|v| f(*v)).collect() }+}++fn add(a: &Tensor, b: &Tensor) -> Result<Tensor> {+ if a.shape != b.shape {+ return unsupported("an Add that broadcasts");+ }+ Ok(Tensor { shape: a.shape.clone(), data: a.data.iter().zip(&b.data).map(|(x, y)| x + y).collect() })+}++/// `[1, c, h, w]` → `(c, h, w)`.+fn chw(x: &Tensor) -> Result<(usize, usize, usize)> {+ match x.shape.as_slice() {+ [1, c, h, w] => Ok((*c, *h, *w)),+ s => unsupported(format!("a tensor of shape {s:?} (only [1, channels, height, width])")),+ }+}++/// `pads` of an ONNX node as (top, left, bottom, right).+fn pads(node: &Node) -> Result<(usize, usize, usize, usize)> {+ match node.ints("pads") {+ None => Ok((0, 0, 0, 0)),+ Some([t, l, b, r]) => {+ let u = |v: &i64| usize::try_from(*v).map_err(|_| NetError::Shape("a negative pad".into()));+ Ok((u(t)?, u(l)?, u(b)?, u(r)?))+ }+ Some(_) => unsupported("pads that are not [top, left, bottom, right]"),+ }+}++fn pair(node: &Node, name: &str, default: usize) -> Result<(usize, usize)> {+ match node.ints(name) {+ None => Ok((default, default)),+ Some([a, b]) => match (usize::try_from(*a), usize::try_from(*b)) {+ (Ok(a), Ok(b)) if a >= 1 && b >= 1 => Ok((a, b)),+ _ => shape_err(format!("`{name}` must be positive")),+ },+ Some(_) => unsupported(format!("`{name}` that is not two numbers")),+ }+}++fn conv(node: &Node, x: &Tensor, g: &Graph) -> Result<Tensor> {+ let (cin, h, w) = chw(x)?;+ let weight = node.inputs.get(1).and_then(|n| g.weights.get(n)).ok_or_else(|| NetError::Shape("a Conv lost its weights".into()))?;+ let Data::F32(wd) = &weight.data else { return unsupported("non-float Conv weights") };+ let [cout, cin_g, kh, kw] = weight.dims.as_slice() else { return unsupported("a Conv that is not 2-D") };+ let (cout, cin_g, kh, kw) = (*cout, *cin_g, *kh, *kw);+ let groups =+ usize::try_from(node.int("group").unwrap_or(1)).ok().filter(|g| *g >= 1).ok_or_else(|| NetError::Shape("a bad Conv group".into()))?;+ if groups.checked_mul(cin_g) != Some(cin) || cout % groups != 0 || kh == 0 || kw == 0 {+ return shape_err("the Conv weights do not match its input");+ }+ let bias: Option<&[f32]> = match node.inputs.get(2).filter(|b| !b.is_empty()).and_then(|b| g.weights.get(b)) {+ Some(b) => match &b.data {+ Data::F32(v) if v.len() == cout => Some(v),+ _ => return shape_err("the Conv bias does not match"),+ },+ None => None,+ };+ let (sh, sw) = pair(node, "strides", 1)?;+ let (pt, pl, pb, pr) = pads(node)?;+ let (ph, pw) = (h + pt + pb, w + pl + pr);+ if ph < kh || pw < kw {+ return shape_err("the Conv kernel is larger than its input");+ }+ let (oh, ow) = ((ph - kh) / sh + 1, (pw - kw) / sw + 1);+ let mut out = Tensor::zeros(vec![1, cout, oh, ow])?;+ let plane = oh * ow;+ let in_planes: Vec<&[f32]> = x.data.chunks_exact((h * w).max(1)).collect();+ let cout_g = cout / groups;+ for (co, out_plane) in out.data.chunks_exact_mut(plane.max(1)).enumerate() {+ if let Some(b) = bias.and_then(|b| b.get(co)) {+ out_plane.iter_mut().for_each(|o| *o = *b);+ }+ let group = co / cout_g;+ for ci_l in 0..cin_g {+ let Some(in_plane) = in_planes.get(group * cin_g + ci_l) else { return shape_err("a Conv input channel is missing") };+ let base = (co * cin_g + ci_l) * kh * kw;+ let Some(kernel) = wd.get(base..base + kh * kw) else { return shape_err("the Conv weights are too short") };+ for (k, wv) in kernel.iter().enumerate() {+ if *wv == 0.0 {+ continue;+ }+ let (ky, kx) = (k / kw, k % kw);+ for oy in 0..oh {+ // input row for this output row and kernel row (in padded coordinates minus the pad)+ let Some(iy) = (oy * sh + ky).checked_sub(pt).filter(|iy| *iy < h) else { continue };+ let in_row = in_plane.get(iy * w..(iy + 1) * w).unwrap_or(&[]);+ let out_row = out_plane.get_mut(oy * ow..(oy + 1) * ow).unwrap_or(&mut []);+ if sw == 1 {+ // ox runs over outputs whose input column ox + kx - pl lies inside the row+ let lo = pl.saturating_sub(kx);+ let hi = ow.min((w + pl).saturating_sub(kx));+ if lo < hi {+ let src = in_row.get(lo + kx - pl..hi + kx - pl).unwrap_or(&[]);+ let dst = out_row.get_mut(lo..hi).unwrap_or(&mut []);+ dst.iter_mut().zip(src).for_each(|(o, i)| *o += wv * i);+ }+ } else {+ for (ox, o) in out_row.iter_mut().enumerate() {+ if let Some(ix) = (ox * sw + kx).checked_sub(pl).filter(|ix| *ix < w)+ && let Some(i) = in_row.get(ix)+ {+ *o += wv * i;+ }+ }+ }+ }+ }+ }+ }+ Ok(out)+}++fn max_pool(node: &Node, x: &Tensor) -> Result<Tensor> {+ let (c, h, w) = chw(x)?;+ let (kh, kw) = pair(node, "kernel_shape", 1)?;+ let (sh, sw) = pair(node, "strides", 1)?;+ let (pt, pl, pb, pr) = pads(node)?;+ if (pt, pl, pb, pr) != (0, 0, 0, 0) {+ return unsupported("a padded MaxPool");+ }+ if h < kh || w < kw {+ return shape_err("the MaxPool window is larger than its input");+ }+ let (oh, ow) = ((h - kh) / sh + 1, (w - kw) / sw + 1);+ let mut out = Tensor::zeros(vec![1, c, oh, ow])?;+ for (plane_in, plane_out) in x.data.chunks_exact((h * w).max(1)).zip(out.data.chunks_exact_mut((oh * ow).max(1))) {+ for oy in 0..oh {+ for ox in 0..ow {+ let mut m = f32::NEG_INFINITY;+ for ky in 0..kh {+ let row = plane_in.get((oy * sh + ky) * w..(oy * sh + ky + 1) * w).unwrap_or(&[]);+ for kx in 0..kw {+ if let Some(v) = row.get(ox * sw + kx) {+ m = m.max(*v);+ }+ }+ }+ if let Some(o) = plane_out.get_mut(oy * ow + ox) {+ *o = m;+ }+ }+ }+ }+ Ok(out)+}++/// Nearest-neighbour upscale by whole numbers (YuNet's feature pyramid doubles each map).+fn resize(node: &Node, x: &Tensor, g: &Graph) -> Result<Tensor> {+ let (c, h, w) = chw(x)?;+ let scales = match node.inputs.get(2).and_then(|n| g.weights.get(n)).map(|w| &w.data) {+ Some(Data::F32(s)) if s.len() == 4 => s,+ _ => return unsupported("a Resize whose scales are not four floats"),+ };+ let whole = |v: f32| ((1.0..=16.0).contains(&v) && v.fract() == 0.0).then_some(v as usize);+ let (Some(sh), Some(sw)) = (whole(scales.get(2).copied().unwrap_or(0.0)), whole(scales.get(3).copied().unwrap_or(0.0))) else {+ return unsupported("a Resize by a scale that is not a whole number from 1 to 16");+ };+ if scales.first() != Some(&1.0) || scales.get(1) != Some(&1.0) {+ return unsupported("a Resize that scales channels");+ }+ let (oh, ow) = (h * sh, w * sw);+ let mut out = Tensor::zeros(vec![1, c, oh, ow])?;+ for (plane_in, plane_out) in x.data.chunks_exact((h * w).max(1)).zip(out.data.chunks_exact_mut((oh * ow).max(1))) {+ for (oy, row_out) in plane_out.chunks_exact_mut(ow.max(1)).enumerate() {+ let row_in = plane_in.get((oy / sh) * w..(oy / sh + 1) * w).unwrap_or(&[]);+ for (ox, o) in row_out.iter_mut().enumerate() {+ *o = row_in.get(ox / sw).copied().unwrap_or(0.0);+ }+ }+ }+ Ok(out)+}++fn transpose(node: &Node, x: &Tensor) -> Result<Tensor> {+ let perm: Vec<usize> = node+ .ints("perm")+ .unwrap_or(&[])+ .iter()+ .map(|p| usize::try_from(*p).map_err(|_| NetError::Shape("a negative permutation".into())))+ .collect::<Result<_>>()?;+ let rank = x.shape.len();+ let mut seen = vec![false; rank];+ if perm.len() != rank || perm.iter().any(|p| *p >= rank || std::mem::replace(seen.get_mut(*p).unwrap_or(&mut true), true)) {+ return shape_err("the Transpose permutation does not match the tensor");+ }+ let out_shape: Vec<usize> = perm.iter().filter_map(|p| x.shape.get(*p).copied()).collect();+ // strides of the input, in elements+ let mut in_strides = vec![1usize; rank];+ for i in (0..rank.saturating_sub(1)).rev() {+ in_strides[i] = in_strides.get(i + 1).copied().unwrap_or(1) * x.shape.get(i + 1).copied().unwrap_or(1);+ }+ let strides_for_out: Vec<usize> = perm.iter().filter_map(|p| in_strides.get(*p).copied()).collect();+ let mut out = Tensor::zeros(out_shape.clone())?;+ let mut counter = vec![0usize; rank];+ let mut src = 0usize;+ for o in out.data.iter_mut() {+ *o = x.data.get(src).copied().unwrap_or(0.0);+ // advance the multi-index of the output and the matching input offset+ for d in (0..rank).rev() {+ let (Some(c), Some(len), Some(stride)) = (counter.get_mut(d), out_shape.get(d), strides_for_out.get(d)) else { break };+ *c += 1;+ src += stride;+ if *c < *len {+ break;+ }+ src -= stride * *len;+ *c = 0;+ }+ }+ Ok(out)+}++fn reshape(node: &Node, x: &Tensor, g: &Graph) -> Result<Tensor> {+ let Some(Data::I64(dims)) = node.inputs.get(1).and_then(|n| g.weights.get(n)).map(|w| &w.data) else {+ return unsupported("a Reshape with a computed shape");+ };+ let total = x.data.len();+ let mut shape: Vec<usize> = Vec::with_capacity(dims.len());+ let mut infer = None;+ for (i, d) in dims.iter().enumerate() {+ match *d {+ -1 if infer.is_none() => {+ infer = Some(i);+ shape.push(1);+ }+ 0 => shape.push(x.shape.get(i).copied().ok_or_else(|| NetError::Shape("a Reshape copies a missing dimension".into()))?),+ d if d > 0 => shape.push(usize::try_from(d).map_err(|_| NetError::Shape("a Reshape dimension is too large".into()))?),+ _ => return shape_err("a bad Reshape dimension"),+ }+ }+ let known = shape.iter().try_fold(1usize, |a, d| a.checked_mul(*d)).filter(|k| *k > 0);+ if let (Some(i), Some(known)) = (infer, known) {+ if !total.is_multiple_of(known) {+ return shape_err("the Reshape does not divide evenly");+ }+ if let Some(s) = shape.get_mut(i) {+ *s = total / known;+ }+ }+ Tensor::new(shape, x.data.clone())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::graph::{Attr, Weight};++ fn node(op: &str, inputs: &[&str], attrs: &[(&str, Attr)]) -> Node {+ Node {+ op: op.into(),+ inputs: inputs.iter().map(|s| s.to_string()).collect(),+ outputs: vec!["y".into()],+ attrs: attrs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(),+ }+ }+ fn graph(nodes: Vec<Node>, weights: Vec<(&str, Weight)>) -> Graph {+ Graph {+ nodes,+ weights: weights.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),+ inputs: vec![("x".into(), vec![1, 1, 3, 3])],+ outputs: vec!["y".into()],+ }+ }+ fn w(dims: &[usize], v: Vec<f32>) -> Weight {+ Weight { dims: dims.to_vec(), data: Data::F32(v) }+ }+ fn input(c: usize, h: usize, wd: usize, f: impl Fn(usize) -> f32) -> Tensor {+ Tensor::new(vec![1, c, h, wd], (0..c * h * wd).map(f).collect()).unwrap()+ }+ fn run(g: Graph, x: Tensor) -> Result<Tensor> {+ Ok(Net::new(g)?.run(x)?.remove(0).1)+ }++ /// A direct, slow reference convolution to check the fast one against.+ fn reference_conv(x: &Tensor, wd: &[f32], dims: [usize; 4], bias: &[f32], s: usize, p: usize, groups: usize) -> Tensor {+ let (c, h, wi) = (x.shape[1], x.shape[2], x.shape[3]);+ let [co_n, cin_g, kh, kw] = dims;+ let (oh, ow) = ((h + 2 * p - kh) / s + 1, (wi + 2 * p - kw) / s + 1);+ let mut out = vec![0.0f32; co_n * oh * ow];+ for co in 0..co_n {+ let g = co / (co_n / groups);+ for oy in 0..oh {+ for ox in 0..ow {+ let mut acc = bias[co];+ for cl in 0..cin_g {+ for ky in 0..kh {+ for kx in 0..kw {+ let (iy, ix) = ((oy * s + ky) as isize - p as isize, (ox * s + kx) as isize - p as isize);+ if iy >= 0 && ix >= 0 && (iy as usize) < h && (ix as usize) < wi {+ acc +=+ x.data[((g * cin_g + cl) * h + iy as usize) * wi + ix as usize] * wd[((co * cin_g + cl) * kh + ky) * kw + kx];+ }+ }+ }+ }+ out[(co * oh + oy) * ow + ox] = acc;+ }+ }+ }+ let _ = c;+ Tensor::new(vec![1, co_n, oh, ow], out).unwrap()+ }++ #[test]+ fn convolutions_match_a_slow_reference() {+ // (cin, cout, groups, kernel, stride, pad, h, w)+ for (cin, cout, groups, k, s, p, h, wi) in [+ (3, 4, 1, 3, 1, 1, 7, 9),+ (3, 4, 1, 3, 2, 1, 8, 8),+ (4, 4, 4, 3, 1, 1, 6, 5),+ (2, 6, 1, 1, 1, 0, 5, 5),+ (4, 8, 2, 3, 1, 1, 5, 6),+ (1, 1, 1, 3, 1, 0, 3, 3),+ ] {+ let cin_g = cin / groups;+ let wd: Vec<f32> = (0..cout * cin_g * k * k).map(|i| ((i * 37 % 11) as f32 - 5.0) * 0.1).collect();+ let bias: Vec<f32> = (0..cout).map(|i| i as f32 * 0.25 - 0.5).collect();+ let x = input(cin, h, wi, |i| ((i * 13 % 17) as f32 - 8.0) * 0.2);+ let attrs = [("group", Attr::Int(groups as i64)), ("strides", Attr::Ints(vec![s as i64; 2])), ("pads", Attr::Ints(vec![p as i64; 4]))];+ let g = graph(+ vec![node("Conv", &["x", "w", "b"], &attrs)],+ vec![("w", w(&[cout, cin_g, k, k], wd.clone())), ("b", w(&[cout], bias.clone()))],+ );+ let got = run(g, x.clone()).unwrap();+ let want = reference_conv(&x, &wd, [cout, cin_g, k, k], &bias, s, p, groups);+ assert_eq!(got.shape, want.shape, "{cin} {cout} {groups} {k} {s} {p}");+ for (a, b) in got.data.iter().zip(&want.data) {+ assert!((a - b).abs() < 1e-4, "{cin} {cout} {groups} {k} {s} {p}: {a} vs {b}");+ }+ }+ }++ #[test]+ fn the_small_operators() {+ let x = input(1, 4, 4, |i| i as f32 - 6.0);+ // Relu, Sigmoid+ let r = run(graph(vec![node("Relu", &["x"], &[])], vec![]), x.clone()).unwrap();+ assert!(r.data.iter().all(|v| *v >= 0.0) && r.data.get(7) == Some(&1.0));+ let s = run(graph(vec![node("Sigmoid", &["x"], &[])], vec![]), x.clone()).unwrap();+ assert!((s.data[6] - 0.5).abs() < 1e-6 && s.data.iter().all(|v| (0.0..=1.0).contains(v)));+ // MaxPool 2x2/2+ let m = run(+ graph(vec![node("MaxPool", &["x"], &[("kernel_shape", Attr::Ints(vec![2, 2])), ("strides", Attr::Ints(vec![2, 2]))])], vec![]),+ x.clone(),+ )+ .unwrap();+ assert_eq!((m.shape.clone(), m.data.clone()), (vec![1, 1, 2, 2], vec![-1.0, 1.0, 7.0, 9.0]));+ // Resize x2 nearest+ let z = run(graph(vec![node("Resize", &["x", "", "s"], &[])], vec![("s", w(&[4], vec![1.0, 1.0, 2.0, 2.0]))]), input(1, 2, 2, |i| i as f32))+ .unwrap();+ assert_eq!(z.shape, vec![1, 1, 4, 4]);+ assert_eq!(&z.data[..8], &[0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0]);+ // Add+ let a = run(graph(vec![node("Add", &["x", "x"], &[])], vec![]), x.clone()).unwrap();+ assert_eq!(a.data[5], 2.0 * x.data[5]);+ // Transpose [0,2,3,1] then Reshape [1,-1,2]+ let t = run(graph(vec![node("Transpose", &["x"], &[("perm", Attr::Ints(vec![0, 2, 3, 1]))])], vec![]), input(2, 2, 3, |i| i as f32)).unwrap();+ assert_eq!(t.shape, vec![1, 2, 3, 2]);+ assert_eq!(t.data, vec![0.0, 6.0, 1.0, 7.0, 2.0, 8.0, 3.0, 9.0, 4.0, 10.0, 5.0, 11.0]);+ let rs = run(+ graph(vec![node("Reshape", &["x", "s"], &[])], vec![("s", Weight { dims: vec![3], data: Data::I64(vec![1, -1, 2]) })]),+ input(2, 2, 3, |i| i as f32),+ )+ .unwrap();+ assert_eq!(rs.shape, vec![1, 6, 2]);+ }++ #[test]+ fn unsupported_and_inconsistent_models_are_errors() {+ let x = input(1, 3, 3, |i| i as f32);+ for (what, g) in [+ ("unknown op", graph(vec![node("Softmax", &["x"], &[])], vec![])),+ (+ "dilated conv",+ graph(vec![node("Conv", &["x", "w"], &[("dilations", Attr::Ints(vec![2, 2]))])], vec![("w", w(&[1, 1, 1, 1], vec![1.0]))]),+ ),+ ("conv without weights", graph(vec![node("Conv", &["x", "w"], &[])], vec![])),+ ("channels do not match", graph(vec![node("Conv", &["x", "w"], &[])], vec![("w", w(&[1, 5, 1, 1], vec![1.0; 5]))])),+ ("kernel too big", graph(vec![node("Conv", &["x", "w"], &[])], vec![("w", w(&[1, 1, 5, 5], vec![1.0; 25]))])),+ ("zero group", graph(vec![node("Conv", &["x", "w"], &[("group", Attr::Int(0))])], vec![("w", w(&[1, 1, 1, 1], vec![1.0]))])),+ ("zero stride", graph(vec![node("Conv", &["x", "w"], &[("strides", Attr::Ints(vec![0, 0]))])], vec![("w", w(&[1, 1, 1, 1], vec![1.0]))])),+ (+ "negative pad",+ graph(vec![node("Conv", &["x", "w"], &[("pads", Attr::Ints(vec![-1, 0, 0, 0]))])], vec![("w", w(&[1, 1, 1, 1], vec![1.0]))]),+ ),+ ("bad perm", graph(vec![node("Transpose", &["x"], &[("perm", Attr::Ints(vec![0, 0, 1, 2]))])], vec![])),+ (+ "huge reshape",+ graph(vec![node("Reshape", &["x", "s"], &[])], vec![("s", Weight { dims: vec![2], data: Data::I64(vec![i64::MAX, 1]) })]),+ ),+ ("reshape mismatch", graph(vec![node("Reshape", &["x", "s"], &[])], vec![("s", Weight { dims: vec![2], data: Data::I64(vec![4, 4]) })])),+ ("non-integer resize", graph(vec![node("Resize", &["x", "", "s"], &[])], vec![("s", w(&[4], vec![1.0, 1.0, 1.5, 1.5]))])),+ ("add that broadcasts", graph(vec![node("Add", &["x", "c"], &[])], vec![])),+ ] {+ assert!(run(g, x.clone()).is_err(), "{what}");+ }+ }+}diff --git a/crates/faces/src/onnx.rs b/crates/faces/src/onnx.rsindex f4c981b08..f94f67000 100644--- a/crates/faces/src/onnx.rs+++ b/crates/faces/src/onnx.rs@@ -51,36 +51,37 @@ pub enum ProbeError {Io(#[from] io::Error),}-type Result<T> = std::result::Result<T, ProbeError>;+pub(crate) type Result<T> = std::result::Result<T, ProbeError>;-enum Wire {+pub(crate) enum Wire {Varint(u64),/// A length-delimited field: its bytes are `start..end` and the reader sits at `start`.Len {start: u64,end: u64,},- /// Fixed-width data already skipped.- Skipped,+ Fixed32(u32),+ #[allow(dead_code)]+ Fixed64(u64),}-struct Walker<'a, R> {- r: &'a mut R,- total: u64,- fields: u32,+pub(crate) struct Walker<'a, R> {+ pub(crate) r: &'a mut R,+ pub(crate) total: u64,+ pub(crate) fields: u32,}impl<R: Read + Seek> Walker<'_, R> {- fn pos(&mut self) -> Result<u64> {+ pub(crate) fn pos(&mut self) -> Result<u64> {Ok(self.r.stream_position()?)}- fn seek_to(&mut self, at: u64) -> Result<()> {+ pub(crate) fn seek_to(&mut self, at: u64) -> Result<()> {self.r.seek(SeekFrom::Start(at))?;Ok(())}- fn byte(&mut self) -> Result<u8> {+ pub(crate) fn byte(&mut self) -> Result<u8> {let mut b = [0u8; 1];self.r.read_exact(&mut b)@@ -89,7 +90,7 @@ impl<R: Read + Seek> Walker<'_, R> {Ok(x)}- fn varint(&mut self) -> Result<u64> {+ pub(crate) fn varint(&mut self) -> Result<u64> {let mut v = 0u64;for shift in (0..70u32).step_by(7) {let b = self.byte()?;@@ -104,7 +105,7 @@ impl<R: Read + Seek> Walker<'_, R> {}/// The next field of the message that ends at `end`, or `None` at its end.- fn next(&mut self, end: u64) -> Result<Option<(u32, Wire)>> {+ pub(crate) fn next(&mut self, end: u64) -> Result<Option<(u32, Wire)>> {let here = self.pos()?;if here >= end {return Ok(None);@@ -117,14 +118,23 @@ impl<R: Read + Seek> Walker<'_, R> {let number = u32::try_from(tag >> 3).map_err(|_| ProbeError::Malformed("field number too large"))?;let wire = match tag & 7 {0 => Wire::Varint(self.varint()?),- 1 | 5 => {- let n = if tag & 7 == 1 { 8 } else { 4 };- let at = self.pos()?.checked_add(n).ok_or(ProbeError::Malformed("offset overflow"))?;- if at > end {+ 1 => {+ let at = self.pos()?.checked_add(8).ok_or(ProbeError::Malformed("offset overflow"))?;+ if at > end || at > self.total {return Err(ProbeError::Malformed("field runs past its message"));}- self.seek_to(at)?;- Wire::Skipped+ let mut b = [0u8; 8];+ self.r.read_exact(&mut b).map_err(|_| ProbeError::Malformed("file ends inside a field"))?;+ Wire::Fixed64(u64::from_le_bytes(b))+ }+ 5 => {+ let at = self.pos()?.checked_add(4).ok_or(ProbeError::Malformed("offset overflow"))?;+ if at > end || at > self.total {+ return Err(ProbeError::Malformed("field runs past its message"));+ }+ let mut b = [0u8; 4];+ self.r.read_exact(&mut b).map_err(|_| ProbeError::Malformed("file ends inside a field"))?;+ Wire::Fixed32(u32::from_le_bytes(b))}2 => {let len = self.varint()?;@@ -141,7 +151,7 @@ impl<R: Read + Seek> Walker<'_, R> {}/// A bounded UTF-8 string occupying `start..end` (empty when it is longer than we care about).- fn string(&mut self, start: u64, end: u64) -> Result<String> {+ pub(crate) fn string(&mut self, start: u64, end: u64) -> Result<String> {let len = end.saturating_sub(start);if len > MAX_STRING {return Ok(String::new());@@ -150,6 +160,20 @@ impl<R: Read + Seek> Walker<'_, R> {self.r.by_ref().take(len).read_to_end(&mut buf)?;Ok(String::from_utf8_lossy(&buf).into_owned())}++ /// The bytes of `start..end`, which must be at most `max` long.+ pub(crate) fn bytes(&mut self, start: u64, end: u64, max: u64) -> Result<Vec<u8>> {+ let len = end.saturating_sub(start);+ if len > max {+ return Err(ProbeError::Malformed("a field is larger than allowed"));+ }+ let mut buf = Vec::new();+ self.r.by_ref().take(len).read_to_end(&mut buf)?;+ if buf.len() as u64 != len {+ return Err(ProbeError::Malformed("file ends inside a field"));+ }+ Ok(buf)+ }}fn dim<R: Read + Seek>(w: &mut Walker<R>, end: u64) -> Result<Option<Dim>> {@@ -201,7 +225,7 @@ fn tensor_type<R: Read + Seek>(w: &mut Walker<R>, end: u64, info: &mut TensorInfOk(())}-fn type_proto<R: Read + Seek>(w: &mut Walker<R>, end: u64, info: &mut TensorInfo) -> Result<()> {+pub(crate) fn type_proto<R: Read + Seek>(w: &mut Walker<R>, end: u64, info: &mut TensorInfo) -> Result<()> {while let Some((n, f)) = w.next(end)? {match (n, f) {(1, Wire::Len { end: e, .. }) => {diff --git a/crates/faces/src/yunet.rs b/crates/faces/src/yunet.rsnew file mode 100644index 000000000..3a24fe18e--- /dev/null+++ b/crates/faces/src/yunet.rs@@ -0,0 +1,337 @@+//! The YuNet face detector (232 KB, MIT, downloaded by the user in Settings ▸ Faces), run by LightCraft's own small+//! interpreter ([`crate::net`]): no extra runtime.+//!+//! A photo is letterboxed (aspect ratio kept, padded at the right and bottom) into the network's square+//! input, the network gives a score, a box and five landmarks for every cell of three grids (strides 8, 16 and+//! 32), and the cells above the score threshold are decoded, de-duplicated by non-maximum suppression and+//! mapped back to the photo as fractions of its width and height.+//!+//! The pixels come from the caller as plain 8-bit RGB; this module has no image types of its own.++use crate::graph;+use crate::net::{Net, NetError, Tensor};++const STRIDES: [usize; 3] = [8, 16, 32];+/// Largest photo side we accept.+const MAX_SIDE: usize = 65_536;+/// Candidate cells kept before suppression, so a hostile or noisy output cannot make it slow.+const MAX_CANDIDATES: usize = 4000;++#[derive(Debug, thiserror::Error)]+pub enum DetectError {+ #[error("the detector model is not usable: {0}")]+ Model(String),+ #[error("{0}")]+ Input(String),+}++impl From<NetError> for DetectError {+ fn from(e: NetError) -> Self {+ DetectError::Model(e.to_string())+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Options {+ /// Lowest detection score kept (0 to 1).+ pub score: f32,+ /// Boxes overlapping a better one by more than this (intersection over union) are dropped.+ pub nms_iou: f32,+ /// Most faces returned.+ pub max_faces: usize,+}++impl Default for Options {+ fn default() -> Self {+ Options { score: 0.6, nms_iou: 0.3, max_faces: 200 }+ }+}++/// A detected face, in fractions of the photo's width and height (0 to 1, y down).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Face {+ pub x0: f32,+ pub y0: f32,+ pub x1: f32,+ pub y1: f32,+ pub score: f32,+ /// Right eye, left eye, nose tip, right and left mouth corner, as the detector names them (from the+ /// subject's point of view, so the "right eye" is on the left of the picture). May lie slightly outside 0 to 1.+ pub landmarks: [(f32, f32); 5],+}++pub struct Detector {+ net: Net,+ /// Side of the square network input.+ side: usize,+}++impl Detector {+ /// A detector from YuNet-architecture ONNX bytes (a retrained model of the same shape works too).+ pub fn new(onnx: &[u8]) -> Result<Detector, DetectError> {+ let g = graph::load(onnx).map_err(|e| DetectError::Model(e.to_string()))?;+ let net = Net::new(g)?;+ let side = match net.input_shape() {+ Some(&[1, 3, h, w]) if h == w && (64..=4096).contains(&h) && h % 32 == 0 => h,+ _ => return Err(DetectError::Model("the model's input is not a fixed square image [1, 3, N, N] with N a multiple of 32".into())),+ };+ Ok(Detector { net, side })+ }++ /// Find faces in an upright `width` × `height` photo of 8-bit RGB pixels (`rgb` is `width * height * 3` bytes).+ pub fn detect(&self, rgb: &[u8], width: usize, height: usize, opts: &Options) -> Result<Vec<Face>, DetectError> {+ if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {+ return Err(DetectError::Input(format!("a {width} × {height} picture cannot be searched")));+ }+ if width.checked_mul(height).and_then(|n| n.checked_mul(3)) != Some(rgb.len()) {+ return Err(DetectError::Input("the pixel data does not match the picture's size".into()));+ }+ let opts = Options {+ score: if opts.score.is_finite() { opts.score.clamp(0.0, 1.0) } else { 0.6 },+ nms_iou: if opts.nms_iou.is_finite() { opts.nms_iou.clamp(0.0, 1.0) } else { 0.3 },+ max_faces: opts.max_faces.min(10_000),+ };+ let scale = (self.side as f32 / width as f32).min(self.side as f32 / height as f32);+ let input = self.letterbox(rgb, width, height, scale)?;+ let outputs = self.net.run(input)?;+ let find = |name: String| {+ outputs.iter().find(|(n, _)| *n == name).map(|(_, t)| t).ok_or_else(|| DetectError::Model(format!("the model has no output `{name}`")))+ };+ let mut candidates: Vec<Face> = Vec::new();+ for stride in STRIDES {+ let (cls, obj) = (find(format!("cls_{stride}"))?, find(format!("obj_{stride}"))?);+ let (bbox, kps) = (find(format!("bbox_{stride}"))?, find(format!("kps_{stride}"))?);+ let cols = self.side / stride;+ let cells = cols * cols;+ if cls.data.len() != cells || obj.data.len() != cells || bbox.data.len() != cells * 4 || kps.data.len() != cells * 10 {+ return Err(DetectError::Model(format!("the outputs for stride {stride} have the wrong size")));+ }+ for (i, (c, o)) in cls.data.iter().zip(&obj.data).enumerate() {+ let score = (c.clamp(0.0, 1.0) * o.clamp(0.0, 1.0)).sqrt();+ if score.is_nan() || score < opts.score {+ continue;+ }+ let (row, col) = ((i / cols) as f32, (i % cols) as f32);+ let (Some(b), Some(k)) = (bbox.data.get(i * 4..i * 4 + 4), kps.data.get(i * 10..i * 10 + 10)) else { continue };+ let s = stride as f32;+ let (cx, cy) = ((col + b[0]) * s, (row + b[1]) * s);+ let (w, h) = (b[2].clamp(-10.0, 10.0).exp() * s, b[3].clamp(-10.0, 10.0).exp() * s);+ let mut landmarks = [(0.0, 0.0); 5];+ for (n, l) in landmarks.iter_mut().enumerate() {+ let (lx, ly) = (k.get(n * 2).copied().unwrap_or(0.0), k.get(n * 2 + 1).copied().unwrap_or(0.0));+ *l = (((lx + col) * s) / scale / width as f32, ((ly + row) * s) / scale / height as f32);+ }+ candidates.push(Face {+ x0: (cx - w / 2.0) / scale / width as f32,+ y0: (cy - h / 2.0) / scale / height as f32,+ x1: (cx + w / 2.0) / scale / width as f32,+ y1: (cy + h / 2.0) / scale / height as f32,+ score,+ landmarks,+ });+ }+ }+ candidates.sort_by(|a, b| b.score.total_cmp(&a.score));+ candidates.truncate(MAX_CANDIDATES);+ let mut kept: Vec<Face> = Vec::new();+ for c in candidates {+ if kept.len() >= opts.max_faces {+ break;+ }+ // the box as it lies inside the photo+ let clipped = Face { x0: c.x0.clamp(0.0, 1.0), y0: c.y0.clamp(0.0, 1.0), x1: c.x1.clamp(0.0, 1.0), y1: c.y1.clamp(0.0, 1.0), ..c };+ if !(clipped.x1 - clipped.x0 > 1e-4 && clipped.y1 - clipped.y0 > 1e-4) || kept.iter().any(|k| iou(k, &clipped) > opts.nms_iou) {+ continue;+ }+ kept.push(clipped);+ }+ Ok(kept)+ }++ /// The photo scaled by `scale` into the top left of a zero-filled square, as BGR 0..255 (the model's own input).+ fn letterbox(&self, rgb: &[u8], width: usize, height: usize, scale: f32) -> Result<Tensor, DetectError> {+ let side = self.side;+ let nw = ((width as f32 * scale).round() as usize).clamp(1, side);+ let nh = ((height as f32 * scale).round() as usize).clamp(1, side);+ let (xt, yt) = (taps(width, nw), taps(height, nh));+ // horizontal pass: every source row, nw columns, three channels+ let mut mid = vec![0.0f32; height * nw * 3];+ for (src_row, mid_row) in rgb.chunks_exact(width * 3).zip(mid.chunks_exact_mut(nw * 3)) {+ for (x, tap) in xt.iter().enumerate() {+ let mut acc = [0.0f32; 3];+ for (j, wt) in tap.weights.iter().enumerate() {+ if let Some(px) = src_row.get((tap.start + j) * 3..(tap.start + j) * 3 + 3) {+ acc[0] += wt * f32::from(px[0]);+ acc[1] += wt * f32::from(px[1]);+ acc[2] += wt * f32::from(px[2]);+ }+ }+ if let Some(o) = mid_row.get_mut(x * 3..x * 3 + 3) {+ o.copy_from_slice(&acc);+ }+ }+ }+ // vertical pass into the planes B, G, R+ let plane = side * side;+ let mut data = vec![0.0f32; 3 * plane];+ for (y, tap) in yt.iter().enumerate() {+ for x in 0..nw {+ let mut acc = [0.0f32; 3];+ for (j, wt) in tap.weights.iter().enumerate() {+ if let Some(px) = mid.get(((tap.start + j) * nw + x) * 3..((tap.start + j) * nw + x) * 3 + 3) {+ acc[0] += wt * px[0];+ acc[1] += wt * px[1];+ acc[2] += wt * px[2];+ }+ }+ let at = y * side + x;+ for (c, v) in [acc[2], acc[1], acc[0]].into_iter().enumerate() {+ if let Some(o) = data.get_mut(c * plane + at) {+ *o = v;+ }+ }+ }+ }+ Ok(Tensor::new(vec![1, 3, side, side], data)?)+ }+}++struct Tap {+ start: usize,+ weights: Vec<f32>,+}++/// For each of `dst` output positions, which `src` positions to average and with what weights: exact area+/// averaging when shrinking, linear interpolation when enlarging.+fn taps(src: usize, dst: usize) -> Vec<Tap> {+ let r = src as f32 / dst as f32;+ (0..dst)+ .map(|i| {+ if r >= 1.0 {+ let (a, b) = (i as f32 * r, (i as f32 + 1.0) * r);+ let first = a.floor() as usize;+ let last = ((b.ceil() as usize).min(src)).max(first + 1);+ let weights: Vec<f32> = (first..last).map(|j| ((j as f32 + 1.0).min(b) - (j as f32).max(a)).max(0.0) / r).collect();+ Tap { start: first.min(src - 1), weights }+ } else {+ let c = ((i as f32 + 0.5) * r - 0.5).max(0.0);+ let lo = (c.floor() as usize).min(src - 1);+ let hi = (lo + 1).min(src - 1);+ let f = c - lo as f32;+ if hi == lo { Tap { start: lo, weights: vec![1.0] } } else { Tap { start: lo, weights: vec![1.0 - f, f] } }+ }+ })+ .collect()+}++fn iou(a: &Face, b: &Face) -> f32 {+ let (w, h) = ((a.x1.min(b.x1) - a.x0.max(b.x0)).max(0.0), (a.y1.min(b.y1) - a.y0.max(b.y0)).max(0.0));+ let inter = w * h;+ let union = (a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - inter;+ if union > 0.0 { inter / union } else { 0.0 }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The real model, for the tests that need it: `LC_YUNET_MODEL=<face_detection_yunet_2023mar.onnx>` (the file+ /// Settings ▸ Faces downloads; nothing is committed). Without it those tests say so and pass.+ fn model() -> Option<Vec<u8>> {+ let path = std::env::var_os("LC_YUNET_MODEL")?;+ let bytes = std::fs::read(path).ok()?;+ assert_eq!(crate::hash::sha256_hex(&bytes), crate::known::YUNET_SHA256, "LC_YUNET_MODEL is not YuNet 2023mar");+ Some(bytes)+ }++ fn detector() -> Option<Detector> {+ let Some(bytes) = model() else {+ eprintln!("LC_YUNET_MODEL is not set: skipping");+ return None;+ };+ Some(Detector::new(&bytes).unwrap())+ }++ #[test]+ fn the_model_loads_and_has_a_square_input() {+ let Some(d) = detector() else { return };+ assert_eq!(d.side, 640);+ }++ #[test]+ fn a_blank_picture_has_no_faces_and_odd_sizes_are_handled() {+ let Some(d) = detector() else { return };+ for (w, h) in [(640, 480), (100, 700), (1, 1), (37, 41), (1000, 20)] {+ let rgb = vec![128u8; w * h * 3];+ let faces = d.detect(&rgb, w, h, &Options::default()).unwrap();+ assert!(faces.is_empty(), "{w}×{h}: {faces:?}");+ }+ }++ #[test]+ fn bad_input_is_an_error_not_a_panic() {+ let Some(d) = detector() else { return };+ let o = Options::default();+ assert!(d.detect(&[], 0, 0, &o).is_err());+ assert!(d.detect(&[0; 12], 2, 3, &o).is_err(), "wrong byte count");+ assert!(d.detect(&[0; 3], usize::MAX, 2, &o).is_err(), "overflowing size");+ assert!(d.detect(&[0; 3], MAX_SIDE + 1, 1, &o).is_err());+ let nan = Options { score: f32::NAN, nms_iou: f32::INFINITY, max_faces: usize::MAX };+ assert!(d.detect(&vec![0u8; 12 * 12 * 3], 12, 12, &nan).is_ok(), "non-finite options fall back to defaults");+ }++ #[test]+ fn a_model_that_is_not_yunet_shaped_is_refused() {+ assert!(Detector::new(b"nonsense").is_err());+ assert!(Detector::new(&crate::synthetic::embedder_model(512)).is_err());+ if let Some(bytes) = model() {+ for n in [0, 1, 100, bytes.len() / 2, bytes.len() - 1] {+ assert!(Detector::new(&bytes[..n]).is_err(), "truncated at {n}");+ }+ }+ }++ /// Opt-in: `LC_YUNET_REF=<folder> cargo test -p lightcraft-faces -- --ignored --nocapture` compares every output+ /// of the network with ONNX Runtime's on the same input (`input.bin`, `out_<name>.bin`, raw little-endian f32).+ #[test]+ #[ignore = "needs reference files: set LC_YUNET_REF"]+ fn the_network_matches_onnx_runtime() {+ let Some(dir) = std::env::var_os("LC_YUNET_REF") else { return };+ let dir = std::path::PathBuf::from(dir);+ let floats =+ |name: &str| -> Vec<f32> { std::fs::read(dir.join(name)).unwrap().as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() };+ let Some(d) = detector() else { return };+ let started = std::time::Instant::now();+ let outs = d.net.run(Tensor::new(vec![1, 3, 640, 640], floats("input.bin")).unwrap()).unwrap();+ println!("network run: {:?}", started.elapsed());+ assert_eq!(outs.len(), 12);+ for (name, t) in outs {+ let want = floats(&format!("out_{name}.bin"));+ assert_eq!(t.data.len(), want.len(), "{name}");+ let worst = t.data.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);+ println!("{name}: {} values, worst difference {worst:e}", want.len());+ assert!(worst < 2e-3, "{name} differs by {worst}");+ }+ }++ #[test]+ fn taps_cover_the_source_and_sum_to_one() {+ for (src, dst) in [(6000, 640), (640, 640), (37, 640), (3, 5), (1, 1), (1, 640), (641, 640)] {+ let t = taps(src, dst);+ assert_eq!(t.len(), dst);+ for tap in &t {+ assert!(tap.start + tap.weights.len() <= src, "{src}→{dst}");+ let sum: f32 = tap.weights.iter().sum();+ assert!((sum - 1.0).abs() < 1e-3, "{src}→{dst}: {sum}");+ }+ }+ }++ #[test]+ fn overlap_is_symmetric() {+ let f = |x0, y0, x1, y1| Face { x0, y0, x1, y1, score: 1.0, landmarks: [(0.0, 0.0); 5] };+ let (a, b) = (f(0.0, 0.0, 0.5, 0.5), f(0.25, 0.25, 0.75, 0.75));+ assert!((iou(&a, &b) - iou(&b, &a)).abs() < 1e-6 && (iou(&a, &b) - 0.0625 / 0.4375).abs() < 1e-5);+ assert_eq!(iou(&a, &f(0.6, 0.6, 0.9, 0.9)), 0.0);+ }+}diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rsindex d7e5e4806..6278c2771 100644--- a/crates/ui-egui/src/headless.rs+++ b/crates/ui-egui/src/headless.rs@@ -455,6 +455,41 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// Photo > Detect Faces without the detector offers the download: the terms first, nothing fetched before they are+ /// accepted, and the model's row in Settings has its Download button.+ #[test]+ fn detect_faces_without_the_detector_offers_the_download_and_fetches_nothing_before_acceptance() {+ use crate::state::Dialog;+ let mut h = demo([1400.0, 900.0]);+ let dir = std::env::temp_dir().join(format!("lc-ui-detector-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ h.app.session.face_models_dir = Some(dir.join("models"));++ let r = h.app.run("faces.detect", json!({}));+ assert!(r.is_err(), "no detector yet");+ let Some(dlg) = h.app.ui.dialog.clone() else { panic!("the download was not offered") };+ let Dialog::FaceModel { info, accepted, .. } = &dlg else { panic!("{dlg:?}") };+ assert!(!accepted);+ assert_eq!((info["download"].as_str(), info["host"].as_str()), (Some("yunet-2023mar"), Some("github.com")));+ assert_eq!(info["model"]["licence"]["name"], "MIT");+ // OK without accepting the terms starts nothing+ assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_err());+ assert!(h.app.session.face_downloads.snapshot().is_empty());+ assert!(!dir.join("models").join(".downloads").exists());+ assert!(h.app.caches.faces_dl_watch.is_empty());++ // Settings > Faces shows the detector with a Download button+ h.app.ui.dialog = Some(Dialog::Settings { tab: "faces".into() });+ h.step();+ // (the first request switches the widget list on, the next frame fills it)+ h.request("ui.widgets", json!({}), Duration::from_secs(10));+ h.step();+ let w = h.request("ui.widgets", json!({"filter": "faces:"}), Duration::from_secs(10));+ assert!(w.to_string().contains("faces:download:yunet-2023mar"), "{w}");+ let _ = std::fs::remove_dir_all(&dir);+ }+/// Profile browser: live variant thumbnails, hover previews in the loupe without touching the/// photo or its history, click applies, the star toggles the favourite.#[test]diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 36b72f31b..7f1e7cdf2 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -344,9 +344,17 @@ impl LightcraftApp {let now = self.tasks.repaint.as_ref().map(|ctx| ctx.input(|i| i.time)).unwrap_or(self.last_time);self.ui.toast = Some((text, now + TOAST_SECONDS, label));}- if let Err(e) = &r {- log::warn!("{id}: {e}");- self.ui.status = e.clone();+ match &r {+ Err(e) => {+ log::warn!("{id}: {e}");+ self.ui.status = e.clone();+ // no detector yet: offer it (its terms first) instead of only saying so+ if id == "faces.detect" && e.contains("Settings > Faces") {+ panels::faces::offer_detector(self);+ }+ }+ Ok(v) if id == "faces.detect" => self.ui.status = detect_summary(v),+ Ok(_) => {}}r}@@ -710,6 +718,7 @@ impl LightcraftApp {self.preview_build_status(ctx);self.save_status(ctx);self.slideshow_tick(ctx);+ panels::faces::pump(self, ctx);// back from an external editor: pick up the files it savedlet focused = ctx.input(|i| i.focused);if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() {@@ -965,6 +974,20 @@ pub fn is_bw(d: &lightcraft_develop::DevelopSettings) -> bool {d.treatment == lightcraft_develop::Treatment::Bw || d.profile.id == "lc.mono" || d.profile.id.starts_with("lc.bw.")}+/// "Found 3 faces in 2 photos" for a `faces.detect` result.+fn detect_summary(v: &Value) -> String {+ let photos = v["photos"].as_array().map(Vec::as_slice).unwrap_or_default();+ let counts: Vec<usize> = photos.iter().map(|p| p["faces"].as_array().map_or(0, Vec::len)).collect();+ let (faces, with) = (counts.iter().sum::<usize>(), counts.iter().filter(|n| **n > 0).count());+ let plural = |n: usize, w: &str| format!("{n} {w}{}", if n == 1 { "" } else { "s" });+ match (faces, photos.len()) {+ (0, 1) => "No faces found".into(),+ (0, n) => format!("No faces found in {}", plural(n, "photo")),+ (f, 1) => format!("Found {}", plural(f, "face")),+ (f, _) => format!("Found {} in {}", plural(f, "face"), plural(with, "photo")),+ }+}+/// A dropped face model file (`.onnx`).pub fn is_model_file(path: &str) -> bool {std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("onnx"))@@ -978,6 +1001,18 @@ pub fn is_preset_file(path: &str) -> bool {#[cfg(test)]mod drop_tests {+ #[test]+ fn detection_results_are_summarised_in_words() {+ let r =+ |counts: &[usize]| serde_json::json!({"photos": counts.iter().map(|n| serde_json::json!({"faces": vec![0; *n]})).collect::<Vec<_>>()});+ assert_eq!(super::detect_summary(&r(&[0])), "No faces found");+ assert_eq!(super::detect_summary(&r(&[1])), "Found 1 face");+ assert_eq!(super::detect_summary(&r(&[3])), "Found 3 faces");+ assert_eq!(super::detect_summary(&r(&[0, 0])), "No faces found in 2 photos");+ assert_eq!(super::detect_summary(&r(&[2, 0, 1])), "Found 3 faces in 2 photos");+ assert_eq!(super::detect_summary(&serde_json::json!({})), "No faces found in 0 photos");+ }+#[test]fn dropped_face_models_are_told_apart() {for p in ["/a/model.onnx", "/a/dir/M.ONNX"] {@@ -1014,6 +1049,8 @@ pub struct Caches {pub album_count_scans: usize,/// Bumped when a face model is installed, removed or chosen, so Settings re-reads the list at once.pub faces_epoch: u64,+ /// Face model downloads the user started, followed until installed (see `panels::faces::pump`).+ pub faces_dl_watch: Vec<String>,/// The grid's date runs, layout and indexes (by the visible list's generation).pub grid: panels::grid::GridCache,/// What the grid did on its frames (benchmarks and tests check unchanged frames stay cheap).diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex fa879359d..5c05d0ae8 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -62,6 +62,7 @@ pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md");pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {let Some(mut dlg) = app.ui.dialog.clone() else { return };+ let at_start = dlg.clone();let t = Tokens::get(ctx);let screen = ctx.content_rect();// The backdrop is an area below the dialog window (a bare `Middle` layer painter would be@@ -85,6 +86,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::NewSmartAlbum { .. } => "Create Smart Album",Dialog::AllMetadata { .. } => "All Metadata",Dialog::SystemInfo { .. } => "System Info",+ Dialog::FaceModel { info, .. } if info["download"].is_string() => "Download Face Model",Dialog::FaceModel { .. } => "Add Face Model",Dialog::WhatsNew => "What's New",Dialog::Cull { .. } => "Assisted Culling",@@ -815,6 +817,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {add_label.as_str()}Dialog::Merge { .. } => "Merge",+ Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download",Dialog::FaceModel { .. } if !informational => "Install",Dialog::ConfirmDelete { .. } => "Delete",Dialog::RemoveFolder { .. } => "Remove",@@ -870,6 +873,10 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {_ => close = true,}}+ // a dialog opened from inside this one (a button in Settings that shows a licence) takes its place+ if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) {+ return;+ }app.ui.dialog = if close { None } else { Some(dlg) };}@@ -1033,7 +1040,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jsoDialog::RenameKeyword { from, to } => app.run("keyword.rename", json!({"from": from, "to": to})),Dialog::MergeKeywords { from, into } => app.run("keyword.merge", json!({"from": from, "into": into})),Dialog::AutoStack { gap } => app.run("stack.auto", json!({"gap": gap})),- Dialog::FaceModel { path, accepted, .. } => crate::panels::faces::install(app, path, *accepted),+ Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted),Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null),Dialog::Cull { reject_below, pick_best } => {let mut p = json!({"pickBest": pick_best});diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rsindex 5dad9bfcf..423a849b5 100644--- a/crates/ui-egui/src/panels/faces.rs+++ b/crates/ui-egui/src/panels/faces.rs@@ -3,7 +3,9 @@//!//! Adding a model is: pick or drop a `.onnx` file → the engine inspects it (`faces.models.inspect`) →//! this dialog shows what it is and its terms → the user ticks "I accept" → `faces.models.install`.-//! LightCraft never fetches a model by itself: "Get…" opens the model's own page in the browser.+//! LightCraft fetches a model only when the user presses Download on a model it has a pinned address for: the same+//! dialog shows its terms first, and accepting them downloads it (`faces.models.download`: checked against its size and+//! SHA-256, then installed). "Open page" opens the model's own page in the browser.use egui::RichText;use serde_json::{Value, json};@@ -96,16 +98,18 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {hint(ui, t, "Models can be added and chosen now. Running them arrives in a later update.");}let all: Vec<Value> = list["models"].as_array().cloned().unwrap_or_default();+ let downloads =+ app.session.execute("faces.models.downloads", &json!({})).map(|v| v["downloads"].as_array().cloned().unwrap_or_default()).unwrap_or_default();heading(ui, t, "Face detector");for m in all.iter().filter(|m| m["role"] == "detector") {- ui.horizontal(|ui| {- ui.label(RichText::new(m["name"].as_str().unwrap_or("")).color(t.text));- ui.label(RichText::new(format!("{} · included", mb(m["sizeBytes"].as_u64()))).color(t.text_dim));- });+ model_row(app, ui, t, m, downloads.iter().find(|d| d["id"] == m["id"]));+ }+ if !all.iter().any(|m| m["role"] == "detector" && m["installed"] == true) {+ hint(ui, t, "Detect Faces (Photo menu) needs it: a small one-time download.");}heading(ui, t, "Recognition models");for m in all.iter().filter(|m| m["role"] == "embedder") {- model_row(app, ui, t, m);+ model_row(app, ui, t, m, downloads.iter().find(|d| d["id"] == m["id"]));}ui.add_space(6.0);ui.horizontal(|ui| {@@ -119,9 +123,12 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {});}-fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value) {+fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, dl: Option<&Value>) {let id = m["id"].as_str().unwrap_or("").to_string();let (installed, selected) = (m["installed"].as_bool() == Some(true), m["selected"].as_bool() == Some(true));+ let detector = m["role"] == "detector";+ let dl_state = if installed { None } else { dl.and_then(|d| d["state"].as_str()) };+ let host = m["downloadHost"].as_str().unwrap_or("").to_string();egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 3)).show(ui, |ui| {ui.horizontal(|ui| {ui.vertical(|ui| {@@ -142,6 +149,27 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value)} else {t.caution}));+ match (dl_state, dl) {+ (Some("running"), Some(d)) => {+ let (got, total) = (d["bytes"].as_u64().unwrap_or(0), d["total"].as_u64().unwrap_or(0));+ let frac = if total > 0 { (got as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 };+ let text = if total > 0 && got >= total {+ "Checking…".to_string()+ } else {+ format!("{} of {} from {host}", mb(Some(got)), mb(Some(total)))+ };+ let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.font(11.5))));+ register(ui.ctx(), format!("faces:progress:{id}"), bar.rect);+ }+ (Some("done"), _) => {+ ui.label(RichText::new("Downloaded and checked. Installing…").font(t.font(11.5)).color(t.text_dim));+ }+ (Some("failed"), Some(d)) => {+ let why = sentence(d["error"].as_str().unwrap_or("The download failed"));+ ui.add(egui::Label::new(RichText::new(why).font(t.font(11.5)).color(t.caution)).wrap());+ }+ _ => {}+ }});ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if installed {@@ -151,7 +179,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value)let _ = app.run("faces.models.remove", json!({"id": id}));app.caches.faces_epoch += 1;}- if !selected {+ if !selected && !detector {let r = ui.button("Use");register(ui.ctx(), format!("faces:use:{id}"), r.rect);if r.clicked() {@@ -159,13 +187,35 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value)app.caches.faces_epoch += 1;}}- } else if let Some(url) = m["source"].as_str() {- let r = ui- .button("Get…")- .on_hover_text("Opens the model's own page in your browser. Download the .onnx file there, then add it here.");- register(ui.ctx(), format!("faces:get:{id}"), r.rect);+ } else if dl_state == Some("running") {+ let r = ui.button("Cancel");+ register(ui.ctx(), format!("faces:cancelDownload:{id}"), r.rect);if r.clicked() {- open_page(app, url);+ let _ = app.run("faces.models.downloadCancel", json!({"id": id}));+ app.caches.faces_dl_watch.retain(|w| w != &id);+ }+ } else if dl_state != Some("done") {+ // (a download that has just arrived is installed within a moment: nothing to press)+ if let Some(url) = m["source"].as_str() {+ let r = ui+ .button("Open page")+ .on_hover_text("Opens the model's own page in your browser, to read about it or get the file yourself.");+ register(ui.ctx(), format!("faces:get:{id}"), r.rect);+ if r.clicked() {+ open_page(app, url);+ }+ }+ if !host.is_empty() {+ let label = if dl_state == Some("failed") { "Try again" } else { "Download" };+ let tip = format!(+ "Shows the model's terms, then downloads {} from {host} and installs it. Nothing else is sent.",+ mb(m["sizeBytes"].as_u64())+ );+ let r = ui.button(label).on_hover_text(tip);+ register(ui.ctx(), format!("faces:download:{id}"), r.rect);+ if r.clicked() {+ open_download_dialog(app, m);+ }}}});@@ -198,6 +248,16 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, infoif info["alreadyInstalled"] == true {ui.label(RichText::new("Already installed. Installing again is harmless.").color(t.text_dim));}+ let download = info["download"].is_string();+ if download {+ let host = info["host"].as_str().unwrap_or("its own repository");+ ui.add(+ egui::Label::new(+ RichText::new(format!("Downloads from {host}. Once it has arrived and checked out, LightCraft installs it.")).color(t.text_label),+ )+ .wrap(),+ );+ }let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown");ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution }));let notice = m["licence"]["notice"].as_str().unwrap_or("");@@ -224,7 +284,37 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info}ui.add_space(4.0);check(ui, "faceModel.accept", accepted, "I have read these terms and accept them for my own use");- ui.label(RichText::new("The model is kept on this computer only. LightCraft never uploads or shares it.").font(t.font(11.5)).color(t.text_dim));+ let closing = if download {+ "Nothing is fetched until you accept. The model is kept on this computer only; LightCraft never uploads or shares it."+ } else {+ "The model is kept on this computer only. LightCraft never uploads or shares it."+ };+ ui.label(RichText::new(closing).font(t.font(11.5)).color(t.text_dim));+}++/// Pressing Download: the model's terms first, in the same dialog as a model file. Accepting them starts the download;+/// nothing is fetched before.+pub fn open_download_dialog(app: &mut LightcraftApp, m: &Value) {+ let info = json!({+ "kind": "known",+ "fileName": m["id"],+ "sizeBytes": m["sizeBytes"],+ "model": m,+ "alreadyInstalled": false,+ "download": m["id"],+ "host": m["downloadHost"],+ "assumptions": [],+ "reason": null,+ });+ app.ui.dialog = Some(crate::state::Dialog::FaceModel { path: String::new(), info, accepted: false });+}++/// Photo ▸ Detect Faces without the detector: offer to download it (its terms first), the same as in Settings.+pub fn offer_detector(app: &mut LightcraftApp) {+ let list = app.session.execute("faces.models.list", &json!({})).unwrap_or(Value::Null);+ if let Some(m) = list["models"].as_array().and_then(|a| a.iter().find(|m| m["role"] == "detector" && m["installed"] != true)) {+ open_download_dialog(app, m);+ }}/// Inspect `path` and open the dialog for it (also what dropping a `.onnx` file on the window does).@@ -234,12 +324,86 @@ pub fn open_dialog(app: &mut LightcraftApp, path: &str) -> Result<Value, String>Ok(Value::Null)}-/// The dialog's OK: install the model (the engine refuses without the acceptance).-pub fn install(app: &mut LightcraftApp, path: &str, accepted: bool) -> Result<Value, String> {+/// The dialog's OK (the engine refuses without the acceptance): for a download, start it and watch it; for a file,+/// install it.+pub fn install(app: &mut LightcraftApp, path: &str, info: &Value, accepted: bool) -> Result<Value, String> {if !accepted {return Err("Tick the box to accept the model's terms first".into());}- let r = app.run("faces.models.install", json!({"path": path, "acknowledged": true}));app.caches.faces_epoch += 1;- r+ if let Some(id) = info["download"].as_str() {+ let r = app.run("faces.models.download", json!({"id": id, "acknowledged": true}));+ if r.is_ok() {+ app.caches.faces_dl_watch.push(id.to_string());+ // the progress is in Settings: go there+ app.ui.dialog = Some(crate::state::Dialog::Settings { tab: "faces".into() });+ }+ return r;+ }+ app.run("faces.models.install", json!({"path": path, "acknowledged": true}))+}++/// Sort the watched downloads: those that have been installed (to announce), and those still to watch (running, or+/// arrived and being installed). A failed or cancelled one is dropped: the model's row in Settings says what happened.+fn due(rows: &[Value], watched: Vec<String>) -> (Vec<String>, Vec<String>) {+ let (mut installed, mut keep) = (Vec::new(), Vec::new());+ for id in watched {+ match rows.iter().find(|r| r["id"] == id.as_str()).and_then(|r| r["state"].as_str()) {+ Some("running" | "done") => keep.push(id),+ Some("installed") => installed.push(id),+ _ => {}+ }+ }+ (installed, keep)+}++/// Called every frame: follows the downloads the user started. Keeps redrawing while one runs (the progress bar), installs+/// what has arrived (the engine does that when asked) and says so when a model is installed.+pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) {+ if app.caches.faces_dl_watch.is_empty() {+ return;+ }+ let Ok(v) = app.session.execute("faces.models.downloads", &json!({})) else {+ app.caches.faces_dl_watch.clear();+ return;+ };+ let rows: Vec<Value> = v["downloads"].as_array().cloned().unwrap_or_default();+ let (installed, keep) = due(&rows, std::mem::take(&mut app.caches.faces_dl_watch));+ app.caches.faces_dl_watch = keep;+ for id in installed {+ let name = app+ .session+ .execute("faces.models.list", &json!({}))+ .ok()+ .and_then(|l| {+ l["models"].as_array().and_then(|a| a.iter().find(|m| m["id"] == id.as_str()).and_then(|m| m["name"].as_str().map(str::to_string)))+ })+ .unwrap_or_else(|| id.clone());+ let _ = app.session.execute("faces.models.downloadCancel", &json!({"id": id}));+ app.caches.faces_epoch += 1;+ let text = format!("{name} is installed");+ app.ui.status = text.clone();+ app.toast(ctx, text);+ }+ ctx.request_repaint_after(std::time::Duration::from_millis(120));+}++#[cfg(test)]+mod tests {+ use super::*;++ fn row(id: &str, state: &str) -> Value {+ json!({"id": id, "state": state})+ }++ #[test]+ fn an_installed_download_is_announced_once_and_the_rest_are_followed() {+ let rows = vec![row("a", "running"), row("b", "done"), row("c", "installed"), row("d", "failed"), row("e", "cancelled")];+ let watched = ["a", "b", "c", "d", "e", "gone"].map(String::from).to_vec();+ let (installed, keep) = due(&rows, watched);+ assert_eq!(installed, ["c"]);+ // running and just-arrived ones are watched; failed, cancelled and vanished ones are dropped+ assert_eq!(keep, ["a", "b"]);+ assert_eq!(due(&[], vec!["x".into()]), (vec![], vec![]));+ }}diff --git a/docs/faces.md b/docs/faces.mdnew file mode 100644index 000000000..d4357995b--- /dev/null+++ b/docs/faces.md@@ -0,0 +1,76 @@+# Faces++LightCraft reads the face names other apps (Lightroom, digiKam…) write into your photos, shows them in the loupe+(boxes you can switch off, resize and remove) and groups photos by person in the People view. This page is about the+*models* that find and recognise faces by themselves.++## Nothing is bundled; every model is an opt-in download++No model weights are part of LightCraft. Each one is a file you choose to get, from **Settings ▸ Faces**:++- **Face detection:** [YuNet](https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet) (232 KB, MIT).+ It runs in LightCraft's own code, with no extra runtime. It was trained on the WIDER FACE dataset; an MIT licence on+ weights does not settle that dataset's terms, so this is flagged for the maintainer. It finds faces; it does not+ identify anyone. **Photo ▸ Detect Faces** offers the download the first time you use it.+- **Face recognition models** are large (AuraFace is 261 MB), and their licences and training data deserve a decision by+ the person installing them. Everything works without one: names from XMP, the People view, the face boxes.++## Downloading a model++**Settings ▸ Faces ▸ Download** (or Photo ▸ Detect Faces, which offers it for the detector):++1. A dialog shows the model's licence, whether commercial use is allowed, what it was trained on (or that this is not+ known) and which site the file comes from. **Download stays disabled until you tick "I have read these terms and+ accept them for my own use".** Nothing is fetched before that.+2. LightCraft downloads the file from the model's own repository (GitHub for YuNet and SFace, Hugging Face for+ AuraFace), at an address pinned to a commit, over https, in pure Rust (the `lightcraft-fetch` crate: no `curl`, no+ OpenSSL). An interrupted download resumes where it stopped.+3. The file must match the model's recorded size and SHA-256, or it is thrown away. A file that matches is installed+ by itself. Nothing else is sent anywhere, and no token or account is involved.++**Open page** opens the model's own page in your browser if you would rather get the file yourself.++## Adding a model file yourself++1. **Settings ▸ Faces ▸ Add a model file…**, or drop a `.onnx` file on the window.+2. LightCraft looks at the file (it never runs it at this point): it recognises models it knows by their SHA-256, and+ for any other file it reads the input and output shapes and describes what it assumed (112 × 112 aligned faces,+ RGB, `(x − 127.5) / 127.5`, one vector per face: the ArcFace convention that InsightFace models also use).+3. The same dialog shows the licence, whether commercial use is allowed and what the model was trained on, and+ **Install stays disabled until you tick the acceptance box**.+4. The model is copied into LightCraft's models folder and checked against the original by hash.++Non-commercial models (InsightFace, for example) can be added this way for your own use; LightCraft never bundles,+hosts, downloads or links them from a picker, and the dialog says so.++The models folder is `<config>/models` (`%APPDATA%\LightCraft\models` on Windows, `~/Library/Application Support/LightCraft/models`+on macOS, `~/.config/lightcraft/models` on Linux), or `$LIGHTCRAFT_FACE_MODELS`. The desktop app, the CLI and the MCP+server share it.++## What is known about the models LightCraft recognises++| Model | Licence of the weights | Trained on | Notes |+| --- | --- | --- | --- |+| YuNet 2023mar (detector) | MIT | WIDER FACE | 232 KB |+| AuraFace v1 | Apache-2.0 | "a commercial dataset", undisclosed | 261 MB; the best measured on sculpted busts |+| SFace 2021dec | labelled Apache-2.0 | undocumented (the upstream repository mentions CASIA-WebFace, VGGFace2, MS1MV2) | 39 MB; two questions about commercial use are unanswered upstream |++"Commercial use allowed" in the dialog is the weights' licence; it says nothing about the training data.++## Finding faces yourself++**Photo ▸ Detect Faces** (`faces.detect`) runs the YuNet detector on the selected photos and adds what it finds as+unnamed face boxes, in one undo step. A new run replaces earlier detections; boxes that came from XMP, or that you drew or+named, are never touched (and a face that already has one is not boxed a second time), and no sidecar is written. It looks at the photo upright and uncropped with default settings,+so your edits and crops do not matter. `apply: false` only reports. It finds faces of about 10 pixels and up in a+640-pixel version of the photo (so very small faces in a large group photo can be missed; looking at tiles is planned).+The detector's output matches OpenCV's own YuNet on a 45-photo public-domain test set (97 of 99 faces found by both,+mean box overlap 0.97), including marble busts and paintings, with no false boxes on the landscape and architecture+photos in the set.++## Commands++All of this is reachable from the control channel, the CLI and MCP: `faces.models.list`, `faces.models.inspect {path}`,+`faces.models.install {path, acknowledged: true}`, `faces.models.download {id, acknowledged: true}` (then `faces.models.downloads` for+progress; the download is installed when it arrives, and `faces.models.downloadCancel {id}` stops it), `faces.models.remove {id}`, `faces.models.select {id}`,+`faces.enable {enabled?}`, and `faces.detect {ids?, apply?}`. `acknowledged` must be `true`: the caller has shown the user the terms and the user agreed.diff --git a/docs/parity.md b/docs/parity.mdindex 53050dc44..1b9447fb2 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -160,7 +160,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins.| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file || LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, label dot plus translucent colour on square-grid/filmstrip surrounds and photo-grid footers (photo pixels unchanged); colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), no custom extra labels || LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; no keyword drag-and-drop |-| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. No face detection, no unnamed people / suggestions, no manual tagging, no writing regions back |+| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; no recognition, no unnamed people / suggestions, no manual tagging, no writing regions back || LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `crates/catalog/src/stacks.rs` | grid/filmstrip count badges, expand/collapse, auto-stack by capture time; no visual-similarity auto-stack || LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M || LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); adding a file that is in Recently Deleted again selects it there (side panel opened) and says how to restore it or import it afresh; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` skip / restore / fresh for files in the trash (`cmd:library.import`; the report flags `existingDeleted` and lists `restored`; the import review dialog offers Leave them / Restore them / Import as new for files that are in the trash; dropped files and Add Photos without a review still skip and point at Restore); no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog) |@@ -482,7 +482,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins.| LR-PREF-ACCOUNT | Account | OOS | 🚫 | | || LR-PREF-INTERFACE | Interface options | P1 | ✅ | `cmd:app.settings` | filmstrip names/badges, grid badges (auto/always/never), square-grid names, navigator, info overlay || LR-PREF-PERFORMANCE | GPU / performance | P1 | ✅ | `cmd:app.gpu`, `cmd:app.memoryBudget`, `cmd:app.settings` | GPU on/off, preview size (Automatic = the whole-frame loupe render at canvas size, up to 2560 px; or a 1600–5120 px size for it; zoomed views add a window at up to 100 %, issue #323), memory budget (a quarter of it is the idle per-view stage caches' share; the open photo's views are counted and reported, and cut only past four times that, the before side's and the zoom window's first — a Before/After at 1:1 on a 2800 px canvas holds about 1 GB of GPU stages, plus the one 288 MB copy of the original, which `ui.inspect` reports as `sharedSourceBytes`), thumbnail cache size in Settings |-| LR-PREF-PEOPLE | Face recognition | P2 | 🟡 | `cmd:faces.enable`, `cmd:faces.models.list`, `cmd:faces.models.inspect`, `cmd:faces.models.install`, `cmd:faces.models.remove`, `cmd:faces.models.select`, `cmd:dialog.faceModel`, `crates/faces/src/lib.rs`, `crates/ui-egui/src/panels/faces.rs` | Settings ▸ Faces: an off-by-default toggle and the face model list. Models are opt-in and never bundled (the YuNet detector, 233 KB, is the one exception, not wired yet): add one by picking or dropping a `.onnx`, which is recognised by hash or described from its shape, shows its licence terms and training-data note, and installs only after an "I accept" box. Nothing runs a model yet (no inference runtime), so nothing recognises faces yet |+| LR-PREF-PEOPLE | Face recognition | P2 | 🟡 | `cmd:faces.enable`, `cmd:faces.models.list`, `cmd:faces.models.inspect`, `cmd:faces.models.install`, `cmd:faces.models.download`, `cmd:faces.models.downloads`, `cmd:faces.models.downloadCancel`, `cmd:faces.models.remove`, `cmd:faces.models.select`, `cmd:dialog.faceModel`, `crates/faces/src/lib.rs`, `crates/ui-egui/src/panels/faces.rs` | Settings ▸ Faces: an off-by-default toggle and the face model list. Models are opt-in and never bundled: **Download** fetches one from its own repository (pure-Rust https via `lightcraft-fetch`, address pinned to a commit, size and SHA-256 checked, installed by itself) after its terms are shown and accepted, or add a `.onnx` by picking or dropping it (recognised by hash or described from its shape, with its licence terms and training-data note, and an "I accept" box). The YuNet detector is wired (Photo ▸ Detect Faces); nothing runs a recognition model yet (no inference runtime), so nothing recognises faces yet || LR-PREF-WATERMARK | Watermark settings | P1 | ✅ | `cmd:export.savePreset`, `crates/ui-egui/src/panels/dialogs.rs` | set in the Export dialog; kept with Export with Previous and in saved export presets || LR-PREF-SHORTCUTS | Shortcut customisation | — | ✅ | `cmd:app.setShortcut`, `cmd:app.resetShortcuts`, `crates/ui-egui/src/panels/keymap.rs` | an extra (the reference app has no keymap editor): Help ▸ Keyboard Shortcuts (⌘/) lists every command; click a shortcut and press the new keys (Esc cancels), × removes, ↺ restores, Reset All; a key another command had moves over; saved in `ui.json`; native menu accelerators follow. Rating/label digits and secondary keys are listed read-only and yield to a key given to a command || LR-PREF-TECHPREVIEW | Early-access toggles | P2 | ⬜ | | |