Cotton code
408 lines · 15.9 KB · RustRaw
//! Who a face looks like — the ONE decision the Mac's analysis worker makes//! about people, stated as a pure function so the thresholds are testable and//! the worker holds no rule of its own (spec//! `2026-09-05-cotton-photos-analysis-design.md` §D6). The port of//! `packages/core/src/engine/media/people.ts`.//!//! The shape of the rule, and what each part defends://!//! **Seeds are the owner's facts.** A person is a candidate only when at least//! [`MIN_SEED_FACES`] of their faces carry an embedding — one face is not a//! face print, and a single wrong Apple assignment would otherwise teach//! itself. The centroid is the normalised mean; it is recomputed every pass//! from the rows as they stand, never stored, so a merge or a re-pointed face//! moves it with nothing to unwind.//!//! **A suggestion, never an assignment.** The output names//! `suggested_person_id`; `person_id` is written only by the owner//! (`setFacePerson`) or an import filling a NULL. A face that already has a//! person, an open suggestion, or a dismissal is never considered.//!//! **Two thresholds, both written.** [`SUGGEST_MAX_DISTANCE`] is the cosine//! distance under which the nearest person is proposed at all;//! [`SUGGEST_MARGIN`] is how much further the SECOND-nearest must be, so two//! people the model cannot tell apart yield no suggestion rather than a coin//! toss. A wrong suggestion about a person is the error this file must not//! make cheaply, so both err towards silence.//!//! **No merging.** Two seeds are two people until the owner says otherwise;//! nothing here compares centroids to each other.//!//! ## `Float32Array` is not an implementation detail//!//! The TypeScript's `normalise` and `centroidOf` return a `Float32Array`, and//! that rounding is load-bearing rather than incidental: its own test pins//! `normalise([3, 4])` at `[0.6000000238418579, 0.800000011920929]`, which is//! `0.6` and `0.8` squeezed through single precision. So [`normalise`] and//! [`centroid_of`] answer `Vec<f32>` here, the accumulation inside//! [`centroid_of`] rounds to `f32` at EVERY step exactly as writing into a//! `Float32Array` does, and every arithmetic step between those roundings is//! `f64` — which is what reading an element of a `Float32Array` gives you in//! JavaScript. Take a shortcut on any of those three and the distances drift//! in the sixth decimal, which is the decimal [`SUGGEST_MARGIN`] is measured//! in.use serde::{Deserialize, Serialize};/// Faces a person needs before their centroid is trusted as a seed.pub const MIN_SEED_FACES: usize = 3;/// The cosine distance (1 − cosine similarity) under which the nearest seed is/// suggested.////// facenet-pytorch's VGGFace2 InceptionResnetV1 puts same-identity pairs at/// roughly 0.30–0.40 at its published LFW operating point; 0.45 with the/// margin below trades a few missed suggestions for very few wrong ones.pub const SUGGEST_MAX_DISTANCE: f64 = 0.45;/// How much further the second-nearest seed must sit for a suggestion.pub const SUGGEST_MARGIN: f64 = 0.05;/// The failures the TypeScript throws. `Display` is its sentence verbatim.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum PeopleError {    #[error("cosineDistance: vectors differ in length ({a} vs {b})")]    CosineLength { a: usize, b: usize },    #[error("centroidOf: no vectors")]    NoVectors,    #[error("centroidOf: vectors differ in length ({found} vs {expected})")]    CentroidLength { found: usize, expected: usize },}/// One face row, as the suggester reads it.////// `embedding` is `Vec<f64>` and not `Vec<f32>` on purpose. The TypeScript's/// type is `Float32Array | readonly number[]`, and BOTH spellings are read as/// double-precision numbers the moment an element is touched — indexing a/// `Float32Array` widens. Storing the row as `f32` here would round the input/// a second time, before the arithmetic rather than after it, and answer/// different distances from the same bytes. A caller holding a single-precision/// blob widens it once with [`widen`].#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct FaceForPeople {    pub face_id: String,    /// The owner's fact, or an import's fill. A set person is never    /// re-suggested.    pub person_id: Option<String>,    /// An open suggestion already on the row.    pub suggested_person_id: Option<String>,    /// The owner said no to a suggestion on this face — never suggest again.    pub dismissed: bool,    /// The face embedding, L2-normalised or not — normalised here.    pub embedding: Vec<f64>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PersonSuggestion {    pub face_id: String,    pub suggested_person_id: String,    /// Cosine distance to the person's centroid, 0 (identical) … 2 (opposite).    pub distance: f64,}/// One person's seed centroid.////// A `Vec` of these rather than a `HashMap`, because the ORDER is observable:/// the TypeScript returns a `Map`, [`suggest_people`] walks it, and its/// "nearest" test is a STRICT `<`, so two people at exactly equal distance are/// decided by which was inserted first — the order in which their faces appear/// in the input. A `HashMap` would decide the same tie by hash seed.#[derive(Debug, Clone, PartialEq)]pub struct SeedCentroid {    pub person_id: String,    pub centroid: Vec<f32>,}/// Options for [`suggest_people`] — the TypeScript's optional second argument.#[derive(Debug, Clone, Default)]pub struct SuggestPeopleOptions {    pub min_seed_faces: Option<usize>,    pub max_distance: Option<f64>,    pub margin: Option<f64>,}/// Read a single-precision vector the way JavaScript reads a `Float32Array`:/// every element widens to a double on the way out.pub fn widen(vector: &[f32]) -> Vec<f64> {    vector.iter().map(|value| f64::from(*value)).collect()}/// L2-normalise; a zero vector stays zero (and then matches nothing).////// The sum, the square root and the division are all double precision; only/// the STORE is single, which is what `out[i] = vector[i] / norm` into a/// `Float32Array` does.pub fn normalise(vector: &[f64]) -> Vec<f32> {    let mut sum = 0.0f64;    for value in vector {        sum += value * value;    }    let norm = sum.sqrt();    if norm == 0.0 {        return vec![0.0f32; vector.len()];    }    vector.iter().map(|value| (value / norm) as f32).collect()}/// `Math.min` / `Math.max`, which propagate NaN where `f64::min` / `f64::max`/// swallow it.fn js_clamp(value: f64, low: f64, high: f64) -> f64 {    // `Math.max(low, Math.min(high, value))`, spelled out.    let capped = if value.is_nan() || high.is_nan() || value < high {        value    } else {        high    };    if capped.is_nan() || low.is_nan() || capped > low {        capped    } else {        low    }}/// 1 − cosine similarity over two vectors of one length.////// A zero-length vector answers 2 — the far end of the range — rather than/// dividing by zero, so a face whose embedding failed to compute matches/// nothing instead of matching everything.////// The clamp is `Math.max(-1, Math.min(1, similarity))` and it is ported with/// JavaScript's NaN behaviour, not Rust's: `Math.min(1, NaN)` is `NaN` while/// `1f64.min(f64::NAN)` is `1`. An embedding read out of a single-precision/// blob CAN hold a NaN where a JSON one cannot, and the honest answer for one/// is a NaN distance — which is neither under [`SUGGEST_MAX_DISTANCE`] nor/// clear of the margin, so the face is left alone.pub fn cosine_distance(a: &[f64], b: &[f64]) -> Result<f64, PeopleError> {    if a.len() != b.len() {        return Err(PeopleError::CosineLength {            a: a.len(),            b: b.len(),        });    }    let mut dot = 0.0f64;    let mut norm_a = 0.0f64;    let mut norm_b = 0.0f64;    for (x, y) in a.iter().zip(b.iter()) {        dot += x * y;        norm_a += x * x;        norm_b += y * y;    }    if norm_a == 0.0 || norm_b == 0.0 {        return Ok(2.0);    }    let similarity = dot / (norm_a.sqrt() * norm_b.sqrt());    Ok(1.0 - js_clamp(similarity, -1.0, 1.0))}/// The normalised mean of normalised vectors. Refuses an empty set.////// Magnitude does not weight a member — each vector is normalised BEFORE it is/// added — so one enormous embedding counts exactly once. The running sum is a/// `Float32Array` in the TypeScript and rounds to single precision on every/// addition; that rounding is reproduced here rather than accumulated in `f64`/// and rounded at the end, because the two answers differ.pub fn centroid_of(vectors: &[&[f64]]) -> Result<Vec<f32>, PeopleError> {    let Some(first) = vectors.first() else {        return Err(PeopleError::NoVectors);    };    let dimension = first.len();    let mut sum = vec![0.0f32; dimension];    for vector in vectors {        if vector.len() != dimension {            return Err(PeopleError::CentroidLength {                found: vector.len(),                expected: dimension,            });        }        let unit = normalise(vector);        for (slot, component) in sum.iter_mut().zip(unit.iter()) {            *slot = (f64::from(*slot) + f64::from(*component)) as f32;        }    }    Ok(normalise(&widen(&sum)))}/// person → centroid, for every person with enough embedded faces, in the/// order each person's first face appears.pub fn seed_centroids(    faces: &[FaceForPeople],    min_seed_faces: usize,) -> Result<Vec<SeedCentroid>, PeopleError> {    let mut order: Vec<&str> = Vec::new();    let mut by_person: std::collections::HashMap<&str, Vec<&[f64]>> =        std::collections::HashMap::new();    for face in faces {        let Some(person_id) = face.person_id.as_deref() else {            continue;        };        if !by_person.contains_key(person_id) {            order.push(person_id);        }        by_person            .entry(person_id)            .or_default()            .push(face.embedding.as_slice());    }    let mut centroids = Vec::new();    for person_id in order {        let Some(vectors) = by_person.get(person_id) else {            continue;        };        if vectors.len() < min_seed_faces {            continue;        }        centroids.push(SeedCentroid {            person_id: person_id.to_string(),            centroid: centroid_of(vectors)?,        });    }    Ok(centroids)}/// The suggestions this pass would make: for each unassigned, unsuggested,/// undismissed face, the nearest seed if it is near enough AND clearly nearer/// than the next. Deterministic and order-independent; nothing is written.////// With exactly one seed the second-nearest distance is `+∞`, so the margin is/// satisfied by construction — one known person and a face that looks like/// them is a suggestion, and there is nothing it could be confused with.pub fn suggest_people(    faces: &[FaceForPeople],    options: &SuggestPeopleOptions,) -> Result<Vec<PersonSuggestion>, PeopleError> {    let min_seed_faces = options.min_seed_faces.unwrap_or(MIN_SEED_FACES);    let max_distance = options.max_distance.unwrap_or(SUGGEST_MAX_DISTANCE);    let margin = options.margin.unwrap_or(SUGGEST_MARGIN);    let centroids = seed_centroids(faces, min_seed_faces)?;    if centroids.is_empty() {        return Ok(Vec::new());    }    let widened: Vec<(&str, Vec<f64>)> = centroids        .iter()        .map(|seed| (seed.person_id.as_str(), widen(&seed.centroid)))        .collect();    let mut out = Vec::new();    for face in faces {        if face.person_id.is_some() || face.suggested_person_id.is_some() || face.dismissed {            continue;        }        let mut best: Option<(&str, f64)> = None;        let mut second = f64::INFINITY;        for (person_id, centroid) in &widened {            let distance = cosine_distance(&face.embedding, centroid)?;            match best {                None => best = Some((person_id, distance)),                Some((_, best_distance)) if distance < best_distance => {                    second = best_distance;                    best = Some((person_id, distance));                }                _ => {                    if distance < second {                        second = distance;                    }                }            }        }        let Some((person_id, distance)) = best else {            continue;        };        if distance > max_distance {            continue;        }        if second - distance < margin {            continue;        }        out.push(PersonSuggestion {            face_id: face.face_id.clone(),            suggested_person_id: person_id.to_string(),            distance,        });    }    Ok(out)}/// The cosine distance under which a face is LINKED to a person, not merely/// suggested — stricter than [`SUGGEST_MAX_DISTANCE`], because a link puts the/// photo on the person's page and in their album without a tap. VGGFace2/// same-identity pairs sit around 0.30–0.40; 0.35 keeps the near half of them.pub const LINK_MAX_DISTANCE: f64 = 0.35;/// How much further the second-nearest person must sit for a link — wider/// than [`SUGGEST_MARGIN`] for the same reason.pub const LINK_MARGIN: f64 = 0.08;/// One person's face prints: every picture known to be them — the face read/// off their profile picture, and each face the OWNER named as them. A face/// the engine itself linked is never a print, so a wrong link cannot teach/// itself.#[derive(Debug, Clone, PartialEq)]pub struct PersonPrints {    pub person_id: String,    pub prints: Vec<Vec<f64>>,}/// A face the matcher would link, and how near its nearest print was.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PersonLink {    pub face_id: String,    pub person_id: String,    pub distance: f64,}/// The links one pass makes: for EVERY open face (no person, not dismissed —/// an open suggestion does not stop a link), the person whose nearest print is/// within [`LINK_MAX_DISTANCE`] and clearly nearer than any other person's.////// One print is enough: a person's print is a known picture of them, unlike/// a seed centroid, which has to be trusted from several faces. Every face is/// judged in the one call, so a person with a print has every matching face/// linked in one pass. Pure: nothing is written.pub fn match_people(people: &[PersonPrints], faces: &[FaceForPeople]) -> Result<Vec<PersonLink>, PeopleError> {    let mut out = Vec::new();    if people.iter().all(|person| person.prints.is_empty()) {        return Ok(out);    }    for face in faces {        if face.person_id.is_some() || face.dismissed || face.embedding.is_empty() {            continue;        }        let mut best: Option<(&str, f64)> = None;        let mut second = f64::INFINITY;        for person in people {            let mut nearest = f64::INFINITY;            for print in &person.prints {                if print.len() != face.embedding.len() {                    continue;                }                let distance = cosine_distance(&face.embedding, print)?;                if distance < nearest {                    nearest = distance;                }            }            if !nearest.is_finite() {                continue;            }            match best {                Some((_, best_distance)) if nearest >= best_distance => second = second.min(nearest),                Some((_, best_distance)) => {                    second = best_distance;                    best = Some((person.person_id.as_str(), nearest));                }                None => best = Some((person.person_id.as_str(), nearest)),            }        }        let Some((person_id, distance)) = best else { continue };        if distance <= LINK_MAX_DISTANCE && second - distance >= LINK_MARGIN {            out.push(PersonLink { face_id: face.face_id.clone(), person_id: person_id.to_string(), distance });        }    }    Ok(out)}#[cfg(test)]#[path = "people_tests.rs"]mod tests;