rufuzzy 0.5.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.
rufuzzy/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitry Korshikov (Коршиков Дмитрий)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rufuzzy/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """rufuzzy — Russian & cross-script (EN<->RU) phonetic and indexed fuzzy matching.
2
+
3
+ Zero external Python dependencies (stdlib only). Wraps the native Go C-ABI v1
4
+ library (`librufuzzy`) via `ctypes` for stateless scoring, phonetic encoding,
5
+ and thread-safe in-process byte-arena index search (`RuFuzzy`, `RuFuzzyIndex`).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ __version__ = "0.5.0"
10
+ EXPECTED_ABI_VERSION = 1
11
+ EXPECTED_INDEX_SCHEMA_VERSION = 1
12
+ EXPECTED_PHONETIC_RULES_VERSION = 7
13
+
14
+ from .client import (
15
+ IndexMeta,
16
+ MatchResult,
17
+ PhoneticResult,
18
+ RuFuzzy,
19
+ RuFuzzyError,
20
+ RuFuzzyForkError,
21
+ RuFuzzyIndex,
22
+ RuFuzzyVersionError,
23
+ ScoreBreakdown,
24
+ ScoreResult,
25
+ check_version,
26
+ version_info,
27
+ )
28
+
29
+ __all__ = [
30
+ "__version__",
31
+ "EXPECTED_ABI_VERSION",
32
+ "EXPECTED_INDEX_SCHEMA_VERSION",
33
+ "EXPECTED_PHONETIC_RULES_VERSION",
34
+ "RuFuzzyError",
35
+ "RuFuzzyVersionError",
36
+ "RuFuzzyForkError",
37
+ "ScoreBreakdown",
38
+ "ScoreResult",
39
+ "MatchResult",
40
+ "PhoneticResult",
41
+ "IndexMeta",
42
+ "RuFuzzy",
43
+ "RuFuzzyIndex",
44
+ "version_info",
45
+ "check_version",
46
+ ]
rufuzzy/_native.py ADDED
@@ -0,0 +1,230 @@
1
+ """Low-level ctypes loader for librufuzzy (C-ABI v1) with fork-after-load protection."""
2
+ from __future__ import annotations
3
+
4
+ import ctypes
5
+ import json
6
+ import os
7
+ import platform
8
+ import threading
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from . import EXPECTED_ABI_VERSION
13
+
14
+ # Required C-ABI v1 capability bitmask (phonetic | score | score_batch | index |
15
+ # index_save_load | index_search_batch | fingerprint).
16
+ REQUIRED_CAPABILITIES = 0x7F
17
+
18
+
19
+ class RuFuzzyError(RuntimeError):
20
+ """Base error raised by rufuzzy Python bindings."""
21
+
22
+
23
+ class RuFuzzyVersionError(RuFuzzyError):
24
+ """Raised when the native library version, ABI, schema, capabilities, or phonetic rules are incompatible."""
25
+
26
+
27
+ class RuFuzzyForkError(RuFuzzyError):
28
+ """Raised when a process forks AFTER loading the Go C-shared runtime (unsafe in Go)."""
29
+
30
+
31
+ _LOCK = threading.Lock()
32
+ _LIB: ctypes.CDLL | None = None
33
+ _LIB_PATH: Path | None = None
34
+ _LOADED_PID: int | None = None
35
+ _LOADING = False
36
+ _FORKED_AFTER_LOAD = False
37
+ _DLL_DIR_HANDLES: list[Any] = []
38
+
39
+
40
+ def _on_fork_child() -> None:
41
+ """Reset loader lock in a forked child and poison calls if Go runtime was loading or loaded."""
42
+ global _LOCK, _FORKED_AFTER_LOAD
43
+ if _LIB is not None or _LOADING or _LOADED_PID is not None:
44
+ _FORKED_AFTER_LOAD = True
45
+ _LOCK = threading.Lock()
46
+
47
+
48
+ if hasattr(os, "register_at_fork"):
49
+ os.register_at_fork(after_in_child=_on_fork_child)
50
+
51
+
52
+ def shared_lib_filename() -> str:
53
+ sys_name = platform.system()
54
+ if sys_name == "Darwin":
55
+ return "librufuzzy.dylib"
56
+ if sys_name == "Windows":
57
+ return "rufuzzy.dll"
58
+ return "librufuzzy.so"
59
+
60
+
61
+ def _find_library(explicit_path: str | os.PathLike[str] | None = None) -> Path:
62
+ candidates: list[Path] = []
63
+ if explicit_path is not None:
64
+ p = Path(explicit_path)
65
+ if not p.is_file():
66
+ raise RuFuzzyError(f"rufuzzy shared library not found at explicit path: {p}")
67
+ return p
68
+
69
+ env_path = os.environ.get("RUFUZZY_LIB_PATH")
70
+ if env_path:
71
+ p = Path(env_path)
72
+ if p.is_file():
73
+ return p
74
+ raise RuFuzzyError(f"RUFUZZY_LIB_PATH points to a missing file: {p}")
75
+
76
+ lib_name = shared_lib_filename()
77
+ pkg_dir = Path(__file__).resolve().parent
78
+ candidates.append(pkg_dir / lib_name)
79
+ candidates.append(pkg_dir.parent.parent / "python" / "rufuzzy" / lib_name)
80
+ candidates.append(pkg_dir.parent.parent / lib_name)
81
+ for cand in candidates:
82
+ if cand.is_file():
83
+ return cand
84
+ searched = ", ".join(str(c) for c in candidates)
85
+ raise RuFuzzyError(
86
+ f"Native rufuzzy shared library ({lib_name}) not found. Searched: {searched}. "
87
+ "Run `make build-capi` or install a prebuilt rufuzzy wheel."
88
+ )
89
+
90
+
91
+ def _require_symbol(lib: ctypes.CDLL, name: str) -> Any:
92
+ fn = getattr(lib, name, None)
93
+ if fn is None:
94
+ raise RuFuzzyVersionError(
95
+ f"Incompatible rufuzzy native library: missing required C-ABI symbol {name!r}."
96
+ )
97
+ return fn
98
+
99
+
100
+ def _verify_abi_and_capabilities(lib: ctypes.CDLL) -> None:
101
+ """Validate ABI version and required capability flags BEFORE binding working symbols."""
102
+ abi_fn = _require_symbol(lib, "rufuzzy_abi_version")
103
+ abi_fn.argtypes = []
104
+ abi_fn.restype = ctypes.c_int
105
+
106
+ abi = int(abi_fn())
107
+ if abi != EXPECTED_ABI_VERSION:
108
+ raise RuFuzzyVersionError(
109
+ f"Incompatible rufuzzy C-ABI version: library reports {abi}, "
110
+ f"Python package requires {EXPECTED_ABI_VERSION}."
111
+ )
112
+
113
+ caps_fn = _require_symbol(lib, "rufuzzy_capabilities")
114
+ caps_fn.argtypes = []
115
+ caps_fn.restype = ctypes.c_uint64
116
+
117
+ caps = int(caps_fn())
118
+ missing = REQUIRED_CAPABILITIES & ~caps
119
+ if missing:
120
+ raise RuFuzzyVersionError(
121
+ f"Incompatible rufuzzy C-ABI capabilities: library reports 0x{caps:x}, "
122
+ f"missing required bitmask 0x{missing:x}."
123
+ )
124
+
125
+
126
+ def _configure_work_signatures(lib: ctypes.CDLL) -> None:
127
+ c_char_p = ctypes.c_char_p
128
+ c_void_p = ctypes.c_void_p
129
+ c_int = ctypes.c_int
130
+ c_int64 = ctypes.c_int64
131
+
132
+ # All string-returning C-ABI functions use c_void_p so we keep the exact raw pointer
133
+ # and release it via rufuzzy_free_str (required for safe cross-CRT memory freeing on Windows).
134
+ specs: list[tuple[str, list[Any], Any]] = [
135
+ ("rufuzzy_index_schema_version", [], c_int),
136
+ ("rufuzzy_phonetic_rules_version", [], c_int),
137
+ ("rufuzzy_version", [], c_void_p),
138
+ ("rufuzzy_version_info_json", [], c_void_p),
139
+ ("rufuzzy_free_str", [c_void_p], None),
140
+ ("rufuzzy_normalize_json", [c_char_p, c_char_p], c_void_p),
141
+ ("rufuzzy_phonetic_json", [c_char_p, c_char_p], c_void_p),
142
+ ("rufuzzy_score_json", [c_char_p, c_char_p, c_char_p], c_void_p),
143
+ ("rufuzzy_score_batch_json", [c_char_p], c_void_p),
144
+ ("rufuzzy_index_build_json", [c_char_p], c_void_p),
145
+ ("rufuzzy_index_load_json", [c_char_p], c_void_p),
146
+ ("rufuzzy_index_save_json", [c_int64, c_char_p], c_void_p),
147
+ ("rufuzzy_index_stats_json", [c_int64], c_void_p),
148
+ ("rufuzzy_index_search_json", [c_int64, c_char_p], c_void_p),
149
+ ("rufuzzy_index_search_batch_json", [c_int64, c_char_p], c_void_p),
150
+ ("rufuzzy_index_free", [c_int64], c_int),
151
+ ]
152
+ for sym, argtypes, restype in specs:
153
+ fn = _require_symbol(lib, sym)
154
+ fn.argtypes = argtypes
155
+ fn.restype = restype
156
+
157
+
158
+ def check_fork_safety() -> None:
159
+ """Reject calls from a child process forked AFTER loading the Go C-shared runtime."""
160
+ if _FORKED_AFTER_LOAD or (_LOADED_PID is not None and os.getpid() != _LOADED_PID):
161
+ owner = _LOADED_PID if _LOADED_PID is not None else "parent"
162
+ raise RuFuzzyForkError(
163
+ f"rufuzzy native library was loaded in PID {owner} before fork() "
164
+ f"(current PID {os.getpid()}). Go C-shared runtimes cannot be used across fork(). "
165
+ "Use multiprocessing start method 'spawn', fork BEFORE loading rufuzzy, "
166
+ "or use ThreadPoolExecutor."
167
+ )
168
+
169
+
170
+ def load_native(lib_path: str | os.PathLike[str] | None = None) -> ctypes.CDLL:
171
+ global _LIB, _LIB_PATH, _LOADED_PID, _LOADING
172
+ check_fork_safety()
173
+ if _LIB is not None:
174
+ return _LIB
175
+ with _LOCK:
176
+ check_fork_safety()
177
+ if _LIB is not None:
178
+ return _LIB
179
+ path = _find_library(lib_path)
180
+ _LOADING = True
181
+ try:
182
+ if platform.system() == "Windows" and hasattr(os, "add_dll_directory"):
183
+ _DLL_DIR_HANDLES.append(os.add_dll_directory(str(path.parent)))
184
+ lib = ctypes.CDLL(str(path))
185
+ # Once dlopen succeeds, Go runtime threads are live in this PID.
186
+ _LOADED_PID = os.getpid()
187
+ _verify_abi_and_capabilities(lib)
188
+ _configure_work_signatures(lib)
189
+ _LIB = lib
190
+ _LIB_PATH = path
191
+ return _LIB
192
+ finally:
193
+ _LOADING = False
194
+
195
+
196
+ def loaded_library_path() -> Path | None:
197
+ return _LIB_PATH
198
+
199
+
200
+ def take_c_string(lib: ctypes.CDLL, ptr: int | None) -> str:
201
+ if not ptr:
202
+ raise RuFuzzyError("rufuzzy native call returned NULL string pointer")
203
+ try:
204
+ return ctypes.string_at(ptr).decode("utf-8")
205
+ finally:
206
+ lib.rufuzzy_free_str(ptr)
207
+
208
+
209
+ def take_json_envelope(lib: ctypes.CDLL, ptr: int | None) -> dict[str, Any]:
210
+ raw = take_c_string(lib, ptr)
211
+ try:
212
+ data = json.loads(raw)
213
+ except json.JSONDecodeError as exc:
214
+ raise RuFuzzyError(f"rufuzzy native call returned invalid JSON: {exc}") from exc
215
+ if not isinstance(data, dict):
216
+ raise RuFuzzyError("rufuzzy native call returned unexpected JSON payload")
217
+ if not data.get("ok", False):
218
+ raise RuFuzzyError(str(data.get("error") or "unknown native rufuzzy error"))
219
+ return data
220
+
221
+
222
+ def encode_c_str(s: str) -> bytes:
223
+ if "\x00" in s:
224
+ raise ValueError("NUL byte (\\x00) is not allowed in C-ABI string arguments")
225
+ return s.encode("utf-8")
226
+
227
+
228
+ def encode_c_json(payload: dict[str, Any]) -> bytes:
229
+ # json.dumps escapes U+0000 as \u0000, so the resulting UTF-8 payload never contains raw NUL bytes.
230
+ return json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
rufuzzy/client.py ADDED
@@ -0,0 +1,473 @@
1
+ """High-level data models and local native (ctypes C-ABI v1) Python client for rufuzzy."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import os
6
+ import re
7
+ import threading
8
+ from dataclasses import dataclass
9
+ from typing import Any, Iterable, Sequence
10
+
11
+ from . import (
12
+ EXPECTED_ABI_VERSION,
13
+ EXPECTED_INDEX_SCHEMA_VERSION,
14
+ EXPECTED_PHONETIC_RULES_VERSION,
15
+ __version__,
16
+ )
17
+ from ._native import (
18
+ RuFuzzyError,
19
+ RuFuzzyForkError,
20
+ RuFuzzyVersionError,
21
+ check_fork_safety,
22
+ encode_c_json,
23
+ encode_c_str,
24
+ load_native,
25
+ loaded_library_path,
26
+ take_json_envelope,
27
+ )
28
+
29
+ __all__ = [
30
+ "RuFuzzyError",
31
+ "RuFuzzyVersionError",
32
+ "RuFuzzyForkError",
33
+ "ScoreBreakdown",
34
+ "ScoreResult",
35
+ "MatchResult",
36
+ "PhoneticResult",
37
+ "IndexMeta",
38
+ "RuFuzzy",
39
+ "RuFuzzyIndex",
40
+ "version_info",
41
+ "check_version",
42
+ ]
43
+
44
+ _VER_NUM_RE = re.compile(r"\d+")
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ScoreBreakdown:
49
+ edit: float
50
+ jaro_winkler: float
51
+ trigram: float
52
+ token_sort: float
53
+ token_set: float
54
+ phonetic: float
55
+ cross_script: float
56
+ numeric_penalty: float
57
+ short_penalty: float
58
+ cross_script_pair: bool
59
+
60
+ @classmethod
61
+ def from_dict(cls, d: dict[str, Any]) -> ScoreBreakdown:
62
+ return cls(
63
+ edit=float(d.get("edit", 0.0)),
64
+ jaro_winkler=float(d.get("jaro_winkler", 0.0)),
65
+ trigram=float(d.get("trigram", 0.0)),
66
+ token_sort=float(d.get("token_sort", 0.0)),
67
+ token_set=float(d.get("token_set", 0.0)),
68
+ phonetic=float(d.get("phonetic", 0.0)),
69
+ cross_script=float(d.get("cross_script", 0.0)),
70
+ numeric_penalty=float(d.get("numeric_penalty", 0.0)),
71
+ short_penalty=float(d.get("short_penalty", 0.0)),
72
+ cross_script_pair=bool(d.get("cross_script_pair", False)),
73
+ )
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class ScoreResult:
78
+ score: float
79
+ breakdown: ScoreBreakdown
80
+
81
+ @classmethod
82
+ def from_dict(cls, d: dict[str, Any]) -> ScoreResult:
83
+ return cls(
84
+ score=float(d.get("score", 0.0)),
85
+ breakdown=ScoreBreakdown.from_dict(d.get("breakdown") or {}),
86
+ )
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class MatchResult:
91
+ index: int
92
+ text: str
93
+ score: float
94
+ breakdown: ScoreBreakdown
95
+
96
+ @classmethod
97
+ def from_dict(cls, d: dict[str, Any]) -> MatchResult:
98
+ return cls(
99
+ index=int(d.get("index", -1)),
100
+ text=str(d.get("text", "")),
101
+ score=float(d.get("score", 0.0)),
102
+ breakdown=ScoreBreakdown.from_dict(d.get("breakdown") or {}),
103
+ )
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class PhoneticResult:
108
+ norm: str
109
+ ru_meta: str
110
+ cross_keys: tuple[str, ...]
111
+
112
+ @classmethod
113
+ def from_dict(cls, d: dict[str, Any]) -> PhoneticResult:
114
+ keys = d.get("cross_keys") or []
115
+ return cls(
116
+ norm=str(d.get("norm", "")),
117
+ ru_meta=str(d.get("ru_meta", "")),
118
+ cross_keys=tuple(str(k) for k in keys),
119
+ )
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class IndexMeta:
124
+ name: str
125
+ fingerprint: str
126
+ docs: int
127
+ arena_bytes: int
128
+ posting_bytes: int
129
+ total_postings: int
130
+ index_schema_version: int
131
+ phonetic_rules_version: int
132
+ loaded_at: str = ""
133
+
134
+ @classmethod
135
+ def from_dict(cls, d: dict[str, Any]) -> IndexMeta:
136
+ return cls(
137
+ name=str(d.get("name", "")),
138
+ fingerprint=str(d.get("fingerprint", "")),
139
+ docs=int(d.get("docs", 0)),
140
+ arena_bytes=int(d.get("arena_bytes", 0)),
141
+ posting_bytes=int(d.get("posting_bytes", 0)),
142
+ total_postings=int(d.get("total_postings", 0)),
143
+ index_schema_version=int(d.get("index_schema_version", 0)),
144
+ phonetic_rules_version=int(d.get("phonetic_rules_version", 0)),
145
+ loaded_at=str(d.get("loaded_at", "")),
146
+ )
147
+
148
+
149
+ def _parse_semver(raw: str) -> tuple[int, int, int]:
150
+ nums = [int(x) for x in _VER_NUM_RE.findall(str(raw or ""))]
151
+ nums.extend([0, 0, 0])
152
+ return nums[0], nums[1], nums[2]
153
+
154
+
155
+ def _validate_min_score(min_score: float | None) -> float | None:
156
+ if min_score is None:
157
+ return None
158
+ val = float(min_score)
159
+ if math.isnan(val) or math.isinf(val) or val < 0.0 or val > 1.0:
160
+ raise ValueError(f"min_score must be finite in [0, 1], got {min_score!r}")
161
+ return val
162
+
163
+
164
+ def version_info(lib_path: str | os.PathLike[str] | None = None) -> dict[str, Any]:
165
+ """Return full version, ABI, schema, phonetic rules, and capability metadata."""
166
+ lib = load_native(lib_path)
167
+ info = take_json_envelope(lib, lib.rufuzzy_version_info_json())
168
+ path = loaded_library_path()
169
+ return {
170
+ "backend": "native",
171
+ "package_version": __version__,
172
+ "library_version": str(info["version"]),
173
+ "abi_version": int(info["abi_version"]),
174
+ "index_schema_version": int(info["index_schema_version"]),
175
+ "phonetic_rules_version": int(info["phonetic_rules_version"]),
176
+ "capabilities": int(info["capabilities"]),
177
+ "library_path": str(path) if path is not None else "",
178
+ }
179
+
180
+
181
+ def check_version(
182
+ *,
183
+ min_version: str | None = None,
184
+ expected_abi: int = EXPECTED_ABI_VERSION,
185
+ expected_schema: int | None = EXPECTED_INDEX_SCHEMA_VERSION,
186
+ expected_rules: int | None = None,
187
+ lib_path: str | os.PathLike[str] | None = None,
188
+ ) -> dict[str, Any]:
189
+ """Verify native rufuzzy backend compatibility and return version_info()."""
190
+ info = version_info(lib_path=lib_path)
191
+ if info["abi_version"] != expected_abi:
192
+ raise RuFuzzyVersionError(
193
+ f"Incompatible rufuzzy C-ABI: got {info['abi_version']}, expected {expected_abi}"
194
+ )
195
+ if expected_schema is not None and info["index_schema_version"] != expected_schema:
196
+ raise RuFuzzyVersionError(
197
+ f"Incompatible rufuzzy index schema: got {info['index_schema_version']}, expected {expected_schema}"
198
+ )
199
+ if expected_rules is not None and info["phonetic_rules_version"] != expected_rules:
200
+ raise RuFuzzyVersionError(
201
+ f"Incompatible rufuzzy phonetic rules: got {info['phonetic_rules_version']}, expected {expected_rules}"
202
+ )
203
+ if min_version and _parse_semver(info["library_version"]) < _parse_semver(min_version):
204
+ raise RuFuzzyVersionError(
205
+ f"rufuzzy version {info['library_version']!r} is older than required {min_version!r}"
206
+ )
207
+ return info
208
+
209
+
210
+ class RuFuzzyIndex:
211
+ """In-process native byte-arena inverted index handle (thread-safe, context-managed)."""
212
+
213
+ def __init__(self, lib: Any, handle: int, meta: IndexMeta) -> None:
214
+ self._lib = lib
215
+ self._handle = int(handle)
216
+ self._meta = meta
217
+ self._lock = threading.Lock()
218
+ self._closed = False
219
+ self._owner_pid = os.getpid()
220
+
221
+ @classmethod
222
+ def build(
223
+ cls,
224
+ corpus: Sequence[str],
225
+ *,
226
+ profile: str = "entity",
227
+ candidate_cap: int = 48,
228
+ max_posting_df: int = 2048,
229
+ min_score: float = 0.0,
230
+ lib_path: str | os.PathLike[str] | None = None,
231
+ ) -> RuFuzzyIndex:
232
+ ms = _validate_min_score(min_score)
233
+ lib = load_native(lib_path)
234
+ payload = encode_c_json(
235
+ {
236
+ "corpus": [str(x) for x in corpus],
237
+ "profile": profile,
238
+ "candidate_cap": int(candidate_cap),
239
+ "max_posting_df": int(max_posting_df),
240
+ "min_score": 0.0 if ms is None else ms,
241
+ }
242
+ )
243
+ res = take_json_envelope(lib, lib.rufuzzy_index_build_json(payload))
244
+ return cls(lib, int(res["handle"]), IndexMeta.from_dict(res.get("meta") or {}))
245
+
246
+ @classmethod
247
+ def load(
248
+ cls,
249
+ path: str | os.PathLike[str],
250
+ *,
251
+ lib_path: str | os.PathLike[str] | None = None,
252
+ ) -> RuFuzzyIndex:
253
+ lib = load_native(lib_path)
254
+ res = take_json_envelope(lib, lib.rufuzzy_index_load_json(encode_c_str(os.fspath(path))))
255
+ return cls(lib, int(res["handle"]), IndexMeta.from_dict(res.get("meta") or {}))
256
+
257
+ def _active_handle(self) -> int:
258
+ check_fork_safety()
259
+ if self._closed or self._handle <= 0:
260
+ raise RuFuzzyError("RuFuzzyIndex is already closed")
261
+ return self._handle
262
+
263
+ @property
264
+ def fingerprint(self) -> str:
265
+ return self._meta.fingerprint
266
+
267
+ @property
268
+ def meta(self) -> IndexMeta:
269
+ return self._meta
270
+
271
+ def __len__(self) -> int:
272
+ return self._meta.docs
273
+
274
+ def save(self, path: str | os.PathLike[str]) -> str:
275
+ h = self._active_handle()
276
+ res = take_json_envelope(self._lib, self._lib.rufuzzy_index_save_json(h, encode_c_str(os.fspath(path))))
277
+ return str(res.get("fingerprint", self._meta.fingerprint))
278
+
279
+ def stats(self) -> dict[str, Any]:
280
+ h = self._active_handle()
281
+ res = take_json_envelope(self._lib, self._lib.rufuzzy_index_stats_json(h))
282
+ return {
283
+ "len": int(res["len"]),
284
+ "fingerprint": str(res["fingerprint"]),
285
+ **(res.get("stats") or {}),
286
+ }
287
+
288
+ def search(
289
+ self,
290
+ query: str,
291
+ *,
292
+ top_k: int = 5,
293
+ min_score: float | None = None,
294
+ profile: str = "",
295
+ ) -> list[MatchResult]:
296
+ h = self._active_handle()
297
+ req: dict[str, Any] = {"query": str(query), "top_k": int(top_k), "profile": profile}
298
+ ms = _validate_min_score(min_score)
299
+ if ms is not None:
300
+ req["min_score"] = ms
301
+ res = take_json_envelope(self._lib, self._lib.rufuzzy_index_search_json(h, encode_c_json(req)))
302
+ return [MatchResult.from_dict(item) for item in (res.get("hits") or [])]
303
+
304
+ def search_batch(
305
+ self,
306
+ queries: Sequence[str],
307
+ *,
308
+ top_k: int = 5,
309
+ min_score: float | None = None,
310
+ workers: int = 0,
311
+ profile: str = "",
312
+ ) -> list[list[MatchResult]]:
313
+ h = self._active_handle()
314
+ req: dict[str, Any] = {
315
+ "queries": [str(q) for q in queries],
316
+ "top_k": int(top_k),
317
+ "workers": int(workers),
318
+ "profile": profile,
319
+ }
320
+ ms = _validate_min_score(min_score)
321
+ if ms is not None:
322
+ req["min_score"] = ms
323
+ res = take_json_envelope(self._lib, self._lib.rufuzzy_index_search_batch_json(h, encode_c_json(req)))
324
+ return [
325
+ [MatchResult.from_dict(item) for item in (row or [])]
326
+ for row in (res.get("results") or [])
327
+ ]
328
+
329
+ def close(self) -> None:
330
+ # Check PID BEFORE touching self._lock so a forked child never deadlocks on an inherited lock.
331
+ if os.getpid() != self._owner_pid:
332
+ self._closed = True
333
+ self._handle = 0
334
+ return
335
+ with self._lock:
336
+ if self._closed or self._handle <= 0:
337
+ return
338
+ self._closed = True
339
+ h = self._handle
340
+ self._handle = 0
341
+ try:
342
+ self._lib.rufuzzy_index_free(h)
343
+ except Exception:
344
+ pass
345
+
346
+ def __enter__(self) -> RuFuzzyIndex:
347
+ return self
348
+
349
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
350
+ self.close()
351
+
352
+ def __del__(self) -> None:
353
+ try:
354
+ self.close()
355
+ except Exception:
356
+ pass
357
+
358
+
359
+ class RuFuzzy:
360
+ """Local in-process rufuzzy engine over C-ABI v1 (thread-safe, zero pip dependencies)."""
361
+
362
+ def __init__(
363
+ self,
364
+ *,
365
+ profile: str = "entity",
366
+ lib_path: str | os.PathLike[str] | None = None,
367
+ ) -> None:
368
+ norm_profile = str(profile or "entity").strip().lower()
369
+ if norm_profile not in ("entity", "product"):
370
+ raise ValueError(f"Unsupported profile {profile!r}; expected 'entity' or 'product'")
371
+ self._profile = norm_profile
372
+ self._lib_path = lib_path
373
+ self._lib = load_native(lib_path)
374
+
375
+ @property
376
+ def backend(self) -> str:
377
+ return "native"
378
+
379
+ @property
380
+ def profile(self) -> str:
381
+ return self._profile
382
+
383
+ def _resolve_profile(self, profile: str | None) -> str:
384
+ return self._profile if profile is None else str(profile)
385
+
386
+ def version_info(self) -> dict[str, Any]:
387
+ return version_info(lib_path=self._lib_path)
388
+
389
+ def check_version(
390
+ self,
391
+ *,
392
+ min_version: str | None = None,
393
+ expected_abi: int = EXPECTED_ABI_VERSION,
394
+ expected_schema: int | None = EXPECTED_INDEX_SCHEMA_VERSION,
395
+ expected_rules: int | None = None,
396
+ ) -> dict[str, Any]:
397
+ return check_version(
398
+ min_version=min_version,
399
+ expected_abi=expected_abi,
400
+ expected_schema=expected_schema,
401
+ expected_rules=expected_rules,
402
+ lib_path=self._lib_path,
403
+ )
404
+
405
+ def normalize(self, text: str, *, profile: str | None = None) -> str:
406
+ check_fork_safety()
407
+ res = take_json_envelope(
408
+ self._lib,
409
+ self._lib.rufuzzy_normalize_json(encode_c_str(str(text)), encode_c_str(self._resolve_profile(profile))),
410
+ )
411
+ return str(res["norm"])
412
+
413
+ def phonetic(self, text: str, *, profile: str | None = None) -> PhoneticResult:
414
+ check_fork_safety()
415
+ res = take_json_envelope(
416
+ self._lib,
417
+ self._lib.rufuzzy_phonetic_json(encode_c_str(str(text)), encode_c_str(self._resolve_profile(profile))),
418
+ )
419
+ return PhoneticResult.from_dict(res)
420
+
421
+ def ru_metaphone(self, text: str, *, profile: str | None = None) -> str:
422
+ return self.phonetic(text, profile=profile).ru_meta
423
+
424
+ def cross_keys(self, text: str, *, profile: str | None = None) -> list[str]:
425
+ return list(self.phonetic(text, profile=profile).cross_keys)
426
+
427
+ def score(self, query: str, target: str, *, profile: str | None = None) -> ScoreResult:
428
+ check_fork_safety()
429
+ res = take_json_envelope(
430
+ self._lib,
431
+ self._lib.rufuzzy_score_json(
432
+ encode_c_str(str(query)),
433
+ encode_c_str(str(target)),
434
+ encode_c_str(self._resolve_profile(profile)),
435
+ ),
436
+ )
437
+ return ScoreResult.from_dict(res)
438
+
439
+ def score_batch(
440
+ self,
441
+ pairs: Iterable[tuple[str, str]],
442
+ *,
443
+ profile: str | None = None,
444
+ workers: int = 0,
445
+ ) -> list[ScoreResult]:
446
+ check_fork_safety()
447
+ pair_list = [[str(a), str(b)] for a, b in pairs]
448
+ payload = encode_c_json(
449
+ {"pairs": pair_list, "profile": self._resolve_profile(profile), "workers": int(workers)}
450
+ )
451
+ res = take_json_envelope(self._lib, self._lib.rufuzzy_score_batch_json(payload))
452
+ return [ScoreResult.from_dict(item) for item in (res.get("results") or [])]
453
+
454
+ def build_index(
455
+ self,
456
+ corpus: Sequence[str],
457
+ *,
458
+ profile: str | None = None,
459
+ candidate_cap: int = 48,
460
+ max_posting_df: int = 2048,
461
+ min_score: float = 0.0,
462
+ ) -> RuFuzzyIndex:
463
+ return RuFuzzyIndex.build(
464
+ corpus,
465
+ profile=self._resolve_profile(profile),
466
+ candidate_cap=candidate_cap,
467
+ max_posting_df=max_posting_df,
468
+ min_score=min_score,
469
+ lib_path=self._lib_path,
470
+ )
471
+
472
+ def load_index(self, path: str | os.PathLike[str]) -> RuFuzzyIndex:
473
+ return RuFuzzyIndex.load(path, lib_path=self._lib_path)
rufuzzy/rufuzzy.dll ADDED
Binary file
@@ -0,0 +1,445 @@
1
+ Metadata-Version: 2.4
2
+ Name: rufuzzy
3
+ Version: 0.5.0
4
+ Summary: Быстрый движок русской и кросс-языковой (EN↔RU) фонетики и индексного нечёткого поиска сущностей на Go с нативными Python-биндингами (0 зависимостей) — экосистема rulemma.ru
5
+ Author: Коршиков Дмитрий (Dmitry Korshikov), Gemini
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://rulemma.ru/
8
+ Project-URL: Documentation, https://rulemma.ru/
9
+ Project-URL: Go Reference, https://pkg.go.dev/github.com/DimaKorshikov/rufuzzy
10
+ Project-URL: Repository, https://github.com/DimaKorshikov/rufuzzy
11
+ Project-URL: Changelog, https://github.com/DimaKorshikov/rufuzzy/blob/main/CHANGELOG.md
12
+ Project-URL: Issues, https://github.com/DimaKorshikov/rufuzzy/issues
13
+ Keywords: russian,fuzzy,phonetic,metaphone,transliteration,entity-matching,nlp,golang
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Natural Language :: Russian
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Operating System :: MacOS
20
+ Classifier: Operating System :: Microsoft :: Windows
21
+ Classifier: Programming Language :: Go
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Topic :: Text Processing :: Linguistic
29
+ Requires-Python: >=3.9
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Dynamic: description
33
+ Dynamic: description-content-type
34
+ Dynamic: license-file
35
+
36
+ <div align="center">
37
+
38
+ <a href="https://rulemma.ru/">
39
+ <img src="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/cover.jpg" alt="rufuzzy — движок русской и кросс-языковой фонетики и нечёткого поиска" width="900" />
40
+ </a>
41
+
42
+ <h1>rufuzzy</h1>
43
+
44
+ <p>Движок русской и кросс-языковой (EN↔RU) фонетики и индексного нечёткого поиска сущностей<br />
45
+ Часть открытой экосистемы <a href="https://rulemma.ru/">rulemma.ru</a> · Go (stdlib, 0 зависимостей) · байтовый индекс .rfz и реестр Registry · C-ABI v1 · Python (ctypes) · CLI · WebAssembly</p>
46
+
47
+ <p>
48
+ <a href="https://github.com/DimaKorshikov/rufuzzy/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/DimaKorshikov/rufuzzy/ci.yml?style=flat-square&label=CI" alt="CI" /></a>
49
+ <a href="https://rulemma.ru/"><img src="https://img.shields.io/badge/website-rulemma.ru-C46542?style=flat-square" alt="Website rulemma.ru" /></a>
50
+ <a href="https://pypi.org/project/rufuzzy/"><img src="https://img.shields.io/pypi/v/rufuzzy?style=flat-square&color=4F7D63" alt="PyPI" /></a>
51
+ <a href="https://github.com/DimaKorshikov/rufuzzy/releases/tag/v0.5.0"><img src="https://img.shields.io/badge/release-v0.5.0-4E7B99?style=flat-square" alt="Release v0.5.0" /></a>
52
+ <a href="https://go.dev/"><img src="https://img.shields.io/badge/Go-1.23%2B-4E7B99?style=flat-square" alt="Go 1.23+" /></a>
53
+ <a href="https://www.python.org/"><img src="https://img.shields.io/badge/Python-3.9%2B-4F7D63?style=flat-square" alt="Python 3.9+" /></a>
54
+ <a href="https://github.com/DimaKorshikov/rufuzzy/tree/v0.5.0/examples/10_browser_wasm/"><img src="https://img.shields.io/badge/WASM-1.09%20MB%20gzip-4E7B99?style=flat-square" alt="WebAssembly 1.09 MB gzip" /></a>
55
+ <a href="https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/LICENSE"><img src="https://img.shields.io/badge/License-MIT-2E3538?style=flat-square" alt="License MIT" /></a>
56
+ </p>
57
+
58
+ <p>
59
+ <a href="https://rulemma.ru/">Сайт rulemma.ru</a> ·
60
+ <a href="https://rulemma.ru/tools/">Инструменты в браузере (WASM)</a> ·
61
+ <a href="#сравнение-качества-поиска">Бенчмарк</a> ·
62
+ <a href="#быстрый-старт">Быстрый старт (Go, Python, CLI, WASM)</a> ·
63
+ <a href="#архитектура-поиска">Архитектура</a> ·
64
+ <a href="#примеры-и-jupyter-тетрадки">Примеры и тетрадки</a> ·
65
+ <a href="https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/ROADMAP.md">Дорожная карта</a> ·
66
+ <a href="https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/CHANGELOG.md">Changelog</a>
67
+ </p>
68
+
69
+ <p><sub>v0.5.0 · pip install rufuzzy (Linux/macOS/Windows, 0 зависимостей) · 91.7% RU→EN R@5 в индексе (91.8% в полном переборе) на Wikidata · 0.0% FPR на 455 парах golden · 200k (замер 0.4.1): 1.21 мс Go / 1.75 мс Python · WASM 1.09 МБ gzip</sub></p>
70
+
71
+ </div>
72
+
73
+ ---
74
+
75
+ ## Зачем появилась эта библиотека
76
+
77
+ Обычные строковые метрики (`RapidFuzz`, расстояние Левенштейна, триграммы) сравнивают символы, а не звучание слов. Когда в справочнике записано «Grundfos» или «Xiaomi», а пользователь вводит «грюндфос» или «ксяоми», совпадение по символам равно нулю. Транслитерация в сочетании с RapidFuzz частично решает проблему, но часто ошибочно объединяет разные модели (`iPhone 14` и `iPhone 15`, `Bort BWS-900` и `BWS-950`), похожие короткие слова (`Омск` и `Томск`, `Bosch` и `Boss`) и даёт лишние совпадения на юридических формах компаний.
78
+
79
+ | Задача | RapidFuzz (и AnyAscii) | rufuzzy 0.5.0 (ядро правил v7) |
80
+ |---|---|---|
81
+ | Бренды EN↔RU | 0.7% без транслита; 87.6% с AnyAscii | 91.8% полный перебор / 91.7% индекс (Wikidata R@5, бренды 94.1%), побуквенные акронимы (`RGB ↔ эрджиби`, `HDMI ↔ эйчдиэмай`) |
82
+ | Русская фонетика | Штрафует безударные гласные и оглушение | `потшипник ↔ подшипник`, `збербанк ↔ сбербанк` (0.978), `ниндзя ↔ Ninja` (1.000), `Х5 group ↔ X5 Group` (1.000) |
83
+ | Организации и СМИ | Лишний шум от ОПФ, склеивает каналы и госорганы | `ООО «ТехноМир» ↔ Техномир` (1.000), `Telegram-канал ≠ Telegram` (0.533), `Гос. Собрание ≠ (Ил Тумэн)` (0.594) |
84
+ | Компактные артикулы | Дефис и пробел ломают совпадение кода | `P-6000 == P6000`, `Bort BWS-900 == Bort BWS900`, `чехол на поко х7 про == Чехол на POCO X7 Pro` (1.000) |
85
+ | Смешанные омоглифы | Кириллическая `с`/`а` ломает латинский бренд | Ремонт омоглифов (`Bоsch ↔ Bosch`) с защитой индексов ГОСТ (`IIа`, `Iб`) |
86
+ | Многословные компании | Однословный город выбивает название из Top-5 | 1-к-1 сопоставление токенов: 79.1% на предприятиях, защита `The Washington Post ≠ Вашингтон` (0.747) |
87
+ | Модели, серии и товары | 42–61% ложных склеек (`realme P == B`, `POCO == Nike`) | `realme P ≠ Realme B` (0.563), `Чехол для смартфона POCO ≠ Nike` (0.554), `Чехол для смартфона POCO ↔ на смартфон` (0.844) |
88
+ | Короткие корни | Склеивает `Омск ↔ Томск` и `Дайсон ↔ Tyson` | Защита в обоих алфавитах: `Омск ≠ Томск`, `Дайсон ≠ Tyson`, `KP.RU ≠ КПРФ` (0.400), `progoroduhta.ru ≠ прокуратура` (0.684) |
89
+ | Поиск по 200 тыс. записей | 11.05–487.1 мс (пакет 22.7 запр/с, пик 322.8 МБ) | Замер 0.4.1 — Go: 1.21 мс, пик 74.0 МБ (пакет 3 538 запр/с) · Python: 1.75 мс (пакет 3 171 запр/с) |
90
+ | Браузер и Node.js (WASM) | Нет единого офлайн-индекса с русской фонетикой | `rufuzzy.wasm` 1.09 МБ gzip (замер времени на 0.4.1: старт 53 мс в Chromium · 10k за 3.72 мс / 50k за 3.12 мс в Node.js V8) |
91
+
92
+ В версии `0.5.0` доступны:
93
+ - **Готовые сборки Python в PyPI (`pip install rufuzzy`, 0 зависимостей) и рецепт `conda-forge` (`packaging/conda-forge/`):** предсобранные колёса (`py3-none-<plat>`) для Linux (`manylinux_2_28_x86_64`, `manylinux_2_28_aarch64`), macOS `11+` (Apple Silicon и Intel) и Windows (`win_amd64`, со статической линковкой `libgcc` без внешних DLL MinGW) устанавливаются без компилятора Go; также публикуется исходный архив `sdist`;
94
+ - **Go-ядро и многоиндексный `Registry`:** полный перебор (`MatchTopK`), байтовый индекс (`BuildIndex`, `BuildIndexContext`, `Search`, `SearchContext`, `SearchBatchContext`), бинарный формат `.rfz` (`Save`, `WriteTo`, `LoadIndex`, `LoadIndexMemory`, SHA-256 `Fingerprint()`) и потокобезопасный реестр `Registry` (`LoadDir`, `BuildAndRegisterContext`, горячее обновление и лимиты ресурсов);
95
+ - **Стабильный `C-ABI v1` (`capi/`) и Python-клиент (`python/rufuzzy/`):** локальный потокобезопасный клиент `RuFuzzy` / `RuFuzzyIndex` поверх `ctypes` с проверкой версий и защитой `os.fork()`;
96
+ - **Браузерный и Node.js WebAssembly (`cmd/rufuzzy-wasm`, `wasm/rufuzzy.js`):** компактный бинарник `1.09 МБ gzip` (0 путей хоста, 0 внешних JS-зависимостей) с прямой загрузкой и сохранением бинарного `.rfz` через `Uint8Array`;
97
+ - **Режимы для организаций и товаров, плюс потоковый CLI (`cmd/rufuzzy`):** `DefaultMatchOptions` для компаний и `ProductMatchOptions` для товарных каталогов (`PhoneticRulesVersion = 7` — побитово идентично движку `v0.4.3`, пересборка `.rfz` не требуется).
98
+
99
+ Если ваша обработка уже использует морфологию [rulemma](https://github.com/DimaKorshikov/rulemma), передавайте в `rufuzzy` остаток, который не сопоставился точными леммами — см. тетрадку [03 · Связка rulemma и rufuzzy](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/notebooks/03_rulemma_and_rufuzzy.ipynb).
100
+
101
+ ---
102
+
103
+ <a id="сравнение-качества-поиска"></a>
104
+
105
+ ## Сравнение качества поиска
106
+
107
+ Мы сравнили движок `rufuzzy` (качество измерено на `0.4.3`, в `0.5.0` Go-ядро и `PhoneticRulesVersion = 7` не менялись; замеры скорости `200k` и времени выполнения WebAssembly перенесены с чистых прогонов `0.4.1` без фоновой нагрузки на хост) с 12 вариантами решений на Python, настоящим `PostgreSQL 17.10 pg_trgm` и 3 Go-библиотеками. Для воспроизводимого замера используются скрипты [benchmarks/compare_models.py](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/benchmarks/compare_models.py), [benchmarks/bench_pg_trgm.py](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/benchmarks/bench_pg_trgm.py), [benchmarks/bench_wasm.py](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/benchmarks/bench_wasm.py) и [benchmarks/go_competitors/](https://github.com/DimaKorshikov/rufuzzy/tree/v0.5.0/benchmarks/go_competitors/). Каждый инструмент запускался в отдельном изолированном подпроцессе (`--worker`) на Linux x86_64 (32 потока, Go 1.23, Python 3.12.3, Node.js v22) на трёх открытых наборах:
108
+
109
+ - [tests/golden/golden_pairs.tsv](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/tests/golden/golden_pairs.tsv) — 455 пар по 6 срезам после построчной вычитки (57 пар с точным и опечаточным написанием, включая 10 контрольных совпадений; 49 пар русской фонетики; 162 пары EN↔RU, побуквенных акронимов и смешанных омоглифов; 41 организация с юрсуффиксами и доменами; 37 артикулов, единиц измерения и модификаторов; 109 трудных отрицательных пар);
110
+ - **Wikidata Aliases (CC0)** — 3 591 сущность, строгое разбиение `dev` (1 843 Q-ID для настройки общих правил) / `test` (1 748 Q-ID, 0 пересечений Q-ID, контрольный прогон), 681 русский алиас и 400 трудных отрицательных пар (зафиксированный CC0-архив публикуется в GitHub Release Assets для точного совпадения SHA-256);
111
+ - **Yandex Geo Reviews 2023 (MIT)** — 200 000 строк справочника (143 417 уникальных названий и 56 583 сочетания с указанием города) для замеров масштабирования Top-5 на 10k, 50k и 200k на едином фиксированном пуле из 100 запросов с проверкой попадания нужного варианта в Top-5 (`Top-5 hit`).
112
+
113
+ <p align="center">
114
+ <picture>
115
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/benchmark-dark.svg" />
116
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/benchmark-light.svg" />
117
+ <img src="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/benchmark-light.svg" alt="Сравнение методов поиска по названиям: Golden R@5, Wikidata CC0 RU→EN, Golden FPR и 200k организаций" width="960" />
118
+ </picture>
119
+ </p>
120
+
121
+ | Метод | RU→EN, Wikidata R@5 | Бренды, golden R@5 | FPR на 400 трудных парах Wikidata |
122
+ |---|---:|---:|---:|
123
+ | rufuzzy 0.4.3 (Index) | 91.7% | 98.1% | 4.0% |
124
+ | rufuzzy 0.4.3 (MatchTopK) | 91.8% | 100.0% | 4.0% |
125
+ | AnyAscii + RapidFuzz ratio | 87.6% | 94.4% | 27.8% |
126
+ | RapidFuzz ratio | 1.5% | 4.9% | 24.5% |
127
+ | RapidFuzz WRatio | 0.7% | 4.3% | 28.0% |
128
+
129
+ На контрольном наборе из 346 положительных и 109 отрицательных пар в полном переборе `MatchTopK` общий Recall@5 составил 100.0% по всем пяти положительным срезам (R@1 97.4%, MRR@10 0.987, ROC-AUC 0.999), в байтовом индексе `Index.Search` — 99.1%, против 97.4% у AnyAscii + RapidFuzz ratio и 54.6% у RapidFuzz WRatio. При пороге 0.80 rufuzzy не допустил ложных совпадений (0.0%), тогда как конкуренты ошиблись в 42.2% и 45.9% случаев.
130
+
131
+ ### Скорость и память на 200 000 организаций (Yandex Geo Reviews MIT)
132
+
133
+ | Инструмент | Запр. | Индексация / загрузка | p50 (1 запр.) | p99 (1 запр.) | Скорость | Top-5 hit | База / пик RSS |
134
+ |---|---:|---:|---:|---:|---:|---:|---:|
135
+ | rufuzzy 0.4.1 Index (Go, 1 поток) | 100 | 3 171 / 94 мс | 1.21 мс | 9.91 мс | 544.3 запр/с | 98% | 50.5 / 74.0 МБ |
136
+ | rufuzzy 0.4.1 Index batch (Go, 32 ядра) | 100 | 3 201 / 90 мс | — | — | 3 537.9 запр/с | 98% | 50.7 / 91.2 МБ |
137
+ | rufuzzy 0.4.1 Python ctypes (1 поток) | 100 | 3 167 / 89 мс | 1.75 мс | 9.49 мс | 428.9 запр/с | 98% | 74.9 / 100.9 МБ |
138
+ | rufuzzy 0.4.1 Python batch (32 ядра) | 100 | 3 122 / 93 мс | — | — | 3 171.2 запр/с | 98% | 74.8 / 116.8 МБ |
139
+ | PostgreSQL 17.10 pg_trgm (GIN %) | 100 | 1 663 мс / БД | 8.98 мс | 140.69 мс | 53.4 запр/с | 97% | 13.6 МБ индекс |
140
+ | PostgreSQL 17.10 pg_trgm (GiST KNN) | 100 | 4 779 мс / БД | 54.46 мс | 193.03 мс | 13.1 запр/с | 98% | 23.6 МБ индекс |
141
+ | AnyAscii + RapidFuzz ratio | 40 | 454 мс / — | 11.05 мс | 18.89 мс | 85.7 запр/с | 98% | 68.7 / 81.2 МБ |
142
+ | RapidFuzz WRatio (1 поток) | 40 | 37 мс / — | 487.14 мс | 1 569.15 мс | 1.7 запр/с | 90% | 73.5 / 86.9 МБ |
143
+ | RapidFuzz WRatio cdist (32 ядра) | 100 | 33 мс / — | — | — | 22.7 запр/с | 91% | 73.4 / 322.8 МБ |
144
+ | agnivade/levenshtein v1.2.2 (Go, O(N)) | 30 | — | 103.28 мс | — | 7.0 запр/с | 100% | — |
145
+ | RuMetaphone (2002, Python) | 100 | 1 568 мс / — | 0.41 мс | 1.85 мс | 2 008.4 запр/с | 61% | 114.1 / 115.0 МБ |
146
+
147
+ Для WebAssembly (`rufuzzy.wasm` в v0.4.3: 3.94 МБ без сжатия / 1.09 МБ `gzip -9`; замер времени выполнен на 0.4.1 без фоновой нагрузки) первый запуск занимает 52.9 мс в браузере Chromium и 27.7 мс в Node.js v22 (V8). В Node.js v22 (V8) по 100 фиксированных запросов для каждого размера медиана поиска Top-5 на 10 000 организаций составляет p50 = 3.72 мс (`.rfz` 2.85 МБ, загрузка из памяти 36 мс, Top-5 hit = 100%), а на 50 000 организаций — p50 = 3.12 мс (`.rfz` 12.85 МБ, загрузка 144 мс, Top-5 hit = 100%).
148
+
149
+ По сравнению с полным перебором `MatchTopK` байтовый индекс `Index.Search` на контрольном `Wikidata test` (1 748 запросов RU→EN) удерживает 91.7% Recall@5 против 91.8% (−0.1 п.п., при росте R@1 до 85.5%), на EN→RU — 91.2% (R@1 85.8%), на русских алиасах RU→RU — 64.8% против 63.1% (+1.6 п.п.), а на 346 положительных парах `tests/golden/` — 99.1% против 100.0% (−0.9 п.п.).
150
+
151
+ <details>
152
+ <summary>Примеры оценок: положительные пары и артикулы против трудных ловушек (порог 0.80)</summary>
153
+
154
+ <br />
155
+
156
+ | Пара | Тип проверки | Оценка rufuzzy | Порог 0.80 |
157
+ |---|---|---:|---|
158
+ | сяоми ↔ Xiaomi | EN↔RU бренд | 1.000 | совпадение |
159
+ | грюндфос ↔ Grundfos | EN↔RU вариант гласной и оглушение | 1.000 | совпадение |
160
+ | ниндзя ↔ Ninja | EN↔RU диграф `дз`/`nj` | 1.000 | совпадение |
161
+ | ООО «ТехноМир» ↔ Техномир | Очистка юрсуффиксов (`entity`) | 1.000 | совпадение |
162
+ | P-6000 ↔ P6000 / Bort BWS-900 ↔ Bort BWS900 | Компактные 1–3-буквенные артикулы (`product`) | 1.000 | совпадение |
163
+ | збербанк ↔ сбербанк | Русская фонетика | 0.978 | совпадение |
164
+ | СберСтрахование vs СберСтрахование жизни | Дочерняя организация с ролевым словом | 0.750 | разные сущности |
165
+ | омск vs томск | Короткий топоним | 0.556 | разные сущности |
166
+ | iPhone SE vs iPhone | Модификатор модели | 0.543 | разные сущности |
167
+ | Bosch vs Boss | Короткий бренд | 0.504 | разные сущности |
168
+ | iPhone 14 vs iPhone 15 | Номер модели | 0.467 | разные сущности |
169
+ | чехол для Samsung vs Samsung | Аксессуар vs основной товар | 0.420 | разные сущности |
170
+ | Bort BWS-900 vs Bort BWS-950 | Разный номер артикула | 0.471 | разные сущности |
171
+
172
+ Полный запускаемый пример: [examples/04_contrastive_pairs_and_thresholds/main.go](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/04_contrastive_pairs_and_thresholds/main.go) и [examples/08_python_ctypes_bindings/demo.py](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/08_python_ctypes_bindings/demo.py).
173
+
174
+ </details>
175
+
176
+ ### Открытые оговорки по методике замера
177
+
178
+ 1. **Состав выборки Wikidata.** В контрольном срезе 1 176 из 1 748 запросов относятся к городам. rufuzzy опережает AnyAscii + RapidFuzz ratio на всех шести срезах сущностей: на 85 брендах — 94.1% против 85.9%, на 151 торговой марке — 88.7% против 85.4%, на 206 предприятиях — 79.1% против 75.2%, на 103 записях бизнеса — 77.7% против 63.1%, на 27 автопроизводителях — 70.4% против 59.3% и на 1 176 городах — 95.9% против 92.9%. Справочник содержит 1 735 уникальных английских названий; проверяется попадание нужного варианта в пятёрку, поэтому у 26 одноимённых сущностей (1.5%, 13 коллизионных записей) идентификатор Q-ID может различаться.
179
+ 2. **Настройка порога объединения записей.** 400 отрицательных пар Wikidata специально отобраны по высокому строковому сходству внутри одного алфавита. Из них 16 пар (4.0%) прошли порог 0.80 у rufuzzy (против 27.8% у AnyAscii + RapidFuzz ratio). Для автоматического объединения записей порог стоит настроить на размеченных примерах своего каталога. Открытый набор `tests/golden/` (455 пар после построчной вычитки) служит регрессионным тестом правил.
180
+ 3. **Условия замера памяти и масштабирования.** Для `rufuzzy` (и в Go, и в Python `ctypes`) задержка и RSS измерены в чистом процессе после загрузки сохранённого бинарного индекса `.rfz` (`48.0 МБ`, `LoadIndex` за 89–94 мс с двойной проверкой SHA-256 и границ секций; сборка индекса из текста `BuildIndex` занимает ~3.1–3.2 с и временно использует больше памяти на сортировку постингов — см. `build_peak_rss_mb` в JSON). Все размеры файлов и памяти в таблицах указаны в двоичных мегабайтах (`1 МБ = 1024 × 1024 байт`, в JSON — поля `*_mib` / `*_mb`). Все инструменты на 200 тыс. организаций получают единый фиксированный пул запросов; для медленных методов с линейным перебором берётся его детерминированный префикс (100 строк у `rufuzzy`, `RapidFuzz cdist`, `PostgreSQL`, `RuMetaphone`, 3-грамм и `TF-IDF`; 40 у одиночных `RapidFuzz` и `AnyAscii`; 30 у `agnivade/levenshtein`; 10 у `jellyfish`; 3 у `thefuzz`; 2 у `difflib` — точное число показано в столбце «Запр.» и поле `n_queries`). Скорость (`запр/с`) в таблицах вычислена из общего времени серии (для PostgreSQL — по сумме серверных времён отдельных запросов внутри БД), а `Base RSS` и `Peak RSS` снимаются из одного источника (`/proc/self/status`).
181
+
182
+ Полные таблицы по всем конфигурациям, `10k / 50k / 200k`, Go-библиотекам, `PostgreSQL 17 pg_trgm`, WebAssembly и SHA-256 входных файлов собраны в [benchmarks/RESULTS.md](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/benchmarks/RESULTS.md) и [benchmarks/results.json](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/benchmarks/results.json).
183
+
184
+ ---
185
+
186
+ <a id="быстрый-старт"></a>
187
+
188
+ ## Быстрый старт (Go, Python, CLI и WebAssembly)
189
+
190
+ Модуль Go не имеет внешних зависимостей; конкурентное чтение `Prepared`, `MatchTopK`, `Index` и `Registry` проверено под `go test -count=1 -race ./...`.
191
+
192
+ ```bash
193
+ go get github.com/DimaKorshikov/rufuzzy@v0.5.0
194
+ ```
195
+
196
+ ```go
197
+ package main
198
+
199
+ import (
200
+ "fmt"
201
+
202
+ "github.com/DimaKorshikov/rufuzzy"
203
+ )
204
+
205
+ func main() {
206
+ // 1. Построение индекса на байтовых аренах (0 указателей для GC)
207
+ catalog := []string{
208
+ "Xiaomi", "Grundfos", "Kärcher", "Nike P-6000",
209
+ "DeWalt DWE560K", "Bort BWS900", "iPhone 14", "iPhone 15",
210
+ }
211
+ idx := rufuzzy.BuildIndex(catalog, rufuzzy.ProductIndexOptions())
212
+
213
+ // 2. Поиск Top-K с разбором оценки и SHA-256 отпечатком
214
+ hits := idx.Search("ксяоми", 3)
215
+ fmt.Printf("Top-1: %s (score=%.3f, cross=%.3f, fp=%s)\n",
216
+ hits[0].Text, hits[0].Score, hits[0].Breakdown.CrossScript, idx.Fingerprint()[:12])
217
+
218
+ // 3. Сохранение и потоковая загрузка с проверкой SHA-256
219
+ _ = idx.Save("catalog.rfz")
220
+ loaded, _ := rufuzzy.LoadIndex("catalog.rfz")
221
+ fmt.Println("Загружено сущностей:", loaded.Len())
222
+
223
+ // 4. Точечная оценка пары: 1–3-буквенные артикулы, модели и единицы
224
+ fmt.Printf("DeWalt DWE-560K vs DeWalt DWE560K: %.3f\n",
225
+ rufuzzy.Score("DeWalt DWE-560K", "DeWalt DWE560K", rufuzzy.ProductMatchOptions()).Score)
226
+ fmt.Printf("iPhone 14 vs iPhone 15: %.3f\n",
227
+ rufuzzy.Score("iPhone 14", "iPhone 15", rufuzzy.ProductMatchOptions()).Score)
228
+ }
229
+ ```
230
+
231
+ <details>
232
+ <summary>Python: установка из PyPI (pip install rufuzzy), C-ABI v1 и ctypes (0 зависимостей)</summary>
233
+
234
+ Пакет `rufuzzy` использует только стандартную библиотеку Python (`ctypes`) и обращается напрямую к встроенному бинарному модулю `librufuzzy` (`C-ABI v1`, 0 внешних зависимостей). Готовые колёса собраны для Linux (`x86_64`, `aarch64`), macOS (`11+`, Apple Silicon и Intel) и Windows (`win_amd64`) — компилятор Go для установки не нужен.
235
+
236
+ ```bash
237
+ # Установка готового колеса из PyPI (Python 3.9+, компилятор Go не требуется)
238
+ pip install rufuzzy
239
+
240
+ # Или локальная сборка из исходников репозитория (требуется Go 1.23+)
241
+ pip install .
242
+ ```
243
+
244
+ Рецепт для публикации в `conda-forge` (`conda install -c conda-forge rufuzzy`) находится в [packaging/conda-forge/](https://github.com/DimaKorshikov/rufuzzy/tree/v0.5.0/packaging/conda-forge/).
245
+
246
+ ```python
247
+ from rufuzzy import RuFuzzy, RuFuzzyIndex, check_version
248
+
249
+ check_version(min_version="0.5.0", expected_abi=1, expected_rules=7)
250
+
251
+ # Попарная оценка и фонетика (профиль 'product' сохраняет единицы и склеивает 1–3-буквенные артикулы)
252
+ rf = RuFuzzy(profile="product")
253
+ print(rf.score("ксяоми", "Xiaomi").score) # 1.000
254
+ print(rf.score("Bort BWS-900", "Bort BWS900").score) # 1.000
255
+ print(rf.score("Bort BWS-900", "Bort BWS-950").score) # 0.471
256
+
257
+ # Построение/сохранение байтового индекса .rfz и многопоточный поиск search_batch
258
+ with RuFuzzyIndex.build(["Xiaomi", "Grundfos", "Bort BWS900"], profile="product") as idx:
259
+ idx.save("catalog.rfz")
260
+ batch = idx.search_batch(["ксяоми", "Bort BWS-900"], top_k=3)
261
+ ```
262
+
263
+ > В многопроцессном коде на Linux используйте `multiprocessing` в режиме `spawn` либо загружайте `rufuzzy` после `fork()`: при попытке вызова после `fork()` в дочернем процессе библиотека сразу поднимет `RuFuzzyForkError`.
264
+
265
+ </details>
266
+
267
+ <details>
268
+ <summary>WebAssembly: браузер и Node.js (1.09 МБ gzip, 0 JS-зависимостей, бинарный .rfz)</summary>
269
+
270
+ Модуль `cmd/rufuzzy-wasm` компилируется стандартным компилятором Go (`-trimpath -ldflags="-s -w"`, 0 путей хоста) и подключается через тонкую обёртку `wasm/rufuzzy.js`.
271
+
272
+ ```bash
273
+ # Сборка автономного каталога build/wasm/ (rufuzzy.wasm, wasm_exec.js, rufuzzy.js, index.html)
274
+ make build-wasm
275
+
276
+ # Запуск примера в Node.js (v20+, либо v18 с globalThis.crypto)
277
+ node examples/10_browser_wasm/demo_node.mjs
278
+
279
+ # Безопасный локальный запуск в браузере (только 127.0.0.1 и только каталог build/wasm)
280
+ python3 -m http.server 8080 --bind 127.0.0.1 --directory build/wasm
281
+ ```
282
+
283
+ ```js
284
+ // В браузере (при раздаче build/wasm) после подключения <script src="./wasm_exec.js"> и <script src="./rufuzzy.js">
285
+ const rf = await window.RuFuzzyWasm.load({ wasmUrl: "./rufuzzy.wasm" });
286
+ console.log(rf.score("ниндзя", "Ninja", "entity").score); // 1.0
287
+ console.log(rf.score("Bort BWS-900", "Bort BWS900", "product").score); // 1.0
288
+
289
+ // Можно построить индекс в браузере или загрузить готовый бинарный .rfz (Uint8Array)
290
+ const idx = rf.buildIndex(["Xiaomi", "Grundfos", "Bort BWS900"], { profile: "product" });
291
+ const rfzBytes = idx.saveBytes();
292
+ idx.close();
293
+
294
+ const loaded = rf.loadIndexBytes(rfzBytes);
295
+ console.log(loaded.search("ксяоми", { topK: 3 }));
296
+ loaded.close();
297
+ await rf.close();
298
+ ```
299
+
300
+ Полный запускаемый пример с HTML-демо и Node.js-скриптом: [examples/10_browser_wasm/](https://github.com/DimaKorshikov/rufuzzy/tree/v0.5.0/examples/10_browser_wasm/).
301
+
302
+ </details>
303
+
304
+ <details>
305
+ <summary>Многоиндексный Registry в Go: горячее обновление .rfz и отмена по контексту</summary>
306
+
307
+ ```go
308
+ reg := rufuzzy.NewRegistry(rufuzzy.DefaultRegistryOptions())
309
+ defer reg.Close()
310
+
311
+ // Первичная регистрация и атомарная замена справочника из .rfz без простоя запросов
312
+ meta, err := reg.LoadAndRegister("brands", "/var/lib/rufuzzy/brands.rfz")
313
+ if err != nil {
314
+ panic(err)
315
+ }
316
+
317
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
318
+ defer cancel()
319
+
320
+ // Пакетный поиск с контролем лимитов (MaxBatchSize, MaxQueryRunes, MaxTopK) и таймаута
321
+ batch, err := reg.SearchBatch(ctx, "brands", []string{"ксяоми", "грюндфос"}, 5, 0, nil)
322
+ fmt.Println(meta.Fingerprint[:12], len(batch))
323
+ ```
324
+
325
+ Полный запускаемый пример с горячим обновлением и статистикой памяти: [examples/09_registry_hot_reload/main.go](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/09_registry_hot_reload/main.go).
326
+
327
+ </details>
328
+
329
+ <details>
330
+ <summary>Потоковый CLI (сборка индекса .rfz и поиск по TSV/CSV/stdin)</summary>
331
+
332
+ ```bash
333
+ # Сборка CLI (0 внешних зависимостей)
334
+ go install github.com/DimaKorshikov/rufuzzy/cmd/rufuzzy@v0.5.0
335
+ # или локально из репозитория: make build-cli
336
+
337
+ # Быстрые команды для проверки ключей и пар
338
+ rufuzzy version
339
+ rufuzzy phonetic "ООО «ТехноМир»"
340
+ rufuzzy score --json "ксяоми" "Xiaomi"
341
+
342
+ # Индексация справочника в бинарный файл .rfz и потоковый поиск с сохранением порядка строк
343
+ rufuzzy index --in catalog.tsv --out catalog.rfz --col 2 --header
344
+ rufuzzy match --index catalog.rfz --in queries.tsv --col 2 --header --top 5 --workers 8 > matches.tsv
345
+ ```
346
+
347
+ </details>
348
+
349
+ ---
350
+
351
+ <a id="архитектура-поиска"></a>
352
+
353
+ ## Как устроен поиск
354
+
355
+ <p align="center">
356
+ <picture>
357
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/pipeline-dark.svg" />
358
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/pipeline-light.svg" />
359
+ <img src="https://raw.githubusercontent.com/DimaKorshikov/rufuzzy/v0.5.0/assets/pipeline-light.svg" alt="Двухступенчатая схема rufuzzy: нормализация, отбор кандидатов по триграммам и фонетике и точное ранжирование" width="960" />
360
+ </picture>
361
+ </p>
362
+
363
+ Подробный разбор альтернатив (Go, Rust, C++, Python) и фонетических алгоритмов: [docs/research/2026-11-29-landscape-and-architecture.md](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/docs/research/2026-11-29-landscape-and-architecture.md).
364
+
365
+ ---
366
+
367
+ <a id="примеры-и-jupyter-тетрадки"></a>
368
+
369
+ ## Примеры и Jupyter-тетрадки
370
+
371
+ В папке [examples/](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/README.md) собраны два набора проверяемых примеров (автоматически выполняются в CI через `tests/test_examples.py` и `tests/test_wasm.py`):
372
+
373
+ - **10 локальных примеров (`examples/01..10`):** [фонетика RU и EN↔RU](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/01_phonetic_ru_and_cross_script/main.go), [строковые метрики и веса](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/02_string_metrics_and_weights/main.go), [нормализация юрсуффиксов и омоглифов](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/03_entity_normalization_and_legal_suffixes/main.go), [контрастные пары](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/04_contrastive_pairs_and_thresholds/main.go), [байтовый индекс Top-K и SearchBatch](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/05_index_top_k_and_breakdown/main.go), [сохранение и загрузка `.rfz` с SHA-256](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/06_index_save_load/main.go), [потоковый CLI по TSV](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/07_cli_tsv_matching/pipeline.sh), [Python `ctypes` и `.rfz`](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/08_python_ctypes_bindings/demo.py), [многоиндексный Go `Registry` с горячим обновлением](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/09_registry_hot_reload/main.go) и [браузерный и Node.js WebAssembly](https://github.com/DimaKorshikov/rufuzzy/tree/v0.5.0/examples/10_browser_wasm/).
374
+ - **3 интерактивные Jupyter/Colab-тетрадки ([examples/notebooks/](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/notebooks/README.md)):**
375
+ - [01 · Сравнение rufuzzy и RapidFuzz](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/notebooks/01_rufuzzy_vs_rapidfuzz.ipynb) ([открыть в Google Colab](https://colab.research.google.com/github/DimaKorshikov/rufuzzy/blob/main/examples/notebooks/01_rufuzzy_vs_rapidfuzz.ipynb));
376
+ - [02 · Байтовый индекс на 200 тыс. строк и потоковый CLI](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/notebooks/02_index_200k_and_cli.ipynb) ([открыть в Google Colab](https://colab.research.google.com/github/DimaKorshikov/rufuzzy/blob/main/examples/notebooks/02_index_200k_and_cli.ipynb));
377
+ - [03 · Связка морфологии (`rulemma`) и `rufuzzy` в Python](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/examples/notebooks/03_rulemma_and_rufuzzy.ipynb) ([открыть в Google Colab](https://colab.research.google.com/github/DimaKorshikov/rufuzzy/blob/main/examples/notebooks/03_rulemma_and_rufuzzy.ipynb)).
378
+
379
+ ---
380
+
381
+ ## Когда лучше взять RapidFuzz, pg_trgm, fuse.js или Elasticsearch
382
+
383
+ - Берите **RapidFuzz**, если нужно быстро сравнить две одноязычные строки или небольшой список без русской фонетики и кросс-языковых брендов.
384
+ - Берите **PostgreSQL `pg_trgm`**, если справочник уже хранится в Postgres, нужен SQL-поиск по подстрокам внутри одного алфавита и не требуется EN↔RU фонетика.
385
+ - Берите **fuse.js / fuzzysort / MiniSearch**, если нужен простой клиентский автокомплит (`Cmd+K`) по одноязычному списку без русской фонетики и юрсуффиксов.
386
+ - Берите **Elasticsearch / OpenSearch** или векторные эмбеддинги, если нужен распределённый полнотекстовый кластер на миллионы документов или поиск смысловых синонимов («диван ↔ софа»).
387
+ - Берите **rufuzzy**, если сопоставляете русские и латинские бренды, организации, артикулы и названия моделей, хотите отличать `iPhone 14` от `15` и `Омск` от `Томска` и запускаться в Go, Python (`ctypes`), CLI или браузере через WebAssembly без внешних зависимостей.
388
+
389
+ <details>
390
+ <summary>Структура репозитория</summary>
391
+
392
+ ```text
393
+ rufuzzy/
394
+ ├── version.go # Version 0.5.0, ABI 1, IndexSchema 1, PhoneticRules 7, GetVersionInfo
395
+ ├── normalize.go # NormalizeEntity, омоглифы, диакритика, юрсуффиксы, домены, числа
396
+ ├── phonetic_ru.go # Улучшенный RuMetaphone (оглушение, редукция, аффрикаты)
397
+ ├── phonetic_cross.go # Проектор CrossScriptKeys (EN<->RU) и 1-к-1 матчинг токенов
398
+ ├── metrics.go # Myers u64 Levenshtein, Damerau, WeightedDamerau, JW, 3-gram
399
+ ├── score.go # Prepare, Score, MatchTopK, 1–3-буквенные артикулы и суффиксы, защита моделей
400
+ ├── arena.go # Плоские байтовые арены и uint32 постинги (0 указателей GC)
401
+ ├── index.go # BuildIndex, BuildIndexContext, Search, SearchContext, SearchBatchContext, Fingerprint
402
+ ├── index_io.go # Атомарный Save, потоковый LoadIndex и LoadIndexMemory (SHA-256)
403
+ ├── registry.go # Потокобезопасный Registry, LoadDir, BuildAndRegisterContext, лимиты памяти
404
+ ├── capi/ # Стабильный C-ABI v1 (18 символов rufuzzy_*, JSON-конверты, free_str)
405
+ ├── python/rufuzzy/ # Python-пакет (pip install rufuzzy, 0 deps): RuFuzzy и RuFuzzyIndex (ctypes)
406
+ ├── packaging/ # Рецепт conda-forge (rattler-build recipe.yaml) и инструкция публикации
407
+ ├── cmd/rufuzzy/ # Потоковый CLI (version, phonetic, distance, score, index, match)
408
+ ├── cmd/rufuzzy-wasm/ # Браузерный и Node.js WebAssembly (1.09 МБ gzip, -trimpath)
409
+ ├── wasm/ # Тонкая JS-обёртка rufuzzy.js (0 зависимостей, браузер + Node.js)
410
+ ├── cmd/rufuzzy-bench/ # Изолированный Go-раннер для benchmarks/compare_models.py
411
+ ├── docs/ # Исследование рынка, алгоритмов и архитектуры
412
+ ├── examples/ # 10 проверяемых примеров (Go/Python/CLI/WASM) и 3 Colab-тетрадки
413
+ ├── benchmarks/ # compare_models.py, bench_pg_trgm.py, bench_wasm.py, go_competitors/, render_charts.py
414
+ ├── assets/ # Акварельная обложка cover.jpg и Light/Dark SVG-графики
415
+ ├── tests/ # tests/golden/golden_pairs.tsv (455 пар, 6 срезов) и автотесты Python/WASM
416
+ └── tools/ # release_check.py (версии, синхронность README, SVG, WASM, гигиена)
417
+ ```
418
+
419
+ </details>
420
+
421
+ <details>
422
+ <summary>Воспроизведение тестов, бенчмарков и графиков</summary>
423
+
424
+ ```bash
425
+ # Проверка версий, Go (-race), C-ABI, Python, WASM, эталонного набора, примеров и тетрадок
426
+ make release-check
427
+
428
+ # Воспроизведение сравнения с конкурентами (Wikidata CC0 + Geo Reviews MIT + WASM)
429
+ python3 -m venv .venv-bench
430
+ .venv-bench/bin/pip install -r benchmarks/requirements.txt
431
+ make fetch-bench-data
432
+ make bench
433
+ python3 benchmarks/bench_wasm.py
434
+ make charts
435
+ ```
436
+
437
+ </details>
438
+
439
+ ---
440
+
441
+ ## Авторы и лицензия
442
+
443
+ Авторы: **Коршиков Дмитрий и Gemini**. Часть открытой экосистемы [rulemma.ru](https://rulemma.ru/).
444
+
445
+ Код распространяется под лицензией MIT — см. [LICENSE](https://github.com/DimaKorshikov/rufuzzy/blob/v0.5.0/LICENSE). Открытые эталоны для воспроизводимых бенчмарков загружаются отдельно (`benchmarks/fetch_open_datasets.py`) либо распаковываются из CC0-архива релиза с соблюдением лицензий источников (`Wikidata CC0-1.0`, `Yandex Geo Reviews 2023 MIT`).
@@ -0,0 +1,10 @@
1
+ rufuzzy/LICENSE,sha256=h7akLSBz2gDC6-rgCZ3y92uSgpcEtghwZGEDljLGYrg,1107
2
+ rufuzzy/__init__.py,sha256=pVICfYx9JX8VuDxehaO79b1RXPzCWHCyRl6KGLBsp1o,1110
3
+ rufuzzy/_native.py,sha256=nAaXEYKGkx5NbFze3w13doXfhhWHfjhhaOJHd7dq8tk,8273
4
+ rufuzzy/client.py,sha256=5IdIs7a5XYBRxMnt_rr_yJXBI_L8xCdKSTUHcfydALo,15397
5
+ rufuzzy/rufuzzy.dll,sha256=Fk3Mr_o_nHFHeFAr-Z9t6im1kF3lrTNkuX-mxMMF288,2618368
6
+ rufuzzy-0.5.0.dist-info/licenses/LICENSE,sha256=h7akLSBz2gDC6-rgCZ3y92uSgpcEtghwZGEDljLGYrg,1107
7
+ rufuzzy-0.5.0.dist-info/METADATA,sha256=Wd5-WbeyGQJMgQjsJVYsiQh7hMqN93S9zOk5wkB5bs0,43761
8
+ rufuzzy-0.5.0.dist-info/WHEEL,sha256=79BCzrXBJOa2YV6ugKrK59dqWifMGjAkgVd_6AQrqbU,98
9
+ rufuzzy-0.5.0.dist-info/top_level.txt,sha256=u0z-sD-B6FEP-lFBjgk1t4TMm7sDPaW35J5Rdu4v_gQ,8
10
+ rufuzzy-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitry Korshikov (Коршиков Дмитрий)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ rufuzzy