Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
IX1, IX3: Index's fast pass, raea-sys-index: a folder's pictures listed, decoded from their small copy and embedded by SigLIP 2 B/16-256 on the Neural Engine, searchable by words
shinyobjectzef747f9b247f
diff --git a/Cargo.lock b/Cargo.lockindex 1f31ced0..01db9a79 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11460,6 +11460,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea"dependencies = [+ "block2 0.6.2","objc2 0.6.5","objc2-core-foundation","objc2-core-graphics",@@ -15783,6 +15784,29 @@ dependencies = ["bevy",]+[[package]]+name = "raea-sys-index"+version = "0.1.0"+dependencies = [+ "anyhow",+ "half",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-ml",+ "objc2-core-video",+ "objc2-foundation 0.3.2",+ "objc2-image-io",+ "ort",+ "raea-sys-ml",+ "rayon",+ "rusqlite",+ "serde",+ "serde_json",+ "tokenizers",+ "walkdir",+]+[[package]]name = "raea-sys-k"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 12e54b17..8b2034b2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -85,6 +85,7 @@ members = ["systems/layout","systems/vision","systems/columns",+ "systems/index","systems/fingerprint","systems/fingerprint-use","systems/fingerprint-things",diff --git a/docs/index.feature b/docs/index.featurenew file mode 100644index 00000000..f7601008--- /dev/null+++ b/docs/index.feature@@ -0,0 +1,146 @@+Feature: Index: every picture and video you have, searchable in minutes (0.1.5)+ Shane, 11-14: "the big thing I need you to ship in 0.1.5 is the fastest fucking indexing tool for videos and images+ on the OS and on your phone/photos/icloud ... a plugin that is able to do this for google drive, apple photos and+ icloud and locally or on a local drive of course. if free that index just stays local. if pro or team we can factor+ it into their plan. ITs vital that a wow moment is just how fast we can index tons of content, embed it all and+ manage those embeddings across search." 0.1.5 carries this and the 0.1.4 feed fixes; Character SDK moves to 0.1.6.++ This builds on Libraries (docs/libraries.feature): its libraries, sources, local index, cloud index (turbopuffer+ through raea-api) and fused search stay. What changes is the first pass. Today a file is hashed, cut into shots and+ embedded by EmbeddingGemma 2 on the CPU before it can be found: LB1 took 316 s for 25 files, 12.6 s a file. A+ photo library of 50,000 would take a week. EmbeddingGemma 2's picture tower is a 16-layer ViT over up to 2,520+ patches, about 0.9 TFLOP a picture, so no runtime makes it the first pass.++ So indexing has two passes:+ - the fast pass: every picture, and a few frames of every video, through SigLIP 2 B/16-256 on the Neural Engine,+ from the small copy the file or Photos already holds, searchable by words through SigLIP 2's text tower. Minutes+ for a whole library.+ - the deep pass (Libraries as it is): shots, sound, transcripts and EmbeddingGemma 2, in the background, after+ the fast pass, never on battery. It adds what's said and heard, and better ranking for video.++ Measured 11-14 on this Mac (M5 Pro), with nothing else changed (ixbench in the scratchpad, 600 real files, mostly+ big PNGs with no embedded preview, the worst case for decoding):+ | step | per second | note |+ | ImageIO thumbnail decode to 256 px, all cores | 383-399 | JPEG and HEIC with a preview are faster |+ | SigLIP 2 B/16-256, Core ML, CPU + Neural Engine | 194-200 | batch 32 or 64; cosine 0.9985 to fp32 (10-16) |+ | the same on Core ML's GPU | 297 | wrong vectors on this Mac (coreml-gpu-siglip) |+ | EmbeddingGemma 2, q8 on CPU (LB1) | 0.08 files | 12.6 s a file, shots and sound included |++ Rule: The fast pass++ Scenario: IX1. A picture is found by words seconds after raea sees it+ Given a source with pictures (a folder, a drive, Photos, iCloud Drive, Google Drive)+ When the fast pass runs+ Then each picture is listed (its place, size, dates, dimensions), decoded to 256 px from its embedded preview+ when it has one (ImageIO; PhotoKit's own derivative for Photos), and embedded by SigLIP 2 B/16-256 on Core ML's+ CPU and Neural Engine, 32 at a time, while the next batch decodes+ And its vector (768 f16, normalised) and a 256 px JPEG thumbnail are written as soon as its batch is done, so+ search finds the first pictures while the rest are still going+ And an item is keyed by where it lives (a path, a Photos asset, a Drive file id) with its size and dates; its+ sha256 comes with the deep pass, or when the original is read anyway. The fast pass never reads a whole+ original only to hash it+ And sustained, it runs at 150 pictures a second or better on an M-series Mac with nothing else heavy running+ (bench/index), and says how fast it went++ Scenario: IX2. A video's first pass is a few frames+ Then a video gets its poster and one frame every 4 s, at most 16, from the nearest sync frames (AVFoundation,+ VideoToolbox's hardware decoder), each a row with its time, so "the dog jumps in the pool" finds the moment+ And a video is listed with its length and dimensions before its frames are read++ Scenario: IX3. Search reads both passes+ Then a query's words are embedded by SigLIP 2's text tower (ONNX on CPU, one query in milliseconds) and scored+ against every fast-pass row (brute force over f16 rows in Rust, fast enough to a million rows), and by+ EmbeddingGemma 2 against the deep pass's rows as now+ And the lists are fused by site/api src/library/fuse.ts with the fast list as one more list of its own weight and+ MARGIN, measured on LB1's queries plus a photo set before the weights are set; a model's vectors are never+ scored against another model's+ And a picture or a frame can be the query ("more like this"), against the fast rows+ And results show the thumbnails, grouped per file, with the moment for a video++ Scenario: IX4. The deep pass follows+ Then once a source's fast pass is done, Libraries' indexFile runs on its videos, sounds and words at low priority,+ through antsy, never on battery, its own files before claimed jobs (LB6b)+ And a picture needs no deep pass to be found; its EmbeddingGemma 2 row comes when the deep pass reaches it++ Rule: Sources++ Scenario: IX5. This Mac's folders and drives+ Then a folder or a drive is listed fast (getattrlistbulk through fts, skipping packages, caches and raea's own+ media), watched with FSEvents, and a drive's mount and unmount set it online or offline (Libraries' volume+ sources); an offline drive stays searchable from its thumbnails++ Scenario: IX6. Apple Photos, and so iCloud Photos and the iPhone's camera roll+ Then turning Photos on asks macOS once (raea.app's NSPhotoLibraryUsageDescription; read-only, never a change to+ the library)+ And every asset is fetched from PhotoKit at once (PHAsset, newest first), each picture's 256 px image requested+ from PHImageManager (its local derivative; one only in iCloud is fetched at that size when "include photos only+ in iCloud" is on, by default), a video's frames from its local AVAsset, else its poster+ And an asset is keyed by its local identifier; its dates, place, favourite and media subtypes (screenshot,+ selfie, live photo, slo-mo) become filters+ And photos taken on the iPhone arrive through iCloud Photos and are indexed as they land (PHPhotoLibrary's change+ observer)++ Scenario: IX7. iCloud Drive+ Then iCloud Drive is a folder source (~/Library/Mobile Documents/com~apple~CloudDocs); a file kept only in iCloud+ is indexed from its Quick Look thumbnail (QLThumbnailGenerator) without downloading it, marked "in iCloud", and+ downloaded only when opened++ Scenario: IX8. Google Drive+ Then through the Drive connection (raea-api src/connect; Drive is live since 11-11), raea-api lists the Drive's+ pictures and videos (files.list: id, name, mimeType, md5Checksum, imageMediaMetadata, videoMediaMetadata,+ thumbnailLink) and hands the Mac each thumbnail through the API; the Mac embeds it. The token stays in raea-api+ And a Drive of 20,000 pictures is searchable without one original downloaded; an original streams through the API+ (LB6's job media route) only when opened or deep-indexed+ And Google Drive for desktop's own folder (~/Library/CloudStorage/GoogleDrive-*), when it is there, is a folder+ source like any other++ Scenario: IX9. The phone itself, later+ Then 0.1.5 reaches the phone's library through iCloud Photos on the Mac. Indexing on the iPhone in raea's iOS app+ (PhotoKit on the device, its Neural Engine, the same model) waits for its Photos usage string and a TestFlight+ build in App Store Connect++ Rule: Plans++ Scenario: IX10. Free keeps the index on the Mac; Pro and Team also keep it in raea's cloud+ Then on Free every source is indexed and searched on the Mac, and nothing leaves it (Libraries' local index)+ And on Pro and Team the index (vectors, thumbnails, the words and labels, never the media) also goes to raea's+ cloud through raea-api, so the library is searchable from raea.io, the iPad and the account's other Macs; a+ Team's workspace index is shared by its members+ And the cloud index counts toward the plan: its thumbnails and vectors as storage bytes (about 20 KB an item),+ shown on Settings → Storage beside media; what each plan includes is Shane's call (open question 1)++ Rule: Managing the index++ Scenario: IX11. Settings → Index says what's indexed, where, by which model, and lets you change it+ Then per source: found, fast-indexed, deep-indexed, waiting and failed, with its speed while it runs; pause,+ resume, index again, and remove (its rows and thumbnails go; the files are never touched)+ And per model (siglip2-b16-256@768, embeddinggemma-2@768): rows, bytes on disk, bytes in the cloud, and its+ version; a model's vectors can be dropped and made again; a newer model makes its rows beside the old ones+ and search moves over once it is done+ And where it all lives (~/.raea/library), and a button that shows it in Finder++ Scenario: IX12. The wow: the counter+ Then turning a source on starts the fast pass at once and shows it: items found, items searchable, pictures a+ second, and the newest thumbnails landing as a wall; search works from the first batch+ And the first run on a library of 10,000 photos is searchable in about a minute on an M-series Mac++ Rule: How it ships++ Scenario: IX13. Where the work runs+ Then the engine does the work, in its own crate (systems/index, raea-sys-index: sources, decode, embed, store,+ search) on raea-sys-vision's Core ML (CpuAndNe), and `raea index` drives it: add, status, search, serve (a+ resident process the feed's host keeps, JSON lines)+ And the feed shows it: the Index plugin (its sources' switches and the counter), Settings → Index, and search,+ which asks `raea index search` and the deep index and fuses them+ And agents reach it as they reach Libraries: `raea library search` and the feed's library tools read both passes++ Scenario: IX14. Measured, not guessed+ Then bench/index runs the fast pass on a fixed public set (pictures and clips under permissive licences) and+ prints pictures a second, video minutes a second, peak memory and recall@5 for a fixed list of queries; a+ release doesn't regress it++ Rule: Open questions for Shane+ Scenario: To decide+ Then 1. What Pro and Team include for the cloud index (items or bytes), and what past it costs+ And 2. Whether Photos' "include photos only in iCloud" is on by default (it fetches each one's small copy over+ the network)diff --git a/systems/index/Cargo.toml b/systems/index/Cargo.tomlnew file mode 100644index 00000000..55903fba--- /dev/null+++ b/systems/index/Cargo.toml@@ -0,0 +1,29 @@+[package]+name = "raea-sys-index"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Index's fast pass (docs/index.feature IX1-IX3): every picture, and a few frames of every video, listed, decoded from its small copy and embedded by SigLIP 2 on the Neural Engine, kept as f16 rows beside a SQLite list, and searched by words through SigLIP 2's text tower"++[dependencies]+anyhow = "1"+half = "2"+rayon = "1"+rusqlite = { version = "0.37", features = ["bundled"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+# the text tower: ONNX on ONNX Runtime's CPU kernels, as raea's other encoders+raea-sys-ml = { path = "../ml" }+ort = { version = "=2.0.0-rc.13", features = ["half"] }+tokenizers = { version = "0.23", default-features = false, features = ["onig"] }+walkdir = "2"++[target.'cfg(target_vendor = "apple")'.dependencies]+objc2 = "0.6"+objc2-foundation = { version = "0.3", features = ["NSString", "NSURL", "NSError", "NSDictionary", "NSArray", "NSValue"] }+objc2-core-foundation = { version = "0.3", features = ["CFString", "CFDictionary", "CFNumber", "CFURL", "CFData"] }+objc2-core-ml = { version = "0.3", features = ["MLModel", "MLModelConfiguration", "MLFeatureProvider", "MLDictionaryFeatureProvider", "MLFeatureValue", "MLMultiArray", "MLModel_MLModelCompilation", "MLArrayBatchProvider", "MLBatchProvider", "objc2-core-video"] }+objc2-core-video = { version = "0.3", features = ["CVPixelBuffer", "CVImageBuffer", "CVBuffer", "CVReturn"] }+objc2-core-graphics = { version = "0.3", features = ["CGImage", "CGColorSpace", "CGContext", "CGBitmapContext"] }+objc2-image-io = { version = "0.3", features = ["CGImageSource", "CGImageDestination", "CGImageProperties"] }diff --git a/systems/index/examples/fast.rs b/systems/index/examples/fast.rsnew file mode 100644index 00000000..caf90d3e--- /dev/null+++ b/systems/index/examples/fast.rs@@ -0,0 +1,42 @@+//! The fast pass by hand, to measure it (docs/index.feature IX1, IX14):+//! fast index FOLDER list it and embed its pictures, printing progress as JSON lines+//! fast search WORDS... the best ten for the words+//! RAEA_INDEX_HOME picks the index's folder.+use raea_sys_index::{Progress, search, store::Store, text::Text};+use std::path::Path;++fn main() -> anyhow::Result<()> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let mut store = Store::open(&Store::default_dir())?;+ let say = |p: &Progress| println!("{}", serde_json::to_string(p).unwrap());+ match args.first().map(String::as_str) {+ Some("index") => {+ let root = Path::new(&args[1]);+ let (source, found) = raea_sys_index::list_folder(&mut store, root, &mut |p| say(p))?;+ eprintln!("listed {found}");+ let t = std::time::Instant::now();+ let model = raea_sys_index::apple::Model::load(&raea_sys_index::image_package()).map_err(anyhow::Error::msg)?;+ eprintln!("model loaded in {:.2} s", t.elapsed().as_secs_f64());+ let p = raea_sys_index::embed_pictures(&mut store, &model, &source, &mut |p| say(p))?;+ eprintln!("done: {} embedded, {} failed, {:.0}/s over {:.1} s", p.done, p.failed, p.per_sec, p.seconds);+ }+ Some("search") => {+ let words = args[1..].join(" ");+ let (m, tok) = raea_sys_index::text_files();+ let t = std::time::Instant::now();+ let mut text = Text::load(&m, &tok)?;+ let rows = search::Rows::load(&store, raea_sys_index::store::MODEL)?;+ eprintln!("loaded {} rows and the text tower in {:.2} s", rows.len(), t.elapsed().as_secs_f64());+ let t = std::time::Instant::now();+ let q = text.embed(&words)?;+ let e = t.elapsed().as_secs_f64();+ let hits = search::search(&store, &rows, &q, 10)?;+ eprintln!("query {:.0} ms, search {:.0} ms", e * 1e3, (t.elapsed().as_secs_f64() - e) * 1e3);+ for h in hits {+ println!("{:.3} {}", h.score, h.locator);+ }+ }+ _ => eprintln!("fast index FOLDER | fast search WORDS..."),+ }+ Ok(())+}diff --git a/systems/index/src/apple.rs b/systems/index/src/apple.rsnew file mode 100644index 00000000..ad1292a6--- /dev/null+++ b/systems/index/src/apple.rs@@ -0,0 +1,214 @@+//! The fast pass on a Mac (docs/index.feature IX1): a picture's small copy from ImageIO (the embedded preview when it+//! is big enough, else the file decoded at a reduced size), squashed into a 256 x 256 BGRA pixel buffer as SigLIP's+//! processor resizes, a 256 px JPEG thumbnail written beside it, and SigLIP 2 B/16-256 on Core ML's CPU and Neural+//! Engine, a batch at a time. Never Core ML's GPU: on an M5 Pro it computes SigLIP 2 wrong (coreml-gpu-siglip).++use objc2::rc::Retained;+use objc2::runtime::{AnyObject, ProtocolObject};+use objc2::AnyThread;+use objc2_core_foundation::{CFBoolean, CFDictionary, CFNumber, CFRetained, CFString, CFType, CFURL};+use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGImage, CGInterpolationQuality};+use objc2_core_ml::{+ MLArrayBatchProvider, MLBatchProvider, MLComputeUnits, MLDictionaryFeatureProvider, MLFeatureProvider, MLFeatureValue, MLModel, MLModelConfiguration,+ MLMultiArray, MLMultiArrayDataType,+};+use objc2_core_video::{+ CVPixelBuffer, CVPixelBufferCreate, CVPixelBufferGetBaseAddress, CVPixelBufferGetBytesPerRow, CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags,+ CVPixelBufferUnlockBaseAddress, kCVPixelFormatType_32BGRA,+};+use objc2_foundation::{NSArray, NSDictionary, NSString, NSURL};+use objc2_image_io::{+ CGImageDestination, CGImageSource, kCGImageDestinationLossyCompressionQuality, kCGImageSourceCreateThumbnailFromImageAlways,+ kCGImageSourceCreateThumbnailFromImageIfAbsent, kCGImageSourceCreateThumbnailWithTransform, kCGImageSourceShouldCache,+ kCGImageSourceShouldCacheImmediately, kCGImageSourceThumbnailMaxPixelSize,+};+use std::path::{Path, PathBuf};+use std::ptr::NonNull;++/// SigLIP 2 B/16-256's side+pub const SIDE: usize = 256;++/// A picture ready for the model: its 256 x 256 pixel buffer and its own size+pub struct Ready {+ pub item: i64,+ pub t: f64,+ pub px: CFRetained<CVPixelBuffer>,+ pub w: u32,+ pub h: u32,+}+// a pixel buffer is a reference-counted CF object; it moves between the decoding and embedding threads, used by one+// at a time+unsafe impl Send for Ready {}++fn dict(pairs: &[(&CFString, &CFType)]) -> CFRetained<CFDictionary<CFString, CFType>> {+ let (k, v): (Vec<&CFString>, Vec<&CFType>) = pairs.iter().copied().unzip();+ CFDictionary::from_slices(&k, &v)+}++fn thumbnail(src: &CGImageSource, max: i32, always: bool) -> Option<CFRetained<CGImage>> {+ let n = CFNumber::new_i32(max);+ let yes = CFBoolean::new(true);+ let from = if always { unsafe { kCGImageSourceCreateThumbnailFromImageAlways } } else { unsafe { kCGImageSourceCreateThumbnailFromImageIfAbsent } };+ let d = dict(&[+ (from, yes.as_ref()),+ (unsafe { kCGImageSourceThumbnailMaxPixelSize }, n.as_ref()),+ (unsafe { kCGImageSourceCreateThumbnailWithTransform }, yes.as_ref()),+ (unsafe { kCGImageSourceShouldCacheImmediately }, yes.as_ref()),+ ]);+ unsafe { src.thumbnail_at_index(0, Some(d.as_opaque())) }+}++/// A picture file's small copy at `SIDE`, its thumbnail written to `thumb`: the embedded preview when it's at least+/// `SIDE` on its long side, else the file decoded at a reduced size+pub fn picture(path: &Path, thumb: Option<&Path>) -> Result<(CFRetained<CVPixelBuffer>, u32, u32), String> {+ let url = CFURL::from_file_path(path).ok_or("not a file path")?;+ let no = CFBoolean::new(false);+ let opts = dict(&[(unsafe { kCGImageSourceShouldCache }, no.as_ref())]);+ let src = unsafe { CGImageSource::with_url(&url, Some(opts.as_opaque())) }.ok_or("ImageIO can't read it")?;+ let side = SIDE as i32;+ let img = thumbnail(&src, side, false)+ .filter(|i| CGImage::width(Some(i)).max(CGImage::height(Some(i))) >= SIDE)+ .or_else(|| thumbnail(&src, side, true))+ .ok_or("no picture in it")?;+ let (w, h) = (CGImage::width(Some(&img)) as u32, CGImage::height(Some(&img)) as u32);+ if let Some(t) = thumb {+ let _ = write_jpeg(&img, t);+ }+ Ok((squash(&img)?, w, h))+}++/// The picture drawn into a SIDE x SIDE BGRA pixel buffer, stretched to the square+pub fn squash(img: &CGImage) -> Result<CFRetained<CVPixelBuffer>, String> {+ let mut raw: *mut CVPixelBuffer = std::ptr::null_mut();+ let r = unsafe { CVPixelBufferCreate(None, SIDE, SIDE, kCVPixelFormatType_32BGRA, None, NonNull::new(&mut raw).unwrap()) };+ if r != 0 || raw.is_null() {+ return Err(format!("CVPixelBufferCreate: {r}"));+ }+ let px = unsafe { CFRetained::from_raw(NonNull::new(raw).unwrap()) };+ unsafe { CVPixelBufferLockBaseAddress(&px, CVPixelBufferLockFlags(0)) };+ let base = CVPixelBufferGetBaseAddress(&px);+ let row = CVPixelBufferGetBytesPerRow(&px);+ let space = CGColorSpace::new_device_rgb();+ // premultiplied first, little-endian: BGRA in memory+ let info = 2u32 | (2 << 12);+ let ctx = unsafe { CGBitmapContextCreate(base, SIDE, SIDE, 8, row, space.as_deref(), info) };+ let drawn = ctx.map(|c| {+ CGContext::set_interpolation_quality(Some(&c), CGInterpolationQuality::Medium);+ CGContext::draw_image(Some(&c), objc2_core_foundation::CGRect::new(objc2_core_foundation::CGPoint::new(0.0, 0.0), objc2_core_foundation::CGSize::new(SIDE as f64, SIDE as f64)), Some(img));+ });+ unsafe { CVPixelBufferUnlockBaseAddress(&px, CVPixelBufferLockFlags(0)) };+ drawn.ok_or("no bitmap context")?;+ Ok(px)+}++/// A JPEG of the picture at quality 0.7+pub fn write_jpeg(img: &CGImage, to: &Path) -> Result<(), String> {+ if let Some(d) = to.parent() {+ std::fs::create_dir_all(d).map_err(|e| e.to_string())?;+ }+ let url = CFURL::from_file_path(to).ok_or("not a file path")?;+ let kind = CFString::from_static_str("public.jpeg");+ let dest = unsafe { CGImageDestination::with_url(&url, &kind, 1, None) }.ok_or("ImageIO can't write there")?;+ let q = CFNumber::new_f64(0.7);+ let props = dict(&[(unsafe { kCGImageDestinationLossyCompressionQuality }, q.as_ref())]);+ unsafe { dest.add_image(img, Some(props.as_opaque())) };+ if unsafe { dest.finalize() } { Ok(()) } else { Err("the JPEG wasn't written".into()) }+}++/// SigLIP 2 B/16-256's image tower on Core ML+pub struct Model(Retained<MLModel>);+unsafe impl Send for Model {}++fn modified(p: &Path) -> std::time::SystemTime {+ fn walk(p: &Path, best: &mut std::time::SystemTime) {+ if let Ok(m) = std::fs::metadata(p).and_then(|m| m.modified()) {+ *best = (*best).max(m);+ }+ if let Ok(rd) = std::fs::read_dir(p) {+ for e in rd.flatten() {+ walk(&e.path(), best);+ }+ }+ }+ let mut best = std::time::UNIX_EPOCH;+ walk(p, &mut best);+ best+}++impl Model {+ /// The package compiled once into ~/Library/Caches/raea-index, loaded on the CPU and Neural Engine+ pub fn load(package: &Path) -> Result<Model, String> {+ if !package.exists() {+ return Err(format!("{}: not installed", package.display()));+ }+ let caches = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("Library/Caches/raea-index");+ std::fs::create_dir_all(&caches).map_err(|e| e.to_string())?;+ let name = package.file_stem().and_then(|s| s.to_str()).unwrap_or("model");+ let compiled = caches.join(format!("{name}.mlmodelc"));+ if !compiled.exists() || modified(&compiled) < modified(package) {+ let url = NSURL::from_directory_path(package).ok_or("bad package path")?;+ #[allow(deprecated)]+ let fresh = unsafe { MLModel::compileModelAtURL_error(&url) }.map_err(|e| format!("compiling {name}: {}", e.localizedDescription()))?;+ let from = fresh.to_file_path().ok_or("no compiled path")?;+ let _ = std::fs::remove_dir_all(&compiled);+ std::fs::rename(&from, &compiled).map_err(|e| e.to_string())?;+ }+ let config = unsafe { MLModelConfiguration::new() };+ let units = match std::env::var("RAEA_COREML_UNITS").as_deref() {+ // to measure one against another; the default is the only right one on an M5 Pro+ Ok("cpu") => MLComputeUnits::CPUOnly,+ Ok("all") => MLComputeUnits::All,+ _ => MLComputeUnits::CPUAndNeuralEngine,+ };+ unsafe { config.setComputeUnits(units) };+ let url = NSURL::from_directory_path(&compiled).ok_or("bad compiled path")?;+ let m = unsafe { MLModel::modelWithContentsOfURL_configuration_error(&url, &config) }.map_err(|e| format!("loading {name}: {}", e.localizedDescription()))?;+ Ok(Model(m))+ }++ /// Each picture's embedding, L2-normalised, one batch through the model+ pub fn embed(&self, batch: &[&CVPixelBuffer]) -> Result<Vec<Vec<f32>>, String> {+ let key = NSString::from_str("image");+ let mut provs: Vec<Retained<ProtocolObject<dyn MLFeatureProvider>>> = Vec::with_capacity(batch.len());+ for px in batch {+ let v = unsafe { MLFeatureValue::featureValueWithPixelBuffer(px) };+ let d: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::from_slices(&[&*key], &[v.as_ref() as &AnyObject]);+ let p = unsafe { MLDictionaryFeatureProvider::initWithDictionary_error(MLDictionaryFeatureProvider::alloc(), &d) }.map_err(|e| format!("inputs: {}", e.localizedDescription()))?;+ provs.push(ProtocolObject::from_retained(p));+ }+ let arr = NSArray::from_retained_slice(&provs);+ let bp = unsafe { MLArrayBatchProvider::initWithFeatureProviderArray(MLArrayBatchProvider::alloc(), &arr) };+ let out = unsafe { self.0.predictionsFromBatch_error(ProtocolObject::from_ref(&*bp)) }.map_err(|e| format!("prediction: {}", e.localizedDescription()))?;+ let name = NSString::from_str("embedding");+ let n = unsafe { out.count() } as usize;+ let mut vs = Vec::with_capacity(n);+ for i in 0..n {+ let f = unsafe { out.featuresAtIndex(i as isize) };+ let v = unsafe { f.featureValueForName(&name) }.ok_or("no embedding output")?;+ let a: Retained<MLMultiArray> = unsafe { v.multiArrayValue() }.ok_or("embedding isn't an array")?;+ vs.push(floats(&a)?);+ }+ Ok(vs)+ }+}++fn floats(a: &MLMultiArray) -> Result<Vec<f32>, String> {+ let shape: Vec<usize> = unsafe { a.shape() }.iter().map(|n| n.integerValue() as usize).collect();+ let strides: Vec<usize> = unsafe { a.strides() }.iter().map(|n| n.integerValue() as usize).collect();+ let dim = *shape.last().ok_or("empty shape")?;+ let step = *strides.last().ok_or("empty strides")?;+ let kind = unsafe { a.dataType() };+ #[allow(deprecated)]+ let base = unsafe { a.dataPointer() }.as_ptr();+ let mut v: Vec<f32> = (0..dim)+ .map(|i| unsafe {+ if kind == MLMultiArrayDataType::Float16 {+ half::f16::from_bits(*(base as *const u16).add(i * step)).to_f32()+ } else {+ *(base as *const f32).add(i * step)+ }+ })+ .collect();+ crate::normalise(&mut v);+ Ok(v)+}diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rsnew file mode 100644index 00000000..ff7b9e14--- /dev/null+++ b/systems/index/src/lib.rs@@ -0,0 +1,161 @@+//! Index (docs/index.feature): every picture and video a person has, searchable in minutes. This crate is the fast+//! pass: sources are listed (walk.rs), each picture's small copy decoded and embedded by SigLIP 2 B/16-256 on the+//! Neural Engine (apple.rs) while the next ones decode, its row appended as its batch finishes (store.rs), and rows+//! searched by words through SigLIP 2's text tower (text.rs, search.rs). Libraries' deep pass (EmbeddingGemma 2 per+//! shot, sound and words) follows in the feed's host.++#[cfg(target_vendor = "apple")]+pub mod apple;+pub mod search;+pub mod store;+pub mod text;+pub mod walk;++use anyhow::Result;+use std::path::{Path, PathBuf};+use std::time::Instant;+use store::{DONE, LISTED, MODEL, Store};++/// A picture or a video a source holds, before the fast pass reads it+#[derive(Debug, Clone, Default)]+pub struct Found {+ /// where it lives in its source: a path, a Photos asset id, a Drive file id+ pub locator: String,+ /// "picture" or "video"+ pub kind: String,+ pub name: String,+ pub size: u64,+ /// seconds since 1970+ pub mtime: i64,+ pub taken: Option<i64>,+ pub w: Option<u32>,+ pub h: Option<u32>,+ pub dur: Option<f64>,+}++/// How a run is going, said as it goes+#[derive(Debug, Clone, Default, serde::Serialize)]+pub struct Progress {+ pub source: String,+ pub found: u64,+ pub done: u64,+ pub failed: u64,+ /// pictures embedded a second since the fast pass started+ pub per_sec: f64,+ pub seconds: f64,+ /// the items finished since the last report, newest last, for the wall of thumbnails+ pub newest: Vec<i64>,+ pub stage: &'static str,+}++pub fn normalise(v: &mut [f32]) {+ let n = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-12);+ v.iter_mut().for_each(|x| *x /= n);+}++/// Where SigLIP 2 B/16-256's files are: $RAEA_MODELS, else ~/.local/share/raea-models+pub fn models_dir() -> PathBuf {+ std::env::var_os("RAEA_MODELS").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models"))+}++pub fn image_package() -> PathBuf {+ models_dir().join("siglip2-base-p16-256/SigLIP2Image.mlpackage")+}++pub fn text_files() -> (PathBuf, PathBuf) {+ let d = models_dir().join("siglip2-base-p16-256");+ (d.join("onnx/text_model.onnx"), d.join("tokenizer.json"))+}++/// Lists a folder or a drive into the index; returns its source id and how many it found+pub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)) -> Result<(String, u64)> {+ let label = root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string());+ let source = store.source("folder", &root.to_string_lossy(), &label)?;+ let started = Instant::now();+ let mut found = 0u64;+ let mut err = None;+ walk::walk(root, 2000, &mut |batch| {+ found += batch.len() as u64;+ if let Err(e) = store.list(&source, &batch) {+ err.get_or_insert(e);+ }+ on(&Progress { source: source.clone(), found, stage: "listing", seconds: started.elapsed().as_secs_f64(), ..Progress::default() });+ });+ if let Some(e) = err {+ return Err(e);+ }+ Ok((source, found))+}++/// The fast pass over a source's pictures that wait for it: decoded on every core but two, embedded 32 at a time on+/// the Neural Engine, each batch's rows written as it finishes. Videos wait for their frames (IX2).+#[cfg(target_vendor = "apple")]+pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on: &mut dyn FnMut(&Progress)) -> Result<Progress> {+ use rayon::prelude::*;+ const BATCH: usize = 32;+ let all: Vec<store::Pending> = store.pending(source, usize::MAX)?.into_iter().filter(|p| p.kind == "picture").collect();+ let base = store.counts(Some(source))?;+ let (tx, rx) = std::sync::mpsc::sync_channel::<Result<apple::Ready, (i64, String)>>(BATCH * 8);+ let thumbs: Vec<PathBuf> = all.iter().map(|p| store.thumb(p.id)).collect();+ let threads = std::thread::available_parallelism().map(|n| n.get().saturating_sub(2).max(2)).unwrap_or(4);+ let decoder = std::thread::spawn(move || {+ let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().expect("a decoding pool");+ pool.install(|| {+ all.par_iter().zip(thumbs.par_iter()).for_each_with(tx, |tx, (p, thumb)| {+ let r = apple::picture(Path::new(&p.locator), Some(thumb)).map(|(px, w, h)| apple::Ready { item: p.id, t: 0.0, px, w, h }).map_err(|e| (p.id, e));+ let _ = tx.send(r);+ })+ })+ });+ let started = Instant::now();+ let mut last = Instant::now();+ let mut prog = Progress { source: source.into(), found: base.found, done: base.done, failed: base.failed, stage: "embedding", ..Progress::default() };+ let mut batch: Vec<apple::Ready> = Vec::with_capacity(BATCH);+ let mut embedded = 0u64;+ let mut flush = |batch: &mut Vec<apple::Ready>, prog: &mut Progress, store: &mut Store| -> Result<()> {+ if batch.is_empty() {+ return Ok(());+ }+ let pxs: Vec<&objc2_core_video::CVPixelBuffer> = batch.iter().map(|r| &*r.px).collect();+ let vs = model.embed(&pxs).map_err(|e| anyhow::anyhow!(e))?;+ let rows: Vec<(i64, f64, Vec<f32>)> = batch.iter().zip(vs).map(|(r, v)| (r.item, r.t, v)).collect();+ let dims: Vec<(i64, u32, u32)> = batch.iter().map(|r| (r.item, r.w, r.h)).collect();+ store.append(MODEL, &rows, &dims)?;+ prog.done += batch.len() as u64;+ prog.newest.extend(batch.iter().map(|r| r.item));+ batch.clear();+ Ok(())+ };+ for r in rx {+ match r {+ Ok(ready) => {+ batch.push(ready);+ if batch.len() == BATCH {+ embedded += BATCH as u64;+ flush(&mut batch, &mut prog, store)?;+ }+ }+ Err((item, why)) => {+ store.fail(item, &why)?;+ prog.failed += 1;+ }+ }+ if last.elapsed().as_millis() >= 250 {+ prog.seconds = started.elapsed().as_secs_f64();+ prog.per_sec = embedded as f64 / prog.seconds.max(1e-3);+ on(&prog);+ prog.newest.clear();+ last = Instant::now();+ }+ }+ embedded += batch.len() as u64;+ flush(&mut batch, &mut prog, store)?;+ let _ = decoder.join();+ prog.seconds = started.elapsed().as_secs_f64();+ prog.per_sec = embedded as f64 / prog.seconds.max(1e-3);+ prog.stage = "done";+ on(&prog);+ prog.newest.clear();+ let _ = (LISTED, DONE);+ Ok(prog)+}diff --git a/systems/index/src/search.rs b/systems/index/src/search.rsnew file mode 100644index 00000000..888f6299--- /dev/null+++ b/systems/index/src/search.rs@@ -0,0 +1,90 @@+//! Searching the fast pass (docs/index.feature IX3): a query vector against every row of the model's file, brute+//! force over f16 on every core, best `k` kept, one hit per item (its best moment). Rows of removed or changed items+//! are left out.++use crate::store::{DIM, Store};+use anyhow::Result;+use rayon::prelude::*;+use std::collections::HashMap;++#[derive(Debug, Clone, serde::Serialize)]+pub struct Hit {+ pub item: i64,+ pub score: f32,+ /// the moment in a video, seconds; 0 for a picture+ pub t: f64,+ pub kind: String,+ pub name: String,+ pub locator: String,+ pub thumb: String,+}++/// The rows' vectors as f16 bits, and which item and moment each row is+pub struct Rows {+ pub bits: Vec<u16>,+ pub item: Vec<i64>,+ pub t: Vec<f64>,+}++impl Rows {+ pub fn load(store: &Store, model: &str) -> Result<Rows> {+ let raw = std::fs::read(store.vectors(model)).unwrap_or_default();+ let n = raw.len() / (DIM * 2);+ let bits: Vec<u16> = raw[..n * DIM * 2].chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();+ let mut item = vec![-1i64; n];+ let mut t = vec![0f64; n];+ let mut q = store.db.prepare("SELECT r.row, r.item, r.t FROM rows r JOIN items i ON i.id = r.item WHERE r.model = ?1 AND i.state = 1")?;+ let mut it = q.query(rusqlite::params![model])?;+ while let Some(r) = it.next()? {+ let row: i64 = r.get(0)?;+ if (row as usize) < n {+ item[row as usize] = r.get(1)?;+ t[row as usize] = r.get(2)?;+ }+ }+ Ok(Rows { bits, item, t })+ }++ pub fn len(&self) -> usize {+ self.item.len()+ }+}++fn dot(bits: &[u16], q: &[f32]) -> f32 {+ let mut acc = [0f32; 8];+ for (c, qc) in bits.chunks_exact(8).zip(q.chunks_exact(8)) {+ for j in 0..8 {+ acc[j] += half::f16::from_bits(c[j]).to_f32() * qc[j];+ }+ }+ acc.iter().sum()+}++/// The `k` best items for the query, best first+pub fn search(store: &Store, rows: &Rows, q: &[f32], k: usize) -> Result<Vec<Hit>> {+ let scored: Vec<(usize, f32)> = rows+ .bits+ .par_chunks_exact(DIM)+ .enumerate()+ .filter(|(i, _)| rows.item[*i] >= 0)+ .map(|(i, v)| (i, dot(v, q)))+ .collect();+ // best row per item+ let mut best: HashMap<i64, (usize, f32)> = HashMap::new();+ for (i, s) in scored {+ let e = best.entry(rows.item[i]).or_insert((i, f32::MIN));+ if s > e.1 {+ *e = (i, s);+ }+ }+ let mut top: Vec<(i64, usize, f32)> = best.into_iter().map(|(item, (i, s))| (item, i, s)).collect();+ top.sort_by(|a, b| b.2.total_cmp(&a.2));+ top.truncate(k);+ let mut q = store.db.prepare_cached("SELECT kind, name, locator FROM items WHERE id = ?1")?;+ let mut hits = Vec::with_capacity(top.len());+ for (item, i, score) in top {+ let (kind, name, locator): (String, String, String) = q.query_row([item], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;+ hits.push(Hit { item, score, t: rows.t[i], kind, name, locator, thumb: store.thumb(item).to_string_lossy().into_owned() });+ }+ Ok(hits)+}diff --git a/systems/index/src/store.rs b/systems/index/src/store.rsnew file mode 100644index 00000000..baf14635--- /dev/null+++ b/systems/index/src/store.rs@@ -0,0 +1,153 @@+//! Where the fast pass keeps what it found (docs/index.feature IX1): a SQLite list of sources and items, and one file+//! of f16 rows per model, appended as batches finish, so search reads the first pictures while the rest are going.+//! An item is keyed by where it lives (its source and locator: a path, a Photos asset, a Drive file id), never by a+//! hash of a whole original. A row's number is its place in the model's file; a removed item's rows stay in the file+//! and are left out of search (compacted later).++use anyhow::{Context, Result};+use rusqlite::{Connection, OptionalExtension, params};+use std::fs::OpenOptions;+use std::io::Write;+use std::path::{Path, PathBuf};++/// The fast pass's model, and the name of its rows' file+pub const MODEL: &str = "siglip2-b16-256@768";+pub const DIM: usize = 768;++const SCHEMA: &str = "+CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, kind TEXT NOT NULL, root TEXT NOT NULL, label TEXT NOT NULL, created INTEGER NOT NULL);+CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, source TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE, locator TEXT NOT NULL,+ kind TEXT NOT NULL, name TEXT NOT NULL, size INTEGER NOT NULL, mtime INTEGER NOT NULL, taken INTEGER, w INTEGER, h INTEGER, dur REAL,+ sha256 TEXT, state INTEGER NOT NULL DEFAULT 0, err TEXT, UNIQUE (source, locator));+CREATE INDEX IF NOT EXISTS items_state ON items (source, state);+CREATE TABLE IF NOT EXISTS rows (model TEXT NOT NULL, row INTEGER NOT NULL, item INTEGER NOT NULL, t REAL NOT NULL DEFAULT 0, PRIMARY KEY (model, row));+CREATE INDEX IF NOT EXISTS rows_item ON rows (item);";++/// An item's state: listed, embedded (searchable), or failed with its reason+pub const LISTED: i64 = 0;+pub const DONE: i64 = 1;+pub const FAILED: i64 = 2;++pub struct Store {+ pub dir: PathBuf,+ pub db: Connection,+}++/// What a source holds, by state+#[derive(Debug, Default, Clone, serde::Serialize)]+pub struct Counts {+ pub found: u64,+ pub done: u64,+ pub failed: u64,+ pub rows: u64,+}++/// An item waiting for the fast pass+#[derive(Debug, Clone)]+pub struct Pending {+ pub id: i64,+ pub locator: String,+ pub kind: String,+}++impl Store {+ /// The index in `dir` ($RAEA_INDEX_HOME, else ~/.raea/library/fast), made if it isn't there+ pub fn open(dir: &Path) -> Result<Store> {+ std::fs::create_dir_all(dir.join("thumbs")).with_context(|| format!("making {}", dir.display()))?;+ let db = Connection::open(dir.join("index.db"))?;+ db.execute_batch("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?;+ db.execute_batch(SCHEMA)?;+ Ok(Store { dir: dir.to_path_buf(), db })+ }++ pub fn default_dir() -> PathBuf {+ std::env::var_os("RAEA_INDEX_HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".raea/library/fast"))+ }++ pub fn vectors(&self, model: &str) -> PathBuf {+ self.dir.join(format!("{}.f16", model.replace('@', "-")))+ }++ pub fn thumb(&self, item: i64) -> PathBuf {+ self.dir.join("thumbs").join(format!("{}/{item}.jpg", item % 256))+ }++ /// A source by its kind and root; the same root again is the same source+ pub fn source(&self, kind: &str, root: &str, label: &str) -> Result<String> {+ if let Some(id) = self.db.query_row("SELECT id FROM sources WHERE kind = ?1 AND root = ?2", params![kind, root], |r| r.get(0)).optional()? {+ return Ok(id);+ }+ let n: i64 = self.db.query_row("SELECT COUNT(*) FROM sources", [], |r| r.get(0))?;+ let id = format!("ix{}-{n}", kind.chars().next().unwrap_or('s'));+ self.db.execute("INSERT INTO sources (id, kind, root, label, created) VALUES (?1, ?2, ?3, ?4, strftime('%s','now'))", params![id, kind, root, label])?;+ Ok(id)+ }++ /// Lists items in one transaction: new ones as LISTED, a changed one (size or mtime) back to LISTED; the rest kept+ pub fn list(&mut self, source: &str, items: &[crate::Found]) -> Result<usize> {+ let tx = self.db.transaction()?;+ let mut added = 0;+ {+ let mut up = tx.prepare_cached(+ "INSERT INTO items (source, locator, kind, name, size, mtime, taken, w, h, dur) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)+ ON CONFLICT (source, locator) DO UPDATE SET size = excluded.size, mtime = excluded.mtime, state = 0, err = NULL+ WHERE items.size != excluded.size OR items.mtime != excluded.mtime",+ )?;+ for f in items {+ added += up.execute(params![source, f.locator, f.kind, f.name, f.size as i64, f.mtime, f.taken, f.w, f.h, f.dur])?;+ }+ }+ tx.commit()?;+ Ok(added)+ }++ pub fn pending(&self, source: &str, limit: usize) -> Result<Vec<Pending>> {+ let mut q = self.db.prepare_cached("SELECT id, locator, kind FROM items WHERE source = ?1 AND state = 0 ORDER BY taken DESC, id LIMIT ?2")?;+ let rows = q.query_map(params![source, limit as i64], |r| Ok(Pending { id: r.get(0)?, locator: r.get(1)?, kind: r.get(2)? }))?;+ Ok(rows.collect::<rusqlite::Result<_>>()?)+ }++ /// One batch's vectors: appended to the model's file, each row tied to its item and moment, the items marked done+ pub fn append(&mut self, model: &str, batch: &[(i64, f64, Vec<f32>)], dims: &[(i64, u32, u32)]) -> Result<()> {+ let file = self.vectors(model);+ let mut f = OpenOptions::new().create(true).append(true).open(&file)?;+ let start = f.metadata()?.len() / (DIM as u64 * 2);+ let mut bytes = Vec::with_capacity(batch.len() * DIM * 2);+ for (_, _, v) in batch {+ for x in v {+ bytes.extend_from_slice(&half::f16::from_f32(*x).to_le_bytes());+ }+ }+ f.write_all(&bytes)?;+ f.sync_data()?;+ let tx = self.db.transaction()?;+ {+ let mut row = tx.prepare_cached("INSERT OR REPLACE INTO rows (model, row, item, t) VALUES (?1, ?2, ?3, ?4)")?;+ for (i, (item, t, _)) in batch.iter().enumerate() {+ row.execute(params![model, start as i64 + i as i64, item, t])?;+ }+ let mut done = tx.prepare_cached("UPDATE items SET state = 1, w = COALESCE(w, ?2), h = COALESCE(h, ?3) WHERE id = ?1")?;+ for (item, w, h) in dims {+ done.execute(params![item, w, h])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ pub fn fail(&self, item: i64, why: &str) -> Result<()> {+ self.db.execute("UPDATE items SET state = 2, err = ?2 WHERE id = ?1", params![item, why])?;+ Ok(())+ }++ pub fn counts(&self, source: Option<&str>) -> Result<Counts> {+ let (w, p) = match source {+ Some(s) => ("WHERE source = ?1", vec![s.to_string()]),+ None => ("", vec![]),+ };+ let q = format!("SELECT COUNT(*), SUM(state = 1), SUM(state = 2) FROM items {w}");+ let (found, done, failed): (i64, Option<i64>, Option<i64>) = self.db.query_row(&q, rusqlite::params_from_iter(p.iter()), |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;+ let rows: i64 = self.db.query_row("SELECT COUNT(*) FROM rows", [], |r| r.get(0))?;+ Ok(Counts { found: found as u64, done: done.unwrap_or(0) as u64, failed: failed.unwrap_or(0) as u64, rows: rows as u64 })+ }+}diff --git a/systems/index/src/text.rs b/systems/index/src/text.rsnew file mode 100644index 00000000..9394d940--- /dev/null+++ b/systems/index/src/text.rs@@ -0,0 +1,36 @@+//! SigLIP 2 B/16-256's text tower (docs/index.feature IX3): a query's words into the fast pass's space, on ONNX+//! Runtime's CPU kernels. Lower case, padded to 64 tokens, as SigLIP 2 was trained.++use anyhow::{Context, Result, anyhow};+use ort::session::Session;+use ort::value::Tensor;+use std::path::Path;++const LEN: usize = 64;++pub struct Text {+ s: Session,+ tok: tokenizers::Tokenizer,+ pad: i64,+}++impl Text {+ pub fn load(model: &Path, tokenizer: &Path) -> Result<Text> {+ let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("SigLIP 2's tokenizer: {e}"))?;+ let pad = tok.token_to_id("<pad>").unwrap_or(0) as i64;+ Ok(Text { s: raea_sys_ml::session(model).context("SigLIP 2's text tower")?, tok, pad })+ }++ /// The words' vector, L2-normalised+ pub fn embed(&mut self, words: &str) -> Result<Vec<f32>> {+ let e = self.tok.encode(words.to_lowercase(), true).map_err(|e| anyhow!("tokenizing {words:?}: {e}"))?;+ let mut ids: Vec<i64> = e.get_ids().iter().map(|&i| i as i64).take(LEN).collect();+ ids.resize(LEN, self.pad);+ let input = Tensor::from_array((vec![1i64, LEN as i64], ids))?;+ let out = self.s.run(ort::inputs!["input_ids" => input])?;+ let (_, d) = out.get("pooler_output").ok_or_else(|| anyhow!("no pooler_output"))?.try_extract_tensor::<f32>()?;+ let mut v = d.to_vec();+ crate::normalise(&mut v);+ Ok(v)+ }+}diff --git a/systems/index/src/walk.rs b/systems/index/src/walk.rsnew file mode 100644index 00000000..877f7e50--- /dev/null+++ b/systems/index/src/walk.rs@@ -0,0 +1,79 @@+//! Listing a folder or a drive (docs/index.feature IX5): every picture and video under it, with its size and dates,+//! fast, without opening a file. Packages (a Photos library, an app, a Final Cut library), hidden folders, caches and+//! raea's own working folders are skipped: Photos has its own source, and the rest isn't anyone's media.++use crate::Found;+use std::path::Path;+use std::time::UNIX_EPOCH;++pub const PICTURES: &[&str] = &["jpg", "jpeg", "heic", "heif", "png", "webp", "gif", "tif", "tiff", "bmp", "avif", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2"];+pub const VIDEOS: &[&str] = &["mp4", "mov", "m4v", "avi", "mkv", "webm", "mts", "m2ts", "3gp"];++/// What a file is by its extension: "picture", "video", or nothing+pub fn kind_of(p: &Path) -> Option<&'static str> {+ let ext = p.extension()?.to_str()?.to_ascii_lowercase();+ if PICTURES.contains(&ext.as_str()) {+ Some("picture")+ } else if VIDEOS.contains(&ext.as_str()) {+ Some("video")+ } else {+ None+ }+}++const PACKAGES: &[&str] = &["photoslibrary", "app", "fcpbundle", "imovielibrary", "photolibrary", "aplibrary", "bundle", "framework", "xcassets", "mlpackage", "mlmodelc"];+const SKIP: &[&str] = &["node_modules", "target", "Caches", "Library", ".Trash", "proxies", "scene-frames"];++fn skipped(name: &str, depth: usize) -> bool {+ if name.starts_with('.') {+ return true;+ }+ if let Some(ext) = Path::new(name).extension().and_then(|e| e.to_str()) {+ if PACKAGES.contains(&ext.to_ascii_lowercase().as_str()) {+ return true;+ }+ }+ // a home folder's own Library is skipped; one deeper (a project called Library) is kept+ SKIP.contains(&name) && (name != "Library" || depth <= 1)+}++/// Every picture and video under `root`, `on` called with each batch of `every` as they're found+pub fn walk(root: &Path, every: usize, on: &mut dyn FnMut(Vec<Found>)) -> u64 {+ let mut batch = Vec::with_capacity(every);+ let mut n = 0u64;+ let it = walkdir::WalkDir::new(root).follow_links(false).into_iter().filter_entry(|e| e.depth() == 0 || !skipped(&e.file_name().to_string_lossy(), e.depth()));+ for e in it.flatten() {+ // a link to a file counts as the file (a link to a folder isn't followed: no loops)+ let link = e.path_is_symlink();+ if !e.file_type().is_file() && !link {+ continue;+ }+ let Some(kind) = kind_of(e.path()) else { continue };+ let Ok(m) = (if link { std::fs::metadata(e.path()) } else { e.metadata().map_err(std::io::Error::other) }) else { continue };+ if !m.is_file() {+ continue;+ }+ if m.len() < 1024 {+ continue;+ }+ let secs = |t: std::io::Result<std::time::SystemTime>| t.ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64);+ let mtime = secs(m.modified()).unwrap_or(0);+ batch.push(Found {+ locator: e.path().to_string_lossy().into_owned(),+ kind: kind.into(),+ name: e.file_name().to_string_lossy().into_owned(),+ size: m.len(),+ mtime,+ taken: secs(m.created()).or(Some(mtime)),+ ..Found::default()+ });+ n += 1;+ if batch.len() >= every {+ on(std::mem::replace(&mut batch, Vec::with_capacity(every)));+ }+ }+ if !batch.is_empty() {+ on(batch);+ }+ n+}