snarlik 0.2.0__py3-none-win_amd64.whl
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.
- snarlik/__init__.py +67 -0
- snarlik/py.typed +0 -0
- snarlik-0.2.0.data/scripts/snarlik.exe +0 -0
- snarlik-0.2.0.dist-info/METADATA +260 -0
- snarlik-0.2.0.dist-info/RECORD +7 -0
- snarlik-0.2.0.dist-info/WHEEL +4 -0
- snarlik-0.2.0.dist-info/licenses/LICENSE +22 -0
snarlik/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""snarlik: every pair of near-identical strings, scored as pg_trgm does.
|
|
2
|
+
|
|
3
|
+
The wheel carries the snarlik binary; this module runs it.
|
|
4
|
+
|
|
5
|
+
>>> import snarlik
|
|
6
|
+
>>> snarlik.self_join(["The Daily", "the daily!", "Daily Show"], threshold=0.85)
|
|
7
|
+
[(0, 1, 1.0)]
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import sysconfig
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
|
|
19
|
+
__all__ = ["find_snarlik_bin", "self_join"]
|
|
20
|
+
|
|
21
|
+
_EXE = "snarlik" + (".exe" if sys.platform == "win32" else "")
|
|
22
|
+
_NULL = "\\N"
|
|
23
|
+
_ESCAPES = str.maketrans({"\\": "\\\\", "\t": "\\t", "\n": "\\n", "\r": "\\r"})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find_snarlik_bin() -> str:
|
|
27
|
+
"""Path of the snarlik binary this package installed."""
|
|
28
|
+
schemes = [sysconfig.get_default_scheme()]
|
|
29
|
+
user = sysconfig.get_preferred_scheme("user")
|
|
30
|
+
if user not in schemes:
|
|
31
|
+
schemes.append(user)
|
|
32
|
+
for scheme in schemes:
|
|
33
|
+
path = os.path.join(sysconfig.get_path("scripts", scheme), _EXE)
|
|
34
|
+
if os.path.isfile(path):
|
|
35
|
+
return path
|
|
36
|
+
# Installed with --target or --prefix: bin/ next to the package's root.
|
|
37
|
+
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
38
|
+
for path in (os.path.join(root, "bin", _EXE), shutil.which(_EXE)):
|
|
39
|
+
if path and os.path.isfile(path):
|
|
40
|
+
return path
|
|
41
|
+
raise FileNotFoundError(f"the {_EXE} binary isn't installed next to this package")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def self_join(
|
|
45
|
+
texts: Sequence[str | None], threshold: float = 0.3, threads: int | None = None
|
|
46
|
+
) -> list[tuple[int, int, float]]:
|
|
47
|
+
"""Every pair (i, j, similarity) of texts whose pg_trgm similarity is at
|
|
48
|
+
least threshold, with i < j indexes into texts and the score Postgres's
|
|
49
|
+
similarity() gives. None entries are skipped, like NULL. Pairs come in
|
|
50
|
+
no particular order. threads: at most one per CPU, the default."""
|
|
51
|
+
if not 0 < threshold <= 1:
|
|
52
|
+
raise ValueError(f"threshold must be in (0, 1], got {threshold}")
|
|
53
|
+
rows = "".join(
|
|
54
|
+
f"{i}\t{_NULL if t is None else t.translate(_ESCAPES)}\n" for i, t in enumerate(texts)
|
|
55
|
+
)
|
|
56
|
+
args = [find_snarlik_bin(), "-t", repr(float(threshold))]
|
|
57
|
+
if threads is not None:
|
|
58
|
+
args += ["-j", str(threads)]
|
|
59
|
+
out = subprocess.run(args, input=rows.encode(), capture_output=True, check=False)
|
|
60
|
+
if out.returncode != 0:
|
|
61
|
+
raise RuntimeError(f"snarlik failed: {out.stderr.decode(errors='replace').strip()}")
|
|
62
|
+
pairs = []
|
|
63
|
+
for line in out.stdout.splitlines():
|
|
64
|
+
a, b, sim = line.split(b"\t")
|
|
65
|
+
i, j = int(a), int(b)
|
|
66
|
+
pairs.append((i, j, float(sim)) if i < j else (j, i, float(sim)))
|
|
67
|
+
return pairs
|
snarlik/py.typed
ADDED
|
File without changes
|
|
Binary file
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: snarlik
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Every pair of near-identical strings, with the scores PostgreSQL's pg_trgm gives
|
|
5
|
+
Author: Jan K. Griffioen-Järfalk
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Project-URL: Homepage, https://github.com/u840903/snarlik
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# snarlik
|
|
13
|
+
|
|
14
|
+
[](https://github.com/u840903/snarlik/actions/workflows/ci.yml)
|
|
15
|
+
[](LICENSE)
|
|
16
|
+
|
|
17
|
+
Find every pair of near-identical strings in a list, with the same scores
|
|
18
|
+
PostgreSQL's `pg_trgm` gives, without the database. Written in Zig.
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
$ printf '1\tThe Daily\n2\tthe daily!\n3\tDaily Show\n' | snarlik -t 0.85
|
|
22
|
+
1 2 1
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
*Snarlik* is Swedish for "so alike you could mix them up".
|
|
26
|
+
|
|
27
|
+
- **Same answers as Postgres.** A pair comes out exactly when
|
|
28
|
+
`a % b` would match it under `pg_trgm.similarity_threshold`, with the score
|
|
29
|
+
`similarity(a, b)` returns, down to the last digit
|
|
30
|
+
([how](#matching-postgres)).
|
|
31
|
+
- **Fast.** On 145,785 podcast names it finds the 3,227 pairs at 0.85 in
|
|
32
|
+
0.11 seconds,
|
|
33
|
+
where Postgres's self-join takes 14 seconds on eight cores and 106 on one ([benchmark](#benchmark)).
|
|
34
|
+
- **One binary.** No database, no index to build, no runtime. Rows in,
|
|
35
|
+
pairs out.
|
|
36
|
+
|
|
37
|
+
It's the candidate step of deduplication and record linkage: it finds the
|
|
38
|
+
pairs worth a closer look, and you decide what to do with them.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
From PyPI, for the CLI and the [Python module](#from-python):
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
pip install snarlik # or: uv add snarlik
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Or download a binary for Linux, macOS or Windows from the
|
|
49
|
+
[releases](https://github.com/u840903/snarlik/releases), or build from
|
|
50
|
+
source with [Zig](https://ziglang.org/download/) 0.17.1:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
git clone https://github.com/u840903/snarlik
|
|
54
|
+
cd snarlik
|
|
55
|
+
zig build -Doptimize=ReleaseFast # → zig-out/bin/snarlik
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Use
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
snarlik [-t THRESHOLD] [-j THREADS] [-v] [FILE]
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Input (FILE or stdin) is PostgreSQL `COPY` text format, one row per line:
|
|
65
|
+
`id<TAB>text` in every row, or only `text` in every row, in which case the
|
|
66
|
+
id is the row number. Rows with a NULL (`\N`) are skipped. Ids are printed
|
|
67
|
+
back exactly as they were written. Output is one pair per line,
|
|
68
|
+
`id_a<TAB>id_b<TAB>similarity`, in no particular order.
|
|
69
|
+
|
|
70
|
+
| Option | |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `-t`, `--threshold` | Lowest similarity to report, in (0, 1]. Default 0.3, `pg_trgm`'s own default. |
|
|
73
|
+
| `-j`, `--threads` | Threads to use, at most one per CPU. Default: one per CPU. |
|
|
74
|
+
| `-v`, `--verbose` | Print counts to stderr. |
|
|
75
|
+
|
|
76
|
+
Straight from a database:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
psql -c "\copy (SELECT id, name FROM podcasts) TO 'names.tsv'"
|
|
80
|
+
snarlik -t 0.85 names.tsv > pairs.tsv
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### From Python
|
|
84
|
+
|
|
85
|
+
The wheel bundles the binary, and the `snarlik` module runs it:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import snarlik
|
|
89
|
+
|
|
90
|
+
names = ["The Daily", "the daily!", "Daily Show", None]
|
|
91
|
+
snarlik.self_join(names, threshold=0.85) # [(0, 1, 1.0)]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`self_join(texts, threshold=0.3, threads=None)` returns `(i, j, similarity)`
|
|
95
|
+
for every pair, with `i < j` indexes into `texts`; `None` is skipped like a
|
|
96
|
+
NULL. `snarlik.find_snarlik_bin()` gives the binary's path, to run it
|
|
97
|
+
yourself.
|
|
98
|
+
|
|
99
|
+
### As a Zig library
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
zig fetch --save git+https://github.com/u840903/snarlik
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
```zig
|
|
106
|
+
const snarlik = @import("snarlik");
|
|
107
|
+
|
|
108
|
+
const pairs = try snarlik.selfJoin(gpa, texts, .{ .threshold = 0.85 }, null);
|
|
109
|
+
defer gpa.free(pairs);
|
|
110
|
+
for (pairs) |p| std.debug.print("{s} ~ {s}: {d}\n", .{ texts[p.a], texts[p.b], p.similarity });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`selfJoin` uses `gpa` from several threads, so it must be thread-safe, as
|
|
114
|
+
Zig's `DebugAllocator`, `smp_allocator` and `c_allocator` are. Set
|
|
115
|
+
`.threads = 1` to stay on the calling thread.
|
|
116
|
+
`snarlik.similarity(gpa, a, b)` scores a single pair, like Postgres's
|
|
117
|
+
`similarity(a, b)`.
|
|
118
|
+
|
|
119
|
+
## Matching Postgres
|
|
120
|
+
|
|
121
|
+
`pg_trgm` splits text into words, lower-cases them, pads each as `" word "`
|
|
122
|
+
and takes every three-character window. The similarity of two strings is
|
|
123
|
+
the trigrams they share divided by all the distinct trigrams of both. The
|
|
124
|
+
details are where other implementations drift:
|
|
125
|
+
|
|
126
|
+
- **Which characters make up a word** depends on the database's locale.
|
|
127
|
+
Is `²` a letter? Is an Arabic vowel mark? snarlik doesn't guess: its
|
|
128
|
+
tables come from asking Postgres about every Unicode codepoint
|
|
129
|
+
(`tools/pgchars.sql`).
|
|
130
|
+
- **Trigrams with non-ASCII characters** are hashed to three bytes with
|
|
131
|
+
Postgres's old CRC-32 variant, and snarlik hashes them the same way, so
|
|
132
|
+
two different trigrams that happen to share a hash count as shared, as
|
|
133
|
+
they do in Postgres.
|
|
134
|
+
- **Scores** are computed in 32-bit floats, as Postgres does, so a pair
|
|
135
|
+
right at the threshold lands on the same side.
|
|
136
|
+
|
|
137
|
+
The bundled tables come from PostgreSQL 18.3 on Debian with the libc
|
|
138
|
+
provider and `en_US.utf8`, the common default. For another libc locale,
|
|
139
|
+
generate your own (ICU databases aren't supported: ICU lowercases some
|
|
140
|
+
characters to several, and by context):
|
|
141
|
+
|
|
142
|
+
```sh
|
|
143
|
+
psql -tA -F $'\t' -f tools/pgchars.sql > pgchars.tsv
|
|
144
|
+
python3 tools/gen_tables.py pgchars.tsv "PostgreSQL 17, libc sv_SE.utf8" > src/tables.zig
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
To check snarlik against your database on your own data:
|
|
148
|
+
|
|
149
|
+
```sh
|
|
150
|
+
PSQL="psql mydb" tools/check-pg.sh rows.tsv 0.85
|
|
151
|
+
# postgres: 3227 pairs, snarlik: 3227 pairs
|
|
152
|
+
# identical
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
CI runs this against PostgreSQL 18.3 on every change, and checks that the
|
|
156
|
+
bundled tables still match it.
|
|
157
|
+
|
|
158
|
+
Not covered yet: `word_similarity` and `strict_word_similarity` (`<%`,
|
|
159
|
+
`<<%`), and big-endian machines (Postgres's hashed trigrams depend on byte
|
|
160
|
+
order).
|
|
161
|
+
|
|
162
|
+
## How it's fast
|
|
163
|
+
|
|
164
|
+
Postgres's trigram index answers "which rows share any trigram with this
|
|
165
|
+
one?" For common trigrams such as `pod` or `the` that is a large share of the
|
|
166
|
+
table, and every hit gets its similarity computed.
|
|
167
|
+
|
|
168
|
+
snarlik avoids nearly all of that work:
|
|
169
|
+
|
|
170
|
+
- **Prefix filter** (AllPairs; Bayardo, Ma and Srikant, 2007). Trigrams are
|
|
171
|
+
ranked rarest first and records sorted smallest first. A record of *n*
|
|
172
|
+
trigrams can only reach threshold *t* with a record that shares one of its
|
|
173
|
+
first *n − ⌈t·n⌉ + 1* trigrams, so only those are indexed and looked up,
|
|
174
|
+
and records too small to reach *t* are skipped.
|
|
175
|
+
- **Position filter** (PPJoin; Xiao et al., 2008). Where two records' first
|
|
176
|
+
shared trigram sits caps how many they can share in all. Most candidates
|
|
177
|
+
fail that test and are never compared; the rest are compared from that
|
|
178
|
+
trigram on, and the comparison stops as soon as the pair can no longer
|
|
179
|
+
reach *t*.
|
|
180
|
+
- **Threads.** Each record looks up the finished index on its own, so the
|
|
181
|
+
records are split across all CPUs (`-j` to choose how many).
|
|
182
|
+
|
|
183
|
+
The filters use the same float4 arithmetic as the final score, so they never
|
|
184
|
+
drop a pair Postgres would return.
|
|
185
|
+
|
|
186
|
+
## Benchmark
|
|
187
|
+
|
|
188
|
+
Apple M4 Pro (14 cores), PostgreSQL 18.3 in Docker on the same machine.
|
|
189
|
+
The Postgres column is one run of `tools/pg-pairs.sh`: loading the rows into
|
|
190
|
+
a temp table, building the GIN index and the `%` self-join, on one core.
|
|
191
|
+
snarlik's columns are the best of three runs, reading the file included.
|
|
192
|
+
Both found exactly the same pairs in every row of both tables.
|
|
193
|
+
|
|
194
|
+
**Real data:** 145,785 podcast names from [chart.haus](https://chart.haus)
|
|
195
|
+
(not published).
|
|
196
|
+
|
|
197
|
+
| Threshold | Pairs | Postgres, 1 core | snarlik, 1 thread | snarlik, 14 threads |
|
|
198
|
+
|---|---|---|---|---|
|
|
199
|
+
| 0.9 | 2,870 | 88 s | 0.13 s | 0.10 s |
|
|
200
|
+
| 0.85 | 3,227 | 106 s | 0.19 s | 0.11 s |
|
|
201
|
+
| 0.7 | 11,608 | 189 s | 0.61 s | 0.15 s |
|
|
202
|
+
| 0.6 | 52,935 | 297 s | 1.63 s | 0.26 s |
|
|
203
|
+
|
|
204
|
+
**Postgres at its best.** At 0.85, timing the join alone (rows already
|
|
205
|
+
loaded and indexed), the fastest setup found was a GIN index on an unlogged
|
|
206
|
+
table with eight parallel workers (the default `max_worker_processes`):
|
|
207
|
+
14 seconds. A GiST index took 9.5 minutes, and turning JIT off changed
|
|
208
|
+
nothing.
|
|
209
|
+
|
|
210
|
+
**Synthetic data:** 100,000 generated titles, reproducible with the commands
|
|
211
|
+
below. Made-up words share more trigrams than real titles, so there are
|
|
212
|
+
more candidates to rule out and the work per row is higher.
|
|
213
|
+
|
|
214
|
+
| Threshold | Pairs | Postgres, 1 core | snarlik, 1 thread | snarlik, 14 threads |
|
|
215
|
+
|---|---|---|---|---|
|
|
216
|
+
| 0.9 | 11,467 | 117 s | 0.14 s | 0.08 s |
|
|
217
|
+
| 0.8 | 21,753 | 195 s | 0.46 s | 0.11 s |
|
|
218
|
+
| 0.7 | 49,197 | 295 s | 1.43 s | 0.21 s |
|
|
219
|
+
| 0.6 | 180,264 | 454 s | 4.15 s | 0.48 s |
|
|
220
|
+
|
|
221
|
+
To reproduce, or to run it on your own rows:
|
|
222
|
+
|
|
223
|
+
```sh
|
|
224
|
+
zig build -Doptimize=ReleaseFast
|
|
225
|
+
bench/run.sh # synthetic, snarlik only
|
|
226
|
+
PSQL="psql mydb" bench/run.sh # with Postgres (slow)
|
|
227
|
+
THRESHOLDS="0.85 0.6" bench/run.sh rows.tsv # your own rows
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
`bench/gen_names.py` makes the synthetic titles: Zipf-distributed made-up
|
|
231
|
+
words, filler words such as "the" and "podcast", about one row in ten an
|
|
232
|
+
edited copy of an earlier one, and some Swedish, German, French, Cyrillic
|
|
233
|
+
and Japanese words.
|
|
234
|
+
|
|
235
|
+
## Development
|
|
236
|
+
|
|
237
|
+
```
|
|
238
|
+
src/
|
|
239
|
+
root.zig the library's public API
|
|
240
|
+
trigram.zig pg_trgm's trigrams and similarity
|
|
241
|
+
join.zig the self-join: filters, index, threads
|
|
242
|
+
main.zig the CLI and COPY text parsing
|
|
243
|
+
tables.zig generated from Postgres by tools/
|
|
244
|
+
python/ the Python module the wheels carry, and its test
|
|
245
|
+
tools/
|
|
246
|
+
pgchars.sql, gen_tables.py regenerate src/tables.zig
|
|
247
|
+
build_wheel.py package a binary as a Python wheel
|
|
248
|
+
pg-pairs.sh, check-pg.sh Postgres's pairs, and the diff against them
|
|
249
|
+
bench/ benchmark script and synthetic data generator
|
|
250
|
+
tests/ COPY escapes and edge cases for check-pg.sh
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
```sh
|
|
254
|
+
zig build test # unit tests
|
|
255
|
+
PSQL="psql mydb" tools/check-pg.sh tests/copy-escapes.tsv
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## License
|
|
259
|
+
|
|
260
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
snarlik/__init__.py,sha256=tOIbREaNF0QUZsI7MgbwLdlh_ljC8xZymkLq_jJ_NQo,2598
|
|
2
|
+
snarlik/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
snarlik-0.2.0.data/scripts/snarlik.exe,sha256=Bl0wxw1Ov5giQZPaHKZy4CRVLj1sZ9SZM3s1oR4Uw1k,658432
|
|
4
|
+
snarlik-0.2.0.dist-info/licenses/LICENSE,sha256=pn2-_D-aRxCqXoT80C3MKj8CL534bta7zmD3pD2tfDg,1113
|
|
5
|
+
snarlik-0.2.0.dist-info/METADATA,sha256=9s8Yp-c2ElKczevK9YVIzwhcqfbj9MWXD8Og0t1M0Kc,9634
|
|
6
|
+
snarlik-0.2.0.dist-info/WHEEL,sha256=4ac0WsUSLopmJhLzHfprDmCS-QQD7CKWYhdsKGre4Aw,100
|
|
7
|
+
snarlik-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jan K. Griffioen-Järfalk
|
|
4
|
+
Copyright (c) 2024 Kagi Search
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|