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,214 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import date, timedelta
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from nomenklatura.judgement import Judgement
|
|
8
|
+
|
|
9
|
+
from muckrake.db import get_resolver
|
|
10
|
+
from muckrake.dataset import find_datasets, load_config
|
|
11
|
+
from muckrake.dedupe.dedupe import load_statements
|
|
12
|
+
from muckrake.store import get_level_store
|
|
13
|
+
from muckrake.util import parse_date_token
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
ROLE_NORMALIZATION = {
|
|
19
|
+
"consultant lobbyist": "lobbyist",
|
|
20
|
+
"lobbyist": "lobbyist",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class EdgeRecord:
|
|
26
|
+
entity_id: str
|
|
27
|
+
source: str
|
|
28
|
+
target: str
|
|
29
|
+
schema: str
|
|
30
|
+
role: Optional[str]
|
|
31
|
+
start: Optional[date]
|
|
32
|
+
end: Optional[date]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _normalize_role(value: Optional[str]) -> Optional[str]:
|
|
36
|
+
if value is None:
|
|
37
|
+
return None
|
|
38
|
+
normalized = value.strip().lower()
|
|
39
|
+
if not normalized:
|
|
40
|
+
return None
|
|
41
|
+
return ROLE_NORMALIZATION.get(normalized, normalized)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _edge_vertices(entity) -> Optional[tuple[str, str]]:
|
|
45
|
+
source_prop = entity.schema.source_prop
|
|
46
|
+
target_prop = entity.schema.target_prop
|
|
47
|
+
if source_prop is None or target_prop is None:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
sources = list(entity.get(source_prop))
|
|
51
|
+
targets = list(entity.get(target_prop))
|
|
52
|
+
if len(sources) != 1 or len(targets) != 1:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
source = str(sources[0])
|
|
56
|
+
target = str(targets[0])
|
|
57
|
+
if not entity.schema.edge_directed:
|
|
58
|
+
source, target = sorted((source, target))
|
|
59
|
+
return source, target
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _extract_edge_record(entity, resolver) -> Optional[EdgeRecord]:
|
|
63
|
+
if entity.id is None or not entity.schema.edge:
|
|
64
|
+
return None
|
|
65
|
+
if not entity.schema.is_a("Representation"):
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
vertices = _edge_vertices(entity)
|
|
69
|
+
if vertices is None:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
source = resolver.get_canonical(vertices[0])
|
|
73
|
+
target = resolver.get_canonical(vertices[1])
|
|
74
|
+
|
|
75
|
+
roles = sorted(str(value) for value in entity.get("role") if value)
|
|
76
|
+
role = _normalize_role(roles[0] if roles else None)
|
|
77
|
+
|
|
78
|
+
starts = sorted(str(value) for value in entity.get("startDate") if value)
|
|
79
|
+
ends = sorted(str(value) for value in entity.get("endDate") if value)
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
start = parse_date_token(starts[0], is_end=False) if starts else None
|
|
83
|
+
end = parse_date_token(ends[0], is_end=True) if ends else None
|
|
84
|
+
except ValueError:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
if start is not None and end is not None and end < start:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
return EdgeRecord(
|
|
91
|
+
entity_id=entity.id,
|
|
92
|
+
source=source,
|
|
93
|
+
target=target,
|
|
94
|
+
schema=entity.schema.name,
|
|
95
|
+
role=role,
|
|
96
|
+
start=start,
|
|
97
|
+
end=end,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _is_mergeable(a: EdgeRecord, b: EdgeRecord, max_gap_days: int) -> bool:
|
|
102
|
+
if a.start is not None and b.start is not None and a.start == b.start:
|
|
103
|
+
if (a.end is None) != (b.end is None):
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
if a.start is None or a.end is None or b.start is None or b.end is None:
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
return b.start <= a.end + timedelta(days=max_gap_days)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _build_clusters(
|
|
113
|
+
records: list[EdgeRecord], max_gap_days: int
|
|
114
|
+
) -> list[list[EdgeRecord]]:
|
|
115
|
+
grouped: dict[tuple[str, str, str, Optional[str]], list[EdgeRecord]] = defaultdict(
|
|
116
|
+
list
|
|
117
|
+
)
|
|
118
|
+
for record in records:
|
|
119
|
+
key = (record.source, record.target, record.schema, record.role)
|
|
120
|
+
grouped[key].append(record)
|
|
121
|
+
|
|
122
|
+
clusters: list[list[EdgeRecord]] = []
|
|
123
|
+
for group in grouped.values():
|
|
124
|
+
group.sort(
|
|
125
|
+
key=lambda rec: (
|
|
126
|
+
rec.start or date.min,
|
|
127
|
+
rec.end or date.max,
|
|
128
|
+
rec.entity_id,
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
chain: list[EdgeRecord] = []
|
|
133
|
+
for record in group:
|
|
134
|
+
if not chain:
|
|
135
|
+
chain = [record]
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
previous = chain[-1]
|
|
139
|
+
if _is_mergeable(previous, record, max_gap_days=max_gap_days):
|
|
140
|
+
chain.append(record)
|
|
141
|
+
else:
|
|
142
|
+
if len(chain) > 1:
|
|
143
|
+
clusters.append(chain)
|
|
144
|
+
chain = [record]
|
|
145
|
+
|
|
146
|
+
if len(chain) > 1:
|
|
147
|
+
clusters.append(chain)
|
|
148
|
+
|
|
149
|
+
return clusters
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def run_dedupe_edges(
|
|
153
|
+
dataset_name: Optional[str] = None,
|
|
154
|
+
max_gap_days: int = 1,
|
|
155
|
+
dry_run: bool = False,
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Deduplicate relationship edges in resolver (zavod-style)."""
|
|
158
|
+
if max_gap_days < 0:
|
|
159
|
+
raise ValueError("--max-gap-days must be >= 0")
|
|
160
|
+
|
|
161
|
+
configs = find_datasets(dataset_name)
|
|
162
|
+
if not configs:
|
|
163
|
+
raise ValueError(f"No datasets found matching '{dataset_name}'")
|
|
164
|
+
|
|
165
|
+
dataset_names = [load_config(config).name for config in configs]
|
|
166
|
+
store = get_level_store(dataset_names, fresh=True)
|
|
167
|
+
load_statements(store, dataset_names)
|
|
168
|
+
view = store.view(store.dataset)
|
|
169
|
+
|
|
170
|
+
resolver = get_resolver()
|
|
171
|
+
resolver.begin()
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
records: list[EdgeRecord] = []
|
|
175
|
+
for entity in view.entities():
|
|
176
|
+
record = _extract_edge_record(entity, resolver)
|
|
177
|
+
if record is not None:
|
|
178
|
+
records.append(record)
|
|
179
|
+
|
|
180
|
+
clusters = _build_clusters(records, max_gap_days=max_gap_days)
|
|
181
|
+
if dry_run:
|
|
182
|
+
merged_entities = sum(len(cluster) for cluster in clusters)
|
|
183
|
+
log.info(
|
|
184
|
+
"Dry-run complete: %s clusters would be merged (%s edge entities)",
|
|
185
|
+
len(clusters),
|
|
186
|
+
merged_entities,
|
|
187
|
+
)
|
|
188
|
+
resolver.rollback()
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
merged_entities = 0
|
|
192
|
+
for cluster in clusters:
|
|
193
|
+
canonical = resolver.get_canonical(cluster[0].entity_id)
|
|
194
|
+
for record in cluster[1:]:
|
|
195
|
+
other = resolver.get_canonical(record.entity_id)
|
|
196
|
+
if other == canonical:
|
|
197
|
+
continue
|
|
198
|
+
canonical = resolver.decide(
|
|
199
|
+
canonical,
|
|
200
|
+
other,
|
|
201
|
+
judgement=Judgement.POSITIVE,
|
|
202
|
+
user="muckrake/edge-dedupe",
|
|
203
|
+
).id
|
|
204
|
+
merged_entities += 1
|
|
205
|
+
|
|
206
|
+
resolver.commit()
|
|
207
|
+
log.info(
|
|
208
|
+
"Edge dedupe complete: merged %s clusters (%s edge entities)",
|
|
209
|
+
len(clusters),
|
|
210
|
+
merged_entities,
|
|
211
|
+
)
|
|
212
|
+
except Exception:
|
|
213
|
+
resolver.rollback()
|
|
214
|
+
raise
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime, timedelta
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from typing import Any, Dict, Iterable, List, Optional, TypedDict
|
|
6
|
+
|
|
7
|
+
from followthemoney import model
|
|
8
|
+
from nomenklatura.judgement import Judgement
|
|
9
|
+
from sqlalchemy import text
|
|
10
|
+
from sqlalchemy.engine import Connection
|
|
11
|
+
|
|
12
|
+
from muckrake.db import ensure_resolver_lock_schema, get_resolver
|
|
13
|
+
from muckrake.view import get_view, serialize_view_entity
|
|
14
|
+
|
|
15
|
+
LOCK_TTL = timedelta(minutes=30)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DedupeLockError(ValueError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ResolverLock(TypedDict):
|
|
23
|
+
pair_key: str
|
|
24
|
+
left_id: str
|
|
25
|
+
right_id: str
|
|
26
|
+
user_id: str
|
|
27
|
+
user_name: Optional[str]
|
|
28
|
+
locked_at: str
|
|
29
|
+
expires_at: str
|
|
30
|
+
updated_at: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@lru_cache(maxsize=1)
|
|
34
|
+
def get_lock_engine():
|
|
35
|
+
return ensure_resolver_lock_schema()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _utc_now() -> datetime:
|
|
39
|
+
return datetime.now(UTC)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _pair_key(left_id: str, right_id: str) -> str:
|
|
43
|
+
left, right = sorted((left_id, right_id))
|
|
44
|
+
return f"{left}::{right}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _resolve_user_label(user_id: str, user_name: Optional[str]) -> str:
|
|
48
|
+
name = (user_name or "").strip()
|
|
49
|
+
if name:
|
|
50
|
+
return f"openlobbying:{user_id}:{name}"
|
|
51
|
+
return f"openlobbying:{user_id}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _delete_expired_locks(conn: Connection, now: datetime) -> None:
|
|
55
|
+
conn.execute(
|
|
56
|
+
text("DELETE FROM resolver_lock WHERE expires_at <= :now"),
|
|
57
|
+
{"now": now.isoformat()},
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _get_user_lock(
|
|
62
|
+
conn: Connection, user_id: str, now: datetime
|
|
63
|
+
) -> Optional[ResolverLock]:
|
|
64
|
+
row = (
|
|
65
|
+
conn.execute(
|
|
66
|
+
text(
|
|
67
|
+
"""
|
|
68
|
+
SELECT pair_key, left_id, right_id, user_id, user_name, locked_at, expires_at, updated_at
|
|
69
|
+
FROM resolver_lock
|
|
70
|
+
WHERE user_id = :user_id
|
|
71
|
+
AND expires_at > :now
|
|
72
|
+
ORDER BY updated_at DESC
|
|
73
|
+
LIMIT 1
|
|
74
|
+
"""
|
|
75
|
+
),
|
|
76
|
+
{"user_id": user_id, "now": now.isoformat()},
|
|
77
|
+
)
|
|
78
|
+
.mappings()
|
|
79
|
+
.first()
|
|
80
|
+
)
|
|
81
|
+
if row is None:
|
|
82
|
+
return None
|
|
83
|
+
return ResolverLock(**dict(row))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _get_user_locks(
|
|
87
|
+
conn: Connection, user_id: str, now: datetime
|
|
88
|
+
) -> List[ResolverLock]:
|
|
89
|
+
rows = (
|
|
90
|
+
conn.execute(
|
|
91
|
+
text(
|
|
92
|
+
"""
|
|
93
|
+
SELECT pair_key, left_id, right_id, user_id, user_name, locked_at, expires_at, updated_at
|
|
94
|
+
FROM resolver_lock
|
|
95
|
+
WHERE user_id = :user_id
|
|
96
|
+
AND expires_at > :now
|
|
97
|
+
ORDER BY updated_at DESC, pair_key ASC
|
|
98
|
+
"""
|
|
99
|
+
),
|
|
100
|
+
{"user_id": user_id, "now": now.isoformat()},
|
|
101
|
+
)
|
|
102
|
+
.mappings()
|
|
103
|
+
.all()
|
|
104
|
+
)
|
|
105
|
+
return [ResolverLock(**dict(row)) for row in rows]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _release_lock(conn: Connection, pair_key: str) -> None:
|
|
109
|
+
conn.execute(
|
|
110
|
+
text("DELETE FROM resolver_lock WHERE pair_key = :pair_key"),
|
|
111
|
+
{"pair_key": pair_key},
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _release_locks(conn: Connection, pair_keys: Iterable[str]) -> None:
|
|
116
|
+
for pair_key in pair_keys:
|
|
117
|
+
_release_lock(conn, pair_key)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _get_lock_owner(conn: Connection, pair_key: str, now: datetime) -> Optional[str]:
|
|
121
|
+
return conn.execute(
|
|
122
|
+
text(
|
|
123
|
+
"""
|
|
124
|
+
SELECT user_id
|
|
125
|
+
FROM resolver_lock
|
|
126
|
+
WHERE pair_key = :pair_key
|
|
127
|
+
AND expires_at > :now
|
|
128
|
+
"""
|
|
129
|
+
),
|
|
130
|
+
{"pair_key": pair_key, "now": now.isoformat()},
|
|
131
|
+
).scalar_one_or_none()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _upsert_lock(
|
|
135
|
+
conn: Connection,
|
|
136
|
+
*,
|
|
137
|
+
left_id: str,
|
|
138
|
+
right_id: str,
|
|
139
|
+
user_id: str,
|
|
140
|
+
user_name: Optional[str],
|
|
141
|
+
now: datetime,
|
|
142
|
+
) -> bool:
|
|
143
|
+
pair_key = _pair_key(left_id, right_id)
|
|
144
|
+
expires_at = (now + LOCK_TTL).isoformat()
|
|
145
|
+
result = conn.execute(
|
|
146
|
+
text(
|
|
147
|
+
"""
|
|
148
|
+
INSERT INTO resolver_lock(
|
|
149
|
+
pair_key, left_id, right_id, user_id, user_name, locked_at, expires_at, updated_at
|
|
150
|
+
) VALUES (
|
|
151
|
+
:pair_key, :left_id, :right_id, :user_id, :user_name, :locked_at, :expires_at, :updated_at
|
|
152
|
+
)
|
|
153
|
+
ON CONFLICT (pair_key) DO UPDATE SET
|
|
154
|
+
left_id = EXCLUDED.left_id,
|
|
155
|
+
right_id = EXCLUDED.right_id,
|
|
156
|
+
user_id = EXCLUDED.user_id,
|
|
157
|
+
user_name = EXCLUDED.user_name,
|
|
158
|
+
locked_at = EXCLUDED.locked_at,
|
|
159
|
+
expires_at = EXCLUDED.expires_at,
|
|
160
|
+
updated_at = EXCLUDED.updated_at
|
|
161
|
+
WHERE resolver_lock.expires_at <= :now
|
|
162
|
+
OR resolver_lock.user_id = EXCLUDED.user_id
|
|
163
|
+
"""
|
|
164
|
+
),
|
|
165
|
+
{
|
|
166
|
+
"pair_key": pair_key,
|
|
167
|
+
"left_id": left_id,
|
|
168
|
+
"right_id": right_id,
|
|
169
|
+
"user_id": user_id,
|
|
170
|
+
"user_name": user_name,
|
|
171
|
+
"locked_at": now.isoformat(),
|
|
172
|
+
"expires_at": expires_at,
|
|
173
|
+
"updated_at": now.isoformat(),
|
|
174
|
+
"now": now.isoformat(),
|
|
175
|
+
},
|
|
176
|
+
)
|
|
177
|
+
return result.rowcount > 0
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _load_candidate_payload(
|
|
181
|
+
left_id: str,
|
|
182
|
+
right_id: str,
|
|
183
|
+
score: Optional[float],
|
|
184
|
+
expires_at: Optional[str] = None,
|
|
185
|
+
verify_candidate: bool = True,
|
|
186
|
+
) -> Optional[Dict[str, Any]]:
|
|
187
|
+
view = get_view()
|
|
188
|
+
if verify_candidate:
|
|
189
|
+
resolver = get_resolver(begin=True)
|
|
190
|
+
try:
|
|
191
|
+
if not resolver.check_candidate(left_id, right_id):
|
|
192
|
+
return None
|
|
193
|
+
finally:
|
|
194
|
+
resolver.rollback()
|
|
195
|
+
|
|
196
|
+
left = view.get_entity(left_id)
|
|
197
|
+
right = view.get_entity(right_id)
|
|
198
|
+
if left is None or right is None:
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
left_schema = model.get(left.schema.name)
|
|
202
|
+
right_schema = model.get(right.schema.name)
|
|
203
|
+
route = (
|
|
204
|
+
"profile"
|
|
205
|
+
if (
|
|
206
|
+
left_schema is not None
|
|
207
|
+
and right_schema is not None
|
|
208
|
+
and left_schema.is_a("LegalEntity")
|
|
209
|
+
and right_schema.is_a("LegalEntity")
|
|
210
|
+
)
|
|
211
|
+
else "entity"
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
payload: Dict[str, Any] = {
|
|
215
|
+
"left": serialize_view_entity(left),
|
|
216
|
+
"right": serialize_view_entity(right),
|
|
217
|
+
"score": score,
|
|
218
|
+
"route": route,
|
|
219
|
+
}
|
|
220
|
+
if expires_at is not None:
|
|
221
|
+
payload["lock_expires_at"] = expires_at
|
|
222
|
+
return payload
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _list_candidate_rows(limit: int) -> List[tuple[str, str, Optional[float]]]:
|
|
226
|
+
resolver = get_resolver(begin=True)
|
|
227
|
+
try:
|
|
228
|
+
return list(resolver.get_candidates(limit=limit))
|
|
229
|
+
finally:
|
|
230
|
+
resolver.rollback()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def get_next_dedupe_candidate(
|
|
234
|
+
user_id: str,
|
|
235
|
+
user_name: Optional[str] = None,
|
|
236
|
+
limit: int = 200,
|
|
237
|
+
) -> Optional[Dict[str, Any]]:
|
|
238
|
+
engine = get_lock_engine()
|
|
239
|
+
now = _utc_now()
|
|
240
|
+
|
|
241
|
+
with engine.begin() as conn:
|
|
242
|
+
_delete_expired_locks(conn, now)
|
|
243
|
+
|
|
244
|
+
current_lock = _get_user_lock(conn, user_id, now)
|
|
245
|
+
if current_lock is not None:
|
|
246
|
+
payload = _load_candidate_payload(
|
|
247
|
+
current_lock["left_id"],
|
|
248
|
+
current_lock["right_id"],
|
|
249
|
+
score=None,
|
|
250
|
+
expires_at=current_lock["expires_at"],
|
|
251
|
+
)
|
|
252
|
+
if payload is not None:
|
|
253
|
+
return payload
|
|
254
|
+
|
|
255
|
+
_release_lock(conn, current_lock["pair_key"])
|
|
256
|
+
|
|
257
|
+
candidates = _list_candidate_rows(limit)
|
|
258
|
+
|
|
259
|
+
for left_id, right_id, score in candidates:
|
|
260
|
+
with engine.begin() as conn:
|
|
261
|
+
claimed = _upsert_lock(
|
|
262
|
+
conn,
|
|
263
|
+
left_id=left_id,
|
|
264
|
+
right_id=right_id,
|
|
265
|
+
user_id=user_id,
|
|
266
|
+
user_name=user_name,
|
|
267
|
+
now=now,
|
|
268
|
+
)
|
|
269
|
+
if not claimed:
|
|
270
|
+
continue
|
|
271
|
+
|
|
272
|
+
payload = _load_candidate_payload(
|
|
273
|
+
left_id,
|
|
274
|
+
right_id,
|
|
275
|
+
score=score,
|
|
276
|
+
expires_at=(now + LOCK_TTL).isoformat(),
|
|
277
|
+
verify_candidate=False,
|
|
278
|
+
)
|
|
279
|
+
if payload is not None:
|
|
280
|
+
return payload
|
|
281
|
+
|
|
282
|
+
with engine.begin() as conn:
|
|
283
|
+
_release_lock(conn, _pair_key(left_id, right_id))
|
|
284
|
+
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def record_dedupe_judgement(
|
|
289
|
+
left_id: str,
|
|
290
|
+
right_id: str,
|
|
291
|
+
judgement_value: str,
|
|
292
|
+
user_id: str,
|
|
293
|
+
user_name: Optional[str] = None,
|
|
294
|
+
) -> str:
|
|
295
|
+
try:
|
|
296
|
+
judgement = Judgement(judgement_value)
|
|
297
|
+
except ValueError as exc:
|
|
298
|
+
raise ValueError(f"Invalid judgement: {judgement_value}") from exc
|
|
299
|
+
|
|
300
|
+
engine = get_lock_engine()
|
|
301
|
+
now = _utc_now()
|
|
302
|
+
pair_key = _pair_key(left_id, right_id)
|
|
303
|
+
resolver = get_resolver()
|
|
304
|
+
resolver.begin()
|
|
305
|
+
try:
|
|
306
|
+
with engine.begin() as conn:
|
|
307
|
+
_delete_expired_locks(conn, now)
|
|
308
|
+
lock = _get_lock_owner(conn, pair_key, now)
|
|
309
|
+
if lock != user_id:
|
|
310
|
+
raise DedupeLockError("This candidate is not currently locked to you.")
|
|
311
|
+
|
|
312
|
+
if not resolver.check_candidate(left_id, right_id):
|
|
313
|
+
raise ValueError("This candidate has already been judged.")
|
|
314
|
+
|
|
315
|
+
canonical = resolver.decide(
|
|
316
|
+
left_id,
|
|
317
|
+
right_id,
|
|
318
|
+
judgement,
|
|
319
|
+
user=_resolve_user_label(user_id, user_name),
|
|
320
|
+
)
|
|
321
|
+
resolver.commit()
|
|
322
|
+
|
|
323
|
+
with engine.begin() as conn:
|
|
324
|
+
_release_lock(conn, pair_key)
|
|
325
|
+
|
|
326
|
+
return str(canonical)
|
|
327
|
+
except Exception:
|
|
328
|
+
resolver.rollback()
|
|
329
|
+
raise
|
muckrake/entity_query.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from typing import Any, Dict, Sequence
|
|
5
|
+
|
|
6
|
+
from followthemoney import model
|
|
7
|
+
from nomenklatura.db import get_engine
|
|
8
|
+
from sqlalchemy import text
|
|
9
|
+
|
|
10
|
+
from muckrake.dataset import list_dataset_names
|
|
11
|
+
from muckrake.serialize import get_all_datasets_metadata, serialize_entity
|
|
12
|
+
from muckrake.settings import PUBLISHED_SQL_URI, get_working_sql_uri
|
|
13
|
+
from muckrake.store import get_sql_store
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_schema_filter(schema_names: Sequence[str]) -> list[str]:
|
|
17
|
+
if not schema_names:
|
|
18
|
+
return []
|
|
19
|
+
|
|
20
|
+
normalized: list[str] = []
|
|
21
|
+
seen = set()
|
|
22
|
+
for schema_name in schema_names:
|
|
23
|
+
schema_obj = model.get(schema_name)
|
|
24
|
+
if schema_obj is None:
|
|
25
|
+
if schema_name not in seen:
|
|
26
|
+
normalized.append(schema_name)
|
|
27
|
+
seen.add(schema_name)
|
|
28
|
+
continue
|
|
29
|
+
|
|
30
|
+
for candidate in [schema_obj.name, *[child.name for child in schema_obj.descendants]]:
|
|
31
|
+
if candidate not in seen:
|
|
32
|
+
normalized.append(candidate)
|
|
33
|
+
seen.add(candidate)
|
|
34
|
+
return normalized
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _list_db_dataset_names(uri: str) -> list[str]:
|
|
38
|
+
engine = get_engine(uri)
|
|
39
|
+
with engine.connect() as conn:
|
|
40
|
+
result = conn.execute(
|
|
41
|
+
text(
|
|
42
|
+
"SELECT DISTINCT dataset FROM statement "
|
|
43
|
+
"WHERE dataset IS NOT NULL AND dataset != '' ORDER BY dataset"
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
return [row[0] for row in result]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@lru_cache(maxsize=8)
|
|
50
|
+
def list_all_dataset_names(uri: str = PUBLISHED_SQL_URI) -> list[str]:
|
|
51
|
+
names = set(list_dataset_names())
|
|
52
|
+
try:
|
|
53
|
+
names.update(_list_db_dataset_names(uri))
|
|
54
|
+
except Exception:
|
|
55
|
+
pass
|
|
56
|
+
return sorted(names)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@lru_cache(maxsize=8)
|
|
60
|
+
def get_view(uri: str = PUBLISHED_SQL_URI):
|
|
61
|
+
store = get_sql_store(list_all_dataset_names(uri), uri=uri)
|
|
62
|
+
return store.default_view(external=True)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@lru_cache(maxsize=16000)
|
|
66
|
+
def get_entity_details(entity_id: str, uri: str = PUBLISHED_SQL_URI) -> Dict[str, str]:
|
|
67
|
+
view = get_view(uri)
|
|
68
|
+
ent = view.get_entity(entity_id)
|
|
69
|
+
if ent is None:
|
|
70
|
+
return {"caption": entity_id, "schema": "Entity"}
|
|
71
|
+
return {"caption": ent.caption, "schema": ent.schema.name}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def serialize_view_entity(ent, *, uri: str = PUBLISHED_SQL_URI) -> Dict[str, Any]:
|
|
75
|
+
return serialize_entity(
|
|
76
|
+
ent,
|
|
77
|
+
get_all_datasets_metadata(),
|
|
78
|
+
lambda entity_id: get_entity_details(entity_id, uri),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def get_entity_payload(entity_id: str, *, uri: str | None = None) -> Dict[str, Any] | None:
|
|
83
|
+
if uri is None:
|
|
84
|
+
uri = get_working_sql_uri()
|
|
85
|
+
view = get_view(uri)
|
|
86
|
+
ent = view.get_entity(entity_id)
|
|
87
|
+
if ent is None:
|
|
88
|
+
return None
|
|
89
|
+
return serialize_view_entity(ent, uri=uri)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def search_entity_payload(
|
|
93
|
+
query: str,
|
|
94
|
+
schema_filter: Sequence[str],
|
|
95
|
+
limit: int,
|
|
96
|
+
offset: int,
|
|
97
|
+
*,
|
|
98
|
+
uri: str | None = None,
|
|
99
|
+
) -> Any:
|
|
100
|
+
from muckrake.search import search_entities as run_search_entities
|
|
101
|
+
|
|
102
|
+
if uri is None:
|
|
103
|
+
uri = get_working_sql_uri()
|
|
104
|
+
|
|
105
|
+
effective_schema_filter = normalize_schema_filter(schema_filter)
|
|
106
|
+
if not effective_schema_filter:
|
|
107
|
+
effective_schema_filter = [schema.name for schema in model.schemata.values()]
|
|
108
|
+
return run_search_entities(query, effective_schema_filter, limit, offset, uri=uri)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def clear_query_caches() -> None:
|
|
112
|
+
list_all_dataset_names.cache_clear()
|
|
113
|
+
get_view.cache_clear()
|
|
114
|
+
get_entity_details.cache_clear()
|