Cotton code
340 lines · 12.5 KB · RustRaw
//! Which pictures are copies of which — the ONE decision behind//! `cotton_media_duplicates`, stated as a pure function (spec//! `2026-09-05-cotton-photos-analysis-design.md` §D7). The port of//! `packages/core/src/engine/media/duplicates.ts`.//!//! **The key is the perceptual hash.** Two photos whose 64-bit DCT hashes//! differ in at most [`DUPLICATE_MAX_DISTANCE`] bits are candidates — the value//! at which a resave, a resize or a recompression is caught and unrelated//! pictures are not. The hash is blind to a mirrored image and degrades under//! crops; the v39 spec wrote that down and this rule inherits it.//!//! **A group is a connected component** over candidate pairs, and one member is//! the KEEP, chosen by a written rule in order: the favourite; else the most//! pixels; else the most bytes; else the earliest taken; else the lowest id.//! Every other member is a copy of the keep. The rule is total, so two runs//! over the same rows name the same keep.//!//! **An opinion, never an act.** The output is proposals. Deletion is//! `remove_photo`, called by a person.use std::collections::HashMap;use serde::{Deserialize, Serialize};use super::stable_sort_by;/// Hamming distance (of 64) at or under which two hashes are near-duplicates.pub const DUPLICATE_MAX_DISTANCE: u32 = 8;const POPCOUNT_NIBBLE: [u32; 16] = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];/// The failures the TypeScript throws. `Display` is its sentence verbatim, so/// a handler can hand it straight to the error envelope.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum DuplicatesError {    #[error("phashDistance: a hash is 16 hex characters (got {a} and {b})")]    HashLength { a: usize, b: usize },    #[error("phashDistance: not hex")]    NotHex,    #[error("chooseKeep: empty group")]    EmptyGroup,}/// One hex digit, the way `parseInt(ch, 16)` reads one.////// UPPERCASE IS ACCEPTED, which is not obvious from the module's own/// "16 lowercase hex" comment on [`PhotoForDuplicates::phash`]: `parseInt`/// does not care about case, so `phashDistance("A1…", "a1…")` is 0 rather than/// a throw. Pinned by vector. Everything else — a space, a `+`, an/// Arabic-Indic digit, a lone surrogate — is `NaN` there and `None` here.fn hex_digit(unit: u16) -> Option<u32> {    match u8::try_from(unit).ok()? {        b'0'..=b'9' => Some(u32::from(unit) - u32::from(b'0')),        b'a'..=b'f' => Some(u32::from(unit) - u32::from(b'a') + 10),        b'A'..=b'F' => Some(u32::from(unit) - u32::from(b'A') + 10),        _ => None,    }}/// Hamming distance between two 16-hex perceptual hashes.////// The length check counts UTF-16 CODE UNITS, as `String.prototype.length`/// does, and the per-character read indexes them the same way: a string of 14/// zeroes plus one emoji is sixteen units long over there and is refused for/// not being hex, not for its length. Porting the check in `chars()` would/// have made that string fifteen long and refused it for the wrong reason.pub fn phash_distance(a: &str, b: &str) -> Result<u32, DuplicatesError> {    let a_units: Vec<u16> = a.encode_utf16().collect();    let b_units: Vec<u16> = b.encode_utf16().collect();    if a_units.len() != 16 || b_units.len() != 16 {        return Err(DuplicatesError::HashLength {            a: a_units.len(),            b: b_units.len(),        });    }    let mut distance = 0;    for (x, y) in a_units.iter().zip(b_units.iter()) {        let x = hex_digit(*x).ok_or(DuplicatesError::NotHex)?;        let y = hex_digit(*y).ok_or(DuplicatesError::NotHex)?;        distance += POPCOUNT_NIBBLE[(x ^ y) as usize];    }    Ok(distance)}/// What the grouping reads about one photo.////// The three numbers are integers here where `media_items::MessageMedia` holds/// its numbers as `f64`: these are read straight out of `cotton_photos`'/// INTEGER columns and nothing in this module rounds, floors or divides them,/// so there is no JavaScript-number decision to preserve — only a comparison,/// which `i64` makes a total order and `f64` would not (a NaN width returns/// `NaN` from the comparator, which `Array.prototype.sort` reads as zero).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PhotoForDuplicates {    pub id: String,    /// 16 lowercase hex, or `None` when never hashed (then never a candidate).    pub phash: Option<String>,    pub favourite: bool,    pub width: Option<i64>,    pub height: Option<i64>,    pub size_bytes: i64,    /// ISO instant.    pub taken_at: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DuplicateProposal {    pub keep_id: String,    pub copy_id: String,    /// The pHash Hamming distance between COPY and KEEP.    pub distance: u32,}/// Options for [`propose_duplicates`], the TypeScript's optional second/// argument. `Default` is its `{}`.#[derive(Debug, Clone, Default)]pub struct ProposeDuplicatesOptions<'a> {    pub max_distance: Option<u32>,    /// Only groups touching one of these ids are proposed — the photos    /// analysed this pass. `None` = the whole set (a full re-grouping).    pub focus: Option<&'a std::collections::HashSet<String>>,}/// `width × height`, with an unknown dimension counting as zero pixels.fn pixels(photo: &PhotoForDuplicates) -> i64 {    photo        .width        .unwrap_or(0)        .saturating_mul(photo.height.unwrap_or(0))}/// The keep order, clause by clause — the module header's rule.////// It NEVER answers `Equal`: the last clause is the TypeScript's/// `a.id < b.id ? -1 : 1`, which calls two photos with the same id "greater"/// rather than equal. That is harmless in JavaScript and is why/// [`stable_sort_by`] exists here rather than `slice::sort_by`.////// The two string clauses compare BYTES where JavaScript compares UTF-16 code/// units. The two orders differ only when a supplementary character (U+10000/// and above) is weighed against one in U+E000..=U+FFFF — surrogates sort low/// in UTF-16 and high in UTF-8. Neither field can hold one: an id is/// `photo:<64 hex>` and `taken_at` is an ISO instant, both ASCII.fn keep_order(a: &PhotoForDuplicates, b: &PhotoForDuplicates) -> std::cmp::Ordering {    use std::cmp::Ordering;    if a.favourite != b.favourite {        return if a.favourite {            Ordering::Less        } else {            Ordering::Greater        };    }    let (pixels_a, pixels_b) = (pixels(a), pixels(b));    if pixels_a != pixels_b {        return pixels_b.cmp(&pixels_a);    }    if a.size_bytes != b.size_bytes {        return b.size_bytes.cmp(&a.size_bytes);    }    if a.taken_at != b.taken_at {        return if a.taken_at < b.taken_at {            Ordering::Less        } else {            Ordering::Greater        };    }    if a.id < b.id {        Ordering::Less    } else {        Ordering::Greater    }}/// The keep of a group — see the module header's order. Total: never a tie.pub fn choose_keep(members: &[PhotoForDuplicates]) -> Result<&PhotoForDuplicates, DuplicatesError> {    if members.is_empty() {        return Err(DuplicatesError::EmptyGroup);    }    let mut order: Vec<usize> = (0..members.len()).collect();    stable_sort_by(&mut order, |&x, &y| keep_order(&members[x], &members[y]));    Ok(&members[order[0]])}/// Union-find over the unique ids, exactly as the TypeScript's two `Map`s do/// it — path compression on `find`, and `union` pointing the LEFT root at the/// right one.struct UnionFind {    parent: Vec<usize>,}impl UnionFind {    fn new(size: usize) -> Self {        Self {            parent: (0..size).collect(),        }    }    fn find(&mut self, id: usize) -> usize {        let mut root = id;        while self.parent[root] != root {            root = self.parent[root];        }        let mut cursor = id;        while self.parent[cursor] != root {            let next = self.parent[cursor];            self.parent[cursor] = root;            cursor = next;        }        root    }    fn union(&mut self, a: usize, b: usize) {        let (ra, rb) = (self.find(a), self.find(b));        if ra != rb {            self.parent[ra] = rb;        }    }}/// Every "keep A, B is a copy" this set of photos supports.////// Photos without a hash take no part. With `focus`, groups that contain none/// of the focused ids are skipped — the rest of the library was grouped on an/// earlier pass and its rows already exist.////// Returns a `Result` where the TypeScript throws: a malformed `phash` on any/// hashed photo stops the whole pass, because a grouping computed from a hash/// that could not be read is not a grouping at all.pub fn propose_duplicates(    photos: &[PhotoForDuplicates],    options: &ProposeDuplicatesOptions<'_>,) -> Result<Vec<DuplicateProposal>, DuplicatesError> {    let max_distance = options.max_distance.unwrap_or(DUPLICATE_MAX_DISTANCE);    let hashed: Vec<&PhotoForDuplicates> = photos        .iter()        .filter(|photo| photo.phash.is_some())        .collect();    // `new Map(hashed.map(p => [p.id, p]))` — a repeated id keeps the LAST    // row, and that is the row whose hash the reported distance is measured    // from.    let mut by_id: HashMap<&str, &PhotoForDuplicates> = HashMap::new();    // The unique ids in first-appearance order, so the union-find and the    // group map are keyed the way the TypeScript's `Map`s are.    let mut ids: Vec<&str> = Vec::new();    let mut slot_of: HashMap<&str, usize> = HashMap::new();    for photo in &hashed {        by_id.insert(photo.id.as_str(), photo);        if !slot_of.contains_key(photo.id.as_str()) {            slot_of.insert(photo.id.as_str(), ids.len());            ids.push(photo.id.as_str());        }    }    let mut sets = UnionFind::new(ids.len());    for (i, a) in hashed.iter().enumerate() {        for b in hashed.iter().skip(i + 1) {            // Only pairs touching the focus need comparing; the others were            // grouped on an earlier pass.            if let Some(focus) = options.focus {                if !focus.contains(&a.id) && !focus.contains(&b.id) {                    continue;                }            }            let (Some(hash_a), Some(hash_b)) = (a.phash.as_deref(), b.phash.as_deref()) else {                continue;            };            if phash_distance(hash_a, hash_b)? <= max_distance {                sets.union(slot_of[a.id.as_str()], slot_of[b.id.as_str()]);            }        }    }    // Groups in the order their roots were first seen — a `Map`'s iteration    // order, which decides nothing here (the output is sorted) but keeps the    // two implementations reading the same.    let mut group_order: Vec<usize> = Vec::new();    let mut groups: HashMap<usize, Vec<PhotoForDuplicates>> = HashMap::new();    for photo in &hashed {        let root = sets.find(slot_of[photo.id.as_str()]);        if !groups.contains_key(&root) {            group_order.push(root);        }        groups.entry(root).or_default().push((*photo).clone());    }    let mut out: Vec<DuplicateProposal> = Vec::new();    for root in &group_order {        let Some(members) = groups.get(root) else {            continue;        };        if members.len() < 2 {            continue;        }        if let Some(focus) = options.focus {            if !members.iter().any(|member| focus.contains(&member.id)) {                continue;            }        }        let keep = choose_keep(members)?;        let Some(keep_hash) = keep.phash.as_deref() else {            continue;        };        for member in members {            if member.id == keep.id {                continue;            }            let Some(member_hash) = by_id                .get(member.id.as_str())                .and_then(|row| row.phash.as_deref())            else {                continue;            };            out.push(DuplicateProposal {                keep_id: keep.id.clone(),                copy_id: member.id.clone(),                distance: phash_distance(member_hash, keep_hash)?,            });        }    }    // `a.keepId + a.copyId < b.keepId + b.copyId ? -1 : 1` — the CONCATENATION,    // not the pair, and never `Equal`.    stable_sort_by(&mut out, |a, b| {        let left = format!("{}{}", a.keep_id, a.copy_id);        let right = format!("{}{}", b.keep_id, b.copy_id);        if left < right {            std::cmp::Ordering::Less        } else {            std::cmp::Ordering::Greater        }    });    Ok(out)}#[cfg(test)]#[path = "duplicates_tests.rs"]mod tests;