135 lines · 6.0 KB · RustRaw
//! `albums.faces.group`: the phone's faces grouped by the core's GROUPING 1 (`cotton_core::albums::grouping`), so both//! phones group alike (coordinator, NEXT-GROUPING.md; LOOK-ONLY 27 Nov: "People from GROUPING 1 with cannot-link").//!//! Stateless: the phone keeps its faces and his names (face vectors never leave the phone that made them) and hands//! them in; groups come out. Nothing is stored or sent here.//!//! ```text//! request { faces: [{ key, photo, vector: base64 of little-endian f32 }],//! names?: { faceKey: name }, // his Name: those faces are that person (a must-link)//! not?: { faceKey: [name] }, // his "Not this person"//! same?: [[faceKey, faceKey]], // his Merge//! different?: [[faceKey, faceKey]] } // his No to "Same person?"//! answer { groups: [{ faces: [faceKey], photos, person?, shown }], // groups of 2 or more faces, biggest first//! loose: n, // faces in no group//! suggestions: [{ a, b, similarity }] } // indices into `groups`//! ```use base64::Engine;use cotton_core::albums::grouping::{self, Choices, Face};use serde_json::{json, Value};use crate::methods::MethodError;pub const METHODS: [&str; 1] = ["albums.faces.group"];pub fn call(method: &str, request: &Value) -> Result<Value, MethodError> { match method { "albums.faces.group" => group(request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not an albums.faces method"))), }}fn bad(why: impl Into<String>) -> MethodError { MethodError::new("bad_request", why.into())}fn pairs(request: &Value, key: &str) -> Vec<(String, String)> { request[key] .as_array() .map(|all| { all.iter() .filter_map(|p| Some((p.get(0)?.as_str()?.to_string(), p.get(1)?.as_str()?.to_string()))) .collect() }) .unwrap_or_default()}pub fn group(request: &Value) -> Result<Value, MethodError> { let b64 = base64::engine::general_purpose::STANDARD; let given = request["faces"].as_array().ok_or_else(|| bad("`faces` is a list"))?; let names = request["names"].as_object(); let nots = request["not"].as_object(); let mut faces = Vec::with_capacity(given.len()); for f in given { let key = f["key"].as_str().ok_or_else(|| bad("each face has a `key`"))?.to_string(); let photo = f["photo"].as_str().ok_or_else(|| bad("each face has a `photo`"))?.to_string(); let bytes = b64.decode(f["vector"].as_str().unwrap_or("")).map_err(|e| bad(format!("{key} vector: {e}")))?; if bytes.len() % 4 != 0 { return Err(bad(format!("{key} vector: not whole f32s"))); } let vector = bytes.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); let person = names.and_then(|n| n.get(&key)).and_then(Value::as_str).map(str::to_string); let not = nots .and_then(|n| n.get(&key)) .and_then(Value::as_array) .map(|all| all.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) .unwrap_or_default(); faces.push(Face { key, photo, vector, person, not }); } let keys: Vec<String> = faces.iter().map(|f| f.key.clone()).collect(); let choices = Choices { same: pairs(request, "same"), different: pairs(request, "different") }; let g = grouping::group(faces, &choices); // Groups of two or more, in the rule's order (biggest first); a loose face is only counted. let mut index = vec![usize::MAX; g.groups.len()]; let mut groups = vec![]; for (i, one) in g.groups.iter().enumerate() { if one.faces.len() < 2 && one.person.is_none() { continue; } index[i] = groups.len(); let mut out = json!({ "faces": one.faces.iter().map(|&f| keys[f].clone()).collect::<Vec<_>>(), "photos": one.photos, "shown": one.shown, }); if let Some(p) = &one.person { out["person"] = json!(p); } groups.push(out); } let loose = g.groups.iter().filter(|one| one.faces.len() < 2 && one.person.is_none()).count(); let suggestions: Vec<Value> = g .suggestions .iter() .filter(|s| index[s.a] != usize::MAX && index[s.b] != usize::MAX) .map(|s| json!({ "a": index[s.a], "b": index[s.b], "similarity": s.similarity })) .collect(); Ok(json!({ "groups": groups, "loose": loose, "suggestions": suggestions }))}#[cfg(test)]mod tests { use super::*; fn v(axis: usize, jitter: f32) -> String { let mut x = vec![0f32; 8]; x[axis] = 1.0; x[7 - axis] += jitter; base64::engine::general_purpose::STANDARD.encode(x.iter().flat_map(|f| f.to_le_bytes()).collect::<Vec<u8>>()) } #[test] fn faces_come_back_as_groups_and_two_faces_of_one_photo_never_share_one() { let mut faces = vec![]; for k in 0..5 { faces.push(json!({ "key": format!("x{k}"), "photo": format!("px{k}"), "vector": v(0, 0.05 * k as f32) })); faces.push(json!({ "key": format!("y{k}"), "photo": format!("py{k}"), "vector": v(1, 0.05 * k as f32) })); } faces.push(json!({ "key": "twin", "photo": "px0", "vector": v(0, 0.0) })); let out = group(&json!({ "faces": faces, "names": { "x0": "Asha" } })).unwrap(); let groups = out["groups"].as_array().unwrap(); assert_eq!(groups.len(), 2, "{out}"); let asha = groups.iter().find(|g| g["person"] == "Asha").expect("the named group"); assert_eq!(asha["photos"], 5); assert_eq!(asha["shown"], true); assert!(!asha["faces"].as_array().unwrap().iter().any(|k| k == "twin"), "a second face of px0 joined Asha"); assert_eq!(out["loose"], 1); } #[test] fn a_vector_that_is_not_whole_floats_is_refused() { let out = group(&json!({ "faces": [{ "key": "a", "photo": "p", "vector": "AAA=" }] })); assert_eq!(out.unwrap_err().code, "bad_request"); }}