entmatch 0.3.0rc1__py3-none-any.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.
Files changed (241) hide show
  1. entmatch/__init__.py +87 -0
  2. entmatch/__main__.py +7 -0
  3. entmatch/_brand.py +13 -0
  4. entmatch/_hashkey.py +50 -0
  5. entmatch/_hints.py +55 -0
  6. entmatch/_licences.py +42 -0
  7. entmatch/_model_hub.py +36 -0
  8. entmatch/_version.py +3 -0
  9. entmatch/abstain.py +25 -0
  10. entmatch/adapters/__init__.py +67 -0
  11. entmatch/adapters/dedupe_gaz.py +87 -0
  12. entmatch/adapters/gliner_labels.py +58 -0
  13. entmatch/adapters/sbert.py +87 -0
  14. entmatch/adapters/subprocess_gen.py +74 -0
  15. entmatch/adapters/xmen_gen.py +33 -0
  16. entmatch/agent/__init__.py +21 -0
  17. entmatch/agent/audit.py +78 -0
  18. entmatch/agent/runner.py +225 -0
  19. entmatch/agent/tools.py +81 -0
  20. entmatch/agent/types.py +64 -0
  21. entmatch/audit_ids.py +66 -0
  22. entmatch/batch.py +91 -0
  23. entmatch/builtin/__init__.py +1 -0
  24. entmatch/builtin/assign/__init__.py +4 -0
  25. entmatch/builtin/assign/basic.py +61 -0
  26. entmatch/builtin/assign/unique_mapping.py +47 -0
  27. entmatch/builtin/audit/__init__.py +1 -0
  28. entmatch/builtin/audit/jsonl.py +69 -0
  29. entmatch/builtin/calibrators/__init__.py +4 -0
  30. entmatch/builtin/calibrators/isotonic.py +92 -0
  31. entmatch/builtin/calibrators/platt.py +121 -0
  32. entmatch/builtin/comparators/__init__.py +0 -0
  33. entmatch/builtin/comparators/_common.py +86 -0
  34. entmatch/builtin/comparators/date_window.py +50 -0
  35. entmatch/builtin/comparators/directional.py +52 -0
  36. entmatch/builtin/comparators/enum_map.py +39 -0
  37. entmatch/builtin/comparators/fieldwise.py +53 -0
  38. entmatch/builtin/comparators/levels.py +148 -0
  39. entmatch/builtin/comparators/numeric_tol.py +57 -0
  40. entmatch/builtin/comparators/relation.py +36 -0
  41. entmatch/builtin/comparators/set_overlap.py +45 -0
  42. entmatch/builtin/comparators/tf_adjust.py +65 -0
  43. entmatch/builtin/deciders/__init__.py +3 -0
  44. entmatch/builtin/deciders/field_policy.py +212 -0
  45. entmatch/builtin/deciders/threshold.py +169 -0
  46. entmatch/builtin/embedders/__init__.py +13 -0
  47. entmatch/builtin/embedders/cache.py +59 -0
  48. entmatch/builtin/embedders/hashing.py +59 -0
  49. entmatch/builtin/embedders/http.py +102 -0
  50. entmatch/builtin/embedders/sbert.py +61 -0
  51. entmatch/builtin/explain/__init__.py +3 -0
  52. entmatch/builtin/explain/tokens.py +37 -0
  53. entmatch/builtin/fusion/__init__.py +4 -0
  54. entmatch/builtin/fusion/fusers.py +113 -0
  55. entmatch/builtin/fusion/rrf.py +54 -0
  56. entmatch/builtin/generators/__init__.py +18 -0
  57. entmatch/builtin/generators/_util.py +40 -0
  58. entmatch/builtin/generators/alias_exact.py +49 -0
  59. entmatch/builtin/generators/attribute_block.py +27 -0
  60. entmatch/builtin/generators/dense.py +326 -0
  61. entmatch/builtin/generators/fullscan.py +13 -0
  62. entmatch/builtin/generators/lexical.py +221 -0
  63. entmatch/builtin/generators/prior.py +138 -0
  64. entmatch/builtin/index/__init__.py +4 -0
  65. entmatch/builtin/index/flat.py +182 -0
  66. entmatch/builtin/index/persist.py +144 -0
  67. entmatch/builtin/index/rerank.py +125 -0
  68. entmatch/builtin/normalize/__init__.py +0 -0
  69. entmatch/builtin/normalize/default.py +26 -0
  70. entmatch/builtin/render.py +44 -0
  71. entmatch/builtin/rollups/__init__.py +0 -0
  72. entmatch/builtin/rollups/weighted_mean.py +49 -0
  73. entmatch/builtin/stores/__init__.py +1 -0
  74. entmatch/builtin/stores/file.py +101 -0
  75. entmatch/builtin/verify/__init__.py +20 -0
  76. entmatch/builtin/verify/guard.py +156 -0
  77. entmatch/builtin/verify/never_none.py +46 -0
  78. entmatch/builtin/verify/rules.py +96 -0
  79. entmatch/builtin/verify/sampling.py +41 -0
  80. entmatch/builtin/verify/voter.py +110 -0
  81. entmatch/business_weights.py +118 -0
  82. entmatch/canon/__init__.py +29 -0
  83. entmatch/canon/core.py +245 -0
  84. entmatch/canon/enum.py +253 -0
  85. entmatch/canon/infer.py +56 -0
  86. entmatch/catalog.py +935 -0
  87. entmatch/cli.py +220 -0
  88. entmatch/cli_catalog.py +110 -0
  89. entmatch/cli_v3.py +399 -0
  90. entmatch/code_channel.py +291 -0
  91. entmatch/config/__init__.py +23 -0
  92. entmatch/config/expr.py +87 -0
  93. entmatch/config/load.py +41 -0
  94. entmatch/config/schema.py +214 -0
  95. entmatch/contrib/__init__.py +1 -0
  96. entmatch/contrib/restricted/__init__.py +14 -0
  97. entmatch/contrib/workers/__init__.py +6 -0
  98. entmatch/contrib/workers/echo_worker.py +25 -0
  99. entmatch/contrib/workers/xmen_worker.py +53 -0
  100. entmatch/dedupe/__init__.py +8 -0
  101. entmatch/dedupe/api.py +133 -0
  102. entmatch/dedupe/blocking.py +90 -0
  103. entmatch/dedupe/cluster.py +139 -0
  104. entmatch/dedupe/family.py +249 -0
  105. entmatch/dedupe/scoring.py +77 -0
  106. entmatch/eval/__init__.py +27 -0
  107. entmatch/eval/bootstrap.py +95 -0
  108. entmatch/eval/calibration.py +119 -0
  109. entmatch/eval/cluster_metrics.py +65 -0
  110. entmatch/eval/golden.py +61 -0
  111. entmatch/eval/metrics.py +89 -0
  112. entmatch/eval/protocol.py +259 -0
  113. entmatch/eval/report.py +85 -0
  114. entmatch/eval/splits.py +122 -0
  115. entmatch/exact_rerank.py +376 -0
  116. entmatch/export.py +617 -0
  117. entmatch/extract/__init__.py +84 -0
  118. entmatch/extract/blocks.py +255 -0
  119. entmatch/extract/cascade.py +56 -0
  120. entmatch/extract/coerce.py +45 -0
  121. entmatch/extract/llm.py +221 -0
  122. entmatch/extract/ner.py +330 -0
  123. entmatch/extract/pdf_render.py +125 -0
  124. entmatch/extract/ports.py +61 -0
  125. entmatch/extract/regex.py +46 -0
  126. entmatch/extract/relations.py +81 -0
  127. entmatch/extract/roles.py +115 -0
  128. entmatch/extract/row_ner.py +62 -0
  129. entmatch/extract/schema_map.py +224 -0
  130. entmatch/extract/structure.py +241 -0
  131. entmatch/extract/table.py +106 -0
  132. entmatch/extract/testing.py +26 -0
  133. entmatch/extract/types.py +70 -0
  134. entmatch/facade.py +725 -0
  135. entmatch/feasibility.py +364 -0
  136. entmatch/gapfill/__init__.py +187 -0
  137. entmatch/genai/__init__.py +46 -0
  138. entmatch/genai/adapters/__init__.py +1 -0
  139. entmatch/genai/adapters/_common.py +21 -0
  140. entmatch/genai/adapters/anthropic.py +69 -0
  141. entmatch/genai/adapters/bedrock.py +67 -0
  142. entmatch/genai/adapters/local_openai.py +91 -0
  143. entmatch/genai/adapters/openai.py +64 -0
  144. entmatch/genai/batch.py +217 -0
  145. entmatch/genai/cache.py +63 -0
  146. entmatch/genai/client.py +65 -0
  147. entmatch/genai/cost.py +50 -0
  148. entmatch/genai/fake.py +44 -0
  149. entmatch/genai/managed.py +96 -0
  150. entmatch/genai/prompts.py +55 -0
  151. entmatch/genai/redact.py +49 -0
  152. entmatch/genai/types.py +67 -0
  153. entmatch/glossary/__init__.py +32 -0
  154. entmatch/glossary/apply.py +117 -0
  155. entmatch/glossary/miners.py +204 -0
  156. entmatch/glossary/models.py +66 -0
  157. entmatch/glossary/normalizer.py +57 -0
  158. entmatch/glossary/pack.py +346 -0
  159. entmatch/glossary/registry.py +168 -0
  160. entmatch/glossary/researcher.py +126 -0
  161. entmatch/glossary/unknown.py +364 -0
  162. entmatch/hub.py +190 -0
  163. entmatch/intake/__init__.py +46 -0
  164. entmatch/intake/adapters.py +213 -0
  165. entmatch/intake/cognitive.py +71 -0
  166. entmatch/intake/context.py +52 -0
  167. entmatch/intake/document.py +69 -0
  168. entmatch/intake/forwarded.py +146 -0
  169. entmatch/intake/router.py +180 -0
  170. entmatch/interop/__init__.py +0 -0
  171. entmatch/interop/networkx.py +25 -0
  172. entmatch/kpack.py +280 -0
  173. entmatch/lazy.py +225 -0
  174. entmatch/learn/__init__.py +20 -0
  175. entmatch/learn/base.py +103 -0
  176. entmatch/learn/ensemble.py +81 -0
  177. entmatch/learn/estimators.py +168 -0
  178. entmatch/learn/level_weights.py +44 -0
  179. entmatch/learn/pipeline.py +165 -0
  180. entmatch/local/__init__.py +28 -0
  181. entmatch/local/cli.py +89 -0
  182. entmatch/local/embed.py +86 -0
  183. entmatch/local/errors.py +47 -0
  184. entmatch/local/ollama.py +215 -0
  185. entmatch/match_report.py +212 -0
  186. entmatch/matcher.py +238 -0
  187. entmatch/models/__init__.py +51 -0
  188. entmatch/models/_backend.py +84 -0
  189. entmatch/models/base.py +7 -0
  190. entmatch/models/comparison.py +54 -0
  191. entmatch/models/decision.py +85 -0
  192. entmatch/models/entity.py +93 -0
  193. entmatch/models/frame.py +489 -0
  194. entmatch/models/graph.py +212 -0
  195. entmatch/models/reason_report.py +41 -0
  196. entmatch/models/reasons.py +42 -0
  197. entmatch/models/relations.py +71 -0
  198. entmatch/nil_detector.py +141 -0
  199. entmatch/onboard.py +243 -0
  200. entmatch/plugins.py +33 -0
  201. entmatch/ports/__init__.py +41 -0
  202. entmatch/ports/assign.py +40 -0
  203. entmatch/ports/business_policy.py +65 -0
  204. entmatch/ports/comparator.py +35 -0
  205. entmatch/ports/embedder.py +51 -0
  206. entmatch/ports/explain.py +29 -0
  207. entmatch/ports/fuser.py +28 -0
  208. entmatch/ports/generator.py +45 -0
  209. entmatch/ports/scorer.py +54 -0
  210. entmatch/ports/verify.py +46 -0
  211. entmatch/py.typed +0 -0
  212. entmatch/registry/__init__.py +1 -0
  213. entmatch/registry/diff.py +134 -0
  214. entmatch/registry/drift.py +124 -0
  215. entmatch/registry/ingest.py +44 -0
  216. entmatch/registry/judgements.py +231 -0
  217. entmatch/registry/replay.py +153 -0
  218. entmatch/registry/snapshot.py +100 -0
  219. entmatch/registry/table_ingest.py +160 -0
  220. entmatch/scaffold.py +106 -0
  221. entmatch/semantic_rules.py +325 -0
  222. entmatch/serve/__init__.py +24 -0
  223. entmatch/serve/app.py +256 -0
  224. entmatch/serve/cli.py +116 -0
  225. entmatch/shadow.py +273 -0
  226. entmatch/testing/__init__.py +0 -0
  227. entmatch/testing/conformance/__init__.py +0 -0
  228. entmatch/testing/conformance/generator.py +41 -0
  229. entmatch/uncertainty/__init__.py +16 -0
  230. entmatch/uncertainty/conformal.py +178 -0
  231. entmatch/uncertainty/selective.py +81 -0
  232. entmatch/units/__init__.py +37 -0
  233. entmatch/units/normalizer.py +246 -0
  234. entmatch/units/rates.py +108 -0
  235. entmatch/verbs.py +148 -0
  236. entmatch-0.3.0rc1.dist-info/METADATA +393 -0
  237. entmatch-0.3.0rc1.dist-info/RECORD +241 -0
  238. entmatch-0.3.0rc1.dist-info/WHEEL +4 -0
  239. entmatch-0.3.0rc1.dist-info/entry_points.txt +3 -0
  240. entmatch-0.3.0rc1.dist-info/licenses/LICENSE +202 -0
  241. entmatch-0.3.0rc1.dist-info/licenses/THIRD_PARTY_NOTICES.md +36 -0
entmatch/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ """entmatch: typed, calibrated, auditable entity matching."""
2
+
3
+ from . import _brand, extract # noqa: E402
4
+ from ._version import __version__
5
+ from .builtin.deciders.field_policy import FieldPolicy # noqa: E402
6
+ from .catalog import Catalog # noqa: E402
7
+ from .config import PipelineConfig, load_config # noqa: E402
8
+ from .facade import ( # noqa: E402
9
+ DecisionFrame,
10
+ calibrate,
11
+ compare,
12
+ configure,
13
+ evaluate,
14
+ explain,
15
+ link,
16
+ link_many,
17
+ match,
18
+ rank,
19
+ reconcile,
20
+ )
21
+ from .hub import register as register_adapter # noqa: E402
22
+ from .learn.pipeline import Pipeline # noqa: E402
23
+ from .match_report import MatchReport # noqa: E402
24
+ from .matcher import Matcher # noqa: E402
25
+ from .models import ( # noqa: E402
26
+ Candidate,
27
+ Comparison,
28
+ Criterion,
29
+ Decision,
30
+ Outcome,
31
+ Query,
32
+ Record,
33
+ )
34
+ from .onboard import demo # noqa: E402
35
+ from .verbs import ( # noqa: E402
36
+ agent,
37
+ cluster,
38
+ dedupe,
39
+ drift,
40
+ glossary,
41
+ lazy,
42
+ replay,
43
+ route,
44
+ shadow,
45
+ )
46
+
47
+ __all__ = [
48
+ "Candidate",
49
+ "Catalog",
50
+ "MatchReport",
51
+ "Matcher",
52
+ "register_adapter",
53
+ "Comparison",
54
+ "Criterion",
55
+ "Decision",
56
+ "DecisionFrame",
57
+ "FieldPolicy",
58
+ "Outcome",
59
+ "Pipeline",
60
+ "PipelineConfig",
61
+ "Query",
62
+ "Record",
63
+ "__version__",
64
+ "_brand",
65
+ "agent",
66
+ "calibrate",
67
+ "cluster",
68
+ "compare",
69
+ "configure",
70
+ "dedupe",
71
+ "demo",
72
+ "drift",
73
+ "evaluate",
74
+ "explain",
75
+ "extract",
76
+ "glossary",
77
+ "lazy",
78
+ "link",
79
+ "link_many",
80
+ "load_config",
81
+ "match",
82
+ "rank",
83
+ "reconcile",
84
+ "replay",
85
+ "route",
86
+ "shadow",
87
+ ]
entmatch/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """python -m <package> == the CLI."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
entmatch/_brand.py ADDED
@@ -0,0 +1,13 @@
1
+ """Single source of the project name. Rename = edit this file + pyproject."""
2
+
3
+ PACKAGE = "entmatch"
4
+ ENTRY_POINT_PREFIX = "entmatch"
5
+ CLI_NAME = "entmatch"
6
+ ENV_PREFIX = "ENTMATCH_"
7
+ PRESET_R2 = CLI_NAME + "-r2"
8
+ R2_ENV = ENV_PREFIX + "R2"
9
+ R2_REPO_ENV = ENV_PREFIX + "R2_REPO"
10
+ R2_REPO = "felipedjrg3/" + PRESET_R2
11
+ R2_LABEL = CLI_NAME.upper() + "-R2"
12
+ LOCAL_LLM_ENV = ENV_PREFIX + "LOCAL_LLM"
13
+ FALLBACK_LLM_ENV = ENV_PREFIX + "LOCAL_LLM_FALLBACK"
entmatch/_hashkey.py ADDED
@@ -0,0 +1,50 @@
1
+ """Keyed hashing + 0600 log files. HMAC-SHA256 with caller key; plain sha256 only without a key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import os
8
+ import warnings
9
+ from pathlib import Path
10
+ from typing import IO
11
+
12
+ from ._brand import ENV_PREFIX
13
+
14
+ KEY_ENV = ENV_PREFIX + "HASH_KEY"
15
+ _warned = False
16
+
17
+
18
+ def resolve_key(key: str | bytes | None = None) -> bytes | None:
19
+ k = key if key is not None else os.environ.get(KEY_ENV)
20
+ if not k:
21
+ return None
22
+ return k if isinstance(k, bytes) else k.encode("utf-8")
23
+
24
+
25
+ def mode(key: bytes | None) -> str:
26
+ return "hmac" if key else "plain"
27
+
28
+
29
+ def digest(text: str, key: bytes | None) -> str:
30
+ """Full sha256 hex; HMAC-SHA256 when key given."""
31
+ b = text.encode("utf-8")
32
+ return hmac.new(key, b, hashlib.sha256).hexdigest() if key else hashlib.sha256(b).hexdigest()
33
+
34
+
35
+ def warn_plain() -> None:
36
+ global _warned
37
+ if not _warned:
38
+ _warned = True
39
+ warnings.warn(
40
+ f"unkeyed sha256 of query text is dictionary-attackable for short PII; "
41
+ f"set {KEY_ENV} or pass hash_key",
42
+ stacklevel=3,
43
+ )
44
+
45
+
46
+ def open_private(path: str | Path, flags: int = os.O_WRONLY | os.O_CREAT | os.O_TRUNC) -> IO[str]:
47
+ """Open text file for write/append; file created 0600 (existing mode tightened if we create)."""
48
+ p = Path(path)
49
+ fd = os.open(p, flags, 0o600)
50
+ return os.fdopen(fd, "a" if flags & os.O_APPEND else "w", encoding="utf-8")
entmatch/_hints.py ADDED
@@ -0,0 +1,55 @@
1
+ """One place for install hints: every optional import names the exact extra to add."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib import import_module
6
+ from typing import Any
7
+
8
+ from ._brand import PACKAGE
9
+
10
+ # import name -> extra that provides it
11
+ MODULE_EXTRA: dict[str, str] = {
12
+ "pyarrow": "arrow",
13
+ "pandas": "pandas",
14
+ "polars": "polars",
15
+ "openpyxl": "xlsx",
16
+ "pypdf": "pdf",
17
+ "pypdfium2": "pdf",
18
+ "pdf2image": "pdf",
19
+ "PIL": "pdf",
20
+ "transformers": "tables",
21
+ "torch": "tables",
22
+ "spacy": "spacy",
23
+ "gliner": "gliner",
24
+ "sentence_transformers": "local",
25
+ "boto3": "bedrock",
26
+ "anthropic": "anthropic",
27
+ "openai": "openai",
28
+ "rapidfuzz": "fast",
29
+ "faiss": "fast",
30
+ "hnswlib": "hnsw",
31
+ "fastapi": "serve",
32
+ "uvicorn": "serve",
33
+ "networkx": "graph",
34
+ "scipy": "assign",
35
+ "dedupe": "dedupe",
36
+ }
37
+
38
+
39
+ def install_cmd(extra: str) -> str:
40
+ return f"pip install '{PACKAGE}[{extra}]'"
41
+
42
+
43
+ def hint(module: str, extra: str | None = None) -> str:
44
+ """One-line message: what is missing and the exact command that fixes it."""
45
+ ex = extra or MODULE_EXTRA.get(module)
46
+ fix = install_cmd(ex) if ex else f"pip install {module}"
47
+ return f"{module} is required: {fix}"
48
+
49
+
50
+ def require(module: str, extra: str | None = None) -> Any:
51
+ """Import an optional module or raise ImportError naming the exact extra."""
52
+ try:
53
+ return import_module(module)
54
+ except ImportError as exc:
55
+ raise ImportError(hint(module, extra)) from exc
entmatch/_licences.py ADDED
@@ -0,0 +1,42 @@
1
+ """Machine-readable table of vendored third-party code (human view: THIRD_PARTY_NOTICES.md).
2
+
3
+ Depended (pip extra) pieces carry their licence in their hub AdapterMeta instead.
4
+ `restricted` = copyleft / non-commercial; such code must live under contrib/restricted.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TypedDict
10
+
11
+
12
+ class Vendored(TypedDict):
13
+ path: str # file in this package
14
+ upstream: str
15
+ commit: str
16
+ licence: str # SPDX
17
+ restricted: bool
18
+
19
+
20
+ VENDORED: tuple[Vendored, ...] = (
21
+ {
22
+ "path": "builtin/assign/unique_mapping.py",
23
+ "upstream": "https://github.com/AI-team-UoA/pyJedAI",
24
+ "commit": "eb446095f921af3207bbefd570cc65e818194419",
25
+ "licence": "Apache-2.0",
26
+ "restricted": False,
27
+ },
28
+ {
29
+ "path": "builtin/comparators/tf_adjust.py",
30
+ "upstream": "https://github.com/moj-analytical-services/splink",
31
+ "commit": "f319070e56c5b3666ec512811ac1820070f6f2e5",
32
+ "licence": "MIT",
33
+ "restricted": False,
34
+ },
35
+ {
36
+ "path": "registry/judgements.py",
37
+ "upstream": "https://github.com/opensanctions/nomenklatura",
38
+ "commit": "0ef7913d49765d098b2809176a9e48705a0f289b",
39
+ "licence": "MIT",
40
+ "restricted": False,
41
+ },
42
+ )
entmatch/_model_hub.py ADDED
@@ -0,0 +1,36 @@
1
+ """Fetch the R2 weights from Hugging Face on first use (standard HF cache, then offline)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+
8
+ from ._brand import R2_ENV, R2_LABEL, R2_REPO, R2_REPO_ENV
9
+
10
+ DEFAULT_REPO = R2_REPO
11
+ REPO_ENV = R2_REPO_ENV
12
+
13
+
14
+ def _fail(why: str) -> FileNotFoundError:
15
+ return FileNotFoundError(
16
+ f"could not fetch the {R2_LABEL} model: {why}. Fix: run 'pip install huggingface_hub' "
17
+ f"(then retry with network), or set {R2_ENV} to a local model folder."
18
+ )
19
+
20
+
21
+ def resolve_r2_path() -> str:
22
+ """Local dir of the R2 model: cached snapshot, else one download (~2.4 GB)."""
23
+ repo = os.environ.get(REPO_ENV) or DEFAULT_REPO
24
+ try:
25
+ from huggingface_hub import snapshot_download
26
+ except ImportError as e:
27
+ raise _fail("huggingface_hub is not installed") from e
28
+ try:
29
+ return str(snapshot_download(repo_id=repo, local_files_only=True))
30
+ except Exception: # not cached yet -> download below
31
+ pass
32
+ print(f"Downloading {R2_LABEL} (2.4 GB) from Hugging Face, once...", file=sys.stderr)
33
+ try:
34
+ return str(snapshot_download(repo_id=repo))
35
+ except Exception as e:
36
+ raise _fail(f"download of {repo!r} failed ({type(e).__name__}: {e})") from e
entmatch/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single source of the package version (pyproject reads it via hatch)."""
2
+
3
+ __version__ = "0.3.0rc1"
entmatch/abstain.py ADDED
@@ -0,0 +1,25 @@
1
+ """Opt-in abstain for facade.link: nil="off" = never answer NO_MATCH.
2
+
3
+ abstain = fitted Catalog-like object (calibrator, match_at). Its calibrator and match_at
4
+ replace cfg thresholds; nil_below is forced to 0 so NO_MATCH is never returned. The former
5
+ nil="fit" mode (isotonic + risk-controlled NIL cut) was removed: no gain over the fixed
6
+ threshold at equal accepted error.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from typing import Any
13
+
14
+ from .builtin.deciders import DeciderConfig
15
+
16
+
17
+ def resolve_abstain(abstain: Any, nil: str) -> tuple[DeciderConfig, Any]:
18
+ """Fitted Catalog -> (DeciderConfig, calibrator) for ThresholdDecider; nil must be 'off'."""
19
+ if nil != "off":
20
+ raise ValueError("nil must be 'off' (fit mode removed)")
21
+ cal = getattr(abstain, "calibrator", None)
22
+ if cal is None or not getattr(cal, "fitted", False):
23
+ raise ValueError("abstain: not fitted (no calibrator)")
24
+ m = 1.0 if math.isinf(abstain.match_at) else min(1.0, float(abstain.match_at))
25
+ return DeciderConfig(match_t=m, review_t=0.0, abstain_t=0.0), cal
@@ -0,0 +1,67 @@
1
+ """Every hub adapter is registered here (import = register). Upstream imports stay lazy.
2
+
3
+ Drop a module into this package (or run ``<cli> new adapter NAME --port PORT``) and it is
4
+ picked up automatically. Restricted modules under contrib/restricted load only on opt-in.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib
10
+ import os
11
+ import pkgutil
12
+
13
+ from ..builtin.assign import HungarianAssigner, ThresholdAssigner, UniqueMappingAssigner
14
+ from ..builtin.embedders import HashingEmbedder
15
+ from ..builtin.explain import TokenExplainer
16
+ from ..builtin.generators import Dense, Lexical
17
+ from ..hub import ALLOW_RESTRICTED_ENV, register
18
+
19
+ _OWN = {"licence": "Apache-2.0", "upstream": "builtin"}
20
+ register(name="lexical", port="generator", **_OWN)(Lexical)
21
+
22
+
23
+ @register(name="dense-mv", port="generator", **_OWN)
24
+ class DenseMultiView(Dense):
25
+ """Offline multi-view dense (hashing char n-grams); CPU test / fallback twin of entmatch-r2."""
26
+
27
+ name = "dense-mv"
28
+
29
+ def __init__(
30
+ self,
31
+ dim: int = 512,
32
+ ngram: int = 3,
33
+ chunk_words: int = 64,
34
+ view_agg: str = "max",
35
+ csls_k: int = 0,
36
+ cache_dir: str | None = None,
37
+ ) -> None:
38
+ super().__init__(
39
+ HashingEmbedder(dim=dim, ngram=ngram, sublinear=True, normalize=True),
40
+ multiview=True,
41
+ chunk_words=chunk_words,
42
+ view_agg=view_agg,
43
+ csls_k=csls_k,
44
+ cache_dir=cache_dir,
45
+ )
46
+
47
+
48
+ register(name="tokens", port="explainer", **_OWN)(TokenExplainer)
49
+ register(name="threshold", port="assigner", **_OWN)(ThresholdAssigner)
50
+ register(name="hungarian", port="assigner", extra="assign", requires=("scipy.optimize",), **_OWN)(
51
+ HungarianAssigner
52
+ )
53
+ register(
54
+ name="unique-mapping",
55
+ port="assigner",
56
+ licence="Apache-2.0",
57
+ version="eb446095f921af3207bbefd570cc65e818194419",
58
+ upstream="https://github.com/AI-team-UoA/pyJedAI",
59
+ )(UniqueMappingAssigner)
60
+
61
+ for _m in pkgutil.iter_modules(__path__):
62
+ importlib.import_module(f"{__name__}.{_m.name}")
63
+ if os.environ.get(ALLOW_RESTRICTED_ENV) == "1":
64
+ from ..contrib import restricted as _restricted
65
+
66
+ for _m in pkgutil.iter_modules(_restricted.__path__):
67
+ importlib.import_module(f"{_restricted.__name__}.{_m.name}")
@@ -0,0 +1,87 @@
1
+ """dedupe adapter (generator): dedupe.Gazetteer (learned blocking + logistic) over the catalog.
2
+
3
+ Training comes from ``training`` = dedupe labeled pairs {"match": [[messy, canon], ...],
4
+ "distinct": [...]} with records as {field: text}, or ``training="self"``: a bootstrap from the
5
+ catalog itself (upper-cased, one char dropped = match; next entity = distinct). Or load a
6
+ frozen model with ``settings_file`` (StaticGazetteer). Scores are dedupe probabilities.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import random
12
+ from typing import Any
13
+
14
+ from .._hints import require
15
+ from ..builtin.generators._util import entity_text, query_text
16
+ from ..hub import register
17
+ from ..models import Query, RegistrySnapshot
18
+ from ..ports.generator import GenCtx, GenResult, rank_to_result
19
+ from ..registry.snapshot import snapshot_fingerprint
20
+
21
+
22
+ def _self_pairs(canon: dict[str, dict[str, str]], field: str) -> dict[str, list[Any]]:
23
+ ids = sorted(canon)
24
+ noisy = {i: {field: canon[i][field].upper()[:-1] or "?"} for i in ids}
25
+ match = [(noisy[i], canon[i]) for i in ids]
26
+ distinct = [(noisy[i], canon[ids[(n + 1) % len(ids)]]) for n, i in enumerate(ids)]
27
+ return {"match": match, "distinct": distinct}
28
+
29
+
30
+ @register(
31
+ name="dedupe-gazetteer",
32
+ port="generator",
33
+ licence="MIT",
34
+ extra="dedupe",
35
+ requires=("dedupe",),
36
+ version="3.0.3",
37
+ upstream="https://github.com/dedupeio/dedupe",
38
+ )
39
+ class DedupeGazetteer:
40
+ name = "dedupe-gazetteer"
41
+
42
+ def __init__(
43
+ self,
44
+ training: dict[str, list[Any]] | str | None = None,
45
+ settings_file: str | None = None,
46
+ field: str = "name",
47
+ sample_size: int = 1500,
48
+ seed: int = 0,
49
+ ) -> None:
50
+ if training is None and settings_file is None:
51
+ raise ValueError("dedupe needs training pairs, training='self' or settings_file")
52
+ self.training, self.settings_file, self.field = training, settings_file, field
53
+ self.sample_size, self.seed = sample_size, seed
54
+ self._g: tuple[str, Any] | None = None
55
+
56
+ def _gazetteer(self, snapshot: RegistrySnapshot) -> Any:
57
+ key = snapshot_fingerprint(snapshot)
58
+ if self._g is not None and self._g[0] == key:
59
+ return self._g[1]
60
+ dd = require("dedupe", "dedupe")
61
+ np = require("numpy")
62
+ canon = {e.id: {self.field: entity_text(e, None) or "?"} for e in snapshot.entities}
63
+ if self.settings_file is not None:
64
+ with open(self.settings_file, "rb") as f:
65
+ g = dd.StaticGazetteer(f)
66
+ else:
67
+ random.seed(self.seed)
68
+ np.random.seed(self.seed)
69
+ pairs = _self_pairs(canon, self.field) if self.training == "self" else self.training
70
+ if not isinstance(pairs, dict):
71
+ raise ValueError("training must be a dict of labeled pairs or 'self'")
72
+ messy = {f"m{i}": p[0] for i, p in enumerate(pairs["match"] + pairs["distinct"])}
73
+ g = dd.Gazetteer([dd.variables.String(self.field)])
74
+ g.prepare_training(messy, canon, sample_size=self.sample_size)
75
+ g.mark_pairs(pairs)
76
+ g.train(recall=1.0, index_predicates=True)
77
+ g.index(canon)
78
+ self._g = (key, g)
79
+ return g
80
+
81
+ def generate(self, query: Query, snapshot: RegistrySnapshot, k: int, ctx: GenCtx) -> GenResult:
82
+ if not snapshot.entities:
83
+ return GenResult()
84
+ g = self._gazetteer(snapshot)
85
+ hits = g.search({query.id: {self.field: query_text(query) or "?"}}, 0.0, k)
86
+ scored = [(str(eid), float(p)) for _, matches in hits for eid, p in matches]
87
+ return rank_to_result(self.name, scored, k)
@@ -0,0 +1,58 @@
1
+ """GLiNER adapter (generator): GLiNKER's disambiguation idea without its Redis/ES/Postgres stack.
2
+
3
+ Ref names are passed as GLiNER labels (bi-encoder models embed them once per call); the query
4
+ is the text. Score per ref = max span score for that label. Upstream ideas:
5
+ https://github.com/Knowledgator/GLinker (Apache-2.0), model lib https://github.com/urchade/GLiNER.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from .._hints import require
13
+ from ..builtin.generators._util import entity_text, query_text
14
+ from ..hub import register
15
+ from ..models import Query, RegistrySnapshot
16
+ from ..ports.generator import GenCtx, GenResult, rank_to_result
17
+
18
+
19
+ @register(
20
+ name="gliner-labels",
21
+ port="generator",
22
+ licence="Apache-2.0",
23
+ extra="gliner",
24
+ requires=("gliner",),
25
+ version="0.2.30",
26
+ upstream="https://github.com/Knowledgator/GLinker",
27
+ )
28
+ class GlinerLabels:
29
+ name = "gliner-labels"
30
+
31
+ def __init__(
32
+ self, model_name: str = "knowledgator/gliner-bi-large-v2.0", threshold: float = 0.0
33
+ ) -> None:
34
+ self._model: Any = require("gliner", "gliner").GLiNER.from_pretrained(model_name)
35
+ self.threshold = threshold
36
+ self._memo: dict[tuple[str, ...], dict[str, float]] = {} # (labels..., text) -> scores
37
+
38
+ def generate(self, query: Query, snapshot: RegistrySnapshot, k: int, ctx: GenCtx) -> GenResult:
39
+ owners: dict[str, list[str]] = {}
40
+ for e in snapshot.entities:
41
+ owners.setdefault(entity_text(e, None, use_aliases=False) or e.id, []).append(e.id)
42
+ text = query_text(query)
43
+ if not text.strip() or not owners:
44
+ return GenResult()
45
+ key = (*sorted(owners), text)
46
+ best = self._memo.get(key)
47
+ if best is None:
48
+ spans = self._model.predict_entities(
49
+ text, sorted(owners), threshold=self.threshold, multi_label=True
50
+ )
51
+ best = {}
52
+ for s in spans:
53
+ for eid in owners.get(s["label"], ()):
54
+ best[eid] = max(best.get(eid, 0.0), float(s["score"]))
55
+ if len(self._memo) > 1024:
56
+ self._memo.clear()
57
+ self._memo[key] = best
58
+ return rank_to_result(self.name, [b for b in best.items() if b[1] > 0], k)
@@ -0,0 +1,87 @@
1
+ """sentence-transformers adapters: embedder + dense generator (exact cosine, max per entity)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ from .._brand import PRESET_R2, R2_ENV
9
+ from ..builtin.embedders.sbert import SbertEmbedder
10
+ from ..builtin.generators.dense import Dense
11
+ from ..hub import register
12
+
13
+ _META = {
14
+ "licence": "Apache-2.0",
15
+ "extra": "sbert",
16
+ "requires": ("sentence_transformers",),
17
+ "upstream": "https://github.com/UKPLab/sentence-transformers",
18
+ }
19
+ register(name="sbert", port="embedder", **_META)(SbertEmbedder)
20
+
21
+
22
+ @register(name="sbert-dense", port="generator", **_META)
23
+ class SbertDense(Dense):
24
+ name = "sbert-dense"
25
+
26
+ def __init__(
27
+ self, model_name: str, revision: str | None = None, fields: tuple[str, ...] | None = None
28
+ ) -> None:
29
+ super().__init__(SbertEmbedder(model_name, revision), fields=fields)
30
+
31
+
32
+ R2_ENV_NAME = R2_ENV
33
+ R2_QUERY_PREFIX = (
34
+ "Instruct: Given a record or text, retrieve the matching registered catalog entity\nQuery: "
35
+ )
36
+
37
+
38
+ @register(name=PRESET_R2, port="generator", **_META)
39
+ class R2Dense(Dense):
40
+ """Preset: fine-tuned R2 bi-encoder (local dir), multi-view, max per ref.
41
+
42
+ Dir from model_path, else env R2_ENV, else the downloaded release (resolve_r2_path).
43
+ Query prefix = the one used in training (s1_biencoder config.json); docs have none.
44
+ ``model`` injects a loaded SentenceTransformer (tests / reuse).
45
+ Weights stay outside git (docs/RELEASE_GATE.md).
46
+ """
47
+
48
+ name = PRESET_R2
49
+
50
+ def __init__(
51
+ self,
52
+ model_path: str | None = None,
53
+ *,
54
+ device: str | None = None,
55
+ batch_size: int = 32,
56
+ query_prefix: str = R2_QUERY_PREFIX,
57
+ chunk_words: int = 64,
58
+ fields: tuple[str, ...] | None = None,
59
+ model: Any = None,
60
+ view_agg: str = "max",
61
+ csls_k: int = 0,
62
+ cache_dir: str | None = None,
63
+ ) -> None:
64
+ """view_agg max|top2|top3, csls_k (0=off), cache_dir (persistent multi-view index):
65
+ see Dense. All opt-in."""
66
+ path = model_path or os.environ.get(R2_ENV_NAME)
67
+ if not path:
68
+ from .._model_hub import resolve_r2_path
69
+
70
+ path = resolve_r2_path()
71
+ emb = SbertEmbedder(
72
+ str(path),
73
+ model=model,
74
+ query_prefix=query_prefix,
75
+ device=device,
76
+ batch_size=batch_size,
77
+ normalize=True,
78
+ )
79
+ super().__init__(
80
+ emb,
81
+ fields=fields,
82
+ multiview=True,
83
+ chunk_words=chunk_words,
84
+ view_agg=view_agg,
85
+ csls_k=csls_k,
86
+ cache_dir=cache_dir,
87
+ )