legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation

legit-hashes

Similarity hashes of images and text, built to be stored. Each algorithm is a written definition with a version, and a released definition never changes its output, so a hash computed today still compares with one computed years later. The crate compares hashes by Hamming distance and splits them into index keys for finding near matches in a database. Image hashes come in 64 bits, as ImageHash computes them, and in 256 bits: Meta's PDQ, bit for bit with Meta's C++ reference, and blockhash. For text and other sets, MinHash signatures estimate how much two sets overlap, value for value with the Python library datasketch, its current default or the scheme it used before 2.0.0, with band keys to find probable matches.

It's a plain Rust library with no framework dependency.

Installation

cargo add legit-hashes

Add --features image to hash PNG and JPEG files, and --features serde to serialize hashes and signatures. The crate needs Rust 1.99 or newer.

Example

An image, from a file or from pixels you already have:

use legit_hashes::{Algorithm, Hash, LumaBuf, perceptual_v1};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // From a PNG or JPEG file, with the `image` feature...
    let file = std::fs::read("upload.jpg")?;
    let hash = Algorithm::PerceptualV1.hash_encoded(&file)?;

    // ...or from RGB pixels, three bytes a pixel.
    let (width, height, rgb) = (2, 1, [255, 0, 0, 0, 0, 255]);
    let from_pixels = perceptual_v1(LumaBuf::from_rgb8_v1(width, height, &rgb)?.view());

    // Store the string form; it names the algorithm and its version.
    let stored = hash.to_string(); // "perceptual-v1:…"

    let earlier: Hash = stored.parse()?;
    if from_pixels.distance(&earlier)? <= 8 {
        println!("a near match");
    }
    Ok(())
}

PDQ and blockhash start from colour, as RGBA. PDQ also scores the image's quality:

use legit_hashes::{RgbaBuf, blockhash_v1, pdq_v1};

fn main() -> legit_hashes::Result<()> {
    let (width, height) = (64, 48);
    let rgb: Vec<u8> = (0..width * height * 3).map(|i| (i * 7 % 251) as u8).collect();
    let image = RgbaBuf::from_rgb8(width, height, &rgb)?;

    let pdq = pdq_v1(image.view());
    if pdq.quality > 49 {
        println!("{}", pdq.hash); // "pdq-v1:…", 64 hex digits
    }
    println!("{}", blockhash_v1(image.view())); // "blockhash-v1:…"
    Ok(())
}

Text, from its words or its character shingles:

use legit_hashes::{shingles_v1, simhash_v1, words_v1};

fn main() -> legit_hashes::Result<()> {
    let first = simhash_v1(words_v1("The quick brown fox jumps over the lazy dog").map(|word| (word, 1)));
    let second = simhash_v1(words_v1("The quick brown fox jumped over the lazy dog").map(|word| (word, 1)));
    println!("{} bits differ", first.distance(&second)?);

    let shingled = simhash_v1(shingles_v1("The quick brown fox", 4)?.map(|shingle| (shingle, 1)));
    println!("{shingled}");
    Ok(())
}

Text as a set of shingles, with MinHash, for short and edited texts:

use legit_hashes::minhash_v1_shingles;

fn main() -> legit_hashes::Result<()> {
    let first = minhash_v1_shingles("your parcel is waiting: confirm your address today", 5)?;
    let second = minhash_v1_shingles("your parcel is waiting: confirm your adress today!", 5)?;
    println!("about {:.2} of their shingles are shared", first.similarity(&second)?);

    let stored = first.to_string(); // "minhash-v1:…", 1,024 hex digits
    let keys = first.band_keys_i64(32)?; // 32 keys for indexed BIGINT columns
    println!("{} {}", stored.len(), keys.len());
    Ok(())
}

Algorithms

Id Bits Definition First bit Good for From
average-v1 64 Reduce to 8×8; a bit is set when its pixel is above the mean. Top-left pixel Exact copies and light re-encoding; cheapest Krawetz's average hash, as Python ImageHash computes it
difference-v1 64 Reduce to 9×8; a bit is set when a pixel's right neighbour is brighter. Top-left pair Re-encoding and brightness changes Krawetz's difference hash, as ImageHash computes it
perceptual-v1 64 Reduce to 32×32, take the DCT, keep the 8×8 lowest frequencies; a bit is set when its coefficient is above their median. DC term General near-duplicate images in 64 bits The DCT hash of pHash.org and Krawetz, as ImageHash's phash computes it
simhash-v1 64 Hash each weighted feature with SipHash-2-4; a bit is set when the weights of features with that bit set outweigh the rest. Bit 63 of the sum Near-duplicate texts Charikar's SimHash, as Manku, Jain and Das Sarma apply it to documents
pdq-v1 256 Luma in f32; blur with two Jarosz box-filter passes and sample 64×64; take the 16×16 DCT frequencies past the DC term; a bit is set when its coefficient is above their median. Comes with a quality score. Frequency (15, 15): bit k is 2^k of a 256-bit number Exchanging hashes with systems that use PDQ, such as Meta's ThreatExchange; finer matching than 64 bits Meta's PDQ, as its C++ reference computes it
blockhash-v1 256 Cut the image into 16×16 blocks, sharing edge pixels by area; a bit is set when the block's R + G + B sum is above the median of its band of four rows. Transparent pixels count as white. Top-left block Images with transparency; matching blockhash hashes from other tools Yang, Gu and Niu's block mean value hash, as blockhash-python computes it
minhash-v1 128 values of 32 A signature, not a bit hash. Hash each feature with SHA-1 and mix it with MurmurHash3's finalizer; for each of 128 fixed permutations a × h + b mod 2^32, keep the smallest value over the set. Permutation 0's value Near-duplicate and edited texts, short ones included; any set of features Broder's MinHash, as datasketch 2.0.0 computes it by default (affine32)
minhash-legacy-v1 128 values of 32 The same shape. Hash each feature with SHA-1; for each of 128 fixed permutations modulo 2^61 - 1, keep the low 32 bits of the smallest value over the set. Permutation 0's value Agreeing with MinHash signatures datasketch made before 2.0.0 Broder's MinHash, as datasketch computed it by default from 1.1.3 to 1.9.0 (legacy)

The rustdoc of each function holds the full, normative definition. The v1 image hashes read 8-bit luma, converted from RGB with ITU-R 601-2 weights in the integer form Pillow uses, and reduce it with an exact area average in integer arithmetic. perceptual-v1 takes its DCT in exact integer arithmetic too, with a table of integer cosines. Given the same pixels at the working size (8×8, 9×8 or 32×32), all three give the same bits as ImageHash 4.3.2, and to_hex prints the same hex. The one exception is a perceptual-v1 coefficient within floating-point rounding of the median in ImageHash's own arithmetic, which takes the DCT with an FFT: such a bit can go either way there.

pdq-v1 and blockhash-v1 read RGBA. Given the same pixels, at any size, pdq_v1 gives the bits and the quality of Meta's PDQ C++ reference, built with GCC for x86-64, and to_hex prints Meta's hex; blockhash_v1 gives the bits and hex of blockhash-python's blockhash(image, 16). Neither resizes the image first, as neither reference does. PDQ's bits run the opposite way from the others': bit k is worth 2^k in the hex, so the first byte holds the highest frequencies, and chunks reads them in that order.

ImageHash reduces larger images with a Lanczos filter, so on full-size files the two differ. perceptual-v1 is usually identical to ImageHash's phash, or within a couple of bits; average-v1 commonly differs from average_hash by a few bits, and difference-v1 from dhash by several. So recompute hashes stored by another library rather than mix them with this crate's.

minhash-v1 is datasketch 2.0.0's default MinHash(num_perm=128, seed=1), its affine32 scheme: the first four bytes of the feature's SHA-1, little-endian, mixed once with MurmurHash3's 32-bit finalizer, then (a × h + b) mod 2^32 for each permutation, every a odd. Given the same features as bytes, it gives the same 128 values as datasketch 2.0.0's default.

minhash-legacy-v1 is datasketch's MinHash(num_perm=128, seed=1, scheme="legacy"): the first four bytes of the feature's SHA-1, little-endian, then ((a × h + b) mod 2^64) mod (2^61 - 1) for each permutation, low 32 bits kept. Given the same features as bytes, it gives the same 128 values as datasketch 2.0.0 with scheme="legacy". That's the scheme datasketch used from 1.1.3, when it began drawing its permutations with NumPy, and its default until 2.0.0: datasketch 1.9.0's default gives the same values. Releases before 1.1.3 drew other permutations.

For both, the 128 pairs (a, b) are a table taken from datasketch, not recomputed. SHA-1 is only a feature hash here, not a security measure.

Choosing an algorithm

  • To exchange hashes with other systems, use the algorithm they use: pdq-v1 for PDQ, as shared through Meta's ThreatExchange and the tools built on it; blockhash-v1 for blockhash, at 256 bits; perceptual-v1 to sit beside ImageHash's phash.
  • For your own store, perceptual-v1 is a sound default at 64 bits: one BIGINT a hash and integer keys. pdq-v1 costs four times the storage and more work per image, and in return has four times the bits to tell images apart, and a quality score to discard featureless images by.
  • blockhash-v1 is the only one that sees transparency, and the only 256-bit hash with no floating point. It doesn't blur or transform the image: each bit compares the brightness of one block.
  • None of them survives mirroring, rotation or a large crop. PDQ's reference can hash the eight rotations and mirrors of an image at once; this crate doesn't yet.

SimHash or MinHash?

  • simhash-v1 is one 64-bit value a text. It's cheap to store and to index, and its distance is Hamming distance, like the image hashes'. On short texts it carries little signal, and its distance isn't a calibrated measure of overlap.
  • minhash-v1 is 512 bytes a text, and its similarity is an estimate of the Jaccard similarity of the two feature sets, with a standard error of at most about 0.044. It holds up on short and on edited texts: a swapped word, a substituted letter or changed spacing touches only the shingles around it.

minhash-v1 or minhash-legacy-v1?

  • For new data, use minhash-v1. It's datasketch's current default, and new signatures from datasketch 2.0.0 or later agree with it.
  • To agree with signatures datasketch made before 2.0.0, or made with scheme="legacy", use minhash-legacy-v1. datasketch advises against the legacy scheme for new data: it folds a 61-bit range onto 32 bits, which makes features collide on very large sets, so their similarity reads high. datasketch measures two disjoint sets of a billion features at about 0.23, nearly twice the 0.12 of its default. In a measurement made before this release, the excess first showed at 10 million features per set, and not at all at the sizes of texts.
  • The two never mix. A signature, its stored form and its band keys belong to one definition: comparing or merging signatures of the two is an error, and keys of one never find the other's. Keep one definition per column, or store the id with the signature.

For MinHash on text, start with character shingles of 5 (minhash_v1_shingles(text, 5)), and normalise the text in your application first if case, runs of whitespace or Unicode form shouldn't count: lower-case it, collapse whitespace and apply NFC or NFKC. The crate does no Unicode normalisation, because a frozen definition can't depend on a Unicode version's tables.

Stored hashes and versions

The version is part of each algorithm's identity: in the Algorithm variant, in every function name, and in the string form, such as perceptual-v1:c3f00f3c99a5a55a.

  • A released definition never changes its output, on any platform. Every definition but pdq-v1 is integer arithmetic, with no floating point: the v1 image hashes, the DCT of perceptual-v1 included, blockhash-v1, whose block shares are exact sixteenths, and SimHash, which uses SipHash-2-4 with a fixed key, never std::hash::Hash. pdq-v1 is the f32 arithmetic of Meta's reference, operation by operation in its order, each operation IEEE-754 single precision rounded to nearest. On x86-64 and aarch64 that is Rust's f32, which the language guarantees rounds that way and never fuses or reorders; on every other target, where a platform may fall short, such as 32-bit x86 without SSE2, it's the same operations computed in integers. The one table of cosines is committed as bit patterns, so no platform maths library takes part.
  • A change ships as a new version beside the old one, such as perceptual-v2. The old version stays, so stored hashes can still be compared with new ones of the same version.
  • There's no "latest" or "default" algorithm. Upgrading the crate never changes what an application stores.
  • Comparing hashes of different algorithms or versions is an error, never a number.
  • A MinHash signature is a Signature, not a Hash: comparing one with a bit hash doesn't compile, and comparing signatures of different algorithms is an error. Its stored forms are the string minhash-v1: or minhash-legacy-v1: followed by 1,024 hex digits, the hex alone, 512 bytes (each of the 128 values big-endian, in order, so the hex reads as the values), and the 128 values themselves, which are datasketch's digest() in the same order. Only the string names the definition: the two definitions' values look alike, so the hex, the bytes and the values read back as whichever algorithm the caller names.
  • The two text tokenisers, words_v1 and shingles_v1, are frozen the same way. They use no Unicode tables, which change between Rust versions; normalise Unicode or fold case yourself before hashing if you need to.

Decoding isn't part of a definition: the definitions start from pixels. The two decoders, decode_luma_v1 and decode_rgba_v1, are versioned too: how they map greyscale, alpha and 16-bit files to pixels is frozen. A PNG decodes to the same pixels everywhere, but a JPEG decoder may round differently from another, or from a later version of itself, so the hash of a JPEG file can move by a few bits when the image crate changes.

Finding near matches

To find stored hashes within distance d of a new one, split each hash into d + 1 keys with Hash::chunks. Two hashes within distance d always share at least one key at the same position, because d differing bits can touch at most d chunks. Store each key in an indexed integer column, select the rows that share any key with the query, then check the exact distance:

-- Within distance 4: five keys of 13, 13, 13, 13 and 12 bits.
CREATE TABLE images (
    id BIGINT PRIMARY KEY,
    phash BIGINT NOT NULL,  -- hash.to_i64()
    k0 INTEGER NOT NULL, k1 INTEGER NOT NULL, k2 INTEGER NOT NULL,
    k3 INTEGER NOT NULL, k4 INTEGER NOT NULL
);
CREATE INDEX images_k0 ON images (k0);
-- ...and one index for each other key.

SELECT id, phash FROM images
WHERE k0 = $1 OR k1 = $2 OR k2 = $3 OR k3 = $4 OR k4 = $5;

Read each candidate back with Hash::from_i64(Algorithm::PerceptualV1, phash) and keep those whose distance is at most 4. to_i64 is the same bit pattern as to_u64, read as a signed integer, so it fits a BIGINT column. This is multi-index hashing. Fewer, wider keys select fewer candidates, so use the smallest count the guarantee allows, d + 1; more keys find the same matches among more candidates.

A 256-bit hash has no integer form: store its 32 bytes (as_bytes) or its hex. Its keys can be 4 to 256 a hash, each at most 64 bits. Within 15 bits, 16 keys of 16 bits work as above. Larger distances need more, narrower keys, and a key under about 16 bits matches a large share of any table: at Meta's suggested PDQ threshold of 31 bits, 32 keys of 8 bits each match about 1 row in 256. That suits a table of thousands of hashes; for millions, use an index built for Hamming search.

Band keys for MinHash

Chunk keys give every bit hash within a Hamming radius: a guarantee. Band keys give MinHash signatures that are probably above a similarity: a probability. Signature::band_keys(bands) splits the 128 values into bands equal bands, bands dividing 128, and hashes each band, its index included, into a 64-bit key with SipHash-2-4; band_keys_i64 gives the same keys for signed BIGINT columns. The index in the key means equal values in different bands give different keys, so the keys can share one indexed column or have a column each:

CREATE TABLE message_bands (message_id BIGINT NOT NULL, band_key BIGINT NOT NULL);
CREATE INDEX message_bands_key ON message_bands (band_key);

SELECT DISTINCT message_id FROM message_bands WHERE band_key IN ($1, $2, /* ... */ $32);

Look candidates up by key, then rank them by the full similarity of their stored signatures. Two texts with Jaccard similarity s share at least one key with probability 1 - (1 - s^r)^b for b bands of r values:

Bands × values s = 0.3 s = 0.5 s = 0.7 s = 0.85
16 × 8 0.1% 6.1% 61.3% 99.4%
32 × 4 22.9% 87.3% > 99.9% > 99.9%
64 × 2 99.8% > 99.9% > 99.9% > 99.9%

The chance climbs most steeply around a similarity of (1/b)^(1/r), where about two pairs in three share a key: 0.71 for 16 × 8, 0.42 for 32 × 4 and 0.13 for 64 × 2. Choose the bands that put it a little below the similarity you'll rank by; 64 bands match many unrelated pairs too, so they read many candidates. Both MinHash definitions make their keys the same way, but a key compares only with keys of one definition and one band count: keys made by minhash-v1 with 32 bands compare only with keys made by minhash-v1 with 32 bands, and nothing in a key says which made it. Every empty signature has the same keys, so leave empty ones (Signature::is_empty) out of the index.

Choosing a threshold

How many differing bits still mean "the same image" or "the same text" depends on the data: the kind of images, the edits they go through, the length of the texts and how they're tokenised. This crate makes no accuracy claim. Measure a threshold on a labelled sample of your own data, for each algorithm you use.

For 256-bit hashes, scale your expectations: two unrelated images sit around 128 bits apart, give or take about 8, where 64-bit hashes sit around 32. For PDQ, Meta suggests starting at a distance of 31 or less, and discarding hashes whose quality is 49 or less, which are mostly noise; both are starting points from their own data, not guarantees. blockhash publishes no threshold.

Limits

  • Decoding. The image feature decodes at most 16,384 pixels a side and at most 256 MiB of pixels, which for an 8-bit RGB file is about 89 megapixels. A larger image is refused. To hash one, decode it yourself and pass the RGB to LumaBuf::from_rgb8_v1 or the luma to Luma::new. GIF and WebP aren't decoded.
  • Hashing isn't a validity check. A truncated JPEG may decode with its missing part filled in and hash without an error.
  • Orientation and alpha. EXIF orientation isn't applied. Every image hash but blockhash-v1 ignores alpha: a transparent pixel counts as its stored colour, often black. blockhash-v1 counts a fully transparent pixel as white and ignores partial transparency. Apply the orientation or composite the image first if that matters.
  • Geometry. None of the image hashes survives mirroring, large crops, added borders or rotation by more than about a degree. That is the nature of a global hash.
  • No dihedral PDQ. Meta's reference can hash the eight rotations and mirrors of an image in one pass, from one DCT. This version computes only the hash of the image as given.
  • PDQ on flat or symmetric images. PDQ's coefficients are f32 sums. Where symmetry makes a coefficient zero in exact arithmetic, rounding leaves it a tiny positive or negative value, and its bit follows that residue. So a flat or symmetric image hashes to bits that mean nothing, with a low quality. They are the reference's bits too, and the quality score is there to discard them. A 64×64 image of one grey level is an example; an image under 5 pixels a side hashes to all zeros, with quality 0, as in the reference.
  • PDQ's reference depends on its build. The C++ reference built where the compiler fuses a multiply and an add into one instruction, as GCC does for aarch64 and for x86-64 with FMA enabled, rounds differently and gives different bits on some images: 5 of the 48 reference images here. This crate follows the x86-64 build without FMA, on every platform, i586 and other targets without IEEE-754 floating point included. Away from x86-64 and aarch64 it computes in integers, which takes about five times as long.
  • Large images and PDQ. The reference blurs the full image, so the crate does too, with two f32 copies of it, 8 bytes a pixel. Meta's paper suggests resizing large images to about 512×512 first for speed; if you do, the hash depends on your resizer.
  • Greyscale files and PDQ. Meta's file hasher takes a greyscale file's levels as luma. Algorithm::hash_encoded and decode_rgba_v1 make each level an RGB grey, whose PDQ luma lands a rounding step away for 35 of the 256 levels, which can move a bit. Hash a greyscale file with pdq_v1_luma and decode_luma_v1 to match the reference exactly.
  • One blockhash size. blockhash-v1 is 16×16 blocks, 256 bits, the size blockhash's published vectors use. On a side under 16 pixels, a block is narrower than a pixel and the reference's formula gives some blocks nothing; this crate follows it.
  • Words. words_v1 splits only on ASCII whitespace and punctuation. Text written without spaces, such as Chinese or Japanese, isn't split into words, and typographic punctuation such as ’ doesn't split either. Use shingles_v1 for such text, or normalise it first. Case folding is ASCII only.
  • Long and short texts. With words_v1 and every occurrence counted, long unrelated texts in one language land close together, because common words dominate. For long texts prefer shingles_v1 with a size of about 5, or weight and deduplicate the words before hashing. SimHash carries little signal for texts under about 50 words.
  • MinHash sees sets. A feature counts once however often it repeats, so MinHash ignores repetition and order beyond what the shingles capture. Its similarity is of the feature sets, so the shingle size and the normalisation decide what "similar" means: shorter shingles make unrelated texts in one language look closer, longer ones make small edits cost more.
  • Empty texts. A text with no features has the empty signature, every value u32::MAX, and two empty signatures estimate a similarity of 1.0, as datasketch's do. Check Signature::is_empty before treating two texts as duplicates.
  • Very large sets. Features are hashed to 32 bits, so on very large sets different features share a hash and the estimate reads high. datasketch puts this floor at about +0.001 at 10 million features per set, +0.01 at 100 million and +0.12 at a billion, for minhash-v1; minhash-legacy-v1 adds collisions of its own on top. Texts are far below that.
  • SHA-1. Both MinHash definitions hash features with SHA-1 to follow datasketch. It isn't a security measure: anyone can choose texts whose shingles collide.

Features

Feature Enables
image decode_luma_v1, decode_rgba_v1 and Algorithm::hash_encoded, which decode PNG and JPEG with the image crate. Files are limited to 64 MiB, and images to 16,384 pixels a side and to what the decoder can hold in 256 MiB, about 89 megapixels of 8-bit RGB; converting to RGB and luma, or to RGBA, adds at most about 1 GiB more, and hashing with PDQ about 2 GiB more. So a hostile file can't make it allocate without bound.
serde Serialize and Deserialize for Hash, Algorithm, Signature and SignatureAlgorithm, as their string forms.

With no features, the dependencies are siphasher, and RustCrypto's sha1 with its default features off, for MinHash. Nothing compiles C or downloads anything at build time.

Credits

  • Python ImageHash, by Johannes Buchner (BSD-2-Clause). average-v1, difference-v1 and perceptual-v1 follow its definitions, and its output is the pixel-level reference this crate is tested against.
  • Neal Krawetz's articles "Looks Like It" (2011), on the average hash and the DCT hash, and "Kind of Like That" (2013), on the difference hash; and pHash.org for the DCT approach.
  • Moses Charikar, "Similarity Estimation Techniques from Rounding Algorithms" (2002), and Gurmeet Singh Manku, Arvind Jain and Anish Das Sarma, "Detecting Near-Duplicates for Web Crawling" (2007), for SimHash.
  • Jean-Philippe Aumasson and Daniel J. Bernstein for SipHash, and the siphasher crate, by Frank Denis.
  • Mohammad Norouzi, Ali Punjani and David J. Fleet, "Fast Search in Hamming Space with Multi-Index Hashing" (2012), for chunk keys.
  • Meta's PDQ: the C++ reference in ThreatExchange (BSD), which pdq-v1 ports and is tested against, and the paper "The TMK+PDQF Video-Hashing Algorithm and the PDQ Image-Hashing Algorithm" (hashing/hashing.pdf in ThreatExchange). The reference cites Wojciech Jarosz, "Fast Image Convolutions" (2001), for its box filter, Christoph Zauner's "Implementation and Benchmarking of Perceptual Image Hash Functions" (2010) for its DCT, and Torben Mogensen for its median. The pdqhash Python package, which wraps the same C++ code, served as a cross-check.
  • Bian Yang, Fan Gu and Xiamu Niu, "Block Mean Value Based Image Perceptual Hashing" (2006), for the block mean value hash, and Commons Machinery's blockhash and blockhash-python (MIT), which blockhash-v1 follows and is tested against.
  • Andrei Z. Broder, "On the Resemblance and Containment of Documents" (1997), and Andrei Z. Broder, Moses Charikar, Alan M. Frieze and Michael Mitzenmacher, "Min-Wise Independent Permutations" (1998), for MinHash; and Jure Leskovec, Anand Rajaraman and Jeffrey D. Ullman, Mining of Massive Datasets, chapter 3, for banding signatures into keys.
  • datasketch, by ekzhu (MIT), which minhash-v1 and minhash-legacy-v1 follow and are tested against, and whose permutation parameters they hold: its current default, the affine32 scheme with its MurmurHash3 pre-mix, and its earlier legacy scheme.
  • Austin Appleby's MurmurHash3, whose 32-bit finalizer minhash-v1 mixes each feature hash with, as datasketch does.
  • The sha1 crate, by the RustCrypto developers.
  • The image crate, by the image-rs developers, for decoding.

The BSD notice of the PDQ reference, and the MIT notices of blockhash and datasketch, ship with the crate, in THIRD-PARTY-NOTICES.md.

Why not an existing crate?

image_hasher, simhash, pdqhash and blockhash are good crates. For hashes you compute and compare within one run of a program, they may be the better choice: image_hasher offers more algorithms today, such as double gradient, and configurable hash sizes, and blockhash offers 16, 64, 144 and 256-bit hashes, without std.

This crate exists for hashes that are stored. Each definition is written down, versioned and frozen, and gives the same output on every platform: every definition but pdq-v1 is integer arithmetic, and pdq-v1 is its reference's f32 arithmetic, pinned operation by operation. Given the same input, each image and MinHash definition agrees with a named reference: ImageHash, Meta's PDQ C++ reference, blockhash-python and datasketch. The established crates follow their own definitions:

  • As read in the source of image_hasher 3.1.1, it sets a bit when a value is greater than or equal to the threshold, its mean hash uses a truncated integer mean, its DCT hash is fed from an image twice the hash size (16×16 for 64 bits, where ImageHash uses 32×32), and it resizes with a configurable filter.
  • simhash 0.3.0 hashes features through std::hash::Hash, whose output Rust documents as not guaranteed to be stable across compiler versions.
  • pdqhash 0.1.1 (Apache-2.0, last released in 2022) is a careful port of the same C++ reference, in f32 too, from an image 0.23 DynamicImage. It follows its own choices in places: it resizes an image over 512 pixels a side with the image crate's thumbnail filter before hashing, where the reference blurs the full image; it filters a 64×64 image, which the reference takes as it is; its quality is a continuous number from 0 to 1, not the reference's integer score; and as read in its source, its DCT matrix differs from the one the reference computes in the last bits of most entries. So its hashes are close to the reference's, not equal.
  • blockhash 1.0.0 (MIT, 2024) computes in integers, as this crate does. Its tie rule compares a block equal to a median truncated to an integer against 382.5 a pixel, where the reference compares a block within 1 of the exact median against 384, and on a side under 16 pixels it shares pixels by area, where the reference doesn't. So at ties and on small images its bits differ from blockhash-python's.

For MinHash, gaoya and probminhash are the crates in wide use, and minhash-rs and datasketch-minhash-lsh are smaller ones:

  • gaoya 0.2.4 (MIT) is a fast, parallel LSH index held in memory, with Python bindings. Its signatures hash features through std::hash::Hash with a hasher you choose, FNV by default, with permutations modulo 2^31 - 1 drawn from rand's StdRng, which rand doesn't promise to keep reproducible across its versions, and its band keys use AHash under the index's random state. For an index rebuilt each time a program starts, it's a strong choice.
  • probminhash 0.1.12 (MIT or Apache-2.0) implements newer algorithms than classic MinHash: ProbMinHash for weighted Jaccard similarity, SuperMinHash, SetSketch and densified one-permutation hashing. They're faster on large sets, and the weighted ones see multiplicity, which this crate doesn't. For those needs, it's the better choice.
  • minhash-rs 0.6.0 (MIT) keeps sketches small in memory, with sparse forms that promote to dense ones; it hashes values through core::hash::Hash, with SipHash-1-3 by default.
  • datasketch-minhash-lsh 0.0.1 (MIT) ports the structure of datasketch's MinHash LSH, but hashes features with the standard library's DefaultHasher and draws its permutations from rand, so its values aren't datasketch's.

None of them is meant to give a stored signature that stays the same across versions and platforms and agrees with a named reference value for value, which is what minhash-v1 and minhash-legacy-v1 are for.

Each bit hash here is one Hash type and each MinHash signature one Signature type, with one stored form, <algorithm>:<hex>, so a database column, a comparison and the index keys work the same for every algorithm of a type, and comparing hashes or signatures of different algorithms is an error. Each definition is versioned and frozen, gives the same output on every platform, and is tested value for value against vectors captured from its reference, or, for simhash-v1, which has none, from an independent implementation.

Testing

The tests prove each definition three ways. Tier A checks hand-built buffers against values worked out by hand, or by a deliberately naive second implementation in the test, such as a direct DCT with f64::cos, a sorted median or a direct block sum. Tier B checks buffers against references bit for bit: buffers at working size against tests/fixtures/reference.json, captured from ImageHash 4.3.2 and Pillow, and buffers at full size against tests/fixtures/pdq-blockhash.json, captured from Meta's PDQ C++ reference, cross-checked with pdqhash 0.2.9, and from blockhash-python, hash and PDQ quality alike. Tier C hashes procedural images through PNG, JPEG, resizing and brightness changes, small committed files against the references' hashes of the same files, and texts with changed words, against stated bounds that are regression guards, not accuracy claims. Freeze guards hold the stored hash of fixed fixtures for every released definition.

minhash-v1 and minhash-legacy-v1 are tested the same way, each: against a few-line second implementation in 128-bit arithmetic with the permutations recorded from datasketch (tier A); against 64 feature sets from the empty set to 20,000 features, with duplicates, non-ASCII and invalid UTF-8 bytes, and their signatures captured from datasketch 2.0.0 (tier B): tests/fixtures/minhash-affine32.json from its default, as the SHA-1 of each signature and seven signatures in full, and tests/fixtures/minhash-legacy.json from scheme="legacy", every signature in full and checked against datasketch 1.9.0; and on seeded sets of known Jaccard similarity, whose estimates and shared band keys must track the truth and the formula within stated bounds, and on texts with light edits (tier C). Freeze guards hold their signatures and band keys, and tests check that the two never compare, merge or parse as each other.

cargo test -p legit-hashes

Changes in 0.2

New:

  • pdq-v1: pdq_v1, pdq_v1_luma, the Pdq result with its quality, and Algorithm::PdqV1.
  • blockhash-v1: blockhash_v1 and Algorithm::BlockhashV1.
  • Colour input: Rgba and RgbaBuf, Algorithm::hash_rgba, and with the image feature decode_rgba_v1.
  • 256-bit hashes, held inline like 64-bit ones.
  • MinHash set signatures: the Signature type with its stored forms, similarity, union and band keys, and SignatureAlgorithm, under two definitions:
    • minhash-v1, datasketch 2.0.0's default: minhash_v1, minhash_v1_shingles and MinHashV1.
    • minhash-legacy-v1, datasketch's default before 2.0.0: minhash_legacy_v1, minhash_legacy_v1_shingles and MinHashLegacyV1.

Breaking:

  • Algorithm::ALL is [Algorithm; 6], not [Algorithm; 4]: it lists the two new algorithms.
  • Hash is larger in memory, 33 bytes rather than 9, to hold 256 bits without allocating. Its stored forms, equality and Debug output for 64-bit hashes are unchanged.
  • Hash::chunks refuses a count that would make a key wider than 64 bits, so a 256-bit hash splits into 4 or more chunks. For 64-bit hashes nothing changes.
  • Algorithm::from_id with a MinHash id, and parsing a minhash-v1: or minhash-legacy-v1: string as a Hash, return Error::NotABitHash rather than Error::UnknownAlgorithm.
  • The crate depends on sha1, with its default features off.

Algorithm is #[non_exhaustive], so code that matches on it already has a wildcard arm, which the two new variants now reach. For them, Algorithm::bits returns 256, and to_u64, to_i64, from_u64 and from_i64 return Error::NoIntegerForm.

The four v1 definitions give the same bits, hex, bytes, integers and serde forms as in 0.1.0.

License

MIT. See LICENSE.md. The ported PDQ and blockhash code carry their own notices, in THIRD-PARTY-NOTICES.md.