c1v-id 0.1.0__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.
- c1v_id/__init__.py +107 -0
- c1v_id/blocking.py +221 -0
- c1v_id/clustering.py +159 -0
- c1v_id/config.py +130 -0
- c1v_id/golden.py +208 -0
- c1v_id/normalize.py +201 -0
- c1v_id/py.typed +0 -0
- c1v_id/resolver.py +419 -0
- c1v_id/scoring.py +166 -0
- c1v_id-0.1.0.dist-info/METADATA +219 -0
- c1v_id-0.1.0.dist-info/RECORD +13 -0
- c1v_id-0.1.0.dist-info/WHEEL +4 -0
- c1v_id-0.1.0.dist-info/licenses/LICENSE +21 -0
c1v_id/__init__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
c1v-id: Identity resolution for AI applications.
|
|
3
|
+
|
|
4
|
+
Resolve duplicate records into unified golden records in 10 lines of Python.
|
|
5
|
+
|
|
6
|
+
Quick example:
|
|
7
|
+
>>> from c1v_id import IdentityResolver
|
|
8
|
+
>>> resolver = IdentityResolver()
|
|
9
|
+
>>> records = [
|
|
10
|
+
... {"email": "john@gmail.com", "name": "John Doe"},
|
|
11
|
+
... {"email": "john@gmail.com", "name": "J. Doe"},
|
|
12
|
+
... ]
|
|
13
|
+
>>> golden = resolver.resolve(records)
|
|
14
|
+
>>> len(golden)
|
|
15
|
+
1
|
|
16
|
+
|
|
17
|
+
Match two records:
|
|
18
|
+
>>> result = resolver.match(
|
|
19
|
+
... {"email": "john@gmail.com", "name": "John"},
|
|
20
|
+
... {"email": "john@gmail.com", "name": "Johnny"}
|
|
21
|
+
... )
|
|
22
|
+
>>> result.score, result.decision
|
|
23
|
+
(0.95, 'auto_merge')
|
|
24
|
+
|
|
25
|
+
Low-level functions are also available for custom pipelines.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
# High-level API (recommended)
|
|
31
|
+
# Blocking strategies
|
|
32
|
+
from c1v_id.blocking import (
|
|
33
|
+
email_domain_last4,
|
|
34
|
+
email_exact,
|
|
35
|
+
generate_pairs,
|
|
36
|
+
make_blocks,
|
|
37
|
+
name_fsa,
|
|
38
|
+
phone_last7,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Clustering
|
|
42
|
+
from c1v_id.clustering import (
|
|
43
|
+
UnionFind,
|
|
44
|
+
cluster_records,
|
|
45
|
+
)
|
|
46
|
+
from c1v_id.config import ResolverConfig, Thresholds, Weights
|
|
47
|
+
|
|
48
|
+
# Golden records
|
|
49
|
+
from c1v_id.golden import (
|
|
50
|
+
DEFAULT_SURVIVORSHIP_RULES,
|
|
51
|
+
SurvivorshipRule,
|
|
52
|
+
build_golden_records,
|
|
53
|
+
survivorship,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# Normalization functions
|
|
57
|
+
from c1v_id.normalize import (
|
|
58
|
+
fsa,
|
|
59
|
+
norm_address,
|
|
60
|
+
norm_email,
|
|
61
|
+
norm_name,
|
|
62
|
+
norm_phone,
|
|
63
|
+
)
|
|
64
|
+
from c1v_id.resolver import IdentityResolver, MatchResult
|
|
65
|
+
|
|
66
|
+
# Scoring functions
|
|
67
|
+
from c1v_id.scoring import (
|
|
68
|
+
exact_match,
|
|
69
|
+
fuzzy_score,
|
|
70
|
+
score_pair,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
__all__ = [
|
|
74
|
+
# Version
|
|
75
|
+
"__version__",
|
|
76
|
+
# High-level API
|
|
77
|
+
"IdentityResolver",
|
|
78
|
+
"MatchResult",
|
|
79
|
+
"ResolverConfig",
|
|
80
|
+
"Thresholds",
|
|
81
|
+
"Weights",
|
|
82
|
+
# Normalization
|
|
83
|
+
"norm_email",
|
|
84
|
+
"norm_phone",
|
|
85
|
+
"norm_name",
|
|
86
|
+
"norm_address",
|
|
87
|
+
"fsa",
|
|
88
|
+
# Blocking
|
|
89
|
+
"email_domain_last4",
|
|
90
|
+
"phone_last7",
|
|
91
|
+
"name_fsa",
|
|
92
|
+
"email_exact",
|
|
93
|
+
"make_blocks",
|
|
94
|
+
"generate_pairs",
|
|
95
|
+
# Scoring
|
|
96
|
+
"exact_match",
|
|
97
|
+
"fuzzy_score",
|
|
98
|
+
"score_pair",
|
|
99
|
+
# Clustering
|
|
100
|
+
"UnionFind",
|
|
101
|
+
"cluster_records",
|
|
102
|
+
# Golden records
|
|
103
|
+
"SurvivorshipRule",
|
|
104
|
+
"survivorship",
|
|
105
|
+
"build_golden_records",
|
|
106
|
+
"DEFAULT_SURVIVORSHIP_RULES",
|
|
107
|
+
]
|
c1v_id/blocking.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Blocking strategies for identity resolution.
|
|
3
|
+
|
|
4
|
+
Blocking reduces comparison complexity from O(n²) to approximately O(n) by
|
|
5
|
+
grouping records that are likely to match. Only records in the same "block"
|
|
6
|
+
are compared, dramatically reducing the number of comparisons needed.
|
|
7
|
+
|
|
8
|
+
Example: 10,000 records
|
|
9
|
+
- Without blocking: 50 million comparisons (n choose 2)
|
|
10
|
+
- With blocking: ~10,000 comparisons (records only compared within blocks)
|
|
11
|
+
|
|
12
|
+
Blocking keys are intentionally loose to avoid false negatives. It's better
|
|
13
|
+
to compare a few extra pairs than to miss a match.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import itertools
|
|
17
|
+
from typing import Literal
|
|
18
|
+
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
from .normalize import fsa, norm_email, norm_phone
|
|
22
|
+
|
|
23
|
+
# Type alias for blocking strategy names
|
|
24
|
+
BlockingStrategy = Literal["email_domain_last4", "phone_last7", "name_fsa", "email_exact"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def email_domain_last4(email: str | None) -> str | None:
|
|
28
|
+
"""Create blocking key from email domain + last 4 chars of local part.
|
|
29
|
+
|
|
30
|
+
This groups emails that share the same domain and have similar local parts.
|
|
31
|
+
Catches variations like john.doe@gmail.com and johndoe@gmail.com.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
email: Raw email address
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
Blocking key like "gmail.com|ndoe", or None if invalid
|
|
38
|
+
|
|
39
|
+
Examples:
|
|
40
|
+
>>> email_domain_last4("john.doe@gmail.com")
|
|
41
|
+
'gmail.com|ndoe'
|
|
42
|
+
>>> email_domain_last4("jd@example.com")
|
|
43
|
+
'example.com|jd'
|
|
44
|
+
"""
|
|
45
|
+
if not email:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
e = norm_email(email)
|
|
49
|
+
if not e:
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
local, _, domain = e.partition("@")
|
|
53
|
+
|
|
54
|
+
# Get last 4 alphanumeric characters (or all if shorter)
|
|
55
|
+
if len(local) >= 4:
|
|
56
|
+
return f"{domain}|{local[-4:]}"
|
|
57
|
+
else:
|
|
58
|
+
return f"{domain}|{local}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def phone_last7(phone: str | None) -> str | None:
|
|
62
|
+
"""Create blocking key from last 7 digits of phone number.
|
|
63
|
+
|
|
64
|
+
Ignores area code variations and country codes, catching:
|
|
65
|
+
- (555) 123-4567 and 555-123-4567
|
|
66
|
+
- 1-555-123-4567 and +1 555 123 4567
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
phone: Raw phone number
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
Last 7 digits, or None if invalid/too short
|
|
73
|
+
|
|
74
|
+
Examples:
|
|
75
|
+
>>> phone_last7("(555) 123-4567")
|
|
76
|
+
'1234567'
|
|
77
|
+
>>> phone_last7("1-800-555-1234")
|
|
78
|
+
'5551234'
|
|
79
|
+
"""
|
|
80
|
+
p = norm_phone(phone)
|
|
81
|
+
return p[-7:] if p and len(p) >= 7 else None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def name_fsa(first: str | None, last: str | None, postal: str | None) -> str | None:
|
|
85
|
+
"""Create blocking key from last name + first initial + postal FSA.
|
|
86
|
+
|
|
87
|
+
Groups people with the same last name and first initial in the same
|
|
88
|
+
geographic area. Catches name variations like "John" vs "Johnny".
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
first: First name
|
|
92
|
+
last: Last name (required)
|
|
93
|
+
postal: Postal/ZIP code
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
Blocking key like "doe|j|M5V", or None if no last name
|
|
97
|
+
|
|
98
|
+
Examples:
|
|
99
|
+
>>> name_fsa("John", "Doe", "M5V 3A8")
|
|
100
|
+
'doe|j|M5V'
|
|
101
|
+
>>> name_fsa("Johnny", "Doe", "M5V 1A1")
|
|
102
|
+
'doe|j|M5V'
|
|
103
|
+
"""
|
|
104
|
+
if not last:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
last_clean = (last or "").strip().lower()
|
|
108
|
+
first_initial = (first or "").strip()[:1].lower()
|
|
109
|
+
postal_fsa = fsa(postal) or ""
|
|
110
|
+
|
|
111
|
+
return f"{last_clean}|{first_initial}|{postal_fsa}"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def email_exact(email: str | None) -> str | None:
|
|
115
|
+
"""Create blocking key from exact normalized email.
|
|
116
|
+
|
|
117
|
+
The most precise blocking strategy - only exact email matches
|
|
118
|
+
are compared. Use when email is highly reliable.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
email: Raw email address
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
Normalized email, or None if invalid
|
|
125
|
+
|
|
126
|
+
Examples:
|
|
127
|
+
>>> email_exact("John.Doe@Gmail.com")
|
|
128
|
+
'johndoe@gmail.com'
|
|
129
|
+
"""
|
|
130
|
+
return norm_email(email)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def make_blocks(df: pd.DataFrame, strategies: list[str]) -> pd.DataFrame:
|
|
134
|
+
"""Apply multiple blocking strategies to a DataFrame.
|
|
135
|
+
|
|
136
|
+
Creates blocking keys for each record using the specified strategies.
|
|
137
|
+
Records with matching blocking keys will be compared.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
df: DataFrame with records to block. Expected columns depend on
|
|
141
|
+
strategies used (email, phone, first, last, postal).
|
|
142
|
+
strategies: List of strategy names to apply. Options:
|
|
143
|
+
- "email_domain_last4": Groups by domain + last 4 chars
|
|
144
|
+
- "phone_last7": Groups by last 7 digits
|
|
145
|
+
- "name_fsa": Groups by last name + first initial + postal area
|
|
146
|
+
- "email_exact": Groups by exact normalized email
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
DataFrame with blocking key columns (block_0, block_1, etc.)
|
|
150
|
+
|
|
151
|
+
Examples:
|
|
152
|
+
>>> df = pd.DataFrame({"email": ["john@gmail.com"], "phone": ["555-1234"]})
|
|
153
|
+
>>> blocks = make_blocks(df, ["email_domain_last4", "phone_last7"])
|
|
154
|
+
>>> blocks.columns.tolist()
|
|
155
|
+
['block_0', 'block_1']
|
|
156
|
+
"""
|
|
157
|
+
blocks = []
|
|
158
|
+
|
|
159
|
+
for strategy in strategies:
|
|
160
|
+
if strategy == "email_domain_last4":
|
|
161
|
+
if "email" in df.columns:
|
|
162
|
+
blocks.append(df["email"].apply(email_domain_last4))
|
|
163
|
+
elif strategy == "phone_last7":
|
|
164
|
+
if "phone" in df.columns:
|
|
165
|
+
blocks.append(df["phone"].apply(phone_last7))
|
|
166
|
+
elif strategy == "name_fsa":
|
|
167
|
+
# name_fsa needs first, last, and postal
|
|
168
|
+
if "first" in df.columns or "last" in df.columns:
|
|
169
|
+
blocks.append(
|
|
170
|
+
df.apply(
|
|
171
|
+
lambda r: name_fsa(r.get("first"), r.get("last"), r.get("postal")),
|
|
172
|
+
axis=1,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
elif strategy == "email_exact":
|
|
176
|
+
if "email" in df.columns:
|
|
177
|
+
blocks.append(df["email"].apply(email_exact))
|
|
178
|
+
else:
|
|
179
|
+
raise ValueError(f"Unknown blocking strategy: {strategy}")
|
|
180
|
+
|
|
181
|
+
# Combine all blocking keys into a DataFrame
|
|
182
|
+
block_df = pd.concat(blocks, axis=1)
|
|
183
|
+
block_df.columns = [f"block_{i}" for i in range(len(blocks))]
|
|
184
|
+
|
|
185
|
+
return block_df.fillna("")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def generate_pairs(
|
|
189
|
+
df: pd.DataFrame, block_col: str = "block_key"
|
|
190
|
+
) -> list[tuple[int, int]]:
|
|
191
|
+
"""Generate candidate pairs from records sharing the same block key.
|
|
192
|
+
|
|
193
|
+
Only pairs within the same block are returned, dramatically reducing
|
|
194
|
+
the total number of comparisons needed.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
df: DataFrame with a blocking key column
|
|
198
|
+
block_col: Name of the column containing the composite block key
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
List of (index_a, index_b) tuples for records to compare
|
|
202
|
+
|
|
203
|
+
Examples:
|
|
204
|
+
>>> df = pd.DataFrame({"block_key": ["A", "A", "B"]})
|
|
205
|
+
>>> generate_pairs(df, "block_key")
|
|
206
|
+
[(0, 1)] # Only indices 0 and 1 share block "A"
|
|
207
|
+
"""
|
|
208
|
+
pairs = []
|
|
209
|
+
|
|
210
|
+
for block_val, group in df.groupby(block_col):
|
|
211
|
+
# Skip empty blocks
|
|
212
|
+
if not block_val or block_val == "":
|
|
213
|
+
continue
|
|
214
|
+
|
|
215
|
+
ids = list(group.index)
|
|
216
|
+
|
|
217
|
+
# Generate all pairs within this block
|
|
218
|
+
for i, j in itertools.combinations(ids, 2):
|
|
219
|
+
pairs.append((i, j))
|
|
220
|
+
|
|
221
|
+
return pairs
|
c1v_id/clustering.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Clustering algorithms for identity resolution.
|
|
3
|
+
|
|
4
|
+
After scoring pairs of records, we need to group all matches into clusters.
|
|
5
|
+
The key challenge is transitive closure: if A matches B, and B matches C,
|
|
6
|
+
then A, B, and C should all be in the same cluster, even if A and C were
|
|
7
|
+
never directly compared.
|
|
8
|
+
|
|
9
|
+
Union-Find (Disjoint Set Union) solves this efficiently:
|
|
10
|
+
- union(a, b): Merge the clusters containing a and b
|
|
11
|
+
- find(x): Find which cluster x belongs to
|
|
12
|
+
- Path compression: Makes repeated lookups O(1) amortized
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from collections.abc import Iterable
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UnionFind:
|
|
21
|
+
"""Union-Find data structure with path compression for transitive clustering.
|
|
22
|
+
|
|
23
|
+
This is the standard algorithm for grouping matches transitively.
|
|
24
|
+
If you union(1, 2) and union(2, 3), then find(1) == find(3).
|
|
25
|
+
|
|
26
|
+
Time complexity:
|
|
27
|
+
- union: O(α(n)) amortized (nearly constant)
|
|
28
|
+
- find: O(α(n)) amortized (nearly constant)
|
|
29
|
+
- get_clusters: O(n)
|
|
30
|
+
|
|
31
|
+
Examples:
|
|
32
|
+
>>> uf = UnionFind([1, 2, 3, 4, 5])
|
|
33
|
+
>>> uf.union(1, 2)
|
|
34
|
+
>>> uf.union(2, 3) # Transitive: 1-2-3 now in same cluster
|
|
35
|
+
>>> uf.find(1) == uf.find(3)
|
|
36
|
+
True
|
|
37
|
+
>>> uf.get_clusters()
|
|
38
|
+
{1: [1, 2, 3], 4: [4], 5: [5]}
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, elements: Iterable[int]) -> None:
|
|
42
|
+
"""Initialize Union-Find with element IDs.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
elements: Iterable of unique integer identifiers (e.g., DataFrame indices)
|
|
46
|
+
"""
|
|
47
|
+
self.parent: dict[int, int] = {x: x for x in elements}
|
|
48
|
+
self.rank: dict[int, int] = {x: 0 for x in elements}
|
|
49
|
+
|
|
50
|
+
def find(self, x: int) -> int:
|
|
51
|
+
"""Find the root/representative of the cluster containing x.
|
|
52
|
+
|
|
53
|
+
Uses path compression: all nodes along the path point directly
|
|
54
|
+
to the root after this call, making future lookups faster.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
x: Element to find the cluster for
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Root element ID (cluster identifier)
|
|
61
|
+
"""
|
|
62
|
+
if self.parent[x] != x:
|
|
63
|
+
self.parent[x] = self.find(self.parent[x]) # Path compression
|
|
64
|
+
return self.parent[x]
|
|
65
|
+
|
|
66
|
+
def union(self, a: int, b: int) -> None:
|
|
67
|
+
"""Merge the clusters containing a and b.
|
|
68
|
+
|
|
69
|
+
Uses union by rank: the smaller tree is attached under the
|
|
70
|
+
larger tree's root, keeping the tree balanced.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
a: First element
|
|
74
|
+
b: Second element
|
|
75
|
+
"""
|
|
76
|
+
ra, rb = self.find(a), self.find(b)
|
|
77
|
+
if ra != rb:
|
|
78
|
+
# Union by rank: attach smaller tree under larger tree
|
|
79
|
+
if self.rank[ra] < self.rank[rb]:
|
|
80
|
+
ra, rb = rb, ra
|
|
81
|
+
self.parent[rb] = ra
|
|
82
|
+
if self.rank[ra] == self.rank[rb]:
|
|
83
|
+
self.rank[ra] += 1
|
|
84
|
+
|
|
85
|
+
def get_clusters(self) -> dict[int, list[int]]:
|
|
86
|
+
"""Return mapping of cluster root → member IDs.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
Dict where keys are cluster identifiers (root element IDs)
|
|
90
|
+
and values are lists of all elements in that cluster.
|
|
91
|
+
|
|
92
|
+
Examples:
|
|
93
|
+
>>> uf = UnionFind([1, 2, 3])
|
|
94
|
+
>>> uf.union(1, 2)
|
|
95
|
+
>>> uf.get_clusters()
|
|
96
|
+
{1: [1, 2], 3: [3]}
|
|
97
|
+
"""
|
|
98
|
+
clusters: dict[int, list[int]] = {}
|
|
99
|
+
for x in self.parent:
|
|
100
|
+
root = self.find(x)
|
|
101
|
+
if root not in clusters:
|
|
102
|
+
clusters[root] = []
|
|
103
|
+
clusters[root].append(x)
|
|
104
|
+
return clusters
|
|
105
|
+
|
|
106
|
+
def connected(self, a: int, b: int) -> bool:
|
|
107
|
+
"""Check if two elements are in the same cluster.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
a: First element
|
|
111
|
+
b: Second element
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
True if a and b are in the same cluster
|
|
115
|
+
"""
|
|
116
|
+
return self.find(a) == self.find(b)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def cluster_records(
|
|
120
|
+
pairs: pd.DataFrame,
|
|
121
|
+
record_ids: list[int],
|
|
122
|
+
threshold: float,
|
|
123
|
+
score_col: str = "score",
|
|
124
|
+
left_col: str = "left",
|
|
125
|
+
right_col: str = "right",
|
|
126
|
+
) -> dict[int, list[int]]:
|
|
127
|
+
"""Cluster records based on scored pairs above a threshold.
|
|
128
|
+
|
|
129
|
+
Takes a DataFrame of scored pairs and groups records transitively.
|
|
130
|
+
All pairs with score >= threshold are merged.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
pairs: DataFrame with columns for left ID, right ID, and score
|
|
134
|
+
record_ids: List of all record IDs (including those without pairs)
|
|
135
|
+
threshold: Minimum score to consider a match (e.g., 0.7)
|
|
136
|
+
score_col: Name of the score column
|
|
137
|
+
left_col: Name of the left record ID column
|
|
138
|
+
right_col: Name of the right record ID column
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
Dict mapping cluster ID → list of record IDs in that cluster
|
|
142
|
+
|
|
143
|
+
Examples:
|
|
144
|
+
>>> pairs = pd.DataFrame({
|
|
145
|
+
... "left": [0, 1],
|
|
146
|
+
... "right": [1, 2],
|
|
147
|
+
... "score": [0.9, 0.8]
|
|
148
|
+
... })
|
|
149
|
+
>>> cluster_records(pairs, [0, 1, 2, 3], threshold=0.7)
|
|
150
|
+
{0: [0, 1, 2], 3: [3]} # 0-1-2 clustered, 3 alone
|
|
151
|
+
"""
|
|
152
|
+
uf = UnionFind(record_ids)
|
|
153
|
+
|
|
154
|
+
# Union all pairs above threshold
|
|
155
|
+
for _, row in pairs.iterrows():
|
|
156
|
+
if row[score_col] >= threshold:
|
|
157
|
+
uf.union(int(row[left_col]), int(row[right_col]))
|
|
158
|
+
|
|
159
|
+
return uf.get_clusters()
|
c1v_id/config.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration for identity resolution.
|
|
3
|
+
|
|
4
|
+
Provides dataclasses for configuring thresholds, weights, and blocking strategies.
|
|
5
|
+
All values have sensible defaults — you can use IdentityResolver() with no config.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from c1v_id import ResolverConfig
|
|
9
|
+
>>> config = ResolverConfig(auto_merge_threshold=0.95) # Stricter matching
|
|
10
|
+
>>> resolver = IdentityResolver(config=config)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from c1v_id.golden import SurvivorshipRule
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Thresholds:
|
|
21
|
+
"""Decision thresholds for match classification.
|
|
22
|
+
|
|
23
|
+
Attributes:
|
|
24
|
+
auto_merge: Score >= this means records are the same entity (default: 0.9)
|
|
25
|
+
needs_review: Score >= this but < auto_merge means possible match (default: 0.7)
|
|
26
|
+
no_match: Score < needs_review means different entities
|
|
27
|
+
|
|
28
|
+
Example:
|
|
29
|
+
>>> t = Thresholds(auto_merge=0.95, needs_review=0.8)
|
|
30
|
+
>>> t.classify(0.92)
|
|
31
|
+
'needs_review'
|
|
32
|
+
>>> t.classify(0.96)
|
|
33
|
+
'auto_merge'
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
auto_merge: float = 0.9
|
|
37
|
+
needs_review: float = 0.7
|
|
38
|
+
|
|
39
|
+
def classify(self, score: float) -> Literal["auto_merge", "needs_review", "no_match"]:
|
|
40
|
+
"""Classify a similarity score into a decision."""
|
|
41
|
+
if score >= self.auto_merge:
|
|
42
|
+
return "auto_merge"
|
|
43
|
+
elif score >= self.needs_review:
|
|
44
|
+
return "needs_review"
|
|
45
|
+
else:
|
|
46
|
+
return "no_match"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Weights:
|
|
51
|
+
"""Attribute weights for similarity scoring.
|
|
52
|
+
|
|
53
|
+
Higher weight = more influence on final score.
|
|
54
|
+
Weights are normalized internally, so relative values matter.
|
|
55
|
+
|
|
56
|
+
Attributes:
|
|
57
|
+
email: Weight for email matching (default: 0.5) — highest because emails are unique
|
|
58
|
+
phone: Weight for phone matching (default: 0.3) — phones can be shared
|
|
59
|
+
name: Weight for name matching (default: 0.15) — names are often similar
|
|
60
|
+
address: Weight for address matching (default: 0.05) — addresses change
|
|
61
|
+
|
|
62
|
+
Example:
|
|
63
|
+
>>> w = Weights(email=0.6, phone=0.4, name=0.0) # Ignore name
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
email: float = 0.5
|
|
67
|
+
phone: float = 0.3
|
|
68
|
+
name: float = 0.15
|
|
69
|
+
address: float = 0.05
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict[str, float]:
|
|
72
|
+
"""Convert to dict for score_pair function."""
|
|
73
|
+
return {
|
|
74
|
+
"email": self.email,
|
|
75
|
+
"phone": self.phone,
|
|
76
|
+
"name": self.name,
|
|
77
|
+
"address": self.address,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def normalized(self) -> dict[str, float]:
|
|
81
|
+
"""Return weights normalized to sum to 1.0."""
|
|
82
|
+
total = self.email + self.phone + self.name + self.address
|
|
83
|
+
if total == 0:
|
|
84
|
+
return {"email": 0.25, "phone": 0.25, "name": 0.25, "address": 0.25}
|
|
85
|
+
return {
|
|
86
|
+
"email": self.email / total,
|
|
87
|
+
"phone": self.phone / total,
|
|
88
|
+
"name": self.name / total,
|
|
89
|
+
"address": self.address / total,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class ResolverConfig:
|
|
95
|
+
"""Complete configuration for IdentityResolver.
|
|
96
|
+
|
|
97
|
+
All fields have sensible defaults — create with ResolverConfig() for standard behavior.
|
|
98
|
+
|
|
99
|
+
Attributes:
|
|
100
|
+
thresholds: Decision thresholds for auto_merge/needs_review/no_match
|
|
101
|
+
weights: Attribute weights for similarity scoring
|
|
102
|
+
blocking_strategies: Which blocking strategies to use (default: all)
|
|
103
|
+
survivorship_rules: How to pick winning values for golden records
|
|
104
|
+
source_priority: Ordered list of source names (highest priority first)
|
|
105
|
+
|
|
106
|
+
Example:
|
|
107
|
+
>>> config = ResolverConfig(
|
|
108
|
+
... thresholds=Thresholds(auto_merge=0.95),
|
|
109
|
+
... weights=Weights(email=0.6, phone=0.4),
|
|
110
|
+
... )
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
thresholds: Thresholds = field(default_factory=Thresholds)
|
|
114
|
+
weights: Weights = field(default_factory=Weights)
|
|
115
|
+
blocking_strategies: list[str] = field(
|
|
116
|
+
default_factory=lambda: ["email_domain_last4", "phone_last7", "name_fsa"]
|
|
117
|
+
)
|
|
118
|
+
survivorship_rules: dict[str, SurvivorshipRule] = field(default_factory=dict)
|
|
119
|
+
source_priority: list[str] = field(default_factory=list)
|
|
120
|
+
|
|
121
|
+
def __post_init__(self) -> None:
|
|
122
|
+
"""Apply defaults for survivorship rules if not provided."""
|
|
123
|
+
if not self.survivorship_rules:
|
|
124
|
+
self.survivorship_rules = {
|
|
125
|
+
"email": SurvivorshipRule.MOST_RECENT,
|
|
126
|
+
"phone": SurvivorshipRule.MOST_RECENT,
|
|
127
|
+
"first": SurvivorshipRule.FIRST_NON_NULL,
|
|
128
|
+
"last": SurvivorshipRule.FIRST_NON_NULL,
|
|
129
|
+
"address": SurvivorshipRule.LONGEST,
|
|
130
|
+
}
|