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/crawl.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import logging
|
|
3
|
+
import shutil
|
|
4
|
+
import sys
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Dict, Optional
|
|
8
|
+
from followthemoney.statement.serialize import PackStatementWriter
|
|
9
|
+
|
|
10
|
+
from muckrake.dataset import Dataset, get_dataset_path, load_config, resolve_dataset_root
|
|
11
|
+
from muckrake.artifacts import get_artifact_store
|
|
12
|
+
from muckrake.runs import (
|
|
13
|
+
config_version,
|
|
14
|
+
create_dataset_run,
|
|
15
|
+
detect_code_version,
|
|
16
|
+
finish_dataset_run,
|
|
17
|
+
get_latest_successful_artifact,
|
|
18
|
+
make_storage_prefix,
|
|
19
|
+
record_dataset_run_artifact,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load_timestamps(path: Path) -> Dict[str, str]:
|
|
26
|
+
"""Load previous first_seen timestamps from a pack file."""
|
|
27
|
+
timestamps = {}
|
|
28
|
+
if path.exists() and path.is_file() and path.stat().st_size > 0:
|
|
29
|
+
log.info(f"Loading previous state from {path}...")
|
|
30
|
+
try:
|
|
31
|
+
with open(path, "rb") as fh:
|
|
32
|
+
from followthemoney.statement.serialize import read_pack_statements
|
|
33
|
+
for stmt in read_pack_statements(fh):
|
|
34
|
+
if stmt.id is not None and stmt.first_seen is not None:
|
|
35
|
+
timestamps[stmt.id] = stmt.first_seen
|
|
36
|
+
except Exception as e:
|
|
37
|
+
log.warning(f"Failed to load previous state: {e}")
|
|
38
|
+
return timestamps
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def execute_crawler(config_path: Path, ds: Dataset):
|
|
42
|
+
"""Dynamically load and run the crawler script for a dataset."""
|
|
43
|
+
crawler_path = config_path.parent.resolve() / "crawler.py"
|
|
44
|
+
if not crawler_path.exists():
|
|
45
|
+
raise RuntimeError(f"crawler.py not found at {crawler_path}")
|
|
46
|
+
|
|
47
|
+
# Build a virtual package hierarchy so relative imports inside dataset code keep working
|
|
48
|
+
datasets_root = resolve_dataset_root(config_path)
|
|
49
|
+
parts = ["muckrake", "crawler"]
|
|
50
|
+
try:
|
|
51
|
+
if datasets_root is None:
|
|
52
|
+
raise ValueError("Dataset root could not be resolved")
|
|
53
|
+
rel_path = crawler_path.parent.relative_to(datasets_root)
|
|
54
|
+
if rel_path.parts:
|
|
55
|
+
parts.extend(rel_path.parts)
|
|
56
|
+
else:
|
|
57
|
+
parts.append(ds.name)
|
|
58
|
+
except ValueError:
|
|
59
|
+
parts.append(ds.name)
|
|
60
|
+
|
|
61
|
+
import types
|
|
62
|
+
|
|
63
|
+
# Initialize all parent packages to ensure relative imports work.
|
|
64
|
+
# We walk down the hierarchy and create virtual modules for each level.
|
|
65
|
+
for i in range(1, len(parts) + 1):
|
|
66
|
+
pkg_name = ".".join(parts[:i])
|
|
67
|
+
if pkg_name not in sys.modules:
|
|
68
|
+
mod = types.ModuleType(pkg_name)
|
|
69
|
+
if i >= 2: # muckrake.crawler and below
|
|
70
|
+
# Map this virtual package to the corresponding filesystem directory
|
|
71
|
+
rel_parts = parts[2:i]
|
|
72
|
+
if datasets_root is not None:
|
|
73
|
+
fs_path = datasets_root.joinpath(*rel_parts)
|
|
74
|
+
else:
|
|
75
|
+
fs_path = crawler_path.parent
|
|
76
|
+
if fs_path.exists():
|
|
77
|
+
mod.__path__ = [str(fs_path)]
|
|
78
|
+
|
|
79
|
+
# For packages, __package__ should be the name of the package itself.
|
|
80
|
+
mod.__package__ = pkg_name
|
|
81
|
+
sys.modules[pkg_name] = mod
|
|
82
|
+
|
|
83
|
+
# The actual crawler module is a submodule of the final package
|
|
84
|
+
pkg_name = ".".join(parts)
|
|
85
|
+
module_name = f"{pkg_name}.crawler"
|
|
86
|
+
spec = importlib.util.spec_from_file_location(module_name, str(crawler_path))
|
|
87
|
+
if spec is None or spec.loader is None:
|
|
88
|
+
raise RuntimeError(f"Could not load crawler from {crawler_path}")
|
|
89
|
+
|
|
90
|
+
crawler_module = importlib.util.module_from_spec(spec)
|
|
91
|
+
# Ensure the module knows its package for relative imports
|
|
92
|
+
crawler_module.__package__ = pkg_name
|
|
93
|
+
sys.modules[module_name] = crawler_module
|
|
94
|
+
spec.loader.exec_module(crawler_module)
|
|
95
|
+
|
|
96
|
+
if not hasattr(crawler_module, "crawl"):
|
|
97
|
+
raise RuntimeError(f"crawler.py in {ds.name} must define a 'crawl' function")
|
|
98
|
+
|
|
99
|
+
crawler_module.crawl(ds)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def run_crawl(config_path: Path, output: Optional[str] = None):
|
|
103
|
+
"""Helper to run a single crawl."""
|
|
104
|
+
ds_config = load_config(config_path)
|
|
105
|
+
dataset_name = ds_config.name
|
|
106
|
+
|
|
107
|
+
if output:
|
|
108
|
+
output_path = Path(output)
|
|
109
|
+
else:
|
|
110
|
+
output_path = get_dataset_path(dataset_name) / "statements.pack.csv"
|
|
111
|
+
|
|
112
|
+
previous_artifact = get_latest_successful_artifact(dataset_name)
|
|
113
|
+
previous_path = (
|
|
114
|
+
get_artifact_store().resolve_path(previous_artifact.storage_key)
|
|
115
|
+
if previous_artifact is not None
|
|
116
|
+
else output_path
|
|
117
|
+
)
|
|
118
|
+
timestamps = load_timestamps(previous_path)
|
|
119
|
+
|
|
120
|
+
dataset_run = create_dataset_run(
|
|
121
|
+
dataset_name=dataset_name,
|
|
122
|
+
run_type="crawl",
|
|
123
|
+
triggered_by="muckrake/crawl",
|
|
124
|
+
code_version=detect_code_version(),
|
|
125
|
+
config_version_value=config_version(config_path),
|
|
126
|
+
)
|
|
127
|
+
store = get_artifact_store()
|
|
128
|
+
storage_prefix = make_storage_prefix(dataset_name, dataset_run.id)
|
|
129
|
+
|
|
130
|
+
if output_path.as_posix() == "-":
|
|
131
|
+
writer = PackStatementWriter(sys.stdout)
|
|
132
|
+
temp_output_path = None
|
|
133
|
+
else:
|
|
134
|
+
temp_dir = Path(tempfile.mkdtemp(prefix=f"muckrake-crawl-{dataset_name}-"))
|
|
135
|
+
temp_output_path = temp_dir / "statements.pack.csv"
|
|
136
|
+
writer = PackStatementWriter(open(temp_output_path, "w"))
|
|
137
|
+
|
|
138
|
+
ds: Dataset | None = None
|
|
139
|
+
try:
|
|
140
|
+
ds = Dataset(config_path, writer, timestamps=timestamps)
|
|
141
|
+
execute_crawler(config_path, ds)
|
|
142
|
+
except Exception as exc:
|
|
143
|
+
finish_dataset_run(dataset_run.id, "failed", error_message=str(exc))
|
|
144
|
+
raise
|
|
145
|
+
finally:
|
|
146
|
+
if ds is not None:
|
|
147
|
+
ds.close()
|
|
148
|
+
writer.close()
|
|
149
|
+
|
|
150
|
+
if output_path.as_posix() == "-":
|
|
151
|
+
finish_dataset_run(dataset_run.id, "succeeded")
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
stored_pack = store.put_file(
|
|
156
|
+
temp_output_path,
|
|
157
|
+
f"{storage_prefix}/statements.pack.csv",
|
|
158
|
+
)
|
|
159
|
+
record_dataset_run_artifact(
|
|
160
|
+
dataset_run.id,
|
|
161
|
+
artifact_type="statements_pack",
|
|
162
|
+
storage_backend=stored_pack.storage_backend,
|
|
163
|
+
storage_key=stored_pack.storage_key,
|
|
164
|
+
content_type="text/csv",
|
|
165
|
+
sha256=stored_pack.sha256,
|
|
166
|
+
size_bytes=stored_pack.size_bytes,
|
|
167
|
+
metadata={"dataset_name": dataset_name},
|
|
168
|
+
)
|
|
169
|
+
manifest = {
|
|
170
|
+
"dataset_name": dataset_name,
|
|
171
|
+
"run_id": dataset_run.id,
|
|
172
|
+
"run_type": "crawl",
|
|
173
|
+
"status": "succeeded",
|
|
174
|
+
"code_version": dataset_run.code_version,
|
|
175
|
+
"config_version": dataset_run.config_version,
|
|
176
|
+
"artifacts": [
|
|
177
|
+
{
|
|
178
|
+
"artifact_type": "statements_pack",
|
|
179
|
+
"storage_backend": stored_pack.storage_backend,
|
|
180
|
+
"storage_key": stored_pack.storage_key,
|
|
181
|
+
"sha256": stored_pack.sha256,
|
|
182
|
+
"size_bytes": stored_pack.size_bytes,
|
|
183
|
+
}
|
|
184
|
+
],
|
|
185
|
+
}
|
|
186
|
+
stored_manifest = store.put_json(manifest, f"{storage_prefix}/manifest.json")
|
|
187
|
+
record_dataset_run_artifact(
|
|
188
|
+
dataset_run.id,
|
|
189
|
+
artifact_type="manifest",
|
|
190
|
+
storage_backend=stored_manifest.storage_backend,
|
|
191
|
+
storage_key=stored_manifest.storage_key,
|
|
192
|
+
content_type="application/json",
|
|
193
|
+
sha256=stored_manifest.sha256,
|
|
194
|
+
size_bytes=stored_manifest.size_bytes,
|
|
195
|
+
metadata={"dataset_name": dataset_name},
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
199
|
+
shutil.copy2(temp_output_path, output_path)
|
|
200
|
+
finish_dataset_run(
|
|
201
|
+
dataset_run.id,
|
|
202
|
+
"succeeded",
|
|
203
|
+
stats={
|
|
204
|
+
"output_path": output_path.as_posix(),
|
|
205
|
+
"statements_artifact_key": stored_pack.storage_key,
|
|
206
|
+
"manifest_artifact_key": stored_manifest.storage_key,
|
|
207
|
+
"previous_artifact_key": (
|
|
208
|
+
previous_artifact.storage_key if previous_artifact is not None else None
|
|
209
|
+
),
|
|
210
|
+
},
|
|
211
|
+
)
|
|
212
|
+
except Exception as exc:
|
|
213
|
+
finish_dataset_run(dataset_run.id, "failed", error_message=str(exc))
|
|
214
|
+
raise
|
|
215
|
+
finally:
|
|
216
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
217
|
+
|
|
218
|
+
log.info(
|
|
219
|
+
"Crawl complete: %s -> %s (run_id=%s)",
|
|
220
|
+
dataset_name,
|
|
221
|
+
output_path,
|
|
222
|
+
dataset_run.id,
|
|
223
|
+
)
|
muckrake/dataset.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import shutil
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict, Optional, List
|
|
7
|
+
from lxml.html import HtmlElement
|
|
8
|
+
from datapatch import get_lookups, Lookup
|
|
9
|
+
from followthemoney import Dataset as FTMDataset
|
|
10
|
+
from followthemoney.statement.entity import StatementEntity
|
|
11
|
+
from nomenklatura.cache import Cache
|
|
12
|
+
from nomenklatura.db import get_engine, get_metadata
|
|
13
|
+
|
|
14
|
+
from org_id import make_hashed_id, make_org_id
|
|
15
|
+
|
|
16
|
+
from muckrake.extract.fetch import fetch_file, fetch_json, fetch_html, fetch_text
|
|
17
|
+
from muckrake.settings import BASE_PATH, DATA_PATH, SQL_URI
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_raw_config(path: Path) -> Dict[str, Any]:
|
|
21
|
+
import yaml
|
|
22
|
+
|
|
23
|
+
with path.open("r") as fh:
|
|
24
|
+
return yaml.safe_load(fh) or {}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_dataset_config(data: Dict[str, Any]) -> Dict[str, Any]:
|
|
28
|
+
return data.get("dataset", data)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_dataset_path(name: str) -> Path:
|
|
32
|
+
return DATA_PATH / "datasets" / name
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def list_dataset_roots() -> List[Path]:
|
|
36
|
+
roots: list[Path] = []
|
|
37
|
+
|
|
38
|
+
def add_root(path: Path) -> None:
|
|
39
|
+
resolved = path.expanduser().resolve()
|
|
40
|
+
if resolved in roots or not resolved.is_dir():
|
|
41
|
+
return
|
|
42
|
+
roots.append(resolved)
|
|
43
|
+
|
|
44
|
+
raw_paths = os.getenv("MUCKRAKE_DATASET_PATHS")
|
|
45
|
+
if raw_paths:
|
|
46
|
+
for raw_path in raw_paths.split(os.pathsep):
|
|
47
|
+
raw_path = raw_path.strip()
|
|
48
|
+
if raw_path:
|
|
49
|
+
add_root(Path(raw_path))
|
|
50
|
+
|
|
51
|
+
add_root(Path.cwd() / "datasets")
|
|
52
|
+
return roots
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def resolve_dataset_root(config_path: Path) -> Path | None:
|
|
56
|
+
resolved_config = config_path.resolve()
|
|
57
|
+
|
|
58
|
+
for root in list_dataset_roots():
|
|
59
|
+
try:
|
|
60
|
+
resolved_config.relative_to(root)
|
|
61
|
+
return root
|
|
62
|
+
except ValueError:
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
for parent in resolved_config.parents:
|
|
66
|
+
if parent.name == "datasets":
|
|
67
|
+
return parent
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def clear_dataset(name: str):
|
|
72
|
+
"""Delete all data associated with a dataset."""
|
|
73
|
+
path = get_dataset_path(name)
|
|
74
|
+
if path.exists():
|
|
75
|
+
logging.getLogger(__name__).info(f"Clearing dataset data: {name}")
|
|
76
|
+
shutil.rmtree(path)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_config(path: Path) -> FTMDataset:
|
|
80
|
+
"""Load a dataset configuration from a file path."""
|
|
81
|
+
return FTMDataset.make(get_dataset_config(load_raw_config(path)))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Dataset:
|
|
85
|
+
"""A runner context for a specific data source."""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
config_path: Path,
|
|
90
|
+
writer: Any,
|
|
91
|
+
timestamps: Optional[Dict[str, str]] = None,
|
|
92
|
+
):
|
|
93
|
+
self._data = load_raw_config(config_path)
|
|
94
|
+
config = get_dataset_config(self._data)
|
|
95
|
+
self.ftm = FTMDataset.make(config)
|
|
96
|
+
self.name = self.ftm.name
|
|
97
|
+
self.prefix = config.get("prefix", self.name)
|
|
98
|
+
|
|
99
|
+
self.writer = writer
|
|
100
|
+
self.timestamps = timestamps or {}
|
|
101
|
+
self.run_time = datetime.utcnow().isoformat()
|
|
102
|
+
|
|
103
|
+
# Standardize where resources are kept
|
|
104
|
+
self.data_path = get_dataset_path(self.name)
|
|
105
|
+
self.resources_path = self.data_path / "resources"
|
|
106
|
+
self.log = logging.getLogger(self.name)
|
|
107
|
+
self._cache: Optional[Cache] = None
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def cache(self) -> Cache:
|
|
111
|
+
if self._cache is None:
|
|
112
|
+
self._cache = Cache(
|
|
113
|
+
get_engine(SQL_URI), get_metadata(), self.ftm, create=True
|
|
114
|
+
)
|
|
115
|
+
return self._cache
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def lookups(self) -> Dict[str, Lookup]:
|
|
119
|
+
"""Load datapatch lookups from config (cached after first access)."""
|
|
120
|
+
if not hasattr(self, "_lookups_cache"):
|
|
121
|
+
config = self._data.get("lookups", {})
|
|
122
|
+
self._lookups_cache: Dict[str, Lookup] = get_lookups(config)
|
|
123
|
+
return self._lookups_cache
|
|
124
|
+
|
|
125
|
+
def lookup(self, lookup_name: str, value: Any):
|
|
126
|
+
"""Convenience method to apply a lookup, returning the result object or None."""
|
|
127
|
+
if lookup_name not in self.lookups:
|
|
128
|
+
return None
|
|
129
|
+
return self.lookups[lookup_name].match(value)
|
|
130
|
+
|
|
131
|
+
def make(self, schema: str) -> StatementEntity:
|
|
132
|
+
"""Create an entity tied to this dataset."""
|
|
133
|
+
return StatementEntity(self.ftm, {"schema": schema})
|
|
134
|
+
|
|
135
|
+
def make_id(
|
|
136
|
+
self, *parts: Any, reg_nr: Optional[Any] = None, register: Optional[str] = None
|
|
137
|
+
) -> str:
|
|
138
|
+
"""Create a stable ID, preferring a structured org-id if reg_nr is provided."""
|
|
139
|
+
if reg_nr:
|
|
140
|
+
if not register:
|
|
141
|
+
raise ValueError(
|
|
142
|
+
"Mapping an org-id requires a 'register' (e.g. 'GB-COH')"
|
|
143
|
+
)
|
|
144
|
+
org_id = make_org_id(reg_nr, register=register)
|
|
145
|
+
if org_id:
|
|
146
|
+
return org_id
|
|
147
|
+
|
|
148
|
+
return make_hashed_id(self.prefix, *parts)
|
|
149
|
+
|
|
150
|
+
def emit(self, entity: StatementEntity):
|
|
151
|
+
"""Write entity statements to the output stream with timestamps."""
|
|
152
|
+
for stmt in entity.statements:
|
|
153
|
+
stmt_id = stmt.id
|
|
154
|
+
if stmt_id:
|
|
155
|
+
stmt.first_seen = self.timestamps.get(stmt_id, self.run_time)
|
|
156
|
+
else:
|
|
157
|
+
stmt.first_seen = self.run_time
|
|
158
|
+
stmt.last_seen = self.run_time
|
|
159
|
+
self.writer.write(stmt)
|
|
160
|
+
|
|
161
|
+
def fetch_resource(self, name: str, url: str, **kwargs: Any):
|
|
162
|
+
"""Standard file downloader for datasets."""
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
return fetch_file(url, name, data_path=self.resources_path, **kwargs)
|
|
166
|
+
except Exception as e:
|
|
167
|
+
self.log.error(f"Failed to fetch resource {url}: {e}")
|
|
168
|
+
raise
|
|
169
|
+
|
|
170
|
+
def fetch_text(
|
|
171
|
+
self, url: str, cache_days: Optional[int] = None, **kwargs: Any
|
|
172
|
+
) -> Optional[str]:
|
|
173
|
+
"""Fetch text from a URL, optionally cached."""
|
|
174
|
+
return fetch_text(url, cache=self.cache, cache_days=cache_days, **kwargs)
|
|
175
|
+
|
|
176
|
+
def fetch_json(
|
|
177
|
+
self, url: str, cache_days: Optional[int] = None, **kwargs: Any
|
|
178
|
+
) -> Any:
|
|
179
|
+
"""Fetch JSON from a URL, optionally cached."""
|
|
180
|
+
return fetch_json(url, cache=self.cache, cache_days=cache_days, **kwargs)
|
|
181
|
+
|
|
182
|
+
def fetch_html(
|
|
183
|
+
self, url: str, cache_days: Optional[int] = None, **kwargs: Any
|
|
184
|
+
) -> HtmlElement:
|
|
185
|
+
"""Fetch HTML from a URL, optionally cached."""
|
|
186
|
+
return fetch_html(url, cache=self.cache, cache_days=cache_days, **kwargs)
|
|
187
|
+
|
|
188
|
+
def close(self) -> None:
|
|
189
|
+
"""Close the dataset and persist any cached data."""
|
|
190
|
+
if self._cache is not None:
|
|
191
|
+
self._cache.close()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def find_datasets(name: Optional[str] = None) -> List[Path]:
|
|
195
|
+
"""Find dataset config files across configured dataset roots.
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
name: Dataset name as defined in config (e.g., 'gb_political_finance').
|
|
199
|
+
If None, finds all datasets recursively.
|
|
200
|
+
"""
|
|
201
|
+
configs: list[Path] = []
|
|
202
|
+
for datasets_root in list_dataset_roots():
|
|
203
|
+
for ext in ["yml", "yaml"]:
|
|
204
|
+
configs.extend(datasets_root.glob(f"**/config.{ext}"))
|
|
205
|
+
|
|
206
|
+
if name:
|
|
207
|
+
# Search through all configs to find the one with matching name
|
|
208
|
+
for config in configs:
|
|
209
|
+
try:
|
|
210
|
+
ds = load_config(config)
|
|
211
|
+
if ds.name == name:
|
|
212
|
+
return [config]
|
|
213
|
+
except Exception as e:
|
|
214
|
+
logging.getLogger(__name__).warning(
|
|
215
|
+
f"Failed to load config {config}: {e}"
|
|
216
|
+
)
|
|
217
|
+
continue
|
|
218
|
+
return []
|
|
219
|
+
|
|
220
|
+
unique_configs = sorted({config.resolve() for config in configs})
|
|
221
|
+
return unique_configs
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def list_datasets() -> List[FTMDataset]:
|
|
225
|
+
"""Load all dataset configurations."""
|
|
226
|
+
return [load_config(p) for p in find_datasets()]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def list_dataset_names() -> List[str]:
|
|
230
|
+
"""Get names of all datasets."""
|
|
231
|
+
return [ds.name for ds in list_datasets()]
|