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
IX6: Apple Photos as an index source (raea index add photos:): PhotoKit lists every photo and video, keyed by the asset's local identifier with Photos' original filename, its dates, size and length; the fast pass reads the small copy Photos keeps on this Mac (PHImageManager at 256 px, synchronous, never the network), so an iCloud library goes in without downloading originals, a video by its poster. macOS asks the person once (access(): read-write is the only reading level). Folders and Photos list through one list_source; root_of and list_root are what an add names, for the CLI and serve alike, and serve lists Photos again at start like a folder. The app's Info.plist has NSPhotoLibraryUsageDescription and its entitlements the Photos library (private tools/raea-app). Not yet run against a real library
shinyobjectz8caedfbaa1f7
diff --git a/Cargo.lock b/Cargo.lockindex 5e619cf8..cb1a8901 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11551,6 +11551,20 @@ dependencies = ["objc2-metal 0.3.2",]+[[package]]+name = "objc2-photos"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6ea9a706f18e32cf8a0723e99855af4f135282891e07259301bae9135ae3872"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.6.2",+ "objc2 0.6.5",+ "objc2-app-kit 0.3.2",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+]+[[package]]name = "objc2-quartz-core"version = "0.2.2"@@ -15799,8 +15813,10 @@ name = "raea-sys-index"version = "0.1.0"dependencies = ["anyhow",+ "block2 0.6.2","half","objc2 0.6.5",+ "objc2-app-kit 0.3.2","objc2-av-foundation","objc2-core-foundation","objc2-core-graphics",@@ -15809,6 +15825,7 @@ dependencies = ["objc2-core-video","objc2-foundation 0.3.2","objc2-image-io",+ "objc2-photos","ort","raea-io-home","raea-sys-ml",diff --git a/systems/index/Cargo.toml b/systems/index/Cargo.tomlindex 19876891..a0d6df79 100644--- a/systems/index/Cargo.toml+++ b/systems/index/Cargo.toml@@ -23,7 +23,7 @@ walkdir = "2"[target.'cfg(target_vendor = "apple")'.dependencies]objc2 = "0.6"-objc2-foundation = { version = "0.3", features = ["NSString", "NSURL", "NSError", "NSDictionary", "NSArray", "NSValue"] }+objc2-foundation = { version = "0.3", features = ["NSString", "NSURL", "NSError", "NSDictionary", "NSArray", "NSValue", "NSDate"] }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"] }@@ -32,3 +32,7 @@ objc2-image-io = { version = "0.3", features = ["CGImageSource", "CGImageDestina# a video's keyframes (frames.rs)objc2-av-foundation = { version = "0.3", features = ["objc2-core-media", "objc2-core-graphics"] }objc2-core-media = "0.3"+# Apple Photos (photos.rs): its assets and the small copies it keeps of each, so iCloud Photos indexes from this Mac+objc2-photos = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-app-kit", "PHAsset", "PHFetchResult", "PHFetchOptions", "PHImageManager", "PHPhotoLibrary", "PHAssetResource", "PhotosTypes", "PHObject"] }+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSImage", "NSImageRep", "NSGraphicsContext", "objc2-core-graphics"] }+block2 = "0.6"diff --git a/systems/index/src/cli.rs b/systems/index/src/cli.rsindex 59ef7c8b..e3240a14 100644--- a/systems/index/src/cli.rs+++ b/systems/index/src/cli.rs@@ -9,7 +9,7 @@ use std::path::PathBuf;use std::sync::Arc;use std::sync::atomic::AtomicBool;-pub const USAGE: &str = "raea index add FOLDER... [--json] | raea index search WORDS... [--k N] [--source ID|FOLDER] [--json] | raea index status [--json] | raea index remove ID|FOLDER | raea index serve [--home DIR] (every picture on a folder or a drive made searchable by words on this Mac, fast: add lists it and embeds each picture's small copy with SigLIP 2 on the Neural Engine, a counter as it goes, JSON lines with --json; search gives the best for the words; status lists the sources and what each holds; remove takes one out; serve keeps the index open for the raea app, one JSON ask a line on stdin; the index lives in ~/.raea/library/fast, or --home / RAEA_INDEX_HOME)";+pub const USAGE: &str = "raea index add FOLDER|photos:... [--json] | raea index search WORDS... [--k N] [--source ID|FOLDER] [--json] | raea index status [--json] | raea index remove ID|FOLDER | raea index serve [--home DIR] (every picture and video on a folder, a drive or Apple Photos (photos:) made searchable by words on this Mac, fast: add lists it and embeds each picture's small copy with SigLIP 2 on the Neural Engine, a counter as it goes, JSON lines with --json; search gives the best for the words; status lists the sources and what each holds; remove takes one out; serve keeps the index open for the raea app, one JSON ask a line on stdin; the index lives in ~/.raea/library/fast, or --home / RAEA_INDEX_HOME)";/// The exit code: 0, or 1 with the reason saidpub fn cli(args: &[String]) -> i32 {@@ -82,11 +82,8 @@ fn add(f: &Flags, home: &std::path::Path) -> Result<()> {#[cfg(target_vendor = "apple")]let mut model: Option<crate::apple::Model> = None;for path in &f.rest {- let root = std::fs::canonicalize(path).map_err(|e| anyhow!("{path}: {e}"))?;- if !root.is_dir() {- anyhow::bail!("{path} isn't a folder");- }- let l = crate::list_folder(&mut store, &root, &mut |p| say(p))?;+ let root = crate::root_of(path)?;+ let l = crate::list_root(&mut store, &root, &mut |p| say(p))?;#[cfg(target_vendor = "apple")]{if model.is_none() {diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rsindex 4961b2ff..3ab0bff7 100644--- a/systems/index/src/lib.rs+++ b/systems/index/src/lib.rs@@ -9,6 +9,8 @@ pub mod apple;pub mod cli;#[cfg(target_vendor = "apple")]pub mod frames;+#[cfg(target_vendor = "apple")]+pub mod photos;pub mod search;pub mod serve;pub mod store;@@ -52,6 +54,28 @@ pub struct Progress {pub stage: &'static str,}+/// What an add names for Apple Photos (photos.rs), and the root its source keeps+pub const PHOTOS: &str = "photos:";++/// What an add names: Apple Photos (`photos:`), or a folder or a drive, made absolute+pub fn root_of(path: &str) -> Result<PathBuf> {+ if path == PHOTOS {+ return Ok(PathBuf::from(PHOTOS));+ }+ let root = std::fs::canonicalize(path).map_err(|e| anyhow::anyhow!("{path}: {e}"))?;+ anyhow::ensure!(root.is_dir(), "{path} isn't a folder");+ Ok(root)+}++/// Lists the source an add named (root_of)+pub fn list_root(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {+ #[cfg(target_vendor = "apple")]+ if root == Path::new(PHOTOS) {+ return list_photos(store, on);+ }+ list_folder(store, root, on)+}+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);@@ -80,11 +104,26 @@ pub struct Listed {/// Lists a folder or a drive into the index: new files added, changed ones put back in linepub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {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 each = |f: &mut dyn FnMut(Vec<Found>)| {+ walk::walk(root, 2000, f);+ Ok(())+ };+ list_source(store, ("folder", &root.to_string_lossy(), &label), each, on)+}++/// Lists Apple Photos into the index (photos.rs): its root is `photos:`, each item an asset+#[cfg(target_vendor = "apple")]+pub fn list_photos(store: &mut Store, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {+ list_source(store, ("photos", PHOTOS, "Apple Photos"), |f| photos::list(2000, f).map_err(anyhow::Error::msg), on)+}++/// Lists a source (its kind, root and label) as `each` hands its items over a batch at a time+fn list_source(store: &mut Store, (kind, root, label): (&str, &str, &str), each: impl FnOnce(&mut dyn FnMut(Vec<Found>)) -> Result<()>, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {+ let source = store.source(kind, root, label)?;let started = Instant::now();let mut l = Listed { source: source.clone(), ..Listed::default() };let mut err = None;- walk::walk(root, 2000, &mut |batch| {+ each(&mut |batch| {l.found += batch.len() as u64;match store.list(&source, &batch) {Ok((a, c)) => {@@ -96,7 +135,7 @@ pub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)}}on(&Progress { source: source.clone(), found: l.found, stage: "listing", seconds: started.elapsed().as_secs_f64(), ..Progress::default() });- });+ })?;if let Some(e) = err {return Err(e);}@@ -125,10 +164,15 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, storeturn;}let file = Path::new(&p.locator);- let r = if p.kind == "video" {- frames::video(file, Some(thumb)).map(|f| f.px.into_iter().map(|(px, t)| apple::Ready { item: p.id, t, px, w: f.w, h: f.h }).collect())- } else {- apple::picture(file, Some(thumb)).map(|(px, w, h)| vec![apple::Ready { item: p.id, t: 0.0, px, w, h }])+ // a Photos asset or a picture file gives one small copy; a video file its keyframes+ let one = match p.locator.strip_prefix(PHOTOS) {+ Some(id) => Some(photos::picture(id, Some(thumb))),+ None if p.kind == "video" => None,+ None => Some(apple::picture(file, Some(thumb))),+ };+ let r = match one {+ Some(r) => r.map(|(px, w, h)| vec![apple::Ready { item: p.id, t: 0.0, px, w, h }]),+ None => frames::video(file, Some(thumb)).map(|f| f.px.into_iter().map(|(px, t)| apple::Ready { item: p.id, t, px, w: f.w, h: f.h }).collect()),};let r = r.map_err(|e| (p.id, e));let _ = tx.send(r);diff --git a/systems/index/src/photos.rs b/systems/index/src/photos.rsnew file mode 100644index 00000000..ac42aeb9--- /dev/null+++ b/systems/index/src/photos.rs@@ -0,0 +1,115 @@+//! Apple Photos as a source (docs/index.feature IX6): every photo and video in the person's library, and so their+//! iCloud Photos and iPhone camera roll, listed through PhotoKit and keyed by the asset's local identifier. The fast+//! pass reads the small copy Photos keeps of each on this Mac (PHImageManager at 256 px, never over the network), so a+//! library whose originals stay in iCloud goes in without downloading them. A video gives its poster. macOS asks the+//! person once; the app's Info.plist says why (NSPhotoLibraryUsageDescription).++use crate::Found;+use crate::apple::{SIDE, squash, write_jpeg};+use block2::RcBlock;+use objc2::rc::Retained;+use objc2_app_kit::NSImage;+use objc2_core_foundation::{CFRetained, CGSize};+use objc2_core_graphics::CGImage;+use objc2_core_video::CVPixelBuffer;+use objc2_foundation::{NSArray, NSDate, NSDictionary, NSString};+use objc2_photos::{+ PHAccessLevel, PHAsset, PHAssetMediaType, PHAssetResource, PHAuthorizationStatus, PHImageContentMode, PHImageManager, PHImageRequestOptions,+ PHImageRequestOptionsDeliveryMode, PHImageRequestOptionsResizeMode, PHPhotoLibrary,+};+use std::cell::RefCell;+use std::path::Path;+use std::rc::Rc;++// the source's root, and the start of each of its locators (then the asset's local identifier)+use crate::PHOTOS as ROOT;++/// Whether raea may read the library, asking the person the first time (macOS shows its prompt once)+pub fn access() -> Result<(), String> {+ let level = PHAccessLevel::ReadWrite;+ let mut status = unsafe { PHPhotoLibrary::authorizationStatusForAccessLevel(level) };+ if status == PHAuthorizationStatus::NotDetermined {+ let (tx, rx) = std::sync::mpsc::channel();+ let answer = RcBlock::new(move |s: PHAuthorizationStatus| {+ let _ = tx.send(s);+ });+ unsafe { PHPhotoLibrary::requestAuthorizationForAccessLevel_handler(level, &answer) };+ status = rx.recv().unwrap_or(PHAuthorizationStatus::Denied);+ }+ if status == PHAuthorizationStatus::Authorized || status == PHAuthorizationStatus::Limited {+ return Ok(());+ }+ Err("raea can't read Photos: turn it on in System Settings, Privacy & Security, Photos".into())+}++fn secs(d: Option<Retained<NSDate>>) -> Option<i64> {+ d.map(|d| d.timeIntervalSince1970() as i64)+}++/// One asset as the store lists it: its name is the original file's, as Photos shows it+fn found(a: &PHAsset) -> Option<Found> {+ let kind = match unsafe { a.mediaType() } {+ PHAssetMediaType::Image => "picture",+ PHAssetMediaType::Video => "video",+ _ => return None,+ };+ let taken = secs(unsafe { a.creationDate() });+ let resources = unsafe { PHAssetResource::assetResourcesForAsset(a) };+ let name = resources.firstObject().map(|r| unsafe { r.originalFilename() }.to_string()).unwrap_or_default();+ Some(Found {+ locator: format!("{ROOT}{}", unsafe { a.localIdentifier() }),+ kind: kind.into(),+ name,+ size: 0,+ mtime: secs(unsafe { a.modificationDate() }).or(taken).unwrap_or(0),+ taken,+ w: Some(unsafe { a.pixelWidth() } as u32),+ h: Some(unsafe { a.pixelHeight() } as u32),+ dur: (kind == "video").then(|| unsafe { a.duration() }),+ })+}++/// Every photo and video in the library, `on` called with each `every` as they're read+pub fn list(every: usize, on: &mut dyn FnMut(Vec<Found>)) -> Result<(), String> {+ access()?;+ let all = unsafe { PHAsset::fetchAssetsWithOptions(None) };+ let n = unsafe { all.count() };+ let mut at = 0;+ while at < n {+ let end = (at + every).min(n);+ let batch = objc2::rc::autoreleasepool(|_| (at..end).filter_map(|i| found(&*unsafe { all.objectAtIndex(i) })).collect::<Vec<_>>());+ on(batch);+ at = end;+ }+ Ok(())+}++/// An asset's small copy at `SIDE` from the copies Photos keeps on this Mac, its thumbnail written to `thumb`+pub fn picture(id: &str, thumb: Option<&Path>) -> Result<(CFRetained<CVPixelBuffer>, u32, u32), String> {+ objc2::rc::autoreleasepool(|_| {+ let ids = NSArray::from_retained_slice(&[NSString::from_str(id)]);+ let asset = unsafe { PHAsset::fetchAssetsWithLocalIdentifiers_options(&ids, None).firstObject() }.ok_or("no longer in Photos")?;+ let o = unsafe { PHImageRequestOptions::new() };+ unsafe {+ // one answer, before the call returns; never the network+ o.setSynchronous(true);+ o.setNetworkAccessAllowed(false);+ o.setDeliveryMode(PHImageRequestOptionsDeliveryMode::HighQualityFormat);+ o.setResizeMode(PHImageRequestOptionsResizeMode::Fast);+ }+ let got: Rc<RefCell<Option<Retained<NSImage>>>> = Rc::default();+ let slot = got.clone();+ let take = RcBlock::new(move |img: *mut NSImage, _: *mut NSDictionary| {+ *slot.borrow_mut() = unsafe { Retained::retain(img) };+ });+ let side = CGSize::new(SIDE as f64, SIDE as f64);+ unsafe { PHImageManager::defaultManager().requestImageForAsset_targetSize_contentMode_options_resultHandler(&asset, side, PHImageContentMode::AspectFill, Some(&o), &take) };+ let img = got.borrow_mut().take().ok_or("Photos has no small copy of it on this Mac")?;+ let cg = unsafe { img.CGImageForProposedRect_context_hints(std::ptr::null_mut(), None, None) }.ok_or("no picture in Photos' copy")?;+ let (w, h) = (CGImage::width(Some(&cg)) as u32, CGImage::height(Some(&cg)) as u32);+ if let Some(t) = thumb {+ let _ = write_jpeg(&cg, t);+ }+ Ok((squash(&cg)?, w, h))+ })+}diff --git a/systems/index/src/serve.rs b/systems/index/src/serve.rsindex 6e3ed641..6b4fad85 100644--- a/systems/index/src/serve.rs+++ b/systems/index/src/serve.rs@@ -68,9 +68,10 @@ pub fn serve(dir: &Path) -> Result<()> {let (sh, dir) = (sh.clone(), dir.to_path_buf());std::thread::spawn(move || find(&sh, &dir, frx))};- // what was there before: each folder listed again (new files in, changed ones redone) and its waiting pictures embedded+ // what was there before: each folder (and Photos) listed again (new files in, changed ones redone) and its waiting+ // pictures embeddedfor s in store.sources()? {- if s.kind == "folder" && Path::new(&s.root).is_dir() {+ if (s.kind == "folder" && Path::new(&s.root).is_dir()) || s.kind == "photos" {sh.waiting.lock().unwrap().push(s.root.clone());let _ = jobs.send(PathBuf::from(&s.root));}@@ -114,10 +115,7 @@ fn answer(sh: &Shared, store: &mut Store, jobs: &mpsc::Sender<PathBuf>, finds: &match ask.get("op").and_then(Value::as_str).unwrap_or("") {"add" => {let path = s("path").ok_or_else(|| anyhow!("add needs a path"))?;- let root = std::fs::canonicalize(&path).map_err(|e| anyhow!("{path}: {e}"))?;- if !root.is_dir() {- anyhow::bail!("{path} isn't a folder");- }+ let root = crate::root_of(&path)?;let r = root.to_string_lossy().into_owned();let going = sh.running.lock().unwrap().as_ref().is_some_and(|(x, _)| *x == r);let mut w = sh.waiting.lock().unwrap();@@ -186,7 +184,7 @@ fn work(sh: &Shared, dir: &Path, jobs: mpsc::Receiver<PathBuf>) {sh.stop.store(false, Ordering::Relaxed);}let done = (|| -> Result<()> {- let l = crate::list_folder(&mut store, &root, &mut |p| sh.progress(p))?;+ let l = crate::list_root(&mut store, &root, &mut |p| sh.progress(p))?;if l.changed > 0 {sh.epoch.fetch_add(1, Ordering::Relaxed);}