M13.35: Roto Brush trained model — swappable segment module, MobileSAM in pure Rust
- New L1 crate effectcraft-segment: the MaskModel interface (prompts → foreground probability), a registry of open-licensed models (licence must be MIT/Apache/BSD/…; URL, size, SHA-256), a PyTorch checkpoint reader (zip + pickle subset), dependency-free SHA-256, and MobileSAM (TinyViT-5M + SAM prompt encoder / two-way transformer / mask decoder) on rayon and ndarray's safe GEMM. Loads the official mobile_sam.pt as published; checked against candle (embedding 0.3% RMS, 99.9% equal mask pixels); ~0.7 s/frame encoder at 32 threads, cached per frame, ~0.1 s decoder. - track::roto: segment_with / propagate_with prompt a model with the strokes or the flow-warped matte (box, core points, mask); its probability is a strong, unblurred prior for the same graph cut (strokes stay hard constraints); a failing model or one disagreeing with the flow (IoU < 0.5) is ignored. Prior gets a weight. - effects::roto: Version 2.0 / 3.0 use the model chosen in Settings (set_model / model_for); the model id is part of the chain seed. - engine: roto_models (roto.models, roto.model.select / install / download / remove), weights in the models folder (host::config_dir()/models, shared by the app, CLI and MCP), background loading, downloads through the system curl, verified; Settings ▸ Roto Brush page (prefs roto.model). host::config_dir moved from the desktop app. - Tests: segment (kernels vs direct sums, checkpoint reader, SHA-256 vectors, registry), track (fake model: prior shapes the cut, failing / disagreeing models ignored; real weights with EFFECTCRAFT_MOBILESAM: base IoU 0.989, propagated ≥ 0.980 vs classic 0.973), engine (registry, verification, selection; real install + load), MCP. - Docs: README, ROADMAP, parity (MSK-4 done: 90/2/0), preferences, agents, architecture, crates/segment/README.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
11d4885764
commit
7579de21c6
@@ -133,6 +133,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
SPECS.get_or_init(|| {
|
||||
let mut v = Vec::new();
|
||||
v.extend(file::specs());
|
||||
v.extend(crate::roto_models::specs());
|
||||
v.extend(edit::specs());
|
||||
v.extend(comp::specs());
|
||||
v.extend(layer::specs());
|
||||
|
||||
@@ -34,6 +34,7 @@ pub mod psd_import;
|
||||
pub mod remote;
|
||||
pub mod render_queue;
|
||||
pub mod roto;
|
||||
pub mod roto_models;
|
||||
pub mod scriptui;
|
||||
mod session_settings;
|
||||
pub mod shortcuts;
|
||||
@@ -63,6 +64,7 @@ pub use effectcraft_keyframe as keyframe;
|
||||
pub use effectcraft_project as project;
|
||||
pub use effectcraft_raster as raster;
|
||||
pub use effectcraft_render as render;
|
||||
pub use effectcraft_segment as segment;
|
||||
pub use effectcraft_text as text;
|
||||
pub use effectcraft_time as time;
|
||||
pub use effectcraft_track as track;
|
||||
@@ -347,6 +349,10 @@ pub struct Session {
|
||||
pub camera_pending: Vec<(ItemId, LayerId, Uid)>,
|
||||
/// The running (or finished, not yet polled) Roto Brush propagation / Freeze.
|
||||
pub roto_job: Option<roto::RotoJob>,
|
||||
/// Roto Brush's trained models (Settings ▸ Roto Brush).
|
||||
pub roto_models: roto_models::Models,
|
||||
/// Where installed models live (hosts set it; else `models` next to the settings).
|
||||
pub models_dir: Option<std::path::PathBuf>,
|
||||
/// Roto Brush instances edited since their last propagation: (comp, layer, effect uid).
|
||||
pub roto_pending: Vec<(ItemId, LayerId, Uid)>,
|
||||
pub events: Vec<Event>,
|
||||
@@ -463,6 +469,8 @@ impl Default for Session {
|
||||
camera_job: None,
|
||||
camera_pending: vec![],
|
||||
roto_job: None,
|
||||
roto_models: Default::default(),
|
||||
models_dir: None,
|
||||
roto_pending: vec![],
|
||||
events: vec![],
|
||||
journal: vec![],
|
||||
@@ -1084,3 +1092,5 @@ mod tests_paint;
|
||||
mod tests_panels;
|
||||
#[cfg(test)]
|
||||
mod tests_roto;
|
||||
#[cfg(test)]
|
||||
mod tests_roto_models;
|
||||
|
||||
@@ -209,6 +209,15 @@ page!(ThreeD {
|
||||
realtime_shadows: bool = true,
|
||||
});
|
||||
|
||||
page!(
|
||||
/// Settings ▸ Roto Brush.
|
||||
RotoPrefs {
|
||||
/// The segmentation model Roto Brush 2.0 / 3.0 use: `classical` (built in) or a model id
|
||||
/// from `effectcraft_segment::MODELS` (once installed).
|
||||
model: String = "classical".into(),
|
||||
}
|
||||
);
|
||||
|
||||
page!(Scripting {
|
||||
allow_scripts_write_files: bool = false,
|
||||
warn_executing_files: bool = true,
|
||||
@@ -272,6 +281,7 @@ pub struct Prefs {
|
||||
#[serde(rename = "threeD")]
|
||||
pub three_d: ThreeD,
|
||||
pub scripting: Scripting,
|
||||
pub roto: RotoPrefs,
|
||||
/// File ▸ Open Recent, newest first.
|
||||
pub recent_projects: Vec<String>,
|
||||
/// File ▸ Import Recent Footage, newest first.
|
||||
@@ -312,6 +322,7 @@ impl Default for Prefs {
|
||||
video: Video::default(),
|
||||
three_d: ThreeD::default(),
|
||||
scripting: Scripting::default(),
|
||||
roto: RotoPrefs::default(),
|
||||
recent_projects: vec![],
|
||||
recent_footage: vec![],
|
||||
recent_presets: vec![],
|
||||
@@ -709,6 +720,7 @@ pub fn section_key(page: &str) -> Option<&'static str> {
|
||||
"video" => "video",
|
||||
"3d" | "threeD" => "threeD",
|
||||
"scripting" => "scripting",
|
||||
"roto" => "roto",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -735,6 +747,7 @@ pub fn page_id(name: &str) -> Option<&'static str> {
|
||||
"video" | "videopreview" => "video",
|
||||
"3d" | "threed" => "3d",
|
||||
"scripting" | "scriptingexpressions" => "scripting",
|
||||
"roto" | "rotobrush" | "models" => "roto",
|
||||
_ => return None,
|
||||
};
|
||||
Some(id)
|
||||
@@ -822,6 +835,8 @@ pub enum Item {
|
||||
/// The browser's storage manager (web app only, `storage.*`): usage and quota, persistent
|
||||
/// storage, Clear buttons. Not shown where there is no browser storage.
|
||||
BrowserStorage,
|
||||
/// Roto Brush's segmentation models (`roto.models`): licence, size, install, choose.
|
||||
RotoModels,
|
||||
}
|
||||
|
||||
/// One page of the Settings dialog.
|
||||
@@ -1096,6 +1111,17 @@ pub fn pages() -> Vec<Page> {
|
||||
Note("Expressions use the JavaScript engine. Script errors report their file and line in the Script Console; there is no step debugger."),
|
||||
],
|
||||
},
|
||||
Page {
|
||||
id: "roto",
|
||||
title: "Roto Brush",
|
||||
items: vec![
|
||||
Section("Segmentation Model"),
|
||||
Note(
|
||||
"Roto Brush 2.0 and 3.0 use the model chosen here (Version 1.0 always uses the classic engine). Models are open source, downloaded only when you ask, and checked against their published SHA-256.",
|
||||
),
|
||||
RotoModels,
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1148,6 +1174,7 @@ pub fn pages_json() -> Value {
|
||||
Item::AudioDevices { key } => json!({"type": "device", "key": key, "label": "Default Output"}),
|
||||
Item::Note(t) => json!({"note": t}),
|
||||
Item::BrowserStorage => json!({"browserStorage": "storage.info / storage.persist / storage.clear (web app)"}),
|
||||
Item::RotoModels => json!({"rotoModels": "roto.models / roto.model.select / roto.model.download / roto.model.install / roto.model.remove", "key": "roto.model"}),
|
||||
})
|
||||
.collect();
|
||||
json!({"id": p.id, "title": p.title, "items": items})
|
||||
|
||||
@@ -636,6 +636,7 @@ impl Session {
|
||||
/// Frontends call this every frame: finishes jobs and (with `auto`) propagates edited
|
||||
/// instances in the background.
|
||||
pub fn poll_roto(&mut self, auto: bool) -> bool {
|
||||
self.poll_roto_models();
|
||||
let changed = self.poll_roto_job();
|
||||
if auto && self.roto_job.is_none() && self.offloaded_roto().is_none() && self.state.roto.auto_propagate {
|
||||
while let Some((c, l, e)) = self.roto_pending.first().copied() {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Roto Brush's trained models (Settings ▸ Roto Brush, `roto.model*` commands): which models the
|
||||
//! registry offers (`effectcraft_segment::MODELS`, all open source), which are installed (in the
|
||||
//! `models` folder next to the settings), installing one from a file or downloading the official
|
||||
//! weights (verified against the registry's SHA-256 either way), choosing one, and loading it in
|
||||
//! the background into the Roto Brush effect (`effects::roto::set_model`).
|
||||
//!
|
||||
//! Weights are never bundled: the install stays small and nothing is fetched unless asked for.
|
||||
//! Downloads use the system's `curl` (shipped with Windows 10+, macOS and most Linux systems),
|
||||
//! so no networking code is linked into EffectCraft; without it, the file can be downloaded in a
|
||||
//! browser and installed with Install from File. The browser build segments with the built-in
|
||||
//! engine only, for now.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_segment::{self as seg, ModelInfo};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd, query};
|
||||
|
||||
/// What the background worker reports.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Status {
|
||||
/// What is happening now ("Downloading MobileSAM…").
|
||||
pub busy: Option<String>,
|
||||
/// The model loaded into Roto Brush.
|
||||
pub active: Option<String>,
|
||||
/// The last failure, for the Settings page.
|
||||
pub error: Option<String>,
|
||||
/// A finished job's message, for a toast (taken by [`Session::poll_roto_models`]).
|
||||
pub done: Option<String>,
|
||||
}
|
||||
|
||||
/// The session's model state.
|
||||
#[derive(Default)]
|
||||
pub struct Models {
|
||||
pub status: Arc<Mutex<Status>>,
|
||||
}
|
||||
|
||||
impl Models {
|
||||
pub fn status(&self) -> Status {
|
||||
self.status.lock().map(|s| s.clone()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn set(status: &Arc<Mutex<Status>>, f: impl FnOnce(&mut Status)) {
|
||||
if let Ok(mut s) = status.lock() {
|
||||
f(&mut s);
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The folder installed models live in: the host's, else `models` next to the settings.
|
||||
pub fn models_dir(&self) -> Option<PathBuf> {
|
||||
self.models_dir.clone().or_else(|| Some(self.config.as_ref()?.dir()?.join("models")))
|
||||
}
|
||||
|
||||
/// Where `m` is installed, if it is (a file of the published size).
|
||||
pub fn model_path(&self, m: &ModelInfo) -> Option<PathBuf> {
|
||||
let p = self.models_dir()?.join(m.file_name);
|
||||
std::fs::metadata(&p).ok().filter(|md| md.len() == m.size).map(|_| p)
|
||||
}
|
||||
|
||||
/// Load (or drop) the model Settings ▸ Roto Brush chooses; called whenever settings change.
|
||||
pub fn apply_roto_model(&mut self) {
|
||||
let want = self.prefs.roto.model.clone();
|
||||
let st = self.roto_models.status();
|
||||
if want == seg::CLASSICAL || seg::info(&want).is_none() {
|
||||
if st.active.is_some() {
|
||||
crate::effects::roto::set_model(None);
|
||||
set(&self.roto_models.status, |s| s.active = None);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if st.active.as_deref() == Some(want.as_str()) || st.busy.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(info) = seg::info(&want) else { return };
|
||||
let Some(path) = self.model_path(info) else {
|
||||
crate::effects::roto::set_model(None);
|
||||
set(&self.roto_models.status, |s| s.active = None);
|
||||
return;
|
||||
};
|
||||
spawn(&self.roto_models.status, format!("Loading {}…", info.name), move |status| {
|
||||
let m = load_file(&path, info.id)?;
|
||||
crate::effects::roto::set_model(Some(m));
|
||||
set(status, |s| s.active = Some(info.id.to_string()));
|
||||
Ok(format!("Roto Brush: {} loaded", info.name))
|
||||
});
|
||||
}
|
||||
|
||||
/// Finish what the model worker did: a toast, and loading a model that just arrived.
|
||||
pub fn poll_roto_models(&mut self) {
|
||||
let done = self.roto_models.status.lock().ok().and_then(|mut s| s.done.take());
|
||||
if let Some(msg) = done {
|
||||
let error = msg.starts_with("Roto Brush model:");
|
||||
self.events.push(crate::Event::Toast { message: msg, error });
|
||||
self.apply_roto_model();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_file(path: &Path, id: &str) -> std::result::Result<Arc<dyn seg::MaskModel>, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
|
||||
seg::load(id, &bytes)
|
||||
}
|
||||
|
||||
/// Run `job` on a worker thread, reporting through `status` (desktop; the browser build has no
|
||||
/// trained models yet).
|
||||
fn spawn(status: &Arc<Mutex<Status>>, what: String, job: impl FnOnce(&Arc<Mutex<Status>>) -> std::result::Result<String, String> + Send + 'static) {
|
||||
set(status, |s| {
|
||||
s.busy = Some(what);
|
||||
s.error = None;
|
||||
});
|
||||
let st = status.clone();
|
||||
let run = move || {
|
||||
let r = job(&st);
|
||||
set(&st, |s| {
|
||||
s.busy = None;
|
||||
match r {
|
||||
Ok(msg) => s.done = Some(msg),
|
||||
Err(e) => {
|
||||
s.done = Some(format!("Roto Brush model: {e}"));
|
||||
s.error = Some(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
set(status, |s| {
|
||||
s.busy = None;
|
||||
s.error = Some("trained models are available in the desktop app".into());
|
||||
});
|
||||
return;
|
||||
}
|
||||
if let Err(e) = std::thread::Builder::new().name("ec-roto-model".into()).spawn(run) {
|
||||
set(status, |s| {
|
||||
s.busy = None;
|
||||
s.error = Some(format!("cannot start: {e}"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy verified weights into the models folder (atomically).
|
||||
fn install_bytes(dir: &Path, m: &ModelInfo, bytes: &[u8]) -> std::result::Result<PathBuf, String> {
|
||||
if bytes.len() as u64 != m.size || seg::sha256::hex(bytes) != m.sha256 {
|
||||
return Err(format!("this is not the published {} file (size or SHA-256 differs)", m.name));
|
||||
}
|
||||
let path = dir.join(m.file_name);
|
||||
crate::config::FileOps::write(&crate::config::StdFiles, &path, bytes).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn model_p(p: &Value, cmd: &str) -> Result<&'static ModelInfo> {
|
||||
let id = str_p(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
seg::info(id).ok_or_else(|| bad(cmd, format!("unknown model `{id}` (see roto.models)")))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.roto_models.status();
|
||||
let chosen = s.prefs.roto.model.clone();
|
||||
let mut v = vec![json!({
|
||||
"id": seg::CLASSICAL,
|
||||
"name": "Classic (graph cut)",
|
||||
"description": "Built in: colour models and graph cuts, propagated by optical flow. Always available.",
|
||||
"licence": "MIT OR Apache-2.0",
|
||||
"installed": true,
|
||||
"selected": chosen == seg::CLASSICAL,
|
||||
"active": st.active.is_none(),
|
||||
})];
|
||||
for m in seg::MODELS {
|
||||
v.push(json!({
|
||||
"id": m.id,
|
||||
"name": m.name,
|
||||
"description": m.description,
|
||||
"licence": m.licence,
|
||||
"licenceUrl": m.licence_url,
|
||||
"homepage": m.homepage,
|
||||
"url": m.url,
|
||||
"size": m.size,
|
||||
"sha256": m.sha256,
|
||||
"installed": s.model_path(m).is_some(),
|
||||
"selected": chosen == m.id,
|
||||
"active": st.active.as_deref() == Some(m.id),
|
||||
}));
|
||||
}
|
||||
Ok(json!({"models": v, "busy": st.busy, "error": st.error, "folder": s.models_dir().map(|d| d.display().to_string())}))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_p(p, "id").ok_or_else(|| bad("roto.model.select", "missing `id`"))?;
|
||||
if id != seg::CLASSICAL && seg::info(id).is_none() {
|
||||
return Err(bad("roto.model.select", format!("unknown model `{id}` (see roto.models)")));
|
||||
}
|
||||
s.prefs.roto.model = id.to_string();
|
||||
s.save_prefs();
|
||||
s.prefs_changed();
|
||||
Ok(json!({"model": id}))
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.model.install";
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(cmd, "missing `path` (the downloaded weights file)"))?;
|
||||
let dir = s.models_dir().ok_or_else(|| bad(cmd, "no settings folder to install into"))?;
|
||||
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
// Which model it is: the one asked for, or the one whose checksum it has.
|
||||
let m = match str_p(p, "id") {
|
||||
Some(_) => model_p(p, cmd)?,
|
||||
None => {
|
||||
let h = seg::sha256::hex(&bytes);
|
||||
seg::MODELS.iter().find(|m| m.sha256 == h).ok_or_else(|| bad(cmd, "this file is not a published model in the registry (SHA-256 differs)"))?
|
||||
}
|
||||
};
|
||||
let dest = install_bytes(&dir, m, &bytes).map_err(|e| bad(cmd, e))?;
|
||||
s.apply_roto_model();
|
||||
Ok(json!({"id": m.id, "path": dest.display().to_string()}))
|
||||
}
|
||||
|
||||
fn download(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.model.download";
|
||||
let m = model_p(p, cmd)?;
|
||||
let dir = s.models_dir().ok_or_else(|| bad(cmd, "no settings folder to install into"))?;
|
||||
if s.roto_models.status().busy.is_some() {
|
||||
return Err(bad(cmd, "a model is already downloading or loading"));
|
||||
}
|
||||
spawn(&s.roto_models.status, format!("Downloading {} ({} MB)…", m.name, m.size / 1_000_000), move |_| {
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
let tmp = dir.join(format!("{}.part", m.file_name));
|
||||
let out = std::process::Command::new("curl")
|
||||
.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"])
|
||||
.arg(&tmp)
|
||||
.arg(m.url)
|
||||
.output()
|
||||
.map_err(|e| format!("downloading needs curl ({e}); or download {} in a browser and use Install from File", m.url))?;
|
||||
if !out.status.success() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(format!("download failed: {}", String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
let bytes = std::fs::read(&tmp).map_err(|e| format!("cannot read the download: {e}"))?;
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
install_bytes(&dir, m, &bytes)?;
|
||||
Ok(format!("Roto Brush: {} downloaded and verified", m.name))
|
||||
});
|
||||
Ok(json!({"id": m.id, "downloading": true}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let m = model_p(p, "roto.model.remove")?;
|
||||
let Some(path) = s.model_path(m) else { return Ok(json!({"removed": false})) };
|
||||
if s.roto_models.status().active.as_deref() == Some(m.id) {
|
||||
crate::effects::roto::set_model(None);
|
||||
set(&s.roto_models.status, |st| st.active = None);
|
||||
}
|
||||
std::fs::remove_file(&path).map_err(|e| EngineError::Other(format!("cannot remove {}: {e}", path.display())))?;
|
||||
Ok(json!({"removed": true}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
query!("roto.models", "Roto Brush Models", "{}", list),
|
||||
cmd!("roto.model.select", "Use Roto Brush Model", [], None, "{id: classical|mobilesam} (Roto Brush 2.0 / 3.0 use it)", always, select),
|
||||
cmd!(
|
||||
"roto.model.install",
|
||||
"Install Roto Brush Model",
|
||||
[],
|
||||
None,
|
||||
"{path: weights file, id?} — verified against the registry's SHA-256",
|
||||
always,
|
||||
install
|
||||
),
|
||||
cmd!(
|
||||
"roto.model.download",
|
||||
"Download Roto Brush Model",
|
||||
[],
|
||||
None,
|
||||
"{id} — the official weights, verified (desktop; uses the system curl)",
|
||||
always,
|
||||
download
|
||||
),
|
||||
cmd!("roto.model.remove", "Remove Roto Brush Model", [], None, "{id}", always, remove),
|
||||
]
|
||||
}
|
||||
@@ -38,6 +38,8 @@ impl Session {
|
||||
let levels = self.prefs.general.undo_levels.max(1) as usize;
|
||||
let current = self.project.clone();
|
||||
self.history.trim(levels, ¤t);
|
||||
// Settings ▸ Roto Brush: load (or drop) the chosen trained model.
|
||||
self.apply_roto_model();
|
||||
self.prefs_revision += 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Settings ▸ Roto Brush: the model registry, choosing, installing (verified) and loading a
|
||||
//! trained model into Roto Brush.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::config::{ConfigStore, DirConfig};
|
||||
|
||||
fn session() -> (Session, std::path::PathBuf) {
|
||||
let d = std::env::temp_dir().join(format!("ec-roto-models-{}-{}", std::process::id(), line!()));
|
||||
let store: Arc<dyn ConfigStore> = Arc::new(DirConfig::new(d.join("config")));
|
||||
(Session { config: Some(store), ..Default::default() }, d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_are_listed_chosen_and_verified() {
|
||||
let (mut s, d) = session();
|
||||
let list = s.execute_checked("roto.models", json!({})).unwrap();
|
||||
let ids: Vec<&str> = list["models"].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["classical", "mobilesam"]);
|
||||
let sam = &list["models"][1];
|
||||
assert_eq!((sam["licence"].as_str(), sam["installed"].as_bool()), (Some("Apache-2.0"), Some(false)));
|
||||
assert!(sam["url"].as_str().unwrap().starts_with("https://"));
|
||||
// Unknown ids and files that aren't the published weights are refused.
|
||||
assert!(s.execute_checked("roto.model.select", json!({"id": "nope"})).is_err());
|
||||
let bogus = d.join("bogus.pt");
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(&bogus, b"not the weights").unwrap();
|
||||
let e = s.execute_checked("roto.model.install", json!({"path": bogus.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("SHA-256"), "{e}");
|
||||
assert!(s.execute_checked("roto.model.install", json!({"path": bogus.to_string_lossy(), "id": "mobilesam"})).is_err());
|
||||
// Choosing a model that isn't installed keeps the classic engine.
|
||||
s.execute_checked("roto.model.select", json!({"id": "mobilesam"})).unwrap();
|
||||
assert_eq!(s.prefs.roto.model, "mobilesam");
|
||||
assert!(s.roto_models.status().active.is_none());
|
||||
assert!(crate::prefs::pages().iter().any(|p| p.id == "roto"));
|
||||
// With the real weights (EFFECTCRAFT_MOBILESAM=path/to/mobile_sam.pt): install, load, use.
|
||||
if let Ok(path) = std::env::var("EFFECTCRAFT_MOBILESAM") {
|
||||
s.execute_checked("roto.model.install", json!({"path": path})).unwrap();
|
||||
for _ in 0..200 {
|
||||
s.poll_roto_models();
|
||||
if s.roto_models.status().active.is_some() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(s.roto_models.status().active.as_deref(), Some("mobilesam"));
|
||||
// Roto Brush 3.0 (the default version) now segments with it.
|
||||
let params = crate::effects::Params { values: [("version".to_string(), effectcraft_keyframe::Value::Enum(2))].into_iter().collect() };
|
||||
assert_eq!(crate::effects::roto::model_for(¶ms).map(|m| m.info().id), Some("mobilesam"));
|
||||
s.execute_checked("roto.model.select", json!({"id": "classical"})).unwrap();
|
||||
assert!(crate::effects::roto::model_for(¶ms).is_none());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
Reference in New Issue
Block a user