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.
Files changed (48) hide show
  1. muckrake/__init__.py +61 -0
  2. muckrake/artifacts.py +72 -0
  3. muckrake/cli.py +522 -0
  4. muckrake/crawl.py +223 -0
  5. muckrake/dataset.py +231 -0
  6. muckrake/db.py +478 -0
  7. muckrake/dedupe/README.md +52 -0
  8. muckrake/dedupe/__init__.py +37 -0
  9. muckrake/dedupe/cluster.py +534 -0
  10. muckrake/dedupe/dedupe.py +133 -0
  11. muckrake/dedupe/dedupe_edges.py +214 -0
  12. muckrake/dedupe/review.py +329 -0
  13. muckrake/entity_query.py +114 -0
  14. muckrake/entity_write.py +244 -0
  15. muckrake/env.py +52 -0
  16. muckrake/export.py +40 -0
  17. muckrake/extract/__init__.py +0 -0
  18. muckrake/extract/fetch.py +186 -0
  19. muckrake/extract/ner/README.md +210 -0
  20. muckrake/extract/ner/__init__.py +4 -0
  21. muckrake/extract/ner/engines/__init__.py +32 -0
  22. muckrake/extract/ner/engines/base.py +14 -0
  23. muckrake/extract/ner/engines/delimited.py +39 -0
  24. muckrake/extract/ner/engines/llm.py +164 -0
  25. muckrake/extract/ner/engines/llm_prompt.py +44 -0
  26. muckrake/extract/ner/materialize.py +255 -0
  27. muckrake/extract/ner/pipeline.py +151 -0
  28. muckrake/extract/ner/review.py +706 -0
  29. muckrake/extract/ner/storage.py +200 -0
  30. muckrake/id.py +3 -0
  31. muckrake/load.py +70 -0
  32. muckrake/logging.py +56 -0
  33. muckrake/py.typed +0 -0
  34. muckrake/release.py +356 -0
  35. muckrake/runs.py +228 -0
  36. muckrake/search.py +335 -0
  37. muckrake/serialize.py +119 -0
  38. muckrake/settings.py +41 -0
  39. muckrake/store.py +117 -0
  40. muckrake/util.py +27 -0
  41. muckrake/utils/__init__.py +13 -0
  42. muckrake/utils/dates.py +438 -0
  43. muckrake/utils/gb_coh.py +36 -0
  44. muckrake/view.py +58 -0
  45. muckrake-0.2.1.dist-info/METADATA +136 -0
  46. muckrake-0.2.1.dist-info/RECORD +48 -0
  47. muckrake-0.2.1.dist-info/WHEEL +4 -0
  48. muckrake-0.2.1.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,244 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from followthemoney import Dataset as FTMDataset
8
+ from followthemoney import model as ftm_model
9
+ from followthemoney.exc import InvalidData
10
+ from followthemoney.statement import Statement
11
+ from sqlalchemy import delete, select, update
12
+
13
+ from muckrake.entity_query import clear_query_caches, get_entity_payload, get_view, list_all_dataset_names
14
+ from muckrake.settings import get_working_sql_uri
15
+ from muckrake.store import get_sql_store
16
+
17
+
18
+ @dataclass
19
+ class EntitySpec:
20
+ schema_name: str
21
+ dataset: str
22
+ source_ref: str
23
+ entity_id: str | None
24
+ id_parts: list[str]
25
+ key_prefix: str | None
26
+ properties: dict[str, list[str]]
27
+
28
+
29
+ def parse_properties(items: list[str]) -> dict[str, list[str]]:
30
+ properties: dict[str, list[str]] = {}
31
+ for item in items:
32
+ if "=" not in item:
33
+ raise ValueError(f"Invalid --property value: {item!r}. Expected KEY=VALUE.")
34
+ key, value = item.split("=", 1)
35
+ key = key.strip()
36
+ value = value.strip()
37
+ if not key:
38
+ raise ValueError(
39
+ f"Invalid --property value: {item!r}. Property name is empty."
40
+ )
41
+ properties.setdefault(key, []).append(value)
42
+
43
+ if not properties:
44
+ raise ValueError("At least one --property is required.")
45
+ return properties
46
+
47
+
48
+ def build_entity_spec(
49
+ *,
50
+ schema_name: str,
51
+ dataset: str,
52
+ source_ref: str,
53
+ entity_id: str | None,
54
+ id_parts: list[str],
55
+ key_prefix: str | None,
56
+ property_items: list[str],
57
+ ) -> EntitySpec:
58
+ return EntitySpec(
59
+ schema_name=schema_name,
60
+ dataset=dataset,
61
+ source_ref=source_ref,
62
+ entity_id=entity_id,
63
+ id_parts=id_parts,
64
+ key_prefix=key_prefix,
65
+ properties=parse_properties(property_items),
66
+ )
67
+
68
+
69
+ def build_entity(spec: EntitySpec):
70
+ entity = ftm_model.make_entity(spec.schema_name, key_prefix=spec.key_prefix)
71
+ try:
72
+ for prop_name, values in spec.properties.items():
73
+ entity.add(prop_name, values)
74
+ except InvalidData as exc:
75
+ raise ValueError(str(exc)) from exc
76
+
77
+ if spec.entity_id:
78
+ entity.id = spec.entity_id
79
+ else:
80
+ parts: list[str] = [spec.schema_name]
81
+ if spec.id_parts:
82
+ parts.extend(spec.id_parts)
83
+ else:
84
+ parts.extend([spec.dataset, spec.source_ref])
85
+ parts.extend(entity.get("name", quiet=True)[:1])
86
+ entity.make_id(*parts)
87
+
88
+ entity_dict = entity.to_dict()
89
+ try:
90
+ entity.schema.validate(entity_dict)
91
+ except Exception as exc:
92
+ details = getattr(exc, "errors", None)
93
+ if details is not None:
94
+ raise ValueError(json.dumps(details, indent=2, sort_keys=True)) from exc
95
+ raise
96
+ return entity
97
+
98
+
99
+ def _entity_statements(entity, dataset_name: str, source_ref: str) -> list[Statement]:
100
+ statements: list[Statement] = [
101
+ Statement(
102
+ entity_id=entity.id,
103
+ prop="id",
104
+ schema=entity.schema.name,
105
+ value=entity.id,
106
+ dataset=dataset_name,
107
+ origin=source_ref,
108
+ )
109
+ ]
110
+
111
+ for prop_name, values in entity.properties.items():
112
+ for value in values:
113
+ statements.append(
114
+ Statement(
115
+ entity_id=entity.id,
116
+ prop=prop_name,
117
+ schema=entity.schema.name,
118
+ value=value,
119
+ dataset=dataset_name,
120
+ origin=source_ref,
121
+ )
122
+ )
123
+ return statements
124
+
125
+
126
+ def _dataset_title(name: str) -> str:
127
+ return name
128
+
129
+
130
+ def _mark_existing_statements_canonical(store, entity_id: str) -> None:
131
+ with store.engine.begin() as conn:
132
+ conn.execute(
133
+ update(store.table)
134
+ .where(store.table.c.entity_id == entity_id)
135
+ .values(canonical_id=entity_id)
136
+ )
137
+
138
+
139
+ def add_entity(spec: EntitySpec, *, uri: str | None = None) -> dict[str, Any]:
140
+ if uri is None:
141
+ uri = get_working_sql_uri()
142
+
143
+ entity = build_entity(spec)
144
+ dataset = FTMDataset.make({"name": spec.dataset, "title": _dataset_title(spec.dataset)})
145
+ store = get_sql_store([spec.dataset], uri=uri)
146
+
147
+ with store.engine.begin() as conn:
148
+ existed = (
149
+ conn.execute(
150
+ select(store.table.c.entity_id)
151
+ .where(store.table.c.entity_id == entity.id)
152
+ .limit(1)
153
+ ).first()
154
+ is not None
155
+ )
156
+ conn.execute(delete(store.table).where(store.table.c.entity_id == entity.id))
157
+
158
+ _mark_existing_statements_canonical(store, entity.id)
159
+
160
+ with store.writer() as writer:
161
+ for statement in _entity_statements(entity, dataset.name, spec.source_ref):
162
+ writer.add_statement(statement)
163
+
164
+ clear_query_caches()
165
+ payload = get_entity_payload(entity.id, uri=uri)
166
+ if payload is None:
167
+ raise RuntimeError(f"Failed to read stored entity: {entity.id}")
168
+
169
+ return {
170
+ "status": "ok",
171
+ "action": "updated" if existed else "created",
172
+ "entity": payload,
173
+ "provenance": {
174
+ "dataset": spec.dataset,
175
+ "source": spec.source_ref,
176
+ "origin": spec.source_ref,
177
+ },
178
+ }
179
+
180
+
181
+ def update_entity(
182
+ entity_id: str,
183
+ *,
184
+ property_items: list[str],
185
+ dataset: str | None = None,
186
+ source_ref: str | None = None,
187
+ schema_name: str | None = None,
188
+ uri: str | None = None,
189
+ ) -> dict[str, Any]:
190
+ if uri is None:
191
+ uri = get_working_sql_uri()
192
+
193
+ view = get_view(uri)
194
+ existing = view.get_entity(entity_id)
195
+ if existing is None:
196
+ raise ValueError(f"Entity not found: {entity_id}")
197
+
198
+ existing_data = existing.to_dict()
199
+ properties = {
200
+ prop_name: [str(value) for value in values]
201
+ for prop_name, values in existing_data.get("properties", {}).items()
202
+ }
203
+ for prop_name, values in parse_properties(property_items).items():
204
+ properties[prop_name] = values
205
+
206
+ resolved_dataset = dataset or (sorted(existing.datasets)[0] if existing.datasets else None)
207
+ if resolved_dataset is None:
208
+ raise ValueError("--dataset is required when the existing entity has no dataset")
209
+
210
+ resolved_source = source_ref or _get_existing_origin(entity_id, uri=uri)
211
+ if resolved_source is None:
212
+ raise ValueError("--source is required when the existing entity has no origin")
213
+
214
+ spec = EntitySpec(
215
+ schema_name=schema_name or existing.schema.name,
216
+ dataset=resolved_dataset,
217
+ source_ref=resolved_source,
218
+ entity_id=entity_id,
219
+ id_parts=[],
220
+ key_prefix=None,
221
+ properties=properties,
222
+ )
223
+ return add_entity(spec, uri=uri)
224
+
225
+
226
+ def _get_existing_origin(entity_id: str, *, uri: str) -> str | None:
227
+ store = get_sql_store(list_all_dataset_names(uri), uri=uri)
228
+ with store.engine.connect() as conn:
229
+ row = conn.execute(
230
+ select(store.table.c.origin)
231
+ .where(store.table.c.canonical_id == entity_id)
232
+ .where(store.table.c.origin.is_not(None))
233
+ .limit(1)
234
+ ).first()
235
+ if row is None:
236
+ row = conn.execute(
237
+ select(store.table.c.origin)
238
+ .where(store.table.c.entity_id == entity_id)
239
+ .where(store.table.c.origin.is_not(None))
240
+ .limit(1)
241
+ ).first()
242
+ if row is None:
243
+ return None
244
+ return str(row[0])
muckrake/env.py ADDED
@@ -0,0 +1,52 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ def find_env_file(
6
+ start: Path | None = None, fallback_paths: list[Path] | None = None
7
+ ) -> Path | None:
8
+ explicit = os.getenv("MUCKRAKE_ENV_FILE")
9
+ if explicit:
10
+ path = Path(explicit).expanduser()
11
+ return path if path.exists() else None
12
+
13
+ current = (start or Path.cwd()).resolve()
14
+ if current.is_file():
15
+ current = current.parent
16
+
17
+ for directory in (current, *current.parents):
18
+ candidate = directory / ".env"
19
+ if candidate.exists():
20
+ return candidate
21
+
22
+ for candidate in fallback_paths or []:
23
+ if candidate.exists():
24
+ return candidate
25
+
26
+ return None
27
+
28
+
29
+ def read_env_file(path: Path) -> dict[str, str]:
30
+ if not path.exists():
31
+ return {}
32
+
33
+ values: dict[str, str] = {}
34
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
35
+ line = raw_line.strip()
36
+ if not line or line.startswith("#") or "=" not in line:
37
+ continue
38
+ if line.startswith("export "):
39
+ line = line[7:].strip()
40
+
41
+ key, value = line.split("=", 1)
42
+ key = key.strip()
43
+ value = value.strip().strip("\"'")
44
+ if key:
45
+ values[key] = value
46
+
47
+ return values
48
+
49
+
50
+ def load_env_file(path: Path) -> None:
51
+ for key, value in read_env_file(path).items():
52
+ os.environ.setdefault(key, value)
muckrake/export.py ADDED
@@ -0,0 +1,40 @@
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ from followthemoney.cli.util import write_entity
6
+ from muckrake.dataset import find_datasets, load_config
7
+ from muckrake.store import get_level_store
8
+ from muckrake.dedupe import load_statements
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+
13
+ def run_export_ftm(output_path: Path, dataset_name: Optional[str] = None) -> None:
14
+ """Export entities to FollowTheMoney JSON format."""
15
+ all_configs = find_datasets(dataset_name)
16
+ if not all_configs:
17
+ raise ValueError(f"No datasets found matching: {dataset_name}")
18
+
19
+ dataset_names = [load_config(c).name for c in all_configs]
20
+
21
+ # Initialize store and load data (fresh=True ensures we have latest from packs)
22
+ store = get_level_store(dataset_names, fresh=True)
23
+ load_statements(store, dataset_names)
24
+
25
+ view = store.view(store.dataset)
26
+
27
+ log.info(f"Exporting to {output_path}...")
28
+ count = 0
29
+ with open(output_path, "wb") as fh:
30
+ for entity in view.entities():
31
+ if view.store.linker:
32
+ canonical_id = view.store.linker.get_canonical(entity.id)
33
+ if canonical_id != entity.id:
34
+ continue
35
+ write_entity(fh, entity)
36
+ count += 1
37
+ if count % 10000 == 0:
38
+ log.info(f"Exported {count} entities...")
39
+
40
+ log.info(f"Export complete. Total versions: {count}")
File without changes
@@ -0,0 +1,186 @@
1
+ import json
2
+ import time
3
+ import requests
4
+ from pathlib import Path
5
+ from typing import Optional, Any, TYPE_CHECKING
6
+ from lxml import html
7
+ from lxml.html import HtmlElement
8
+ from banal import hash_data
9
+ from rigour.urls import build_url
10
+ import logging
11
+
12
+ if TYPE_CHECKING:
13
+ from nomenklatura.cache import Cache
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ def request_hash(
19
+ url: str,
20
+ auth: Optional[Any] = None,
21
+ method: str = "GET",
22
+ data: Any = None,
23
+ ) -> str:
24
+ """Generate a unique fingerprint for an HTTP request."""
25
+ hsh = hash_data((auth, method, data))
26
+ return f"{url}[{hsh}]"
27
+
28
+
29
+ def fetch_file(
30
+ url: str,
31
+ name: str,
32
+ data_path: Path,
33
+ session: Optional[requests.Session] = None,
34
+ auth: Optional[Any] = None,
35
+ headers: Optional[Any] = None,
36
+ method: str = "GET",
37
+ data: Optional[Any] = None,
38
+ verify: bool = True,
39
+ timeout: float = 120,
40
+ ) -> Path:
41
+ """Fetch a file via HTTP to the data path, with local caching."""
42
+ out_path = data_path.joinpath(name)
43
+ if out_path.exists():
44
+ # log.info("Using cached file: %s", out_path)
45
+ return out_path
46
+
47
+ log.info("Fetching file from %s", url)
48
+ out_path.parent.mkdir(parents=True, exist_ok=True)
49
+ requester = session.request if session is not None else requests.request
50
+
51
+ with requester(
52
+ method=method,
53
+ url=url,
54
+ auth=auth,
55
+ headers=headers,
56
+ stream=True,
57
+ data=data,
58
+ timeout=timeout,
59
+ verify=verify,
60
+ ) as res:
61
+ res.raise_for_status()
62
+ with open(out_path, "wb") as fh:
63
+ for chunk in res.iter_content(chunk_size=8192 * 10):
64
+ fh.write(chunk)
65
+
66
+ return out_path
67
+
68
+
69
+ def fetch_text(
70
+ url: str,
71
+ params: Optional[dict[str, Any]] = None,
72
+ headers: Optional[dict[str, str]] = None,
73
+ session: Optional[requests.Session] = None,
74
+ auth: Optional[Any] = None,
75
+ method: str = "GET",
76
+ data: Optional[Any] = None,
77
+ cache: Optional["Cache"] = None,
78
+ cache_days: Optional[int] = None,
79
+ sleep: Optional[float] = None,
80
+ verify: bool = True,
81
+ timeout: float = 120,
82
+ ) -> Optional[str]:
83
+ """Execute an HTTP request and return the response text."""
84
+ url = build_url(url, params)
85
+ fingerprint = request_hash(url, auth=auth, method=method, data=data)
86
+
87
+ if cache is not None and cache_days is not None:
88
+ text = cache.get(fingerprint, max_age=cache_days)
89
+ if text is not None:
90
+ log.debug("HTTP cache hit: %s", url)
91
+ return text
92
+ if text is None and sleep is not None and sleep > 0:
93
+ time.sleep(sleep)
94
+
95
+ log.debug("HTTP %s: %s", method, url)
96
+ requester = session.request if session is not None else requests.request
97
+ response = requester(
98
+ method=method,
99
+ url=url,
100
+ headers=headers,
101
+ auth=auth,
102
+ data=data,
103
+ timeout=timeout,
104
+ verify=verify,
105
+ )
106
+ response.raise_for_status()
107
+ text = response.text
108
+
109
+ if cache is not None and cache_days is not None and text is not None:
110
+ cache.set(fingerprint, text)
111
+
112
+ return text
113
+
114
+
115
+ def fetch_json(
116
+ url: str,
117
+ params: Optional[dict[str, Any]] = None,
118
+ headers: Optional[dict[str, str]] = None,
119
+ session: Optional[requests.Session] = None,
120
+ auth: Optional[Any] = None,
121
+ method: str = "GET",
122
+ data: Optional[Any] = None,
123
+ cache: Optional["Cache"] = None,
124
+ cache_days: Optional[int] = None,
125
+ sleep: Optional[float] = None,
126
+ verify: bool = True,
127
+ timeout: float = 120,
128
+ ) -> Any:
129
+ """Execute an HTTP request and return a JSON-decoded object."""
130
+ text = fetch_text(
131
+ url,
132
+ params=params,
133
+ headers=headers,
134
+ session=session,
135
+ auth=auth,
136
+ method=method,
137
+ data=data,
138
+ cache=cache,
139
+ cache_days=cache_days,
140
+ sleep=sleep,
141
+ verify=verify,
142
+ timeout=timeout,
143
+ )
144
+ if text is not None and len(text.strip()):
145
+ return json.loads(text)
146
+ return None
147
+
148
+
149
+ def fetch_html(
150
+ url: str,
151
+ params: Optional[dict[str, Any]] = None,
152
+ headers: Optional[dict[str, str]] = None,
153
+ session: Optional[requests.Session] = None,
154
+ auth: Optional[Any] = None,
155
+ method: str = "GET",
156
+ data: Optional[Any] = None,
157
+ absolute_links: bool = False,
158
+ cache: Optional["Cache"] = None,
159
+ cache_days: Optional[int] = None,
160
+ sleep: Optional[float] = None,
161
+ verify: bool = True,
162
+ timeout: float = 120,
163
+ ) -> HtmlElement:
164
+ """Execute an HTTP request and return an lxml HTML element."""
165
+ full_url = build_url(url, params)
166
+ text = fetch_text(
167
+ url,
168
+ params=params,
169
+ headers=headers,
170
+ session=session,
171
+ auth=auth,
172
+ method=method,
173
+ data=data,
174
+ cache=cache,
175
+ cache_days=cache_days,
176
+ sleep=sleep,
177
+ verify=verify,
178
+ timeout=timeout,
179
+ )
180
+ if text is None or len(text.strip()) == 0:
181
+ raise ValueError(f"Invalid HTML document from {url}")
182
+
183
+ doc = html.fromstring(text)
184
+ if absolute_links and isinstance(doc, html.HtmlElement):
185
+ doc.make_links_absolute(full_url)
186
+ return doc