legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! `perceptual-v1`, the DCT image hash.

use crate::luma::downscale;
use crate::{Algorithm, Hash, Luma};

/// The side of the reduced image the DCT reads.
const N: usize = 32;

/// The side of the block of lowest frequencies that is kept.
const KEPT: usize = 8;

/// Hash an image with `perceptual-v1`, the DCT hash.
///
/// The definition, frozen:
///
/// 1. Reduce the image to 32×32 with [`Luma::downscale_v1`].
/// 2. Take the table `C[k][n] = round(cos(π · k · (2n + 1) / 64) · 2^40)` for `k` from 0 to 7 and
///    `n` from 0 to 31, each rounded to the nearest integer, halves away from zero. `C[0][n]` is
///    `2^40`.
/// 3. The column pass: `T[k][c] = Σ x[r][c] · C[k][r]` over the 32 rows `r`, for `k` from 0 to 7
///    and each of the 32 columns `c`.
/// 4. The row pass: `Y[k][j] = Σ T[k][c] · C[j][c]` over the 32 columns `c`, for `k` and `j` from
///    0 to 7. These are the 64 coefficients, taken row by row, `k` then `j`.
/// 5. Sort the 64 coefficients and let `a` and `b` be the two middle ones. The bit for a
///    coefficient `y` is set when `2 · y > a + b`: when it's strictly above the median, the mean
///    of `a` and `b`.
///
/// The first bit is the most significant bit of the hash.
///
/// Every sum is exact integer arithmetic, with no floating point anywhere, so the order of the
/// additions doesn't matter and every platform computes the same hash. The table is a list of
/// integer literals, never computed at run time.
///
/// `Y` is the 8×8 block of lowest frequencies, the DC term included, of the unnormalised 2-D
/// DCT-II that Python ImageHash's `phash` takes, times the positive constant `2^78`, with each
/// cosine rounded to within `2^-41`. So the comparisons with the median are the same as
/// ImageHash's, except for a coefficient within rounding of the median.
///
/// A coefficient that symmetry makes zero is exactly 0, where floating point would leave rounding
/// residue, so its bit is 0, and stable. An image whose reduction is constant down every column
/// has every row of `Y` past the first at 0; constant along every row, every column past the
/// first; mirror-symmetric left to right, every odd column. So a flat image that isn't black
/// hashes to `8000000000000000`, its DC term alone above the median, and an all-black one to
/// `0000000000000000`.
///
/// ```
/// use legit_hashes::{Algorithm, Luma, perceptual_v1};
///
/// let pixels: Vec<u8> = (0..32 * 32).map(|i| ((i % 32) * 8 ^ (i / 32) * 3) as u8).collect();
/// let hash = perceptual_v1(Luma::new(32, 32, &pixels)?);
/// assert_eq!(hash.algorithm(), Algorithm::PerceptualV1);
///
/// let flat = perceptual_v1(Luma::new(4, 4, &[90; 16])?);
/// assert_eq!(flat.to_hex(), "8000000000000000");
/// let black = perceptual_v1(Luma::new(4, 4, &[0; 16])?);
/// assert_eq!(black.to_hex(), "0000000000000000");
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn perceptual_v1(image: Luma<'_>) -> Hash {
    let coefficients = dct_low_frequencies(&downscale(image, N as u32, N as u32));
    Hash::from_bits(Algorithm::PerceptualV1, bits_above_median(&coefficients))
}

/// One bit for each coefficient, in order, set when it's strictly above the median: when twice
/// the coefficient is above the sum of the two middle values.
fn bits_above_median(coefficients: &[i128; KEPT * KEPT]) -> u64 {
    let mut sorted = *coefficients;
    sorted.sort_unstable();
    let twice_median = sorted[KEPT * KEPT / 2 - 1] + sorted[KEPT * KEPT / 2];
    coefficients.iter().fold(0, |bits, &coefficient| {
        bits << 1 | u64::from(2 * coefficient > twice_median)
    })
}

/// The 8×8 lowest frequencies of the 2-D DCT-II of a 32×32 image, scaled by `COS`, row by row.
fn dct_low_frequencies(pixels: &[u8]) -> [i128; KEPT * KEPT] {
    // The column pass: frequency `k` down each column `c`. Each term is at most 255 · 2^40 in
    // magnitude and there are 32 of them, so a sum stays below 2^53 and fits an `i64`...
    let mut columns = [[0_i64; N]; KEPT];
    for (k, row) in columns.iter_mut().enumerate() {
        for (c, value) in row.iter_mut().enumerate() {
            let column = pixels.iter().skip(c).step_by(N);
            *value = column
                .zip(&COS[k])
                .map(|(&pixel, &cosine)| i64::from(pixel) * cosine)
                .sum();
        }
    }
    // ...then the row pass: frequency `j` along each of those rows. Each term is below
    // 2^53 · 2^40 and there are 32 of them, so a sum stays below 2^98 and fits an `i128`, as do
    // twice a coefficient and the sum of two.
    let mut coefficients = [0; KEPT * KEPT];
    for (index, coefficient) in coefficients.iter_mut().enumerate() {
        let row = columns[index / KEPT].iter();
        *coefficient = row
            .zip(&COS[index % KEPT])
            .map(|(&value, &cosine)| i128::from(value) * i128::from(cosine))
            .sum();
    }
    coefficients
}

/// `COS[k][n] = round(cos(π * k * (2n + 1) / 64) * 2^40)`, rounded to the nearest integer, halves
/// away from zero.
///
/// Written by `tools/hash-ref/dct_table.py` in the repository, which computes them in 60-digit
/// decimal arithmetic. Frozen with `perceptual-v1`.
#[rustfmt::skip]
const COS: [[i64; 32]; 8] = [
    [
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
        1099511627776,
    ],
    [
        1098187217867,
        1087611074629,
        1066560642194,
        1035238647732,
        993946739174,
        943082580171,
        883136020380,
        814684377941,
        738386879591,
        654978311948,
        565261945112,
        470101796741,
        370414311084,
        267159533123,
        161331862813,
        53950478471,
        -53950478471,
        -161331862813,
        -267159533123,
        -370414311084,
        -470101796741,
        -565261945112,
        -654978311948,
        -738386879591,
        -814684377941,
        -883136020380,
        -943082580171,
        -993946739174,
        -1035238647732,
        -1066560642194,
        -1087611074629,
        -1098187217867,
    ],
    [
        1094217178761,
        1052167026225,
        969682684934,
        849933981865,
        697522792521,
        518306193436,
        319171378006,
        107770985514,
        -107770985514,
        -319171378006,
        -518306193436,
        -697522792521,
        -849933981865,
        -969682684934,
        -1052167026225,
        -1094217178761,
        -1094217178761,
        -1052167026225,
        -969682684934,
        -849933981865,
        -697522792521,
        -518306193436,
        -319171378006,
        -107770985514,
        107770985514,
        319171378006,
        518306193436,
        697522792521,
        849933981865,
        969682684934,
        1052167026225,
        1094217178761,
    ],
    [
        1087611074629,
        993946739174,
        814684377941,
        565261945112,
        267159533123,
        -53950478471,
        -370414311084,
        -654978311948,
        -883136020380,
        -1035238647732,
        -1098187217867,
        -1066560642194,
        -943082580171,
        -738386879591,
        -470101796741,
        -161331862813,
        161331862813,
        470101796741,
        738386879591,
        943082580171,
        1066560642194,
        1098187217867,
        1035238647732,
        883136020380,
        654978311948,
        370414311084,
        53950478471,
        -267159533123,
        -565261945112,
        -814684377941,
        -993946739174,
        -1087611074629,
    ],
    [
        1078384820155,
        914210506869,
        610855931251,
        214504077523,
        -214504077523,
        -610855931251,
        -914210506869,
        -1078384820155,
        -1078384820155,
        -914210506869,
        -610855931251,
        -214504077523,
        214504077523,
        610855931251,
        914210506869,
        1078384820155,
        1078384820155,
        914210506869,
        610855931251,
        214504077523,
        -214504077523,
        -610855931251,
        -914210506869,
        -1078384820155,
        -1078384820155,
        -914210506869,
        -610855931251,
        -214504077523,
        214504077523,
        610855931251,
        914210506869,
        1078384820155,
    ],
    [
        1066560642194,
        814684377941,
        370414311084,
        -161331862813,
        -654978311948,
        -993946739174,
        -1098187217867,
        -943082580171,
        -565261945112,
        -53950478471,
        470101796741,
        883136020380,
        1087611074629,
        1035238647732,
        738386879591,
        267159533123,
        -267159533123,
        -738386879591,
        -1035238647732,
        -1087611074629,
        -883136020380,
        -470101796741,
        53950478471,
        565261945112,
        943082580171,
        1098187217867,
        993946739174,
        654978311948,
        161331862813,
        -370414311084,
        -814684377941,
        -1066560642194,
    ],
    [
        1052167026225,
        697522792521,
        107770985514,
        -518306193436,
        -969682684934,
        -1094217178761,
        -849933981865,
        -319171378006,
        319171378006,
        849933981865,
        1094217178761,
        969682684934,
        518306193436,
        -107770985514,
        -697522792521,
        -1052167026225,
        -1052167026225,
        -697522792521,
        -107770985514,
        518306193436,
        969682684934,
        1094217178761,
        849933981865,
        319171378006,
        -319171378006,
        -849933981865,
        -1094217178761,
        -969682684934,
        -518306193436,
        107770985514,
        697522792521,
        1052167026225,
    ],
    [
        1035238647732,
        565261945112,
        -161331862813,
        -814684377941,
        -1098187217867,
        -883136020380,
        -267159533123,
        470101796741,
        993946739174,
        1066560642194,
        654978311948,
        -53950478471,
        -738386879591,
        -1087611074629,
        -943082580171,
        -370414311084,
        370414311084,
        943082580171,
        1087611074629,
        738386879591,
        53950478471,
        -654978311948,
        -1066560642194,
        -993946739174,
        -470101796741,
        267159533123,
        883136020380,
        1098187217867,
        814684377941,
        161331862813,
        -565261945112,
        -1035238647732,
    ],
];

#[cfg(test)]
mod tests {
    use super::*;

    /// `cos(π * m / 64)` with `f64::cos`, the angle first reduced exactly to `[0, π / 2]` so the
    /// float argument carries almost no rounding.
    fn reduced_cos(m: usize) -> f64 {
        let m = m % 128;
        let m = if m > 64 { 128 - m } else { m };
        if m > 32 {
            -(std::f64::consts::PI * (64 - m) as f64 / 64.0).cos()
        } else {
            (std::f64::consts::PI * m as f64 / 64.0).cos()
        }
    }

    /// A 32×32 buffer from a formula of `(row, column)`.
    fn buffer(formula: impl Fn(usize, usize) -> u8) -> Vec<u8> {
        (0..N * N).map(|i| formula(i / N, i % N)).collect()
    }

    /// The bits of the coefficients of a 32×32 buffer, as `perceptual_v1` sets them.
    fn hash(pixels: &[u8]) -> String {
        perceptual_v1(Luma::new(32, 32, pixels).expect("the buffer is 32×32")).to_hex()
    }

    #[test]
    fn coefficients_equal_to_the_median_stay_clear() {
        // 0 to 63 in order: the middle values are 31 and 32, so the median is 31.5...
        let ascending: [i128; 64] = std::array::from_fn(|i| i as i128);
        assert_eq!(bits_above_median(&ascending), 0x0000_0000_ffff_ffff);

        // 30 values below 5, four of exactly 5, 30 above: both middle values are 5, so the median
        // is 5 and the four coefficients equal to it stay clear...
        let tied: [i128; 64] = std::array::from_fn(|i| match i {
            0..30 => i as i128 - 40,
            30..34 => 5,
            _ => i as i128,
        });
        assert_eq!(bits_above_median(&tied), 0x0000_0000_3fff_ffff);

        // A median halfway between two integers: 0 and 1 in the middle, so 0 stays clear and 1 is
        // set...
        let halves: [i128; 64] = std::array::from_fn(|i| if i < 32 { 0 } else { 1 });
        assert_eq!(bits_above_median(&halves), 0x0000_0000_ffff_ffff);

        // The order of the input is the order of the bits, whatever the values...
        let mut reversed = ascending;
        reversed.reverse();
        assert_eq!(bits_above_median(&reversed), 0xffff_ffff_0000_0000);
    }

    #[test]
    fn the_cosine_table_matches_the_cosines_it_stands_for() {
        let scale = (1_u64 << 40) as f64;
        for (k, row) in COS.iter().enumerate() {
            for (n, &entry) in row.iter().enumerate() {
                let expected = reduced_cos(k * (2 * n + 1)) * scale;
                assert!(
                    (entry as f64 - expected).abs() <= 1.0,
                    "COS[{k}][{n}] is {entry}, cos gives {expected}"
                );
            }
        }
        assert_eq!(COS[0], [1 << 40; N]);
    }

    #[test]
    fn the_cosine_table_keeps_the_symmetries_of_the_cosines() {
        for (k, row) in COS.iter().enumerate().skip(1) {
            assert_eq!(row.iter().sum::<i64>(), 0, "row {k} sums to 0");
            for n in 0..N {
                let mirrored = if k % 2 == 1 { -row[N - 1 - n] } else { row[N - 1 - n] };
                assert_eq!(row[n], mirrored, "COS[{k}][{n}] against COS[{k}][{}]", N - 1 - n);
            }
        }
    }

    #[test]
    fn symmetry_makes_coefficients_exactly_zero() {
        // Uneven levels, so that no coefficient but those symmetry forces is 0...
        let level = |i: usize| ((i * i * 37 + i * 11) % 251) as u8;

        // Constant down every column: every row of coefficients past the first is 0...
        let columns = dct_low_frequencies(&buffer(|_, column| level(column)));
        for (index, &coefficient) in columns.iter().enumerate() {
            assert_eq!(coefficient == 0, index >= KEPT, "coefficient {index} is {coefficient}");
        }

        // Constant along every row: every column of coefficients past the first is 0...
        let rows = dct_low_frequencies(&buffer(|row, _| level(row)));
        for (index, &coefficient) in rows.iter().enumerate() {
            assert_eq!(
                coefficient == 0,
                index % KEPT >= 1,
                "coefficient {index} is {coefficient}"
            );
        }

        // Mirror-symmetric left to right: every odd column of coefficients is 0...
        let mirror = dct_low_frequencies(&buffer(|row, column| level(row * N + column.min(N - 1 - column))));
        for (index, &coefficient) in mirror.iter().enumerate() {
            assert_eq!(coefficient == 0, index % 2 == 1, "coefficient {index} is {coefficient}");
        }
    }

    #[test]
    fn a_horizontal_ramp_hashes_as_imagehash_does() {
        // Each column one grey level, 0, 8, ..., 248: the 56 rows past the first are exactly 0, and
        // so are the even frequencies of a straight ramp, 2, 4 and 6. The other four are below 0,
        // so the median is 0 and only the DC term is above it. ImageHash 4.3.2 gives the same...
        let ramp = buffer(|_, column| (column * 8) as u8);
        assert_eq!(hash(&ramp), "8000000000000000");
        let coefficients = dct_low_frequencies(&ramp);
        assert_eq!(coefficients.iter().filter(|&&c| c == 0).count(), 59);
    }

    #[test]
    fn flat_images_hash_to_their_dc_term_alone() {
        for level in [1, 128, 255] {
            assert_eq!(hash(&[level; N * N]), "8000000000000000", "flat at {level}");
        }
        assert_eq!(hash(&[0; N * N]), "0000000000000000");
    }
}