@ac-kit/similarity-hash 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # @ac-kit/similarity-hash
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5152230: New package for similarity-preserving hashes compared by a distance.
8
+
9
+ - `hammingDistance(a, b)` counts the differing bits of two non-negative `bigint`
10
+ hashes (a metric, usable as `VpTree`'s distance); negative input throws
11
+ `RangeError`. `hammingDistancesInto(output, query, hashes)` writes the
12
+ distance from one 64-bit query to every hash of a `BigUint64Array` into a
13
+ `Uint8Array` without creating a `bigint` per hash.
14
+ - `@ac-kit/similarity-hash/image`: `phash(grid, { variant })` returns the 64-bit
15
+ DCT perceptual hash of a `LumaGrid` (`{ width, height, values: Uint8Array }`,
16
+ 8-bit luma, row-major) as a `bigint`, following `imagehash.phash`'s pipeline.
17
+ `variant` names the resampling to 32×32; `"box"` (exact area average, the
18
+ default, which never changes) is the only one today; on 32×32 grids it
19
+ agrees with `imagehash.phash` on every bit clear of the median. `values` must
20
+ be a `Uint8Array` (`TypeError` otherwise). `phashDetails` also returns
21
+ `undecidedBits`, the number of bits set by ties rather than by the image, to
22
+ skip uniform or featureless images before matching.
23
+
24
+ ### Patch Changes
25
+
26
+ - Updated dependencies [2a0fe74]
27
+ - Updated dependencies [5152230]
28
+ - Updated dependencies [2a0fe74]
29
+ - Updated dependencies [5152230]
30
+ - Updated dependencies [5152230]
31
+ - Updated dependencies [2a0fe74]
32
+ - Updated dependencies [2a0fe74]
33
+ - Updated dependencies [5152230]
34
+ - Updated dependencies [5152230]
35
+ - Updated dependencies [5152230]
36
+ - Updated dependencies [5152230]
37
+ - Updated dependencies [5152230]
38
+ - Updated dependencies [5152230]
39
+ - Updated dependencies [5152230]
40
+ - Updated dependencies [5152230]
41
+ - Updated dependencies [5152230]
42
+ - Updated dependencies [5152230]
43
+ - Updated dependencies [5152230]
44
+ - @ac-kit/core@0.10.0
45
+ - @ac-kit/math-signal@0.2.0
46
+ - @ac-kit/math-stats@0.3.0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,124 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/similarity-hash
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Similarity-preserving hashes compared by a distance: a perceptual image hash
4
+ (pHash) over an 8-bit luma grid, and the Hamming distance between hashes.
5
+
6
+ ## Scope
7
+
8
+ `@ac-kit/noncrypto-hash` holds hashes for _equality_: one changed byte gives an
9
+ unrelated value. The hashes here preserve _similarity_: close inputs give close
10
+ values, so near-duplicates are found by a distance rather than by `===`.
11
+
12
+ A hash compared by Hamming distance is a non-negative `bigint` whose width each
13
+ function documents. It compares with `===`, works as a `Map` key, and stores in a
14
+ `BigUint64Array`. Its hex form is `hash.toString(16).padStart(16, "0")` for 64
15
+ bits. To store one in a signed 64-bit column (SQLite `INTEGER`), convert with
16
+ `BigInt.asIntN(64, hash)` and read back with `BigInt.asUintN(64, value)`.
17
+
18
+ The package is portable (no `node:` imports) and synchronous; every call is
19
+ bounded by the size of its input.
20
+
21
+ ## Contents
22
+
23
+ | Symbol | Subpath | Description |
24
+ | ---------------------------------------------- | --------- | -------------------------------------------------------------------- |
25
+ | `hammingDistance(a, b)` | `.` | Number of differing bits; a metric (`Distance<bigint>`) |
26
+ | `hammingDistancesInto(output, query, hashes)` | `.` | The same against a whole `BigUint64Array`, without a `bigint` per hash |
27
+ | `LumaGrid` | `./image` | 8-bit greyscale image: `{ width, height, values: Uint8Array }` |
28
+ | `phash(grid, options?)` | `./image` | 64-bit DCT perceptual hash, the `imagehash.phash` pipeline; `TypeError` or `RangeError` for a malformed grid |
29
+ | `phashDetails(grid, { variant })` | `./image` | The hash and how many of its bits the image actually decides |
30
+
31
+ ## Hashing images
32
+
33
+ ```ts
34
+ import { hammingDistance } from "@ac-kit/similarity-hash";
35
+ import { type LumaGrid, phash } from "@ac-kit/similarity-hash/image";
36
+
37
+ function gradient(width: number, height: number, offset: number): LumaGrid {
38
+ const values = new Uint8Array(width * height);
39
+ for (let y = 0; y < height; y++) {
40
+ for (let x = 0; x < width; x++) {
41
+ values[y * width + x] = Math.min(255, (x * 3 + y * y) % 200 + offset);
42
+ }
43
+ }
44
+ return { width, height, values };
45
+ }
46
+
47
+ const original = phash(gradient(64, 64, 0));
48
+ const brighter = phash(gradient(64, 64, 10));
49
+
50
+ console.log(original.toString(16).padStart(16, "0")); // "849f83859da733ac"
51
+ console.log(hammingDistance(original, brighter)); // 0: brightness only moves the DC term
52
+ ```
53
+
54
+ A decoder gives RGB(A); convert it to luma first. To match `imagehash`, use
55
+ Pillow's `convert("L")` formula, `(19595·R + 38470·G + 7471·B + 0x8000) >> 16`.
56
+
57
+ ### Variants
58
+
59
+ pHash resamples the image to 32×32 before its DCT, and implementations differ in
60
+ that step. `variant` selects it:
61
+
62
+ - `"box"` (the default, and the only one today) — an exact floating-point area
63
+ average. On a 32×32 grid it agrees with `imagehash.phash` on every bit clear
64
+ of the median; bits tied with the median (`undecidedBits`) are set by
65
+ rounding and may differ. At other sizes it differs from `imagehash` by a few
66
+ bits.
67
+
68
+ Other variants may be added; the default never changes, so stored hashes stay
69
+ comparable.
70
+
71
+ ### Uniform and featureless images
72
+
73
+ Every uniform image hashes to `0x8000000000000000` (black to `0`): its AC
74
+ coefficients are all zero and tie with the median, so the bits say nothing about
75
+ the picture. Black, grey and white frames therefore all "match". `phashDetails`
76
+ counts such bits; skip images whose `undecidedBits` is high before matching.
77
+
78
+ ```ts
79
+ import { phashDetails } from "@ac-kit/similarity-hash/image";
80
+
81
+ const frame = {
82
+ width: 640,
83
+ height: 480,
84
+ values: new Uint8Array(640 * 480).fill(16),
85
+ };
86
+ const { hash, undecidedBits } = phashDetails(frame);
87
+ console.log(hash.toString(16), undecidedBits); // "8000000000000000" 63
88
+ ```
89
+
90
+ ## Finding near-duplicates
91
+
92
+ `hammingDistance` is a metric, so it serves as the distance of
93
+ `@ac-kit/data`'s `VpTree`. For a flat column of hashes, `hammingDistancesInto`
94
+ scans tens of millions of hashes per second.
95
+
96
+ ```ts
97
+ import { VpTree } from "@ac-kit/data";
98
+ import {
99
+ hammingDistance,
100
+ hammingDistancesInto,
101
+ } from "@ac-kit/similarity-hash";
102
+
103
+ const known = [0x8f3a00ff12345678n, 0x0123456789abcdefn, 0xfedcba9876543210n];
104
+ const query = 0x8f3a00ff12345679n;
105
+
106
+ const tree = new VpTree(hammingDistance, known);
107
+ for (const [hash, distance] of tree.within(query, 8)) {
108
+ console.log(hash.toString(16), distance); // "8f3a00ff12345678" 1
109
+ }
110
+
111
+ const distances = new Uint8Array(known.length);
112
+ hammingDistancesInto(distances, query, BigUint64Array.from(known));
113
+ console.log(distances); // Uint8Array [1, 33, 31]
114
+ ```
115
+
116
+ See the
117
+ [generated API docs](https://anthochamp.pages.grenadine.io/node-essentials/api/similarity-hash/)
118
+ for the full reference.
119
+
120
+ ## Licences
121
+
122
+ The pHash pipeline follows `imagehash` (BSD-2-Clause); its outputs are used as
123
+ test vectors and none of its code is copied. This is not the GPL `pHash` C++
124
+ library (phash.org), which is a different algorithm.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Number of differing bits between two hashes of the same width: popcount(a ⊕
3
+ * b).
4
+ *
5
+ * - A metric (identity, symmetry, triangle inequality), so it fits
6
+ * `@ac-kit/core`'s `Distance<bigint>` and serves as the distance of
7
+ * `@ac-kit/data`'s `VpTree`.
8
+ * - Width-agnostic: the leading zeros of a W-bit hash contribute nothing.
9
+ * Comparing hashes of different algorithms or widths is meaningless and is
10
+ * the caller's responsibility.
11
+ * - Complexity: one 64-bit SWAR popcount up to 64 bits; O(W) time and memory
12
+ * above, for the wider of the two widths (the XOR and its hex digits).
13
+ *
14
+ * @param a - A non-negative hash.
15
+ * @param b - A non-negative hash of the same algorithm.
16
+ * @returns The Hamming distance, from 0 to the hash width.
17
+ * @throws {RangeError} If either value is negative: hashes are unsigned, and a
18
+ * negative `bigint` has no finite width to compare. Convert a signed 64-bit
19
+ * column with `BigInt.asUintN(64, value)` first.
20
+ */
21
+ export declare function hammingDistance(a: bigint, b: bigint): number;
22
+ //# sourceMappingURL=hamming-distance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hamming-distance.d.ts","sourceRoot":"","sources":["../src/hamming-distance.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAO5D"}
@@ -0,0 +1,28 @@
1
+ import { bigIntPopCount } from "@ac-kit/core";
2
+ /**
3
+ * Number of differing bits between two hashes of the same width: popcount(a ⊕
4
+ * b).
5
+ *
6
+ * - A metric (identity, symmetry, triangle inequality), so it fits
7
+ * `@ac-kit/core`'s `Distance<bigint>` and serves as the distance of
8
+ * `@ac-kit/data`'s `VpTree`.
9
+ * - Width-agnostic: the leading zeros of a W-bit hash contribute nothing.
10
+ * Comparing hashes of different algorithms or widths is meaningless and is
11
+ * the caller's responsibility.
12
+ * - Complexity: one 64-bit SWAR popcount up to 64 bits; O(W) time and memory
13
+ * above, for the wider of the two widths (the XOR and its hex digits).
14
+ *
15
+ * @param a - A non-negative hash.
16
+ * @param b - A non-negative hash of the same algorithm.
17
+ * @returns The Hamming distance, from 0 to the hash width.
18
+ * @throws {RangeError} If either value is negative: hashes are unsigned, and a
19
+ * negative `bigint` has no finite width to compare. Convert a signed 64-bit
20
+ * column with `BigInt.asUintN(64, value)` first.
21
+ */
22
+ export function hammingDistance(a, b) {
23
+ if (a < 0n || b < 0n) {
24
+ throw new RangeError(`hashes must be non-negative, got ${a < 0n ? a : b} (use BigInt.asUintN to read a signed column)`);
25
+ }
26
+ return bigIntPopCount(a ^ b);
27
+ }
28
+ //# sourceMappingURL=hamming-distance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hamming-distance.js","sourceRoot":"","sources":["../src/hamming-distance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,eAAe,CAAC,CAAS,EAAE,CAAS;IACnD,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,UAAU,CACnB,oCAAoC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,+CAA+C,CACjG,CAAC;IACH,CAAC;IACD,OAAO,cAAc,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Writes the Hamming distance between `query` and each 64-bit hash of `hashes`
3
+ * into the same index of `output`: the bulk form of `hammingDistance` for a
4
+ * linear scan over a column of hashes.
5
+ *
6
+ * The scan reads `hashes` as 32-bit words and counts with `number` arithmetic,
7
+ * so no `bigint` is created per element: about 2 ns per hash against about 70
8
+ * ns for `hammingDistance` in a loop (Node 26, x64).
9
+ *
10
+ * - Complexity: O(n) time for n hashes, O(1) extra memory.
11
+ * - The element count is read once, at the call: a view over a growable buffer
12
+ * that grows meanwhile is scanned at its length at the call.
13
+ * - `output` and `hashes` may be disjoint views of one buffer, shared or not.
14
+ * Overlap is detected through the `buffer` objects; two distinct
15
+ * `SharedArrayBuffer` objects mapping the same memory (one posted between
16
+ * agents) cannot be told apart and must not overlap.
17
+ *
18
+ * @param output - Receives one distance (0–64) per hash.
19
+ * @param query - The hash to compare against, in [0, 2⁶⁴).
20
+ * @param hashes - The 64-bit hashes to compare.
21
+ * @throws {RangeError} If `output.length !== hashes.length`, `query` is
22
+ * negative or wider than 64 bits, or `output` overlaps the bytes of
23
+ * `hashes`.
24
+ */
25
+ export declare function hammingDistancesInto(output: Uint8Array, query: bigint, hashes: BigUint64Array): void;
26
+ //# sourceMappingURL=hamming-distances-into.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hamming-distances-into.d.ts","sourceRoot":"","sources":["../src/hamming-distances-into.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,cAAc,GACpB,IAAI,CAmCN"}
@@ -0,0 +1,58 @@
1
+ import { MASK_64N, popCount32 } from "@ac-kit/core";
2
+ /**
3
+ * Writes the Hamming distance between `query` and each 64-bit hash of `hashes`
4
+ * into the same index of `output`: the bulk form of `hammingDistance` for a
5
+ * linear scan over a column of hashes.
6
+ *
7
+ * The scan reads `hashes` as 32-bit words and counts with `number` arithmetic,
8
+ * so no `bigint` is created per element: about 2 ns per hash against about 70
9
+ * ns for `hammingDistance` in a loop (Node 26, x64).
10
+ *
11
+ * - Complexity: O(n) time for n hashes, O(1) extra memory.
12
+ * - The element count is read once, at the call: a view over a growable buffer
13
+ * that grows meanwhile is scanned at its length at the call.
14
+ * - `output` and `hashes` may be disjoint views of one buffer, shared or not.
15
+ * Overlap is detected through the `buffer` objects; two distinct
16
+ * `SharedArrayBuffer` objects mapping the same memory (one posted between
17
+ * agents) cannot be told apart and must not overlap.
18
+ *
19
+ * @param output - Receives one distance (0–64) per hash.
20
+ * @param query - The hash to compare against, in [0, 2⁶⁴).
21
+ * @param hashes - The 64-bit hashes to compare.
22
+ * @throws {RangeError} If `output.length !== hashes.length`, `query` is
23
+ * negative or wider than 64 bits, or `output` overlaps the bytes of
24
+ * `hashes`.
25
+ */
26
+ export function hammingDistancesInto(output, query, hashes) {
27
+ const count = hashes.length;
28
+ if (output.length !== count) {
29
+ throw new RangeError(`output.length must equal hashes.length (${count}), got ${output.length}`);
30
+ }
31
+ if (query < 0n || query > MASK_64N) {
32
+ throw new RangeError(`query must be in [0, 2^64), got ${query}`);
33
+ }
34
+ if (count === 0) {
35
+ return;
36
+ }
37
+ const hashesStart = hashes.byteOffset;
38
+ const hashesEnd = hashesStart + count * 8;
39
+ const outputStart = output.byteOffset;
40
+ const outputEnd = outputStart + count;
41
+ if (output.buffer === hashes.buffer &&
42
+ outputStart < hashesEnd &&
43
+ hashesStart < outputEnd) {
44
+ throw new RangeError("output must not overlap the bytes of hashes");
45
+ }
46
+ // Splitting the query through the same kind of view as the hashes keeps the
47
+ // word order right on either endianness.
48
+ const queryWords = new Uint32Array(BigUint64Array.of(query).buffer);
49
+ const first = queryWords[0];
50
+ const second = queryWords[1];
51
+ const words = new Uint32Array(hashes.buffer, hashesStart, count * 2);
52
+ for (let index = 0; index < count; index++) {
53
+ output[index] =
54
+ popCount32(words[2 * index] ^ first) +
55
+ popCount32(words[2 * index + 1] ^ second);
56
+ }
57
+ }
58
+ //# sourceMappingURL=hamming-distances-into.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hamming-distances-into.js","sourceRoot":"","sources":["../src/hamming-distances-into.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAEpD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,oBAAoB,CACnC,MAAkB,EAClB,KAAa,EACb,MAAsB;IAEtB,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5B,IAAI,MAAM,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;QAC7B,MAAM,IAAI,UAAU,CACnB,2CAA2C,KAAK,UAAU,MAAM,CAAC,MAAM,EAAE,CACzE,CAAC;IACH,CAAC;IACD,IAAI,KAAK,GAAG,EAAE,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;QACpC,MAAM,IAAI,UAAU,CAAC,mCAAmC,KAAK,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO;IACR,CAAC;IACD,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,CAAC;IACtC,MAAM,SAAS,GAAG,WAAW,GAAG,KAAK,GAAG,CAAC,CAAC;IAC1C,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,CAAC;IACtC,MAAM,SAAS,GAAG,WAAW,GAAG,KAAK,CAAC;IACtC,IACC,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM;QAC/B,WAAW,GAAG,SAAS;QACvB,WAAW,GAAG,SAAS,EACtB,CAAC;QACF,MAAM,IAAI,UAAU,CAAC,6CAA6C,CAAC,CAAC;IACrE,CAAC;IACD,4EAA4E;IAC5E,yCAAyC;IACzC,MAAM,UAAU,GAAG,IAAI,WAAW,CAAC,cAAc,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC;IACpE,MAAM,KAAK,GAAG,UAAU,CAAC,CAAC,CAAE,CAAC;IAC7B,MAAM,MAAM,GAAG,UAAU,CAAC,CAAC,CAAE,CAAC;IAC9B,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IACrE,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,CAAC,KAAK,CAAC;YACZ,UAAU,CAAC,KAAK,CAAC,CAAC,GAAG,KAAK,CAAE,GAAG,KAAK,CAAC;gBACrC,UAAU,CAAC,KAAK,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAE,GAAG,MAAM,CAAC,CAAC;IAC7C,CAAC;AACF,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { LumaGrid } from "./luma-grid.js";
2
+ /**
3
+ * @throws {TypeError} If `values` is not a `Uint8Array`.
4
+ * @throws {RangeError} If the grid's dimensions and length disagree.
5
+ */
6
+ export declare function assertLumaGrid_(grid: LumaGrid): void;
7
+ //# sourceMappingURL=_assert-luma-grid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_assert-luma-grid.d.ts","sourceRoot":"","sources":["../../src/image/_assert-luma-grid.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,CAoBpD"}
@@ -0,0 +1,21 @@
1
+ import { isUint8Array } from "@ac-kit/core";
2
+ /**
3
+ * @throws {TypeError} If `values` is not a `Uint8Array`.
4
+ * @throws {RangeError} If the grid's dimensions and length disagree.
5
+ */
6
+ export function assertLumaGrid_(grid) {
7
+ const { width, height, values } = grid;
8
+ if (!isUint8Array(values)) {
9
+ throw new TypeError(`values must be a Uint8Array, got ${Object.prototype.toString.call(values)}`);
10
+ }
11
+ if (!Number.isSafeInteger(width) || width < 1) {
12
+ throw new RangeError(`width must be a positive safe integer, got ${width}`);
13
+ }
14
+ if (!Number.isSafeInteger(height) || height < 1) {
15
+ throw new RangeError(`height must be a positive safe integer, got ${height}`);
16
+ }
17
+ if (values.length !== width * height) {
18
+ throw new RangeError(`values.length must be width * height (${width * height}), got ${values.length}`);
19
+ }
20
+ }
21
+ //# sourceMappingURL=_assert-luma-grid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_assert-luma-grid.js","sourceRoot":"","sources":["../../src/image/_assert-luma-grid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,IAAc;IAC7C,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACvC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,SAAS,CAClB,oCAAoC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAC5E,CAAC;IACH,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,UAAU,CAAC,8CAA8C,KAAK,EAAE,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,UAAU,CACnB,+CAA+C,MAAM,EAAE,CACvD,CAAC;IACH,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,KAAK,GAAG,MAAM,EAAE,CAAC;QACtC,MAAM,IAAI,UAAU,CACnB,yCAAyC,KAAK,GAAG,MAAM,UAAU,MAAM,CAAC,MAAM,EAAE,CAChF,CAAC;IACH,CAAC;AACF,CAAC"}
@@ -0,0 +1,22 @@
1
+ import type { LumaGrid } from "./luma-grid.js";
2
+ /**
3
+ * Area-average (box) resampling of a luma grid to `size`×`size`, in floating
4
+ * point with no intermediate rounding.
5
+ *
6
+ * Each output sample is the mean of the input over its footprint, with partial
7
+ * pixels weighted by their covered fraction; this both downscales and upscales.
8
+ * In units of 1/(size·width) of the image width, input column x spans [size·x,
9
+ * size·(x+1)) and output column o spans [width·o, width·(o+1)), so every
10
+ * overlap is an integer and the weighted sum is exact: the result is one
11
+ * correctly rounded division of an integer below 255·width·height < 2⁵³. A grid
12
+ * already `size`×`size` therefore comes back unchanged.
13
+ *
14
+ * O(height·(width + size) + size²) time, streaming one input row at a time:
15
+ * O(size²) memory whatever the input size.
16
+ *
17
+ * @param grid - A validated grid.
18
+ * @param size - Output side, a positive integer.
19
+ * @returns `size * size` samples, row-major.
20
+ */
21
+ export declare function boxResize_(grid: LumaGrid, size: number): Float64Array;
22
+ //# sourceMappingURL=_box-resize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_box-resize.d.ts","sourceRoot":"","sources":["../../src/image/_box-resize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,CAmCrE"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Area-average (box) resampling of a luma grid to `size`×`size`, in floating
3
+ * point with no intermediate rounding.
4
+ *
5
+ * Each output sample is the mean of the input over its footprint, with partial
6
+ * pixels weighted by their covered fraction; this both downscales and upscales.
7
+ * In units of 1/(size·width) of the image width, input column x spans [size·x,
8
+ * size·(x+1)) and output column o spans [width·o, width·(o+1)), so every
9
+ * overlap is an integer and the weighted sum is exact: the result is one
10
+ * correctly rounded division of an integer below 255·width·height < 2⁵³. A grid
11
+ * already `size`×`size` therefore comes back unchanged.
12
+ *
13
+ * O(height·(width + size) + size²) time, streaming one input row at a time:
14
+ * O(size²) memory whatever the input size.
15
+ *
16
+ * @param grid - A validated grid.
17
+ * @param size - Output side, a positive integer.
18
+ * @returns `size * size` samples, row-major.
19
+ */
20
+ export function boxResize_(grid, size) {
21
+ const { width, height, values } = grid;
22
+ const sums = new Float64Array(size * size);
23
+ const rowSums = new Float64Array(size);
24
+ for (let y = 0; y < height; y++) {
25
+ const rowOffset = y * width;
26
+ for (let column = 0; column < size; column++) {
27
+ const start = width * column;
28
+ const end = start + width;
29
+ const lastX = Math.ceil(end / size) - 1;
30
+ let sum = 0;
31
+ for (let x = Math.floor(start / size); x <= lastX; x++) {
32
+ const overlap = Math.min(end, size * (x + 1)) - Math.max(start, size * x);
33
+ sum += values[rowOffset + x] * overlap;
34
+ }
35
+ rowSums[column] = sum;
36
+ }
37
+ const top = size * y;
38
+ const bottom = top + size;
39
+ const lastRow = Math.ceil(bottom / height) - 1;
40
+ for (let row = Math.floor(top / height); row <= lastRow; row++) {
41
+ const overlap = Math.min(bottom, height * (row + 1)) - Math.max(top, height * row);
42
+ const offset = row * size;
43
+ for (let column = 0; column < size; column++) {
44
+ sums[offset + column] += rowSums[column] * overlap;
45
+ }
46
+ }
47
+ }
48
+ const area = width * height;
49
+ for (let index = 0; index < sums.length; index++) {
50
+ sums[index] = sums[index] / area;
51
+ }
52
+ return sums;
53
+ }
54
+ //# sourceMappingURL=_box-resize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_box-resize.js","sourceRoot":"","sources":["../../src/image/_box-resize.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,UAAU,CAAC,IAAc,EAAE,IAAY;IACtD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACvC,MAAM,IAAI,GAAG,IAAI,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;IACvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,MAAM,SAAS,GAAG,CAAC,GAAG,KAAK,CAAC;QAC5B,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;YAC9C,MAAM,KAAK,GAAG,KAAK,GAAG,MAAM,CAAC;YAC7B,MAAM,GAAG,GAAG,KAAK,GAAG,KAAK,CAAC;YAC1B,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;YACxC,IAAI,GAAG,GAAG,CAAC,CAAC;YACZ,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;gBACxD,MAAM,OAAO,GACZ,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC;gBAC3D,GAAG,IAAI,MAAM,CAAC,SAAS,GAAG,CAAC,CAAE,GAAG,OAAO,CAAC;YACzC,CAAC;YACD,OAAO,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC;QACvB,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,CAAC;QACrB,MAAM,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC;QAC1B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC/C,KAAK,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,IAAI,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC;YAChE,MAAM,OAAO,GACZ,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC,CAAC;YACpE,MAAM,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC;YAC1B,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;gBAC9C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAE,IAAI,OAAO,CAAC,MAAM,CAAE,GAAG,OAAO,CAAC;YACtD,CAAC;QACF,CAAC;IACF,CAAC;IACD,MAAM,IAAI,GAAG,KAAK,GAAG,MAAM,CAAC;IAC5B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,CAAE,GAAG,IAAI,CAAC;IACnC,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./luma-grid.js";
2
+ export * from "./phash.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/image/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./luma-grid.js";
2
+ export * from "./phash.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/image/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * An 8-bit greyscale image: Y′ luma (black 0, white 255), row-major, with no
3
+ * row padding. Element (x, y) is `values[y * width + x]`.
4
+ *
5
+ * To reproduce `imagehash` results, compute Y′ the way Pillow's `convert("L")`
6
+ * does: ITU-R 601-2 on gamma-encoded RGB, `(19595·R + 38470·G + 7471·B +
7
+ * 0x8000) >> 16`, ignoring alpha. EXIF orientation and colour management are
8
+ * the caller's.
9
+ */
10
+ export interface LumaGrid {
11
+ /** Number of columns, a positive safe integer. */
12
+ readonly width: number;
13
+ /** Number of rows, a positive safe integer. */
14
+ readonly height: number;
15
+ /** `width * height` luma samples, row-major. */
16
+ readonly values: Uint8Array;
17
+ }
18
+ //# sourceMappingURL=luma-grid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"luma-grid.d.ts","sourceRoot":"","sources":["../../src/image/luma-grid.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,WAAW,QAAQ;IACxB,kDAAkD;IAClD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC5B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=luma-grid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"luma-grid.js","sourceRoot":"","sources":["../../src/image/luma-grid.ts"],"names":[],"mappings":""}
@@ -0,0 +1,95 @@
1
+ import type { LumaGrid } from "./luma-grid.js";
2
+ /**
3
+ * How {@link phash} brings an image to the 32×32 grid it transforms; every
4
+ * variant then shares the imagehash pipeline (DCT, 8×8 block, median).
5
+ *
6
+ * - `"box"` — area average in floating point, with no rounding between passes.
7
+ * Defined for every size, exact (one correctly rounded division per sample)
8
+ * and therefore identical across implementations of this contract. It is not
9
+ * Pillow's resampler, so above or below 32×32 its hash differs from
10
+ * `imagehash.phash` by a few bits.
11
+ *
12
+ * Every variant leaves a 32×32 grid untouched, so at that size they all agree
13
+ * with `imagehash.phash` on every bit clear of the median (see
14
+ * {@link PhashDetails.undecidedBits}). Further values (a Pillow-LANCZOS variant
15
+ * bit-compatible with `imagehash`, a goimagehash variant matching Stash and
16
+ * StashDB fingerprints) are planned; adding one changes no existing result.
17
+ */
18
+ export type PhashVariant = "box";
19
+ /** Options of {@link phash} and {@link phashDetails}. */
20
+ export interface PhashOptions {
21
+ /**
22
+ * Resampling variant. Defaults to `"box"`, a default that never changes:
23
+ * hashes stored today stay comparable with hashes computed later.
24
+ */
25
+ readonly variant?: PhashVariant;
26
+ }
27
+ /** Result of {@link phashDetails}. */
28
+ export interface PhashDetails {
29
+ /** The 64-bit hash, as {@link phash} returns it. */
30
+ readonly hash: bigint;
31
+ /**
32
+ * Number of bits (0–64) whose coefficient lies within 1e-9 of the largest
33
+ * coefficient magnitude from the median: such a bit is set by a tie or by
34
+ * rounding, not by the image, and two implementations may set it differently.
35
+ * 0 for a typical photograph; 64 for a black image, 63 for any other uniform
36
+ * one, and high for images with little structure (a pure gradient, a fine
37
+ * checkerboard). A caller matching near-duplicates should not trust a match
38
+ * between hashes with many undecided bits: every uniform image hashes alike.
39
+ */
40
+ readonly undecidedBits: number;
41
+ }
42
+ /**
43
+ * The pHash (DCT perceptual hash), following the pipeline of
44
+ * `imagehash.phash(image)` at its defaults (`hash_size=8`,
45
+ * `highfreq_factor=4`):
46
+ *
47
+ * 1. Resample to 32×32 as `options.variant` says ({@link PhashVariant}). A 32×32
48
+ * grid is used as-is.
49
+ * 2. Unnormalised 2D DCT-II (`@ac-kit/math-signal`'s DCT, `"backward"` norm, as
50
+ * `scipy.fftpack.dct`).
51
+ * 3. The 8×8 block of lowest frequencies, DC included: row u is the vertical
52
+ * frequency, column v the horizontal one.
53
+ * 4. Bit (u, v) = coefficient > median of the 64 (the mean of the two middle
54
+ * values), at position 63 − (8u + v).
55
+ *
56
+ * - Result: a 64-bit `bigint`. `phash(g).toString(16).padStart(16, "0")` is the
57
+ * hex form; on a 32×32 grid its bits clear of the median equal those of
58
+ * `str(imagehash.phash(img))` for the same luma bytes. Bits tied with the
59
+ * median are set by floating-point rounding, which differs between this DCT
60
+ * and SciPy's, so the two may disagree there (a periodic pattern can tie
61
+ * dozens of coefficients at zero). Compare hashes with `hammingDistance`.
62
+ * - Low-information images: when coefficients tie with the median, as the zero AC
63
+ * terms of a uniform image do, bits are decided by ties or rounding noise
64
+ * rather than content. Every uniform image hashes to `0x8000000000000000`
65
+ * (black to `0n`), so uniform frames all match each other. Use
66
+ * {@link phashDetails} to detect this.
67
+ * - The hash depends on the grid as given: downscaling before the call (a
68
+ * thumbnail, for example) changes bits slightly. Hash every image through the
69
+ * same pipeline and variant.
70
+ * - Complexity: O(W·H) time for the resampling (O(H·(W + 32)) exactly) plus a
71
+ * constant 32×32 DCT; O(1) memory beyond a few kilobytes of scratch, whatever
72
+ * the image size. Synchronous: a large image blocks for its scan.
73
+ *
74
+ * @param grid - The image, see {@link LumaGrid}.
75
+ * @param options - Variant selection.
76
+ * @returns The 64-bit hash.
77
+ * @throws {TypeError} If `values` is not a `Uint8Array` (from any realm, or a
78
+ * subclass such as Node's `Buffer`).
79
+ * @throws {RangeError} If `width` or `height` is not a positive safe integer,
80
+ * `values.length !== width * height`, or `variant` is unknown.
81
+ */
82
+ export declare function phash(grid: LumaGrid, options?: PhashOptions): bigint;
83
+ /**
84
+ * {@link phash} and how many of its bits the image actually decides, for
85
+ * filtering out low-information images (uniform frames, flat gradients) before
86
+ * matching. Same cost as {@link phash}.
87
+ *
88
+ * @param grid - The image, see {@link LumaGrid}.
89
+ * @param options - Variant selection.
90
+ * @returns The hash and its count of undecided bits.
91
+ * @throws {TypeError} As {@link phash}.
92
+ * @throws {RangeError} As {@link phash}.
93
+ */
94
+ export declare function phashDetails(grid: LumaGrid, options?: PhashOptions): PhashDetails;
95
+ //# sourceMappingURL=phash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phash.d.ts","sourceRoot":"","sources":["../../src/image/phash.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC;AAEjC,yDAAyD;AACzD,MAAM,WAAW,YAAY;IAC5B;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,YAAY,CAAC;CAChC;AAED,sCAAsC;AACtC,MAAM,WAAW,YAAY;IAC5B,oDAAoD;IACpD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB;;;;;;;;OAQG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAC/B;AAQD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,MAAM,CAEpE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAC3B,IAAI,EAAE,QAAQ,EACd,OAAO,CAAC,EAAE,YAAY,GACpB,YAAY,CA0Cd"}
@@ -0,0 +1,105 @@
1
+ import { createDct2d } from "@ac-kit/math-signal";
2
+ import { median } from "@ac-kit/math-stats";
3
+ import { assertLumaGrid_ } from "./_assert-luma-grid.js";
4
+ import { boxResize_ } from "./_box-resize.js";
5
+ const SIDE = 32;
6
+ const BLOCK = 8;
7
+ const RELATIVE_TIE = 1e-9;
8
+ let dctPlan;
9
+ /**
10
+ * The pHash (DCT perceptual hash), following the pipeline of
11
+ * `imagehash.phash(image)` at its defaults (`hash_size=8`,
12
+ * `highfreq_factor=4`):
13
+ *
14
+ * 1. Resample to 32×32 as `options.variant` says ({@link PhashVariant}). A 32×32
15
+ * grid is used as-is.
16
+ * 2. Unnormalised 2D DCT-II (`@ac-kit/math-signal`'s DCT, `"backward"` norm, as
17
+ * `scipy.fftpack.dct`).
18
+ * 3. The 8×8 block of lowest frequencies, DC included: row u is the vertical
19
+ * frequency, column v the horizontal one.
20
+ * 4. Bit (u, v) = coefficient > median of the 64 (the mean of the two middle
21
+ * values), at position 63 − (8u + v).
22
+ *
23
+ * - Result: a 64-bit `bigint`. `phash(g).toString(16).padStart(16, "0")` is the
24
+ * hex form; on a 32×32 grid its bits clear of the median equal those of
25
+ * `str(imagehash.phash(img))` for the same luma bytes. Bits tied with the
26
+ * median are set by floating-point rounding, which differs between this DCT
27
+ * and SciPy's, so the two may disagree there (a periodic pattern can tie
28
+ * dozens of coefficients at zero). Compare hashes with `hammingDistance`.
29
+ * - Low-information images: when coefficients tie with the median, as the zero AC
30
+ * terms of a uniform image do, bits are decided by ties or rounding noise
31
+ * rather than content. Every uniform image hashes to `0x8000000000000000`
32
+ * (black to `0n`), so uniform frames all match each other. Use
33
+ * {@link phashDetails} to detect this.
34
+ * - The hash depends on the grid as given: downscaling before the call (a
35
+ * thumbnail, for example) changes bits slightly. Hash every image through the
36
+ * same pipeline and variant.
37
+ * - Complexity: O(W·H) time for the resampling (O(H·(W + 32)) exactly) plus a
38
+ * constant 32×32 DCT; O(1) memory beyond a few kilobytes of scratch, whatever
39
+ * the image size. Synchronous: a large image blocks for its scan.
40
+ *
41
+ * @param grid - The image, see {@link LumaGrid}.
42
+ * @param options - Variant selection.
43
+ * @returns The 64-bit hash.
44
+ * @throws {TypeError} If `values` is not a `Uint8Array` (from any realm, or a
45
+ * subclass such as Node's `Buffer`).
46
+ * @throws {RangeError} If `width` or `height` is not a positive safe integer,
47
+ * `values.length !== width * height`, or `variant` is unknown.
48
+ */
49
+ export function phash(grid, options) {
50
+ return phashDetails(grid, options).hash;
51
+ }
52
+ /**
53
+ * {@link phash} and how many of its bits the image actually decides, for
54
+ * filtering out low-information images (uniform frames, flat gradients) before
55
+ * matching. Same cost as {@link phash}.
56
+ *
57
+ * @param grid - The image, see {@link LumaGrid}.
58
+ * @param options - Variant selection.
59
+ * @returns The hash and its count of undecided bits.
60
+ * @throws {TypeError} As {@link phash}.
61
+ * @throws {RangeError} As {@link phash}.
62
+ */
63
+ export function phashDetails(grid, options) {
64
+ const variant = options?.variant ?? "box";
65
+ if (variant !== "box") {
66
+ throw new RangeError(`unknown pHash variant ${String(variant)}`);
67
+ }
68
+ assertLumaGrid_(grid);
69
+ const resized = boxResize_(grid, SIDE);
70
+ dctPlan ??= createDct2d({ rows: SIDE, columns: SIDE });
71
+ const transformed = new Float64Array(SIDE * SIDE);
72
+ dctPlan.forwardInto(transformed, resized);
73
+ const block = [];
74
+ let largest = 0;
75
+ for (let row = 0; row < BLOCK; row++) {
76
+ for (let column = 0; column < BLOCK; column++) {
77
+ const coefficient = transformed[row * SIDE + column];
78
+ block.push(coefficient);
79
+ largest = Math.max(largest, Math.abs(coefficient));
80
+ }
81
+ }
82
+ const threshold = median(block);
83
+ const tie = RELATIVE_TIE * largest;
84
+ // Two 32-bit halves avoid a bigint operation per bit.
85
+ let high = 0;
86
+ let low = 0;
87
+ let undecidedBits = 0;
88
+ for (let index = 0; index < block.length; index++) {
89
+ const coefficient = block[index];
90
+ if (Math.abs(coefficient - threshold) <= tie) {
91
+ undecidedBits++;
92
+ }
93
+ if (coefficient > threshold) {
94
+ if (index < 32) {
95
+ high |= 1 << (31 - index);
96
+ }
97
+ else {
98
+ low |= 1 << (63 - index);
99
+ }
100
+ }
101
+ }
102
+ const hash = (BigInt(high >>> 0) << 32n) | BigInt(low >>> 0);
103
+ return { hash, undecidedBits };
104
+ }
105
+ //# sourceMappingURL=phash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phash.js","sourceRoot":"","sources":["../../src/image/phash.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,3 @@
1
+ export * from "./hamming-distance.js";
2
+ export * from "./hamming-distances-into.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./hamming-distance.js";
2
+ export * from "./hamming-distances-into.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@ac-kit/similarity-hash",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Similarity-preserving hashes compared by a distance: perceptual image hash (pHash) over an 8-bit luma grid, and Hamming distance.",
5
+ "keywords": [
6
+ "hamming",
7
+ "image",
8
+ "perceptual-hash",
9
+ "phash",
10
+ "similarity"
11
+ ],
12
+ "homepage": "https://anthochamp.pages.grenadine.io/node-essentials/api/similarity-hash/",
13
+ "bugs": {
14
+ "url": "https://git.grenadine.io/anthochamp/node-essentials/issues"
15
+ },
16
+ "license": "BSD-3-Clause",
17
+ "author": "Anthony Champagne <dev@anthonychampagne.fr>",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://git.grenadine.io/anthochamp/node-essentials.git",
21
+ "directory": "packages/similarity-hash"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "main": "./dist/index.js",
29
+ "exports": {
30
+ ".": "./dist/index.js",
31
+ "./image": "./dist/image/index.js"
32
+ },
33
+ "publishConfig": {
34
+ "main": "./dist/index.js",
35
+ "exports": {
36
+ ".": "./dist/index.js",
37
+ "./image": "./dist/image/index.js"
38
+ },
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "compile": "tsc -p ./tsconfig.build.json -outDir dist",
43
+ "compile:check": "tsc -noEmit -p ./tsconfig.json",
44
+ "clean": "rimraf dist",
45
+ "build": "yarn clean && yarn compile",
46
+ "test": "yarn run -T vitest run",
47
+ "prepack": "yarn build"
48
+ },
49
+ "dependencies": {
50
+ "@ac-kit/core": "^0.10.0",
51
+ "@ac-kit/math-signal": "^0.2.0",
52
+ "@ac-kit/math-stats": "^0.3.0",
53
+ "@types/web": "^0.0.367"
54
+ },
55
+ "devDependencies": {
56
+ "@ac-kit/data": "0.3.2",
57
+ "@ac-kit/math-random": "0.2.0",
58
+ "@ac-kit/tsconfig": "0.1.0",
59
+ "@ac-kit/typedoc-config": "0.1.0",
60
+ "@ac-kit/vitest-config": "0.1.1",
61
+ "@typescript/native": "typescript@7.0.2",
62
+ "rimraf": "6.1.4",
63
+ "typedoc": "0.28.20",
64
+ "typescript": "@typescript/typescript6@6.0.2"
65
+ },
66
+ "engines": {
67
+ "node": ">=24"
68
+ }
6
69
  }