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,255 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Iterator
|
|
5
|
+
|
|
6
|
+
from followthemoney import model
|
|
7
|
+
from followthemoney.statement import Statement
|
|
8
|
+
from followthemoney.statement.serialize import read_pack_statements
|
|
9
|
+
from sqlalchemy import text
|
|
10
|
+
|
|
11
|
+
from org_id import make_hashed_id
|
|
12
|
+
|
|
13
|
+
from .pipeline import text_fingerprint
|
|
14
|
+
from .storage import get_connection
|
|
15
|
+
|
|
16
|
+
log = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _can_use_replacement(schema_name: str, prop_name: str, target_schema: str) -> bool:
|
|
20
|
+
try:
|
|
21
|
+
schema = model.get(schema_name)
|
|
22
|
+
if schema is None:
|
|
23
|
+
return False
|
|
24
|
+
prop = schema.get(prop_name)
|
|
25
|
+
if prop is None:
|
|
26
|
+
return False
|
|
27
|
+
if prop.type.name != "entity":
|
|
28
|
+
return False
|
|
29
|
+
if prop.range is None:
|
|
30
|
+
return True
|
|
31
|
+
target = model.get(target_schema)
|
|
32
|
+
if target is None:
|
|
33
|
+
return False
|
|
34
|
+
return target.is_a(prop.range)
|
|
35
|
+
except Exception:
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _clone_statement(stmt: Statement, value: str) -> Statement:
|
|
40
|
+
return Statement(
|
|
41
|
+
entity_id=stmt.entity_id,
|
|
42
|
+
prop=stmt.prop,
|
|
43
|
+
schema=stmt.schema,
|
|
44
|
+
value=value,
|
|
45
|
+
dataset=stmt.dataset,
|
|
46
|
+
lang=stmt.lang,
|
|
47
|
+
original_value=stmt.original_value,
|
|
48
|
+
first_seen=stmt.first_seen,
|
|
49
|
+
external=stmt.external,
|
|
50
|
+
id=None,
|
|
51
|
+
canonical_id=None,
|
|
52
|
+
last_seen=stmt.last_seen,
|
|
53
|
+
origin=stmt.origin,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_approved_candidates() -> dict[tuple[str, str], dict]:
|
|
58
|
+
try:
|
|
59
|
+
conn = get_connection()
|
|
60
|
+
rows = conn.execute(
|
|
61
|
+
text(
|
|
62
|
+
"""
|
|
63
|
+
SELECT
|
|
64
|
+
property_name,
|
|
65
|
+
fingerprint,
|
|
66
|
+
extraction_json
|
|
67
|
+
FROM ner_candidates
|
|
68
|
+
WHERE status = 'approved'
|
|
69
|
+
ORDER BY updated_at DESC, id DESC
|
|
70
|
+
"""
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
except Exception:
|
|
74
|
+
return {}
|
|
75
|
+
|
|
76
|
+
out: dict[tuple[str, str], dict] = {}
|
|
77
|
+
for row in rows:
|
|
78
|
+
mapping = row._mapping
|
|
79
|
+
key = (mapping["property_name"], mapping["fingerprint"])
|
|
80
|
+
if key in out:
|
|
81
|
+
continue
|
|
82
|
+
try:
|
|
83
|
+
out[key] = json.loads(mapping["extraction_json"])
|
|
84
|
+
except json.JSONDecodeError:
|
|
85
|
+
log.warning(
|
|
86
|
+
"Invalid extraction JSON for %s:%s",
|
|
87
|
+
mapping["property_name"],
|
|
88
|
+
mapping["fingerprint"],
|
|
89
|
+
)
|
|
90
|
+
continue
|
|
91
|
+
conn.close()
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_replacement_plan(
|
|
96
|
+
pack_path: Path, candidates: dict[tuple[str, str], dict]
|
|
97
|
+
) -> dict[str, list[tuple[str, str, dict[str, list[str]]]]]:
|
|
98
|
+
replacements: dict[str, list[tuple[str, str, dict[str, list[str]]]]] = {}
|
|
99
|
+
with open(pack_path, "rb") as fh:
|
|
100
|
+
for stmt in read_pack_statements(fh):
|
|
101
|
+
if stmt.prop != "name":
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
key = (stmt.prop, text_fingerprint(stmt.value))
|
|
105
|
+
candidate = candidates.get(key)
|
|
106
|
+
if candidate is None:
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
entities = candidate
|
|
110
|
+
if not isinstance(entities, list) or not entities:
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
prelim: list[tuple[str | None, str, str, dict[str, list[str]]]] = []
|
|
114
|
+
key_to_id: dict[str, str] = {}
|
|
115
|
+
for fragment in entities:
|
|
116
|
+
schema = fragment.get("schema")
|
|
117
|
+
props = fragment.get("properties")
|
|
118
|
+
if not isinstance(schema, str) or not isinstance(props, dict):
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
schema_obj = model.get(schema)
|
|
122
|
+
if schema_obj is None:
|
|
123
|
+
log.warning("Skipping fragment with unknown schema '%s'", schema)
|
|
124
|
+
continue
|
|
125
|
+
|
|
126
|
+
local_key = fragment.get("key")
|
|
127
|
+
if local_key is not None and not isinstance(local_key, str):
|
|
128
|
+
local_key = None
|
|
129
|
+
|
|
130
|
+
clean_props: dict[str, list[str]] = {}
|
|
131
|
+
for prop_name, values in props.items():
|
|
132
|
+
if not isinstance(prop_name, str) or not isinstance(values, list):
|
|
133
|
+
continue
|
|
134
|
+
prop = schema_obj.get(prop_name)
|
|
135
|
+
if prop is None:
|
|
136
|
+
log.warning(
|
|
137
|
+
"Skipping invalid property '%s' for schema '%s'",
|
|
138
|
+
prop_name,
|
|
139
|
+
schema,
|
|
140
|
+
)
|
|
141
|
+
continue
|
|
142
|
+
|
|
143
|
+
out_values: list[str] = []
|
|
144
|
+
for value in values:
|
|
145
|
+
if not isinstance(value, str):
|
|
146
|
+
continue
|
|
147
|
+
if value.startswith("$ref:"):
|
|
148
|
+
if prop.type.name != "entity":
|
|
149
|
+
continue
|
|
150
|
+
out_values.append(value)
|
|
151
|
+
continue
|
|
152
|
+
cleaned = prop.type.clean(value)
|
|
153
|
+
if cleaned is None:
|
|
154
|
+
continue
|
|
155
|
+
out_values.append(cleaned)
|
|
156
|
+
|
|
157
|
+
if out_values:
|
|
158
|
+
clean_props[prop_name] = out_values
|
|
159
|
+
|
|
160
|
+
prefix = (
|
|
161
|
+
stmt.entity_id.rsplit("-", 1)[0] if "-" in stmt.entity_id else "ner"
|
|
162
|
+
)
|
|
163
|
+
names = clean_props.get("name")
|
|
164
|
+
if names:
|
|
165
|
+
new_id = make_hashed_id(prefix, names[0])
|
|
166
|
+
else:
|
|
167
|
+
stable_props = json.dumps(clean_props, sort_keys=True)
|
|
168
|
+
new_id = make_hashed_id(prefix, schema, stable_props)
|
|
169
|
+
|
|
170
|
+
if local_key:
|
|
171
|
+
key_to_id[local_key] = new_id
|
|
172
|
+
|
|
173
|
+
prelim.append((local_key, new_id, schema, clean_props))
|
|
174
|
+
|
|
175
|
+
fragments: list[tuple[str, str, dict[str, list[str]]]] = []
|
|
176
|
+
for _, new_id, schema, clean_props in prelim:
|
|
177
|
+
resolved_props: dict[str, list[str]] = {}
|
|
178
|
+
for prop_name, values in clean_props.items():
|
|
179
|
+
out_values: list[str] = []
|
|
180
|
+
for value in values:
|
|
181
|
+
if value.startswith("$ref:"):
|
|
182
|
+
ref_key = value[5:]
|
|
183
|
+
ref_id = key_to_id.get(ref_key)
|
|
184
|
+
if ref_id is None:
|
|
185
|
+
continue
|
|
186
|
+
out_values.append(ref_id)
|
|
187
|
+
else:
|
|
188
|
+
out_values.append(value)
|
|
189
|
+
if out_values:
|
|
190
|
+
resolved_props[prop_name] = out_values
|
|
191
|
+
|
|
192
|
+
if resolved_props:
|
|
193
|
+
fragments.append((new_id, schema, resolved_props))
|
|
194
|
+
|
|
195
|
+
if fragments:
|
|
196
|
+
replacements[stmt.entity_id] = fragments
|
|
197
|
+
return replacements
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def iter_transformed_statements(
|
|
201
|
+
pack_path: Path,
|
|
202
|
+
dataset_name: str,
|
|
203
|
+
replacements: dict[str, list[tuple[str, str, dict[str, list[str]]]]],
|
|
204
|
+
) -> Iterator[Statement]:
|
|
205
|
+
emitted_new_entities: set[str] = set()
|
|
206
|
+
|
|
207
|
+
with open(pack_path, "rb") as fh:
|
|
208
|
+
for stmt in read_pack_statements(fh):
|
|
209
|
+
if stmt.entity_id in replacements:
|
|
210
|
+
continue
|
|
211
|
+
|
|
212
|
+
if stmt.prop_type == "entity" and stmt.value in replacements:
|
|
213
|
+
for new_id, new_schema, _ in replacements[stmt.value]:
|
|
214
|
+
if not _can_use_replacement(stmt.schema, stmt.prop, new_schema):
|
|
215
|
+
continue
|
|
216
|
+
yield _clone_statement(stmt, new_id)
|
|
217
|
+
continue
|
|
218
|
+
|
|
219
|
+
yield stmt
|
|
220
|
+
|
|
221
|
+
for fragments in replacements.values():
|
|
222
|
+
for new_id, schema, properties in fragments:
|
|
223
|
+
if new_id in emitted_new_entities:
|
|
224
|
+
continue
|
|
225
|
+
emitted_new_entities.add(new_id)
|
|
226
|
+
yield Statement(
|
|
227
|
+
entity_id=new_id,
|
|
228
|
+
prop="id",
|
|
229
|
+
schema=schema,
|
|
230
|
+
value=new_id,
|
|
231
|
+
dataset=dataset_name,
|
|
232
|
+
)
|
|
233
|
+
for prop_name, values in properties.items():
|
|
234
|
+
for value in values:
|
|
235
|
+
yield Statement(
|
|
236
|
+
entity_id=new_id,
|
|
237
|
+
prop=prop_name,
|
|
238
|
+
schema=schema,
|
|
239
|
+
value=value,
|
|
240
|
+
dataset=dataset_name,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def iter_dataset_statements(dataset_name: str, pack_path: Path) -> Iterator[Statement]:
|
|
245
|
+
candidates = load_approved_candidates()
|
|
246
|
+
replacements = build_replacement_plan(pack_path, candidates)
|
|
247
|
+
|
|
248
|
+
if replacements:
|
|
249
|
+
log.info(
|
|
250
|
+
"Applying NER replacements for %s entities in %s",
|
|
251
|
+
len(replacements),
|
|
252
|
+
dataset_name,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
yield from iter_transformed_statements(pack_path, dataset_name, replacements)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import logging
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Iterable, Optional
|
|
5
|
+
|
|
6
|
+
from followthemoney.statement.serialize import read_pack_statements
|
|
7
|
+
|
|
8
|
+
from muckrake.dataset import find_datasets, get_dataset_path, load_config
|
|
9
|
+
|
|
10
|
+
from .engines import get_extractor
|
|
11
|
+
from .engines.base import RecoverableExtractionError
|
|
12
|
+
from .storage import (
|
|
13
|
+
Candidate,
|
|
14
|
+
get_connection,
|
|
15
|
+
init_db,
|
|
16
|
+
load_cached_keys,
|
|
17
|
+
upsert_candidate,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
TARGET_FIELDS = {
|
|
23
|
+
("LegalEntity", "name"),
|
|
24
|
+
("Organization", "name"),
|
|
25
|
+
("Company", "name"),
|
|
26
|
+
("Person", "name"),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
DEFAULT_EXTRACTOR_VERSION = "default"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def text_fingerprint(value: str) -> str:
|
|
33
|
+
return hashlib.sha1(value.encode("utf-8")).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_complex_text(value: str) -> bool:
|
|
37
|
+
lowered = value.lower()
|
|
38
|
+
if len(value.strip()) < 20:
|
|
39
|
+
return False
|
|
40
|
+
markers = [",", ";", "(", ")", " and ", " & ", ":"]
|
|
41
|
+
return any(marker in lowered for marker in markers)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def iter_text_statements(pack_path: Path) -> Iterable[tuple[str, str, str, str]]:
|
|
45
|
+
with open(pack_path, "rb") as fh:
|
|
46
|
+
for stmt in read_pack_statements(fh):
|
|
47
|
+
if (stmt.schema, stmt.prop) not in TARGET_FIELDS:
|
|
48
|
+
continue
|
|
49
|
+
if not isinstance(stmt.value, str):
|
|
50
|
+
continue
|
|
51
|
+
text = stmt.value.strip()
|
|
52
|
+
if not text:
|
|
53
|
+
continue
|
|
54
|
+
yield stmt.entity_id, stmt.schema, stmt.prop, text
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run_ner_extract(
|
|
58
|
+
dataset_name: Optional[str] = None,
|
|
59
|
+
limit: Optional[int] = None,
|
|
60
|
+
entity_id: Optional[str] = None,
|
|
61
|
+
extractor_name: str = "delimiter",
|
|
62
|
+
) -> None:
|
|
63
|
+
configs = find_datasets(dataset_name)
|
|
64
|
+
if not configs:
|
|
65
|
+
log.error("No datasets found matching '%s'", dataset_name)
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
extractor = get_extractor(extractor_name)
|
|
69
|
+
|
|
70
|
+
conn = get_connection()
|
|
71
|
+
init_db(conn)
|
|
72
|
+
|
|
73
|
+
processed = 0
|
|
74
|
+
written = 0
|
|
75
|
+
cached = 0
|
|
76
|
+
skipped = 0
|
|
77
|
+
|
|
78
|
+
for config in configs:
|
|
79
|
+
ds = load_config(config)
|
|
80
|
+
pack_path = get_dataset_path(ds.name) / "statements.pack.csv"
|
|
81
|
+
if not pack_path.exists():
|
|
82
|
+
log.warning("No statements found for %s", ds.name)
|
|
83
|
+
continue
|
|
84
|
+
|
|
85
|
+
existing = load_cached_keys(
|
|
86
|
+
conn,
|
|
87
|
+
dataset=ds.name,
|
|
88
|
+
extractor=extractor_name,
|
|
89
|
+
extractor_version=DEFAULT_EXTRACTOR_VERSION,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
seen: set[tuple[str, str, str]] = set()
|
|
93
|
+
for stmt_entity_id, schema, prop, text in iter_text_statements(pack_path):
|
|
94
|
+
if limit is not None and processed >= limit:
|
|
95
|
+
break
|
|
96
|
+
if entity_id is not None and stmt_entity_id != entity_id:
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
key = (stmt_entity_id, prop, text)
|
|
100
|
+
if key in seen:
|
|
101
|
+
continue
|
|
102
|
+
seen.add(key)
|
|
103
|
+
|
|
104
|
+
if not is_complex_text(text):
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
fingerprint = text_fingerprint(text)
|
|
108
|
+
cache_key = (stmt_entity_id, prop, fingerprint)
|
|
109
|
+
if cache_key in existing:
|
|
110
|
+
cached += 1
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
extraction = extractor.extract(text)
|
|
115
|
+
except RecoverableExtractionError as exc:
|
|
116
|
+
skipped += 1
|
|
117
|
+
log.warning(
|
|
118
|
+
"Skipping extraction for %s:%s due to recoverable extractor error: %s",
|
|
119
|
+
stmt_entity_id,
|
|
120
|
+
prop,
|
|
121
|
+
exc,
|
|
122
|
+
)
|
|
123
|
+
continue
|
|
124
|
+
candidate = Candidate(
|
|
125
|
+
dataset=ds.name,
|
|
126
|
+
entity_id=stmt_entity_id,
|
|
127
|
+
schema=schema,
|
|
128
|
+
property_name=prop,
|
|
129
|
+
source_text=text,
|
|
130
|
+
fingerprint=fingerprint,
|
|
131
|
+
extractor=extractor_name,
|
|
132
|
+
extractor_version=DEFAULT_EXTRACTOR_VERSION,
|
|
133
|
+
extraction=extraction,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
processed += 1
|
|
137
|
+
if upsert_candidate(conn, candidate):
|
|
138
|
+
written += 1
|
|
139
|
+
existing.add(cache_key)
|
|
140
|
+
|
|
141
|
+
if limit is not None and processed >= limit:
|
|
142
|
+
break
|
|
143
|
+
|
|
144
|
+
conn.close()
|
|
145
|
+
log.info(
|
|
146
|
+
"NER extract complete. Processed=%s candidates, cached=%s, skipped=%s, upserted=%s entries.",
|
|
147
|
+
processed,
|
|
148
|
+
cached,
|
|
149
|
+
skipped,
|
|
150
|
+
written,
|
|
151
|
+
)
|