muckrake 0.2.1__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.
- muckrake/__init__.py +61 -0
- muckrake/artifacts.py +72 -0
- muckrake/cli.py +522 -0
- muckrake/crawl.py +223 -0
- muckrake/dataset.py +231 -0
- muckrake/db.py +478 -0
- muckrake/dedupe/README.md +52 -0
- muckrake/dedupe/__init__.py +37 -0
- muckrake/dedupe/cluster.py +534 -0
- muckrake/dedupe/dedupe.py +133 -0
- muckrake/dedupe/dedupe_edges.py +214 -0
- muckrake/dedupe/review.py +329 -0
- muckrake/entity_query.py +114 -0
- muckrake/entity_write.py +244 -0
- muckrake/env.py +52 -0
- muckrake/export.py +40 -0
- muckrake/extract/__init__.py +0 -0
- muckrake/extract/fetch.py +186 -0
- muckrake/extract/ner/README.md +210 -0
- muckrake/extract/ner/__init__.py +4 -0
- muckrake/extract/ner/engines/__init__.py +32 -0
- muckrake/extract/ner/engines/base.py +14 -0
- muckrake/extract/ner/engines/delimited.py +39 -0
- muckrake/extract/ner/engines/llm.py +164 -0
- muckrake/extract/ner/engines/llm_prompt.py +44 -0
- muckrake/extract/ner/materialize.py +255 -0
- muckrake/extract/ner/pipeline.py +151 -0
- muckrake/extract/ner/review.py +706 -0
- muckrake/extract/ner/storage.py +200 -0
- muckrake/id.py +3 -0
- muckrake/load.py +70 -0
- muckrake/logging.py +56 -0
- muckrake/py.typed +0 -0
- muckrake/release.py +356 -0
- muckrake/runs.py +228 -0
- muckrake/search.py +335 -0
- muckrake/serialize.py +119 -0
- muckrake/settings.py +41 -0
- muckrake/store.py +117 -0
- muckrake/util.py +27 -0
- muckrake/utils/__init__.py +13 -0
- muckrake/utils/dates.py +438 -0
- muckrake/utils/gb_coh.py +36 -0
- muckrake/view.py +58 -0
- muckrake-0.2.1.dist-info/METADATA +136 -0
- muckrake-0.2.1.dist-info/RECORD +48 -0
- muckrake-0.2.1.dist-info/WHEEL +4 -0
- muckrake-0.2.1.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict, deque
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime, timedelta
|
|
6
|
+
from heapq import heappop, heappush
|
|
7
|
+
from typing import Any, Dict, Iterable, List, Optional, TypedDict
|
|
8
|
+
|
|
9
|
+
from nomenklatura.judgement import Judgement
|
|
10
|
+
from sqlalchemy import bindparam, text
|
|
11
|
+
from sqlalchemy.engine import Connection
|
|
12
|
+
|
|
13
|
+
from muckrake.db import get_resolver
|
|
14
|
+
from muckrake.dedupe.review import (
|
|
15
|
+
DedupeLockError,
|
|
16
|
+
LOCK_TTL,
|
|
17
|
+
_delete_expired_locks,
|
|
18
|
+
_get_lock_owner,
|
|
19
|
+
_get_user_locks,
|
|
20
|
+
_list_candidate_rows,
|
|
21
|
+
_pair_key,
|
|
22
|
+
_release_locks,
|
|
23
|
+
_resolve_user_label,
|
|
24
|
+
_upsert_lock,
|
|
25
|
+
_utc_now,
|
|
26
|
+
get_lock_engine,
|
|
27
|
+
)
|
|
28
|
+
from muckrake.view import get_view, serialize_view_entity
|
|
29
|
+
from muckrake.settings import SQL_URI
|
|
30
|
+
from nomenklatura.db import get_engine
|
|
31
|
+
|
|
32
|
+
SKIP_TTL = timedelta(hours=2)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class LockedPair(TypedDict):
|
|
36
|
+
left_id: str
|
|
37
|
+
right_id: str
|
|
38
|
+
score: Optional[float]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ClusterMember(TypedDict):
|
|
42
|
+
entity: Dict[str, Any]
|
|
43
|
+
score: Optional[float]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ClusterCandidate:
|
|
48
|
+
member_ids: List[str]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _delete_expired_skips(conn: Connection, now: datetime) -> None:
|
|
52
|
+
conn.execute(
|
|
53
|
+
text("DELETE FROM resolver_cluster_skip WHERE expires_at <= :now"),
|
|
54
|
+
{"now": now.isoformat()},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _get_skipped_pair_keys(conn: Connection, user_id: str, now: datetime) -> set[str]:
|
|
59
|
+
return set(
|
|
60
|
+
conn.execute(
|
|
61
|
+
text(
|
|
62
|
+
"""
|
|
63
|
+
SELECT pair_key
|
|
64
|
+
FROM resolver_cluster_skip
|
|
65
|
+
WHERE user_id = :user_id
|
|
66
|
+
AND expires_at > :now
|
|
67
|
+
"""
|
|
68
|
+
),
|
|
69
|
+
{"user_id": user_id, "now": now.isoformat()},
|
|
70
|
+
).scalars()
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _store_skipped_pairs(
|
|
75
|
+
conn: Connection,
|
|
76
|
+
*,
|
|
77
|
+
locked_pairs: List[LockedPair],
|
|
78
|
+
user_id: str,
|
|
79
|
+
now: datetime,
|
|
80
|
+
) -> None:
|
|
81
|
+
expires_at = (now + SKIP_TTL).isoformat()
|
|
82
|
+
for pair in locked_pairs:
|
|
83
|
+
conn.execute(
|
|
84
|
+
text(
|
|
85
|
+
"""
|
|
86
|
+
INSERT INTO resolver_cluster_skip(
|
|
87
|
+
pair_key, left_id, right_id, user_id, created_at, expires_at
|
|
88
|
+
) VALUES (
|
|
89
|
+
:pair_key, :left_id, :right_id, :user_id, :created_at, :expires_at
|
|
90
|
+
)
|
|
91
|
+
ON CONFLICT (pair_key, user_id) DO UPDATE SET
|
|
92
|
+
left_id = EXCLUDED.left_id,
|
|
93
|
+
right_id = EXCLUDED.right_id,
|
|
94
|
+
created_at = EXCLUDED.created_at,
|
|
95
|
+
expires_at = EXCLUDED.expires_at
|
|
96
|
+
"""
|
|
97
|
+
),
|
|
98
|
+
{
|
|
99
|
+
"pair_key": _pair_key(pair["left_id"], pair["right_id"]),
|
|
100
|
+
"left_id": pair["left_id"],
|
|
101
|
+
"right_id": pair["right_id"],
|
|
102
|
+
"user_id": user_id,
|
|
103
|
+
"created_at": now.isoformat(),
|
|
104
|
+
"expires_at": expires_at,
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _build_cluster_payload(
|
|
110
|
+
member_ids: List[str],
|
|
111
|
+
locked_pairs: List[LockedPair],
|
|
112
|
+
expires_at: str,
|
|
113
|
+
) -> Optional[Dict[str, Any]]:
|
|
114
|
+
if len(member_ids) < 2 or len(locked_pairs) == 0:
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
view = get_view()
|
|
118
|
+
best_scores: Dict[str, Optional[float]] = {
|
|
119
|
+
entity_id: None for entity_id in member_ids
|
|
120
|
+
}
|
|
121
|
+
for pair in locked_pairs:
|
|
122
|
+
for entity_id in (pair["left_id"], pair["right_id"]):
|
|
123
|
+
score = pair["score"]
|
|
124
|
+
previous = best_scores[entity_id]
|
|
125
|
+
if previous is None or (score is not None and score > previous):
|
|
126
|
+
best_scores[entity_id] = score
|
|
127
|
+
|
|
128
|
+
members: List[ClusterMember] = []
|
|
129
|
+
for entity_id in member_ids:
|
|
130
|
+
entity = view.get_entity(entity_id)
|
|
131
|
+
if entity is None:
|
|
132
|
+
return None
|
|
133
|
+
members.append(
|
|
134
|
+
ClusterMember(
|
|
135
|
+
entity=serialize_view_entity(entity),
|
|
136
|
+
score=best_scores[entity_id],
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"members": members,
|
|
142
|
+
"locked_pairs": locked_pairs,
|
|
143
|
+
"lock_expires_at": expires_at,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _build_locked_cluster_payload(
|
|
148
|
+
locks: List[dict[str, Any]],
|
|
149
|
+
) -> Optional[Dict[str, Any]]:
|
|
150
|
+
if not locks:
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
seed = locks[0]
|
|
154
|
+
adjacency: dict[str, set[str]] = defaultdict(set)
|
|
155
|
+
for lock in locks:
|
|
156
|
+
adjacency[lock["left_id"]].add(lock["right_id"])
|
|
157
|
+
adjacency[lock["right_id"]].add(lock["left_id"])
|
|
158
|
+
|
|
159
|
+
queue = deque([seed["left_id"], seed["right_id"]])
|
|
160
|
+
seen: set[str] = set(queue)
|
|
161
|
+
member_ids = list(queue)
|
|
162
|
+
while queue:
|
|
163
|
+
entity_id = queue.popleft()
|
|
164
|
+
for other_id in sorted(adjacency.get(entity_id, set())):
|
|
165
|
+
if other_id in seen:
|
|
166
|
+
continue
|
|
167
|
+
seen.add(other_id)
|
|
168
|
+
member_ids.append(other_id)
|
|
169
|
+
queue.append(other_id)
|
|
170
|
+
|
|
171
|
+
locked_pairs = [
|
|
172
|
+
LockedPair(left_id=lock["left_id"], right_id=lock["right_id"], score=None)
|
|
173
|
+
for lock in locks
|
|
174
|
+
if lock["left_id"] in seen and lock["right_id"] in seen
|
|
175
|
+
]
|
|
176
|
+
expires_at = max(lock["expires_at"] for lock in locks)
|
|
177
|
+
return _build_cluster_payload(member_ids, locked_pairs, expires_at)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _build_cluster_candidate(
|
|
181
|
+
seed_left_id: str,
|
|
182
|
+
seed_right_id: str,
|
|
183
|
+
candidates: List[tuple[str, str, Optional[float]]],
|
|
184
|
+
*,
|
|
185
|
+
max_members: int,
|
|
186
|
+
) -> Optional[ClusterCandidate]:
|
|
187
|
+
adjacency: dict[str, list[tuple[str, Optional[float]]]] = defaultdict(list)
|
|
188
|
+
has_seed = False
|
|
189
|
+
for left_id, right_id, score in candidates:
|
|
190
|
+
if _pair_key(left_id, right_id) == _pair_key(seed_left_id, seed_right_id):
|
|
191
|
+
has_seed = True
|
|
192
|
+
adjacency[left_id].append((right_id, score))
|
|
193
|
+
adjacency[right_id].append((left_id, score))
|
|
194
|
+
|
|
195
|
+
if not has_seed:
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
member_ids = [seed_left_id]
|
|
199
|
+
if seed_right_id != seed_left_id:
|
|
200
|
+
member_ids.append(seed_right_id)
|
|
201
|
+
seen = set(member_ids)
|
|
202
|
+
heap: list[tuple[float, str]] = []
|
|
203
|
+
for entity_id in member_ids:
|
|
204
|
+
for other_id, score in adjacency.get(entity_id, []):
|
|
205
|
+
if other_id not in seen:
|
|
206
|
+
heappush(heap, (-(score or 0.0), other_id))
|
|
207
|
+
|
|
208
|
+
while heap and len(member_ids) < max_members:
|
|
209
|
+
_, entity_id = heappop(heap)
|
|
210
|
+
if entity_id in seen:
|
|
211
|
+
continue
|
|
212
|
+
seen.add(entity_id)
|
|
213
|
+
member_ids.append(entity_id)
|
|
214
|
+
for other_id, score in adjacency.get(entity_id, []):
|
|
215
|
+
if other_id not in seen:
|
|
216
|
+
heappush(heap, (-(score or 0.0), other_id))
|
|
217
|
+
|
|
218
|
+
if len(member_ids) < 2:
|
|
219
|
+
return None
|
|
220
|
+
return ClusterCandidate(member_ids=member_ids)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _list_cluster_candidate_rows(
|
|
224
|
+
member_ids: List[str], skipped_pair_keys: set[str]
|
|
225
|
+
) -> List[LockedPair]:
|
|
226
|
+
if len(member_ids) < 2:
|
|
227
|
+
return []
|
|
228
|
+
|
|
229
|
+
query = text(
|
|
230
|
+
"""
|
|
231
|
+
SELECT source, target, score
|
|
232
|
+
FROM resolver
|
|
233
|
+
WHERE deleted_at IS NULL
|
|
234
|
+
AND judgement = :judgement
|
|
235
|
+
AND source IN :member_ids
|
|
236
|
+
AND target IN :member_ids
|
|
237
|
+
"""
|
|
238
|
+
).bindparams(bindparam("member_ids", expanding=True))
|
|
239
|
+
|
|
240
|
+
with get_engine(SQL_URI).connect() as conn:
|
|
241
|
+
rows = conn.execute(
|
|
242
|
+
query,
|
|
243
|
+
{
|
|
244
|
+
"judgement": Judgement.NO_JUDGEMENT.value,
|
|
245
|
+
"member_ids": member_ids,
|
|
246
|
+
},
|
|
247
|
+
).fetchall()
|
|
248
|
+
|
|
249
|
+
pairs: dict[str, LockedPair] = {}
|
|
250
|
+
for row in rows:
|
|
251
|
+
left_id = str(row.source)
|
|
252
|
+
right_id = str(row.target)
|
|
253
|
+
pair_key = _pair_key(left_id, right_id)
|
|
254
|
+
if pair_key in skipped_pair_keys:
|
|
255
|
+
continue
|
|
256
|
+
left_id, right_id = sorted((left_id, right_id))
|
|
257
|
+
score = row.score
|
|
258
|
+
existing = pairs.get(pair_key)
|
|
259
|
+
if existing is None or (
|
|
260
|
+
score is not None
|
|
261
|
+
and (existing["score"] is None or score > existing["score"])
|
|
262
|
+
):
|
|
263
|
+
pairs[pair_key] = LockedPair(
|
|
264
|
+
left_id=left_id,
|
|
265
|
+
right_id=right_id,
|
|
266
|
+
score=score,
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
return list(pairs.values())
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _assert_cluster_locked_to_user(
|
|
273
|
+
conn: Connection,
|
|
274
|
+
locked_pairs: List[LockedPair],
|
|
275
|
+
user_id: str,
|
|
276
|
+
now: datetime,
|
|
277
|
+
) -> None:
|
|
278
|
+
for pair in locked_pairs:
|
|
279
|
+
pair_key = _pair_key(pair["left_id"], pair["right_id"])
|
|
280
|
+
if _get_lock_owner(conn, pair_key, now) != user_id:
|
|
281
|
+
raise DedupeLockError("This cluster is not currently locked to you.")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _release_cluster_locks(conn: Connection, locked_pairs: List[LockedPair]) -> None:
|
|
285
|
+
_release_locks(
|
|
286
|
+
conn,
|
|
287
|
+
[_pair_key(pair["left_id"], pair["right_id"]) for pair in locked_pairs],
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _claim_cluster_locks(
|
|
292
|
+
conn: Connection,
|
|
293
|
+
*,
|
|
294
|
+
locked_pairs: List[LockedPair],
|
|
295
|
+
user_id: str,
|
|
296
|
+
user_name: Optional[str],
|
|
297
|
+
now: datetime,
|
|
298
|
+
) -> bool:
|
|
299
|
+
claimed_keys: List[str] = []
|
|
300
|
+
for pair in locked_pairs:
|
|
301
|
+
claimed = _upsert_lock(
|
|
302
|
+
conn,
|
|
303
|
+
left_id=pair["left_id"],
|
|
304
|
+
right_id=pair["right_id"],
|
|
305
|
+
user_id=user_id,
|
|
306
|
+
user_name=user_name,
|
|
307
|
+
now=now,
|
|
308
|
+
)
|
|
309
|
+
if not claimed:
|
|
310
|
+
_release_locks(conn, claimed_keys)
|
|
311
|
+
return False
|
|
312
|
+
claimed_keys.append(_pair_key(pair["left_id"], pair["right_id"]))
|
|
313
|
+
return True
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def get_next_dedupe_cluster(
|
|
317
|
+
user_id: str,
|
|
318
|
+
user_name: Optional[str] = None,
|
|
319
|
+
limit: int = 200,
|
|
320
|
+
max_members: int = 8,
|
|
321
|
+
) -> Optional[Dict[str, Any]]:
|
|
322
|
+
engine = get_lock_engine()
|
|
323
|
+
now = _utc_now()
|
|
324
|
+
|
|
325
|
+
with engine.begin() as conn:
|
|
326
|
+
_delete_expired_locks(conn, now)
|
|
327
|
+
_delete_expired_skips(conn, now)
|
|
328
|
+
current_locks = _get_user_locks(conn, user_id, now)
|
|
329
|
+
if current_locks:
|
|
330
|
+
payload = _build_locked_cluster_payload(current_locks)
|
|
331
|
+
if payload is not None:
|
|
332
|
+
return payload
|
|
333
|
+
_release_locks(conn, [lock["pair_key"] for lock in current_locks])
|
|
334
|
+
|
|
335
|
+
with engine.begin() as conn:
|
|
336
|
+
_delete_expired_skips(conn, now)
|
|
337
|
+
skipped_pair_keys = _get_skipped_pair_keys(conn, user_id, now)
|
|
338
|
+
|
|
339
|
+
candidates = [
|
|
340
|
+
row
|
|
341
|
+
for row in _list_candidate_rows(limit)
|
|
342
|
+
if _pair_key(row[0], row[1]) not in skipped_pair_keys
|
|
343
|
+
]
|
|
344
|
+
|
|
345
|
+
for left_id, right_id, _ in candidates:
|
|
346
|
+
cluster = _build_cluster_candidate(
|
|
347
|
+
left_id,
|
|
348
|
+
right_id,
|
|
349
|
+
candidates,
|
|
350
|
+
max_members=max_members,
|
|
351
|
+
)
|
|
352
|
+
if cluster is None:
|
|
353
|
+
continue
|
|
354
|
+
|
|
355
|
+
cluster_locked_pairs = _list_cluster_candidate_rows(
|
|
356
|
+
cluster.member_ids,
|
|
357
|
+
skipped_pair_keys,
|
|
358
|
+
)
|
|
359
|
+
if not cluster_locked_pairs:
|
|
360
|
+
continue
|
|
361
|
+
|
|
362
|
+
with engine.begin() as conn:
|
|
363
|
+
_delete_expired_locks(conn, now)
|
|
364
|
+
_delete_expired_skips(conn, now)
|
|
365
|
+
claimed = _claim_cluster_locks(
|
|
366
|
+
conn,
|
|
367
|
+
locked_pairs=cluster_locked_pairs,
|
|
368
|
+
user_id=user_id,
|
|
369
|
+
user_name=user_name,
|
|
370
|
+
now=now,
|
|
371
|
+
)
|
|
372
|
+
if not claimed:
|
|
373
|
+
continue
|
|
374
|
+
|
|
375
|
+
payload = _build_cluster_payload(
|
|
376
|
+
cluster.member_ids,
|
|
377
|
+
cluster_locked_pairs,
|
|
378
|
+
(now + LOCK_TTL).isoformat(),
|
|
379
|
+
)
|
|
380
|
+
if payload is not None:
|
|
381
|
+
return payload
|
|
382
|
+
|
|
383
|
+
with engine.begin() as conn:
|
|
384
|
+
_release_cluster_locks(conn, cluster_locked_pairs)
|
|
385
|
+
|
|
386
|
+
return None
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _selected_locked_pairs(
|
|
390
|
+
selected_ids: List[str], locked_pairs: List[LockedPair]
|
|
391
|
+
) -> List[LockedPair]:
|
|
392
|
+
selected_set = set(selected_ids)
|
|
393
|
+
return [
|
|
394
|
+
pair
|
|
395
|
+
for pair in locked_pairs
|
|
396
|
+
if pair["left_id"] in selected_set and pair["right_id"] in selected_set
|
|
397
|
+
]
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _validate_selected_graph(
|
|
401
|
+
selected_ids: List[str],
|
|
402
|
+
selected_pairs: List[LockedPair],
|
|
403
|
+
*,
|
|
404
|
+
require_connected: bool,
|
|
405
|
+
) -> None:
|
|
406
|
+
if len(selected_ids) < 2:
|
|
407
|
+
raise ValueError("Select at least two records to record a judgement.")
|
|
408
|
+
if not selected_pairs:
|
|
409
|
+
raise ValueError(
|
|
410
|
+
"The selected records do not share any locked suggestions to judge."
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
adjacency: dict[str, set[str]] = defaultdict(set)
|
|
414
|
+
covered: set[str] = set()
|
|
415
|
+
for pair in selected_pairs:
|
|
416
|
+
adjacency[pair["left_id"]].add(pair["right_id"])
|
|
417
|
+
adjacency[pair["right_id"]].add(pair["left_id"])
|
|
418
|
+
covered.add(pair["left_id"])
|
|
419
|
+
covered.add(pair["right_id"])
|
|
420
|
+
|
|
421
|
+
uncovered = [entity_id for entity_id in selected_ids if entity_id not in covered]
|
|
422
|
+
if uncovered:
|
|
423
|
+
raise ValueError(
|
|
424
|
+
"Every selected record must share a locked suggestion with another selected record."
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
if not require_connected:
|
|
428
|
+
return
|
|
429
|
+
|
|
430
|
+
queue = deque([selected_ids[0]])
|
|
431
|
+
seen = {selected_ids[0]}
|
|
432
|
+
while queue:
|
|
433
|
+
entity_id = queue.popleft()
|
|
434
|
+
for other_id in adjacency.get(entity_id, set()):
|
|
435
|
+
if other_id in seen:
|
|
436
|
+
continue
|
|
437
|
+
seen.add(other_id)
|
|
438
|
+
queue.append(other_id)
|
|
439
|
+
|
|
440
|
+
if len(seen) != len(selected_ids):
|
|
441
|
+
raise ValueError(
|
|
442
|
+
"Match can only be used when the selected records form a single connected group."
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def record_dedupe_cluster_judgement(
|
|
447
|
+
entity_ids: List[str],
|
|
448
|
+
selected_ids: List[str],
|
|
449
|
+
locked_pairs: List[LockedPair],
|
|
450
|
+
judgement_value: str,
|
|
451
|
+
user_id: str,
|
|
452
|
+
user_name: Optional[str] = None,
|
|
453
|
+
) -> Optional[str]:
|
|
454
|
+
entity_order = list(dict.fromkeys(entity_ids))
|
|
455
|
+
entity_set = set(entity_order)
|
|
456
|
+
selected_order = [
|
|
457
|
+
entity_id
|
|
458
|
+
for entity_id in dict.fromkeys(selected_ids)
|
|
459
|
+
if entity_id in entity_set
|
|
460
|
+
]
|
|
461
|
+
if len(entity_order) < 2:
|
|
462
|
+
raise ValueError("Need at least two entities in a cluster.")
|
|
463
|
+
if not locked_pairs:
|
|
464
|
+
raise ValueError("Missing locked pairs for this cluster.")
|
|
465
|
+
|
|
466
|
+
try:
|
|
467
|
+
judgement = Judgement(judgement_value)
|
|
468
|
+
except ValueError as exc:
|
|
469
|
+
raise ValueError(f"Invalid judgement: {judgement_value}") from exc
|
|
470
|
+
|
|
471
|
+
selected_pairs = _selected_locked_pairs(selected_order, locked_pairs)
|
|
472
|
+
_validate_selected_graph(
|
|
473
|
+
selected_order,
|
|
474
|
+
selected_pairs,
|
|
475
|
+
require_connected=judgement == Judgement.POSITIVE,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
engine = get_lock_engine()
|
|
479
|
+
now = _utc_now()
|
|
480
|
+
resolver = get_resolver()
|
|
481
|
+
resolver.begin()
|
|
482
|
+
try:
|
|
483
|
+
with engine.begin() as conn:
|
|
484
|
+
_delete_expired_locks(conn, now)
|
|
485
|
+
_delete_expired_skips(conn, now)
|
|
486
|
+
_assert_cluster_locked_to_user(conn, locked_pairs, user_id, now)
|
|
487
|
+
|
|
488
|
+
canonical_id: Optional[str] = None
|
|
489
|
+
for pair in selected_pairs:
|
|
490
|
+
left_canonical = resolver.get_canonical(pair["left_id"])
|
|
491
|
+
right_canonical = resolver.get_canonical(pair["right_id"])
|
|
492
|
+
if left_canonical == right_canonical:
|
|
493
|
+
canonical_id = str(left_canonical)
|
|
494
|
+
continue
|
|
495
|
+
|
|
496
|
+
result = resolver.decide(
|
|
497
|
+
pair["left_id"],
|
|
498
|
+
pair["right_id"],
|
|
499
|
+
judgement,
|
|
500
|
+
user=_resolve_user_label(user_id, user_name),
|
|
501
|
+
)
|
|
502
|
+
if judgement == Judgement.POSITIVE:
|
|
503
|
+
canonical_id = str(result)
|
|
504
|
+
|
|
505
|
+
resolver.commit()
|
|
506
|
+
|
|
507
|
+
with engine.begin() as conn:
|
|
508
|
+
_release_cluster_locks(conn, locked_pairs)
|
|
509
|
+
|
|
510
|
+
return canonical_id
|
|
511
|
+
except Exception:
|
|
512
|
+
resolver.rollback()
|
|
513
|
+
raise
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def skip_dedupe_cluster(locked_pairs: List[LockedPair], user_id: str) -> None:
|
|
517
|
+
if not locked_pairs:
|
|
518
|
+
raise ValueError("Missing locked pairs for this cluster.")
|
|
519
|
+
|
|
520
|
+
engine = get_lock_engine()
|
|
521
|
+
now = _utc_now()
|
|
522
|
+
|
|
523
|
+
with engine.begin() as conn:
|
|
524
|
+
_delete_expired_locks(conn, now)
|
|
525
|
+
_delete_expired_skips(conn, now)
|
|
526
|
+
_assert_cluster_locked_to_user(conn, locked_pairs, user_id, now)
|
|
527
|
+
|
|
528
|
+
_store_skipped_pairs(
|
|
529
|
+
conn,
|
|
530
|
+
locked_pairs=locked_pairs,
|
|
531
|
+
user_id=user_id,
|
|
532
|
+
now=now,
|
|
533
|
+
)
|
|
534
|
+
_release_cluster_locks(conn, locked_pairs)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from followthemoney import model
|
|
5
|
+
from nomenklatura.judgement import Judgement
|
|
6
|
+
from nomenklatura.matching import DefaultAlgorithm, get_algorithm
|
|
7
|
+
from nomenklatura.xref import xref as nk_xref
|
|
8
|
+
|
|
9
|
+
from muckrake.db import get_resolver
|
|
10
|
+
from muckrake.dataset import find_datasets, get_dataset_path, load_config
|
|
11
|
+
from muckrake.extract.ner.materialize import iter_dataset_statements
|
|
12
|
+
from muckrake.settings import DATA_PATH
|
|
13
|
+
from muckrake.store import get_level_store
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_statements(store, dataset_names):
|
|
19
|
+
"""Load statements from pack files into a store."""
|
|
20
|
+
log.info("Loading statements into store...")
|
|
21
|
+
with store.writer() as writer:
|
|
22
|
+
for ds_name in dataset_names:
|
|
23
|
+
pack_path = get_dataset_path(ds_name) / "statements.pack.csv"
|
|
24
|
+
if pack_path.exists():
|
|
25
|
+
for stmt in iter_dataset_statements(ds_name, pack_path):
|
|
26
|
+
writer.add_statement(stmt)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run_xref(
|
|
30
|
+
limit: int = 50000,
|
|
31
|
+
threshold: Optional[float] = None,
|
|
32
|
+
algorithm: str = DefaultAlgorithm.NAME,
|
|
33
|
+
schema: Optional[str] = None,
|
|
34
|
+
focus_dataset: Optional[str] = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
"""Generate deduplication candidates."""
|
|
37
|
+
all_configs = find_datasets()
|
|
38
|
+
dataset_names = [load_config(c).name for c in all_configs]
|
|
39
|
+
|
|
40
|
+
store = get_level_store(dataset_names, fresh=True)
|
|
41
|
+
resolver = get_resolver()
|
|
42
|
+
index_dir = DATA_PATH / "xref-index"
|
|
43
|
+
|
|
44
|
+
algorithm_type = get_algorithm(algorithm)
|
|
45
|
+
if algorithm_type is None:
|
|
46
|
+
raise ValueError(f"Unknown algorithm: {algorithm}")
|
|
47
|
+
|
|
48
|
+
load_statements(store, dataset_names)
|
|
49
|
+
|
|
50
|
+
resolver.begin()
|
|
51
|
+
nk_xref(
|
|
52
|
+
resolver,
|
|
53
|
+
store,
|
|
54
|
+
index_dir,
|
|
55
|
+
limit=limit,
|
|
56
|
+
range=model.get(schema) if schema else None,
|
|
57
|
+
auto_threshold=threshold,
|
|
58
|
+
algorithm=algorithm_type,
|
|
59
|
+
focus_dataset=focus_dataset,
|
|
60
|
+
user="muckrake/xref",
|
|
61
|
+
)
|
|
62
|
+
resolver.commit()
|
|
63
|
+
log.info("Xref complete.")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def run_dedupe() -> None:
|
|
67
|
+
"""Interactively judge candidates."""
|
|
68
|
+
from nomenklatura.tui import dedupe_ui
|
|
69
|
+
|
|
70
|
+
all_configs = find_datasets()
|
|
71
|
+
dataset_names = [load_config(c).name for c in all_configs]
|
|
72
|
+
|
|
73
|
+
store = get_level_store(dataset_names, fresh=False)
|
|
74
|
+
if not any(store.view(store.dataset).entities()):
|
|
75
|
+
load_statements(store, dataset_names)
|
|
76
|
+
|
|
77
|
+
resolver = get_resolver()
|
|
78
|
+
resolver.begin()
|
|
79
|
+
dedupe_ui(resolver, store, url_base="https://openlobbying.org/profile/%s/")
|
|
80
|
+
resolver.commit()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run_merge(entity_ids: list[str], force: bool = False) -> None:
|
|
84
|
+
"""Merge multiple entities into a canonical identity."""
|
|
85
|
+
if len(entity_ids) < 2:
|
|
86
|
+
raise ValueError("Need multiple IDs to merge!")
|
|
87
|
+
|
|
88
|
+
resolver = get_resolver()
|
|
89
|
+
resolver.begin()
|
|
90
|
+
try:
|
|
91
|
+
canonical_id = resolver.get_canonical(entity_ids[0])
|
|
92
|
+
for other_id in entity_ids[1:]:
|
|
93
|
+
if resolver.get_canonical(other_id) == canonical_id:
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
resolver.decide(
|
|
97
|
+
canonical_id, other_id, Judgement.POSITIVE, user="muckrake/manual"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
resolver.commit()
|
|
101
|
+
except Exception:
|
|
102
|
+
resolver.rollback()
|
|
103
|
+
raise
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def run_dedupe_explode(entity_id: str) -> None:
|
|
107
|
+
"""Undo deduplication by exploding a resolved entity cluster."""
|
|
108
|
+
resolver = get_resolver()
|
|
109
|
+
resolver.begin()
|
|
110
|
+
try:
|
|
111
|
+
canonical_id = resolver.get_canonical(entity_id)
|
|
112
|
+
restored = 0
|
|
113
|
+
for part_id in resolver.explode(canonical_id):
|
|
114
|
+
restored += 1
|
|
115
|
+
log.info("Restored separate entity: %s", part_id)
|
|
116
|
+
resolver.commit()
|
|
117
|
+
log.info("Exploded cluster %s (%s entities)", canonical_id, restored)
|
|
118
|
+
except Exception:
|
|
119
|
+
resolver.rollback()
|
|
120
|
+
raise
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def run_prune() -> None:
|
|
124
|
+
"""Remove dedupe candidates from resolver file."""
|
|
125
|
+
resolver = get_resolver()
|
|
126
|
+
resolver.begin()
|
|
127
|
+
try:
|
|
128
|
+
resolver.prune()
|
|
129
|
+
resolver.commit()
|
|
130
|
+
log.info("Resolver pruned.")
|
|
131
|
+
except Exception:
|
|
132
|
+
resolver.rollback()
|
|
133
|
+
raise
|