Skip to main content

rosetta_squint_hash/
multihash.rs

1//! ImageMultiHash: variable-length list of Hash objects, output of crop_resistant_hash.
2//!
3//! Distance is FLOAT (not int) — matches Python `imagehash.ImageMultiHash.__sub__`.
4
5use std::fmt;
6
7use crate::{hex_to_hash, Hash, ImageHashError};
8
9/// A collection of per-segment hashes produced by `crop_resistant_hash`.
10///
11/// Distance (`subtract`) returns a `f64` — not an integer — because it sums
12/// best-match Hamming distances and applies a penalty for unmatched segments.
13#[derive(Debug, Clone)]
14pub struct ImageMultiHash {
15    pub segment_hashes: Vec<Hash>,
16}
17
18impl ImageMultiHash {
19    /// Returns the float distance between two `ImageMultiHash` objects.
20    ///
21    /// Matches Python `ImageMultiHash.__sub__`:
22    /// ```python
23    /// matches, sum_distance = self.hash_diff(other)
24    /// max_difference = len(self.segment_hashes)
25    /// if matches == 0: return max_difference
26    /// max_distance = matches * len(self.segment_hashes[0])
27    /// tie_breaker = -(sum_distance / max_distance)
28    /// match_score = matches + tie_breaker
29    /// return max_difference - match_score
30    /// ```
31    pub fn subtract(&self, other: &Self) -> f64 {
32        self.subtract_with(other, None, None)
33    }
34
35    pub fn subtract_with(
36        &self,
37        other: &Self,
38        hamming_cutoff: Option<f64>,
39        bit_error_rate: Option<f64>,
40    ) -> f64 {
41        let (matches, sum_distance) = self.hash_diff(other, hamming_cutoff, bit_error_rate);
42        let max_difference = self.segment_hashes.len() as f64;
43        if matches == 0 {
44            return max_difference;
45        }
46        let max_distance = matches as f64 * self.segment_hashes[0].bit_count() as f64;
47        let tie_breaker = -(sum_distance as f64 / max_distance);
48        let match_score = matches as f64 + tie_breaker;
49        max_difference - match_score
50    }
51
52    /// Returns `(matches, sum_of_hamming_distances)` for segments within cutoff.
53    ///
54    /// Matches Python `ImageMultiHash.hash_diff`.
55    pub fn hash_diff(
56        &self,
57        other: &Self,
58        hamming_cutoff: Option<f64>,
59        bit_error_rate: Option<f64>,
60    ) -> (usize, usize) {
61        if self.segment_hashes.is_empty() {
62            return (0, 0);
63        }
64        let cutoff = match hamming_cutoff {
65            Some(c) => c,
66            None => {
67                let ber = bit_error_rate.unwrap_or(0.25);
68                self.segment_hashes[0].bit_count() as f64 * ber
69            }
70        };
71
72        let mut total_matches = 0usize;
73        let mut total_distance = 0usize;
74
75        for sh in &self.segment_hashes {
76            let lowest = other
77                .segment_hashes
78                .iter()
79                .filter_map(|oh| sh.subtract(oh).ok())
80                .min()
81                .unwrap_or(usize::MAX);
82            if (lowest as f64) <= cutoff {
83                total_matches += 1;
84                total_distance += lowest;
85            }
86        }
87        (total_matches, total_distance)
88    }
89
90    /// True if at least `region_cutoff` segments match within the hamming cutoff.
91    pub fn matches(
92        &self,
93        other: &Self,
94        region_cutoff: usize,
95        hamming_cutoff: Option<f64>,
96        bit_error_rate: Option<f64>,
97    ) -> bool {
98        let (m, _) = self.hash_diff(other, hamming_cutoff, bit_error_rate);
99        m >= region_cutoff
100    }
101
102    /// Returns the `ImageMultiHash` in `others` that minimizes `self.subtract(other)`.
103    pub fn best_match<'a>(&self, others: &'a [Self]) -> Option<&'a Self> {
104        others.iter().min_by(|a, b| {
105            self.subtract(a)
106                .partial_cmp(&self.subtract(b))
107                .unwrap_or(std::cmp::Ordering::Equal)
108        })
109    }
110
111    /// Comma-joined hex of each segment hash (matches Python `str(multihash)`).
112    pub fn to_hex(&self) -> String {
113        self.segment_hashes
114            .iter()
115            .map(|h| h.to_hex())
116            .collect::<Vec<_>>()
117            .join(",")
118    }
119}
120
121impl fmt::Display for ImageMultiHash {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        f.write_str(&self.to_hex())
124    }
125}
126
127/// Parse a comma-separated multi-hash hex string into an `ImageMultiHash`.
128///
129/// Matches Python `imagehash.hex_to_multihash`.
130pub fn hex_to_multihash(s: &str) -> Result<ImageMultiHash, ImageHashError> {
131    let hashes: Result<Vec<Hash>, ImageHashError> =
132        s.split(',').map(|part| hex_to_hash(part)).collect();
133    Ok(ImageMultiHash { segment_hashes: hashes? })
134}