Cotton code
320 lines · 13.6 KB · RustRaw
//! The core's Set, Pick and Tidy rules over a REAL library, on the Mac that holds it: the feed comes from//! the albums-photos-mac feed (the phone's analysis layer over this Mac's Photos, through PhotoKit), through a pipe,//! in the shapes the phone hands `albums.library.take` and `albums.look.take`, and each face vector with its photo's//! made-up id for the face grouping. Nothing of the library is kept: the index lives in a temporary folder deleted at//! the end, vectors only in memory, and only counts and timings are written.//!//! Face grouping is measured without labels: groups by size, and cannot-link violations (two faces from one photo in//! one group, which must be 0). Groupings are pluggable (`Grouping`): two stand-ins, and the core's own (GROUPING 1,//! `core_grouping`); `ALBUMS_GROUPING=core` runs only it.//!//!     mkfifo feed; albums-photos-mac 3000 swift.json > feed &//!     ALBUMS_REAL_FEED=feed ALBUMS_REAL_OUT=core.json cargo test -p cotton-ffi --lib -- --ignored albums_on_a_real_libraryuse super::*;use std::collections::BTreeMap;use std::io::BufRead;use std::time::Instant;fn timed(ix: &mut Index, spent: &mut BTreeMap<&'static str, (u32, f64)>, method: &'static str, body: &Value) -> Value {    let t = Instant::now();    let out = answer(ix, method, body, now_ms()).unwrap_or_else(|e| panic!("{method}: {e:?}"));    let e = spent.entry(method).or_default();    e.0 += 1;    e.1 += t.elapsed().as_secs_f64() * 1000.0;    out}fn now_ms() -> i64 {    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64}/// One face from the pipe: the photo it is in (a made-up id) and its unit vector.struct Face {    photo: String,    vector: Vec<f32>,}/// A face grouping: one group label per face, in the faces' order.trait Grouping {    fn name(&self) -> String;    fn group(&self, faces: &[Face]) -> Vec<usize>;}fn cosine(a: &[f32], b: &[f32]) -> f32 {    a.iter().zip(b).map(|(x, y)| x * y).sum()}/// Stand-in: single linkage at a cosine cut (any one pair above the cut joins two groups; chains across people).struct SingleLinkage(f32);impl Grouping for SingleLinkage {    fn name(&self) -> String {        format!("single_linkage_{:.2}", self.0)    }    fn group(&self, faces: &[Face]) -> Vec<usize> {        let mut parent: Vec<usize> = (0..faces.len()).collect();        fn find(p: &mut [usize], mut x: usize) -> usize {            while p[x] != x {                p[x] = p[p[x]];                x = p[x];            }            x        }        for i in 0..faces.len() {            for j in i + 1..faces.len() {                if cosine(&faces[i].vector, &faces[j].vector) >= self.0 {                    let (a, b) = (find(&mut parent, i), find(&mut parent, j));                    if a != b {                        parent[a] = b;                    }                }            }        }        (0..faces.len()).map(|i| find(&mut parent, i)).collect()    }}/// Stand-in: each face, in order, joins the group whose mean it is nearest, when within the cut; else starts one.struct NearestMean(f32);impl Grouping for NearestMean {    fn name(&self) -> String {        format!("nearest_mean_{:.2}", self.0)    }    fn group(&self, faces: &[Face]) -> Vec<usize> {        let mut sums: Vec<Vec<f32>> = Vec::new();        let mut out = Vec::with_capacity(faces.len());        for f in faces {            let best = sums                .iter()                .enumerate()                .map(|(g, s)| {                    let norm = s.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);                    (g, cosine(&f.vector, s) / norm)                })                .max_by(|a, b| a.1.total_cmp(&b.1));            match best {                Some((g, sim)) if sim >= self.0 => {                    sums[g].iter_mut().zip(&f.vector).for_each(|(s, v)| *s += v);                    out.push(g);                }                _ => {                    sums.push(f.vector.clone());                    out.push(sums.len() - 1);                }            }        }        out    }}/// The core's own grouping (GROUPING 1, `cotton_core::albums::grouping`): two stages under the cannot-link.struct CoreGrouping;impl Grouping for CoreGrouping {    fn name(&self) -> String {        "core".into()    }    fn group(&self, faces: &[Face]) -> Vec<usize> {        use cotton_core::albums::grouping;        let input = faces            .iter()            .enumerate()            .map(|(i, f)| grouping::Face { key: i.to_string(), photo: f.photo.clone(), vector: f.vector.clone(), ..Default::default() })            .collect();        grouping::group(input, &grouping::Choices::default()).labels    }}fn core_grouping() -> Option<Box<dyn Grouping>> {    Some(Box::new(CoreGrouping))}fn groupings() -> Vec<Box<dyn Grouping>> {    if std::env::var("ALBUMS_GROUPING").as_deref() == Ok("core") {        return core_grouping().into_iter().collect();    }    let mut all: Vec<Box<dyn Grouping>> = vec![Box::new(SingleLinkage(0.4)), Box::new(SingleLinkage(0.5)), Box::new(NearestMean(0.4)), Box::new(NearestMean(0.5))];    all.extend(core_grouping());    all}/// Groups by size, and cannot-link violations: two faces of one photo in one group.fn measure(faces: &[Face], labels: &[usize]) -> Value {    let mut groups: BTreeMap<usize, Vec<usize>> = BTreeMap::new();    for (i, &g) in labels.iter().enumerate() {        groups.entry(g).or_default().push(i);    }    let mut by_size: BTreeMap<&str, i64> = BTreeMap::new();    let (mut bad_groups, mut bad_pairs, mut bad_in_shown) = (0i64, 0i64, 0i64);    for members in groups.values() {        let n = members.len();        *by_size.entry(match n { 1 => "1", 2..=4 => "2-4", 5..=9 => "5-9", 10..=49 => "10-49", _ => "50+" }).or_default() += 1;        let mut per_photo: BTreeMap<&str, i64> = BTreeMap::new();        for &i in members {            *per_photo.entry(faces[i].photo.as_str()).or_default() += 1;        }        let pairs: i64 = per_photo.values().map(|k| k * (k - 1) / 2).sum();        if pairs > 0 {            bad_groups += 1;            bad_pairs += pairs;            if n >= 5 {                bad_in_shown += 1;            }        }    }    json!({        "groups": groups.len(),        "by_size": by_size,        "largest": groups.values().map(Vec::len).max().unwrap_or(0),        "shown_5_or_more": groups.values().filter(|m| m.len() >= 5).count(),        "cannot_link": { "violating_groups": bad_groups, "violating_pairs": bad_pairs, "violating_shown_groups": bad_in_shown },    })}fn bucket(n: i64) -> &'static str {    match n {        ..=1 => "1",        2 => "2",        3 => "3",        4 => "4",        5..=9 => "5-9",        10..=24 => "10-24",        _ => "25+",    }}#[test]#[ignore = "runs only on a Mac with its Photos library, fed by the Mac's Photos exporter"]fn albums_on_a_real_library() {    let feed = std::env::var("ALBUMS_REAL_FEED").expect("ALBUMS_REAL_FEED: the pipe from albums-photos-mac");    let out = std::env::var("ALBUMS_REAL_OUT").expect("ALBUMS_REAL_OUT: where the numbers go");    let dir = tempfile::tempdir().unwrap();    let mut ix = Index::open(&Index::path_in(dir.path())).unwrap();    let mut spent = BTreeMap::new();    timed(&mut ix, &mut spent, "albums.start", &json!({ "platform": "ios", "permission": "full" }));    let mut items: Vec<Value> = Vec::new();    let mut looks_sent = 0usize;    let mut faces: Vec<Face> = Vec::new();    let reader = std::io::BufReader::new(std::fs::File::open(&feed).unwrap());    let flush = |ix: &mut Index, spent: &mut BTreeMap<&'static str, (u32, f64)>, items: &mut Vec<Value>| {        for chunk in items.chunks(500) {            timed(ix, spent, "albums.library.take", &json!({ "items": chunk }));        }        items.clear();    };    for line in reader.lines() {        let line = line.unwrap();        let v: Value = serde_json::from_str(&line).unwrap();        if let Some(item) = v.get("item") {            items.push(item.clone());        } else if let Some(looks) = v.get("looks") {            flush(&mut ix, &mut spent, &mut items);            looks_sent += looks.as_array().map_or(0, Vec::len);            timed(&mut ix, &mut spent, "albums.look.take", &json!({ "looks": looks }));        } else if let Some(fs) = v.get("faces").and_then(Value::as_array) {            for f in fs {                let vector: Vec<f32> = f["vector"].as_array().map(|a| a.iter().filter_map(Value::as_f64).map(|x| x as f32).collect()).unwrap_or_default();                if !vector.is_empty() {                    faces.push(Face { photo: f["photo"].as_str().unwrap_or("").to_string(), vector });                }            }        }    }    flush(&mut ix, &mut spent, &mut items);    for m in ["albums.home", "albums.tidy", "albums.sets", "albums.you"] {        timed(&mut ix, &mut spent, m, &json!({}));    }    // face groups, each grouping measured the same way    let mut grouped = serde_json::Map::new();    let same_photo_pairs: i64 = {        let mut per: BTreeMap<&str, i64> = BTreeMap::new();        for f in &faces {            *per.entry(f.photo.as_str()).or_default() += 1;        }        per.values().map(|k| k * (k - 1) / 2).sum()    };    for g in groupings() {        let t = Instant::now();        let labels = g.group(&faces);        let mut m = measure(&faces, &labels);        m["ms"] = json!(t.elapsed().as_millis());        grouped.insert(g.name(), m);    }    let c = &ix.conn;    // a count the index's schema no longer answers is -1, never a lost run    let one = |sql: &str| -> i64 { c.query_row(sql, [], |r| r.get(0)).unwrap_or(-1) };    // Sets by size, picks per set, what the non-picks weigh    let mut by_size: BTreeMap<&str, i64> = BTreeMap::new();    let mut picks: BTreeMap<String, i64> = BTreeMap::new();    let mut picks_big = (0i64, 0i64);    let mut stmt = c.prepare("SELECT count, picks, sure FROM shot_set").unwrap();    let rows: Vec<(i64, i64, bool)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).unwrap().map(Result::unwrap).collect();    for &(n, p, _) in &rows {        *by_size.entry(bucket(n)).or_default() += 1;        *picks.entry(p.to_string()).or_default() += 1;        if n >= 10 {            picks_big.0 += 1;            picks_big.1 += p;        }    }    let sure = rows.iter().filter(|r| r.2).count();    // what each tidy list catches    let mut lists = serde_json::Map::new();    let mut stmt = c.prepare("SELECT list, count(*), coalesce(sum(bytes), 0), sum(exact) FROM offer GROUP BY list ORDER BY list").unwrap();    for (list, n, bytes, exact) in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, i64>(2)?, r.get::<_, i64>(3)?))).unwrap().map(Result::unwrap) {        lists.insert(list, json!({ "items": n, "bytes": bytes, "bytes_exact_items": exact }));    }    let mut levels = serde_json::Map::new();    let mut stmt = c.prepare("SELECT level, count(*) FROM look GROUP BY level").unwrap();    for (l, n) in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?))).unwrap().map(Result::unwrap) {        levels.insert(["none", "small", "full"].get(l as usize).copied().unwrap_or("other").to_string(), json!(n));    }    let spent: serde_json::Map<String, Value> = spent        .into_iter()        .map(|(m, (calls, ms))| (m.to_string(), json!({ "calls": calls, "ms": ms.round(), "ms_a_call": (ms / calls.max(1) as f64 * 10.0).round() / 10.0 })))        .collect();    let numbers = json!({        "build": if cfg!(debug_assertions) { "debug (core timings are slower than a release build)" } else { "release" },        "items": one("SELECT count(*) FROM item WHERE state = 'present'"),        "parts": one("SELECT count(*) FROM item WHERE part_of IS NOT NULL"),        "looks_sent": looks_sent,        "look_levels": levels,        "sets": {            "count": rows.len(),            "photos_in_sets": one("SELECT count(*) FROM member"),            "by_size": by_size,            "picks_per_set": picks,            "mean_picks_sets_of_10_or_more": if picks_big.0 > 0 { (picks_big.1 as f64 / picks_big.0 as f64 * 100.0).round() / 100.0 } else { 0.0 },            "sure": sure,            "non_pick_bytes": one("SELECT coalesce(sum(bytes), 0) FROM shot_set"),        },        "tidy_lists": lists,        "faces": { "with_vector": faces.len(), "same_photo_pairs": same_photo_pairs, "core_grouping": core_grouping().is_some(), "groupings": grouped },        "core_ms": spent,    });    // not a copy: the harness's own numbers file, outside the repo.    std::fs::write(&out, serde_json::to_string_pretty(&numbers).unwrap()).unwrap();    // the index goes with `dir` (dropped after `ix`, which was declared after it)}#[test]fn a_grouping_that_puts_two_faces_of_one_photo_together_is_a_cannot_link_violation() {    let face = |photo: &str, v: [f32; 2]| Face { photo: photo.into(), vector: v.to_vec() };    // two people, A along x and B along y; photo p1 holds both, p2 and p3 one each    let faces = vec![face("p1", [1.0, 0.0]), face("p1", [0.0, 1.0]), face("p2", [1.0, 0.0]), face("p3", [0.0, 1.0])];    for g in [Box::new(SingleLinkage(0.5)) as Box<dyn Grouping>, Box::new(NearestMean(0.5)), Box::new(CoreGrouping)] {        let m = measure(&faces, &g.group(&faces));        assert_eq!(m["groups"], 2, "{}", g.name());        assert_eq!(m["cannot_link"]["violating_pairs"], 0, "{}", g.name());    }    // a cut so loose everything joins: p1's two faces share a group    let m = measure(&faces, &SingleLinkage(-1.0).group(&faces));    assert_eq!(m["groups"], 1);    assert_eq!(m["cannot_link"]["violating_groups"], 1);    assert_eq!(m["cannot_link"]["violating_pairs"], 1);}