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
muckrake/runs.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from sqlalchemy import desc, select, update
|
|
11
|
+
|
|
12
|
+
from muckrake.db import (
|
|
13
|
+
get_dataset_run_artifacts_table,
|
|
14
|
+
get_dataset_runs_table,
|
|
15
|
+
init_database,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def utc_now_iso() -> str:
|
|
20
|
+
return datetime.now(UTC).isoformat()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def detect_code_version() -> str | None:
|
|
24
|
+
try:
|
|
25
|
+
result = subprocess.run(
|
|
26
|
+
["git", "rev-parse", "HEAD"],
|
|
27
|
+
check=True,
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
)
|
|
31
|
+
except Exception:
|
|
32
|
+
return None
|
|
33
|
+
return result.stdout.strip() or None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def config_version(config_path: Path) -> str:
|
|
37
|
+
return f"sha256:{_sha256_bytes(config_path.read_bytes())}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def make_storage_prefix(dataset_name: str, run_id: int) -> str:
|
|
41
|
+
return f"dataset-runs/{dataset_name}/{run_id}"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class DatasetRun:
|
|
46
|
+
id: int
|
|
47
|
+
dataset_name: str
|
|
48
|
+
run_type: str
|
|
49
|
+
status: str
|
|
50
|
+
triggered_by: str | None
|
|
51
|
+
code_version: str | None
|
|
52
|
+
config_version: str | None
|
|
53
|
+
run_key: str | None
|
|
54
|
+
error_message: str | None
|
|
55
|
+
stats_json: str | None
|
|
56
|
+
started_at: str
|
|
57
|
+
finished_at: str | None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class DatasetRunArtifact:
|
|
62
|
+
id: int
|
|
63
|
+
dataset_run_id: int
|
|
64
|
+
artifact_type: str
|
|
65
|
+
storage_backend: str
|
|
66
|
+
storage_key: str
|
|
67
|
+
content_type: str | None
|
|
68
|
+
sha256: str
|
|
69
|
+
size_bytes: int
|
|
70
|
+
metadata_json: str | None
|
|
71
|
+
created_at: str
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def create_dataset_run(
|
|
75
|
+
dataset_name: str,
|
|
76
|
+
run_type: str = "crawl",
|
|
77
|
+
triggered_by: str | None = "muckrake/crawl",
|
|
78
|
+
code_version: str | None = None,
|
|
79
|
+
config_version_value: str | None = None,
|
|
80
|
+
run_key: str | None = None,
|
|
81
|
+
) -> DatasetRun:
|
|
82
|
+
engine = init_database()
|
|
83
|
+
table = get_dataset_runs_table()
|
|
84
|
+
now = utc_now_iso()
|
|
85
|
+
with engine.begin() as conn:
|
|
86
|
+
result = conn.execute(
|
|
87
|
+
table.insert().values(
|
|
88
|
+
dataset_name=dataset_name,
|
|
89
|
+
run_type=run_type,
|
|
90
|
+
status="running",
|
|
91
|
+
triggered_by=triggered_by,
|
|
92
|
+
code_version=code_version,
|
|
93
|
+
config_version=config_version_value,
|
|
94
|
+
run_key=run_key,
|
|
95
|
+
error_message=None,
|
|
96
|
+
stats_json=None,
|
|
97
|
+
started_at=now,
|
|
98
|
+
finished_at=None,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
run_id = result.inserted_primary_key[0]
|
|
102
|
+
row = conn.execute(select(table).where(table.c.id == run_id)).mappings().one()
|
|
103
|
+
return DatasetRun(**row)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def finish_dataset_run(
|
|
107
|
+
run_id: int,
|
|
108
|
+
status: str,
|
|
109
|
+
*,
|
|
110
|
+
error_message: str | None = None,
|
|
111
|
+
stats: dict[str, Any] | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
engine = init_database()
|
|
114
|
+
table = get_dataset_runs_table()
|
|
115
|
+
with engine.begin() as conn:
|
|
116
|
+
conn.execute(
|
|
117
|
+
update(table)
|
|
118
|
+
.where(table.c.id == run_id)
|
|
119
|
+
.values(
|
|
120
|
+
status=status,
|
|
121
|
+
error_message=error_message,
|
|
122
|
+
stats_json=json.dumps(stats, sort_keys=True) if stats else None,
|
|
123
|
+
finished_at=utc_now_iso(),
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def record_dataset_run_artifact(
|
|
129
|
+
run_id: int,
|
|
130
|
+
*,
|
|
131
|
+
artifact_type: str,
|
|
132
|
+
storage_backend: str,
|
|
133
|
+
storage_key: str,
|
|
134
|
+
content_type: str | None,
|
|
135
|
+
sha256: str,
|
|
136
|
+
size_bytes: int,
|
|
137
|
+
metadata: dict[str, Any] | None = None,
|
|
138
|
+
) -> DatasetRunArtifact:
|
|
139
|
+
engine = init_database()
|
|
140
|
+
table = get_dataset_run_artifacts_table()
|
|
141
|
+
now = utc_now_iso()
|
|
142
|
+
with engine.begin() as conn:
|
|
143
|
+
result = conn.execute(
|
|
144
|
+
table.insert().values(
|
|
145
|
+
dataset_run_id=run_id,
|
|
146
|
+
artifact_type=artifact_type,
|
|
147
|
+
storage_backend=storage_backend,
|
|
148
|
+
storage_key=storage_key,
|
|
149
|
+
content_type=content_type,
|
|
150
|
+
sha256=sha256,
|
|
151
|
+
size_bytes=size_bytes,
|
|
152
|
+
metadata_json=json.dumps(metadata, sort_keys=True) if metadata else None,
|
|
153
|
+
created_at=now,
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
artifact_id = result.inserted_primary_key[0]
|
|
157
|
+
row = conn.execute(select(table).where(table.c.id == artifact_id)).mappings().one()
|
|
158
|
+
return DatasetRunArtifact(**row)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def get_dataset_run(run_id: int) -> DatasetRun | None:
|
|
162
|
+
engine = init_database()
|
|
163
|
+
table = get_dataset_runs_table()
|
|
164
|
+
with engine.begin() as conn:
|
|
165
|
+
row = conn.execute(select(table).where(table.c.id == run_id)).mappings().first()
|
|
166
|
+
if row is None:
|
|
167
|
+
return None
|
|
168
|
+
return DatasetRun(**row)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def get_dataset_run_artifact(
|
|
172
|
+
run_id: int,
|
|
173
|
+
artifact_type: str = "statements_pack",
|
|
174
|
+
) -> DatasetRunArtifact | None:
|
|
175
|
+
engine = init_database()
|
|
176
|
+
table = get_dataset_run_artifacts_table()
|
|
177
|
+
with engine.begin() as conn:
|
|
178
|
+
row = conn.execute(
|
|
179
|
+
select(table)
|
|
180
|
+
.where(table.c.dataset_run_id == run_id)
|
|
181
|
+
.where(table.c.artifact_type == artifact_type)
|
|
182
|
+
.order_by(desc(table.c.id))
|
|
183
|
+
).mappings().first()
|
|
184
|
+
if row is None:
|
|
185
|
+
return None
|
|
186
|
+
return DatasetRunArtifact(**row)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def get_latest_successful_artifact(
|
|
190
|
+
dataset_name: str,
|
|
191
|
+
artifact_type: str = "statements_pack",
|
|
192
|
+
) -> DatasetRunArtifact | None:
|
|
193
|
+
engine = init_database()
|
|
194
|
+
runs = get_dataset_runs_table()
|
|
195
|
+
artifacts = get_dataset_run_artifacts_table()
|
|
196
|
+
with engine.begin() as conn:
|
|
197
|
+
row = conn.execute(
|
|
198
|
+
select(artifacts)
|
|
199
|
+
.join(runs, artifacts.c.dataset_run_id == runs.c.id)
|
|
200
|
+
.where(runs.c.dataset_name == dataset_name)
|
|
201
|
+
.where(runs.c.status == "succeeded")
|
|
202
|
+
.where(artifacts.c.artifact_type == artifact_type)
|
|
203
|
+
.order_by(desc(runs.c.started_at), desc(artifacts.c.id))
|
|
204
|
+
).mappings().first()
|
|
205
|
+
if row is None:
|
|
206
|
+
return None
|
|
207
|
+
return DatasetRunArtifact(**row)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def get_latest_successful_run(dataset_name: str) -> DatasetRun | None:
|
|
211
|
+
engine = init_database()
|
|
212
|
+
table = get_dataset_runs_table()
|
|
213
|
+
with engine.begin() as conn:
|
|
214
|
+
row = conn.execute(
|
|
215
|
+
select(table)
|
|
216
|
+
.where(table.c.dataset_name == dataset_name)
|
|
217
|
+
.where(table.c.status == "succeeded")
|
|
218
|
+
.order_by(desc(table.c.started_at), desc(table.c.id))
|
|
219
|
+
).mappings().first()
|
|
220
|
+
if row is None:
|
|
221
|
+
return None
|
|
222
|
+
return DatasetRun(**row)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _sha256_bytes(data: bytes) -> str:
|
|
226
|
+
import hashlib
|
|
227
|
+
|
|
228
|
+
return hashlib.sha256(data).hexdigest()
|
muckrake/search.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from typing import Any, Dict, Iterable, List, Sequence
|
|
6
|
+
|
|
7
|
+
from followthemoney import model
|
|
8
|
+
from nomenklatura.db import get_engine
|
|
9
|
+
from sqlalchemy import text
|
|
10
|
+
|
|
11
|
+
from muckrake.db import is_postgres_uri, refresh_postgres_search
|
|
12
|
+
from muckrake.settings import PUBLISHED_SQL_URI, SQL_URI
|
|
13
|
+
from muckrake.entity_query import get_view
|
|
14
|
+
|
|
15
|
+
ACTOR_SCHEMATA = ("Company", "LegalEntity", "Organization", "Person", "PublicBody")
|
|
16
|
+
SEARCH_PROPS = (
|
|
17
|
+
"name",
|
|
18
|
+
"alias",
|
|
19
|
+
"previousName",
|
|
20
|
+
"weakAlias",
|
|
21
|
+
"abbreviation",
|
|
22
|
+
"title",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class SearchResponse:
|
|
28
|
+
results: List[Dict[str, Any]]
|
|
29
|
+
total: int
|
|
30
|
+
offset: int
|
|
31
|
+
limit: int
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def has_next(self) -> bool:
|
|
35
|
+
return (self.offset + len(self.results)) < self.total
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
POSTGRES_SEARCH_SQL = text(
|
|
39
|
+
"""
|
|
40
|
+
WITH q AS (
|
|
41
|
+
SELECT
|
|
42
|
+
:query AS raw,
|
|
43
|
+
websearch_to_tsquery('simple', unaccent(:query)) AS tsq
|
|
44
|
+
)
|
|
45
|
+
SELECT
|
|
46
|
+
es.id,
|
|
47
|
+
COALESCE(es.display_name, es.id) AS name,
|
|
48
|
+
es.schema AS type,
|
|
49
|
+
similarity(COALESCE(es.display_name, ''), q.raw) AS sim_display,
|
|
50
|
+
word_similarity(q.raw, COALESCE(es.names_text, '')) AS sim_word
|
|
51
|
+
FROM entity_search AS es
|
|
52
|
+
CROSS JOIN q
|
|
53
|
+
WHERE
|
|
54
|
+
(
|
|
55
|
+
(q.tsq != ''::tsquery AND es.tsv @@ q.tsq)
|
|
56
|
+
OR similarity(COALESCE(es.display_name, ''), q.raw) > :similarity
|
|
57
|
+
OR word_similarity(q.raw, COALESCE(es.names_text, '')) > :word_similarity
|
|
58
|
+
OR COALESCE(es.names_text, '') ILIKE ('%' || q.raw || '%')
|
|
59
|
+
)
|
|
60
|
+
AND es.schema = ANY(:schemas)
|
|
61
|
+
ORDER BY
|
|
62
|
+
(lower(COALESCE(es.display_name, '')) = lower(q.raw)) DESC,
|
|
63
|
+
(COALESCE(es.display_name, '') ILIKE (q.raw || '%')) DESC,
|
|
64
|
+
ts_rank_cd(es.tsv, q.tsq) DESC,
|
|
65
|
+
GREATEST(
|
|
66
|
+
similarity(COALESCE(es.display_name, ''), q.raw),
|
|
67
|
+
word_similarity(q.raw, COALESCE(es.names_text, ''))
|
|
68
|
+
) DESC,
|
|
69
|
+
length(COALESCE(es.display_name, es.id)) ASC
|
|
70
|
+
LIMIT :limit OFFSET :offset
|
|
71
|
+
"""
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
POSTGRES_SEARCH_COUNT_SQL = text(
|
|
75
|
+
"""
|
|
76
|
+
WITH q AS (
|
|
77
|
+
SELECT
|
|
78
|
+
:query AS raw,
|
|
79
|
+
websearch_to_tsquery('simple', unaccent(:query)) AS tsq
|
|
80
|
+
)
|
|
81
|
+
SELECT COUNT(*) AS total
|
|
82
|
+
FROM entity_search AS es
|
|
83
|
+
CROSS JOIN q
|
|
84
|
+
WHERE
|
|
85
|
+
(
|
|
86
|
+
(q.tsq != ''::tsquery AND es.tsv @@ q.tsq)
|
|
87
|
+
OR similarity(COALESCE(es.display_name, ''), q.raw) > :similarity
|
|
88
|
+
OR word_similarity(q.raw, COALESCE(es.names_text, '')) > :word_similarity
|
|
89
|
+
OR COALESCE(es.names_text, '') ILIKE ('%' || q.raw || '%')
|
|
90
|
+
)
|
|
91
|
+
AND es.schema = ANY(:schemas)
|
|
92
|
+
"""
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
ACTOR_SITEMAP_IDS_SQL = text(
|
|
96
|
+
"""
|
|
97
|
+
SELECT id
|
|
98
|
+
FROM entity_search
|
|
99
|
+
WHERE schema = ANY(:schemas)
|
|
100
|
+
ORDER BY id
|
|
101
|
+
LIMIT :limit OFFSET :offset
|
|
102
|
+
"""
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
ACTOR_SITEMAP_COUNT_SQL = text(
|
|
106
|
+
"""
|
|
107
|
+
SELECT COUNT(*) AS total
|
|
108
|
+
FROM entity_search
|
|
109
|
+
WHERE schema = ANY(:schemas)
|
|
110
|
+
"""
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
ACTOR_COUNTS_SQL = text(
|
|
114
|
+
"""
|
|
115
|
+
SELECT schema, COUNT(*) AS count
|
|
116
|
+
FROM entity_search
|
|
117
|
+
WHERE schema = ANY(:schemas)
|
|
118
|
+
GROUP BY schema
|
|
119
|
+
"""
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def refresh_search_index(uri: str = SQL_URI) -> None:
|
|
124
|
+
refresh_postgres_search(uri)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@lru_cache(maxsize=4)
|
|
128
|
+
def postgres_search_ready(uri: str = PUBLISHED_SQL_URI) -> bool:
|
|
129
|
+
if not is_postgres_uri(uri):
|
|
130
|
+
return False
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
engine = get_engine(uri)
|
|
134
|
+
with engine.connect() as conn:
|
|
135
|
+
relation = conn.execute(text("SELECT to_regclass('public.entity_search')")).scalar()
|
|
136
|
+
return relation is not None
|
|
137
|
+
except Exception:
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _include_schema(schema_names: Sequence[str]) -> list[Any]:
|
|
142
|
+
include_schema = []
|
|
143
|
+
for schema_name in schema_names:
|
|
144
|
+
schema_obj = model.get(schema_name)
|
|
145
|
+
if schema_obj is not None:
|
|
146
|
+
include_schema.append(schema_obj)
|
|
147
|
+
return include_schema
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _view_search(
|
|
151
|
+
query: str, schema_filter: Sequence[str], limit: int, offset: int, *, uri: str
|
|
152
|
+
) -> SearchResponse:
|
|
153
|
+
engine = get_engine(uri)
|
|
154
|
+
params: dict[str, Any] = {"limit": limit, "offset": offset}
|
|
155
|
+
|
|
156
|
+
prop_sql = ", ".join(f"'{prop}'" for prop in SEARCH_PROPS)
|
|
157
|
+
schema_clause = ""
|
|
158
|
+
if schema_filter:
|
|
159
|
+
schema_params = []
|
|
160
|
+
for index, schema_name in enumerate(schema_filter):
|
|
161
|
+
key = f"schema_{index}"
|
|
162
|
+
params[key] = schema_name
|
|
163
|
+
schema_params.append(f":{key}")
|
|
164
|
+
schema_clause = f" AND schema IN ({', '.join(schema_params)})"
|
|
165
|
+
|
|
166
|
+
search_sql = f"""
|
|
167
|
+
SELECT canonical_id AS entity_id,
|
|
168
|
+
MIN(schema) AS schema,
|
|
169
|
+
MAX(CASE WHEN prop = 'name' THEN value END) AS name,
|
|
170
|
+
MAX(CASE WHEN prop = 'title' THEN value END) AS title,
|
|
171
|
+
0 AS exact_score
|
|
172
|
+
FROM statement
|
|
173
|
+
WHERE canonical_id IS NOT NULL
|
|
174
|
+
AND prop IN ({prop_sql})
|
|
175
|
+
{schema_clause}
|
|
176
|
+
"""
|
|
177
|
+
count_sql = f"""
|
|
178
|
+
SELECT COUNT(*) AS total
|
|
179
|
+
FROM (
|
|
180
|
+
SELECT canonical_id
|
|
181
|
+
FROM statement
|
|
182
|
+
WHERE canonical_id IS NOT NULL
|
|
183
|
+
AND prop IN ({prop_sql})
|
|
184
|
+
{schema_clause}
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
if query:
|
|
188
|
+
params["query"] = query
|
|
189
|
+
search_sql = search_sql.replace(
|
|
190
|
+
"0 AS exact_score",
|
|
191
|
+
"MAX(CASE WHEN lower(value) = lower(:query) THEN 3 ELSE 0 END) AS exact_score",
|
|
192
|
+
)
|
|
193
|
+
search_sql += " AND instr(lower(value), lower(:query)) > 0"
|
|
194
|
+
count_sql += " AND instr(lower(value), lower(:query)) > 0"
|
|
195
|
+
|
|
196
|
+
search_sql += " GROUP BY canonical_id ORDER BY exact_score DESC, COALESCE(name, title, canonical_id) ASC LIMIT :limit OFFSET :offset"
|
|
197
|
+
count_sql += " GROUP BY canonical_id ) AS matches"
|
|
198
|
+
|
|
199
|
+
with engine.connect() as conn:
|
|
200
|
+
total = int(conn.execute(text(count_sql), params).scalar() or 0)
|
|
201
|
+
rows = conn.execute(text(search_sql), params)
|
|
202
|
+
results = []
|
|
203
|
+
for row in rows:
|
|
204
|
+
name = row._mapping["name"] or row._mapping["title"] or row._mapping["entity_id"]
|
|
205
|
+
results.append(
|
|
206
|
+
{
|
|
207
|
+
"id": str(row._mapping["entity_id"]),
|
|
208
|
+
"name": str(name),
|
|
209
|
+
"type": str(row._mapping["schema"]),
|
|
210
|
+
}
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
return SearchResponse(results=results, total=total, offset=offset, limit=limit)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def search_entities(
|
|
217
|
+
query: str,
|
|
218
|
+
schema_filter: Sequence[str],
|
|
219
|
+
limit: int,
|
|
220
|
+
offset: int,
|
|
221
|
+
*,
|
|
222
|
+
uri: str = PUBLISHED_SQL_URI,
|
|
223
|
+
) -> SearchResponse:
|
|
224
|
+
if postgres_search_ready(uri):
|
|
225
|
+
engine = get_engine(uri)
|
|
226
|
+
with engine.connect() as conn:
|
|
227
|
+
total = conn.execute(
|
|
228
|
+
POSTGRES_SEARCH_COUNT_SQL,
|
|
229
|
+
{
|
|
230
|
+
"query": query,
|
|
231
|
+
"similarity": 0.25,
|
|
232
|
+
"word_similarity": 0.55,
|
|
233
|
+
"schemas": list(schema_filter),
|
|
234
|
+
},
|
|
235
|
+
).scalar()
|
|
236
|
+
rows = conn.execute(
|
|
237
|
+
POSTGRES_SEARCH_SQL,
|
|
238
|
+
{
|
|
239
|
+
"query": query,
|
|
240
|
+
"limit": limit,
|
|
241
|
+
"offset": offset,
|
|
242
|
+
"similarity": 0.25,
|
|
243
|
+
"word_similarity": 0.55,
|
|
244
|
+
"schemas": list(schema_filter),
|
|
245
|
+
},
|
|
246
|
+
)
|
|
247
|
+
results = []
|
|
248
|
+
for row in rows:
|
|
249
|
+
item = dict(row._mapping)
|
|
250
|
+
item.pop("sim_display", None)
|
|
251
|
+
item.pop("sim_word", None)
|
|
252
|
+
results.append(item)
|
|
253
|
+
return SearchResponse(
|
|
254
|
+
results=results,
|
|
255
|
+
total=int(total or 0),
|
|
256
|
+
offset=offset,
|
|
257
|
+
limit=limit,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
return _view_search(query, schema_filter, limit, offset, uri=uri)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def list_actor_sitemap_entries(
|
|
264
|
+
schema_filter: Sequence[str],
|
|
265
|
+
limit: int,
|
|
266
|
+
offset: int,
|
|
267
|
+
*,
|
|
268
|
+
uri: str = PUBLISHED_SQL_URI,
|
|
269
|
+
) -> SearchResponse:
|
|
270
|
+
if postgres_search_ready(uri):
|
|
271
|
+
engine = get_engine(uri)
|
|
272
|
+
with engine.connect() as conn:
|
|
273
|
+
total = conn.execute(
|
|
274
|
+
ACTOR_SITEMAP_COUNT_SQL,
|
|
275
|
+
{"schemas": list(schema_filter)},
|
|
276
|
+
).scalar()
|
|
277
|
+
rows = conn.execute(
|
|
278
|
+
ACTOR_SITEMAP_IDS_SQL,
|
|
279
|
+
{
|
|
280
|
+
"schemas": list(schema_filter),
|
|
281
|
+
"limit": limit,
|
|
282
|
+
"offset": offset,
|
|
283
|
+
},
|
|
284
|
+
)
|
|
285
|
+
results = [
|
|
286
|
+
{"id": str(row._mapping["id"]), "path": f"/profile/{row._mapping['id']}"}
|
|
287
|
+
for row in rows
|
|
288
|
+
]
|
|
289
|
+
return SearchResponse(
|
|
290
|
+
results=results,
|
|
291
|
+
total=int(total or 0),
|
|
292
|
+
offset=offset,
|
|
293
|
+
limit=limit,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
view = get_view(uri)
|
|
297
|
+
results = []
|
|
298
|
+
seen_ids = set()
|
|
299
|
+
total = 0
|
|
300
|
+
for ent in view.entities(include_schemata=_include_schema(schema_filter)):
|
|
301
|
+
if ent.id in seen_ids:
|
|
302
|
+
continue
|
|
303
|
+
seen_ids.add(ent.id)
|
|
304
|
+
total += 1
|
|
305
|
+
if total <= offset:
|
|
306
|
+
continue
|
|
307
|
+
if len(results) >= limit:
|
|
308
|
+
continue
|
|
309
|
+
results.append({"id": ent.id, "path": f"/profile/{ent.id}"})
|
|
310
|
+
|
|
311
|
+
return SearchResponse(results=results, total=total, offset=offset, limit=limit)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def get_actor_schema_counts(
|
|
315
|
+
schema_filter: Iterable[str] = ACTOR_SCHEMATA,
|
|
316
|
+
*,
|
|
317
|
+
uri: str = PUBLISHED_SQL_URI,
|
|
318
|
+
) -> Dict[str, int]:
|
|
319
|
+
schema_names = list(schema_filter)
|
|
320
|
+
counts = {schema: 0 for schema in schema_names}
|
|
321
|
+
|
|
322
|
+
if postgres_search_ready(uri):
|
|
323
|
+
engine = get_engine(uri)
|
|
324
|
+
with engine.connect() as conn:
|
|
325
|
+
rows = conn.execute(ACTOR_COUNTS_SQL, {"schemas": schema_names})
|
|
326
|
+
for row in rows:
|
|
327
|
+
schema_name = str(row._mapping["schema"])
|
|
328
|
+
counts[schema_name] = int(row._mapping["count"])
|
|
329
|
+
return counts
|
|
330
|
+
|
|
331
|
+
view = get_view(uri)
|
|
332
|
+
for ent in view.entities(include_schemata=_include_schema(schema_names)):
|
|
333
|
+
if ent.schema.name in counts:
|
|
334
|
+
counts[ent.schema.name] += 1
|
|
335
|
+
return counts
|
muckrake/serialize.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from typing import Any, Dict
|
|
5
|
+
|
|
6
|
+
from followthemoney.types import registry
|
|
7
|
+
|
|
8
|
+
from muckrake.dataset import find_datasets, get_dataset_config, load_raw_config
|
|
9
|
+
from muckrake.util import parse_date_token
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@lru_cache(maxsize=1)
|
|
13
|
+
def get_all_datasets_metadata() -> Dict[str, Dict[str, Any]]:
|
|
14
|
+
datasets = {}
|
|
15
|
+
|
|
16
|
+
for config_path in find_datasets():
|
|
17
|
+
raw = load_raw_config(config_path)
|
|
18
|
+
cfg = get_dataset_config(raw)
|
|
19
|
+
name = cfg.get("name")
|
|
20
|
+
if not name:
|
|
21
|
+
continue
|
|
22
|
+
|
|
23
|
+
publisher = (
|
|
24
|
+
raw.get("publisher", {})
|
|
25
|
+
if isinstance(raw.get("publisher", {}), dict)
|
|
26
|
+
else {}
|
|
27
|
+
)
|
|
28
|
+
licence = (
|
|
29
|
+
cfg.get("licence", {}) if isinstance(cfg.get("licence", {}), dict) else {}
|
|
30
|
+
)
|
|
31
|
+
coverage = (
|
|
32
|
+
raw.get("coverage", {}) if isinstance(raw.get("coverage", {}), dict) else {}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
datasets[name] = {
|
|
36
|
+
"name": name,
|
|
37
|
+
"prefix": cfg.get("prefix"),
|
|
38
|
+
"title": cfg.get("title", name),
|
|
39
|
+
"summary": cfg.get("summary"),
|
|
40
|
+
"tags": cfg.get("tags", []),
|
|
41
|
+
"url": cfg.get("url") or cfg.get("index_url"),
|
|
42
|
+
"index_url": cfg.get("index_url"),
|
|
43
|
+
"publisher": {
|
|
44
|
+
"name": publisher.get("name"),
|
|
45
|
+
"description": publisher.get("description"),
|
|
46
|
+
"url": publisher.get("url"),
|
|
47
|
+
"country": publisher.get("country"),
|
|
48
|
+
"country_label": publisher.get("country_label"),
|
|
49
|
+
"official": publisher.get("official"),
|
|
50
|
+
},
|
|
51
|
+
"licence": {
|
|
52
|
+
"name": licence.get("name"),
|
|
53
|
+
"url": licence.get("url"),
|
|
54
|
+
},
|
|
55
|
+
"coverage": {
|
|
56
|
+
"countries": coverage.get("countries", []),
|
|
57
|
+
"frequency": coverage.get("frequency"),
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return datasets
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _collapse_edge_temporal_extent(data: Dict[str, Any]) -> None:
|
|
65
|
+
if data.get("schema") != "Representation":
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
props = data.get("properties", {})
|
|
69
|
+
starts = [v for v in props.get("startDate", []) if isinstance(v, str)]
|
|
70
|
+
ends = [v for v in props.get("endDate", []) if isinstance(v, str)]
|
|
71
|
+
if len(starts) <= 1 and len(ends) <= 1:
|
|
72
|
+
return
|
|
73
|
+
|
|
74
|
+
start_tokens = []
|
|
75
|
+
end_tokens = []
|
|
76
|
+
for token in starts:
|
|
77
|
+
parsed = parse_date_token(token, is_end=False)
|
|
78
|
+
if parsed is not None:
|
|
79
|
+
start_tokens.append((parsed, token))
|
|
80
|
+
for token in ends:
|
|
81
|
+
parsed = parse_date_token(token, is_end=True)
|
|
82
|
+
if parsed is not None:
|
|
83
|
+
end_tokens.append((parsed, token))
|
|
84
|
+
|
|
85
|
+
if start_tokens:
|
|
86
|
+
start_tokens.sort(key=lambda item: item[0])
|
|
87
|
+
props["startDate"] = [start_tokens[0][1]]
|
|
88
|
+
if end_tokens:
|
|
89
|
+
end_tokens.sort(key=lambda item: item[0], reverse=True)
|
|
90
|
+
props["endDate"] = [end_tokens[0][1]]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def serialize_entity(ent, ds_meta: Dict[str, Any], get_details_fn) -> Dict[str, Any]:
|
|
94
|
+
data = ent.to_dict()
|
|
95
|
+
data["caption"] = ent.caption
|
|
96
|
+
data["canonical_id"] = ent.id
|
|
97
|
+
|
|
98
|
+
datasets = []
|
|
99
|
+
for ds_name in ent.datasets:
|
|
100
|
+
datasets.append(ds_meta.get(ds_name, {"name": ds_name, "title": ds_name}))
|
|
101
|
+
data["datasets"] = datasets
|
|
102
|
+
|
|
103
|
+
for prop, values in data.get("properties", {}).items():
|
|
104
|
+
schema_prop = ent.schema.get(prop)
|
|
105
|
+
if schema_prop and schema_prop.type == registry.entity:
|
|
106
|
+
enriched = []
|
|
107
|
+
for value in values:
|
|
108
|
+
details = get_details_fn(value)
|
|
109
|
+
enriched.append(
|
|
110
|
+
{
|
|
111
|
+
"id": value,
|
|
112
|
+
"caption": details["caption"],
|
|
113
|
+
"schema": details["schema"],
|
|
114
|
+
}
|
|
115
|
+
)
|
|
116
|
+
data["properties"][prop] = enriched
|
|
117
|
+
|
|
118
|
+
_collapse_edge_temporal_extent(data)
|
|
119
|
+
return data
|