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
muckrake/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ import importlib.util
2
+ import os
3
+ import shutil
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+
8
+ def _iter_extension_dirs() -> list[Path]:
9
+ dirs: list[Path] = []
10
+
11
+ raw_paths = os.getenv("MUCKRAKE_FTM_SCHEMA_PATHS")
12
+ if raw_paths:
13
+ for raw_path in raw_paths.split(os.pathsep):
14
+ raw_path = raw_path.strip()
15
+ if not raw_path:
16
+ continue
17
+ path = Path(raw_path).expanduser().resolve()
18
+ if path.is_dir() and path not in dirs:
19
+ dirs.append(path)
20
+
21
+ cwd_dir = (Path.cwd() / "ftm_schema_ext").resolve()
22
+ if cwd_dir.is_dir() and cwd_dir not in dirs:
23
+ dirs.append(cwd_dir)
24
+
25
+ return dirs
26
+
27
+
28
+ def _find_followthemoney_schema_dir() -> Path | None:
29
+ spec = importlib.util.find_spec("followthemoney")
30
+ if spec is None or spec.origin is None:
31
+ return None
32
+ schema_dir = Path(spec.origin).resolve().parent / "schema"
33
+ if not schema_dir.is_dir():
34
+ return None
35
+ return schema_dir
36
+
37
+
38
+ def _configure_ftm_model_path() -> None:
39
+ if os.getenv("FTM_MODEL_PATH"):
40
+ return
41
+
42
+ schema_dir = _find_followthemoney_schema_dir()
43
+ extension_dirs = _iter_extension_dirs()
44
+ if schema_dir is None or not extension_dirs:
45
+ return
46
+
47
+ merged_dir = Path(tempfile.mkdtemp(prefix="muckrake-ftm-model-"))
48
+ shutil.copytree(schema_dir, merged_dir, dirs_exist_ok=True)
49
+ for extension_dir in extension_dirs:
50
+ for pattern in ("*.yaml", "*.yml"):
51
+ for extension in sorted(extension_dir.glob(pattern)):
52
+ shutil.copy2(extension, merged_dir / extension.name)
53
+
54
+ os.environ["FTM_MODEL_PATH"] = str(merged_dir)
55
+
56
+
57
+ _configure_ftm_model_path()
58
+
59
+
60
+ def hello() -> str:
61
+ return "Hello from muckrake!"
muckrake/artifacts.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import shutil
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from muckrake.settings import ARTIFACT_PATH
11
+
12
+
13
+ @dataclass
14
+ class StoredArtifact:
15
+ storage_backend: str
16
+ storage_key: str
17
+ absolute_path: Path
18
+ sha256: str
19
+ size_bytes: int
20
+
21
+
22
+ class LocalArtifactStore:
23
+ storage_backend = "local"
24
+
25
+ def __init__(self, root: Path = ARTIFACT_PATH):
26
+ self.root = root
27
+
28
+ def resolve_path(self, storage_key: str) -> Path:
29
+ return self.root / storage_key
30
+
31
+ def exists(self, storage_key: str) -> bool:
32
+ return self.resolve_path(storage_key).exists()
33
+
34
+ def put_file(self, source_path: Path, storage_key: str) -> StoredArtifact:
35
+ target_path = self.resolve_path(storage_key)
36
+ target_path.parent.mkdir(parents=True, exist_ok=True)
37
+ shutil.copy2(source_path, target_path)
38
+ return StoredArtifact(
39
+ storage_backend=self.storage_backend,
40
+ storage_key=storage_key,
41
+ absolute_path=target_path,
42
+ sha256=file_sha256(target_path),
43
+ size_bytes=target_path.stat().st_size,
44
+ )
45
+
46
+ def put_bytes(self, data: bytes, storage_key: str) -> StoredArtifact:
47
+ target_path = self.resolve_path(storage_key)
48
+ target_path.parent.mkdir(parents=True, exist_ok=True)
49
+ target_path.write_bytes(data)
50
+ return StoredArtifact(
51
+ storage_backend=self.storage_backend,
52
+ storage_key=storage_key,
53
+ absolute_path=target_path,
54
+ sha256=file_sha256(target_path),
55
+ size_bytes=target_path.stat().st_size,
56
+ )
57
+
58
+ def put_json(self, payload: dict[str, Any], storage_key: str) -> StoredArtifact:
59
+ data = json.dumps(payload, indent=2, sort_keys=True).encode("utf-8")
60
+ return self.put_bytes(data, storage_key)
61
+
62
+
63
+ def file_sha256(path: Path) -> str:
64
+ digest = hashlib.sha256()
65
+ with path.open("rb") as fh:
66
+ for chunk in iter(lambda: fh.read(1024 * 1024), b""):
67
+ digest.update(chunk)
68
+ return digest.hexdigest()
69
+
70
+
71
+ def get_artifact_store() -> LocalArtifactStore:
72
+ return LocalArtifactStore()
muckrake/cli.py ADDED
@@ -0,0 +1,522 @@
1
+ import logging
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import click
7
+ from nomenklatura.matching import DefaultAlgorithm
8
+ from muckrake.logging import configure_logging
9
+ from muckrake.dataset import find_datasets, load_config, clear_dataset, list_datasets
10
+ from muckrake.crawl import run_crawl
11
+ from muckrake.dedupe import (
12
+ run_xref,
13
+ run_dedupe,
14
+ run_dedupe_explode,
15
+ run_merge,
16
+ run_prune,
17
+ run_dedupe_edges,
18
+ )
19
+ from muckrake.extract.ner import run_ner_extract, run_ner_review
20
+ from muckrake.extract.ner.engines import list_extractors
21
+ from muckrake.entity_query import (
22
+ get_entity_payload,
23
+ normalize_schema_filter,
24
+ search_entity_payload,
25
+ )
26
+ from muckrake.entity_write import add_entity as run_add_entity
27
+ from muckrake.entity_write import build_entity_spec
28
+ from muckrake.entity_write import update_entity as run_update_entity
29
+ from muckrake.load import run_load
30
+ from muckrake.release import list_releases, run_release_build, run_release_publish
31
+ from muckrake.settings import get_working_sql_uri
32
+
33
+ log = logging.getLogger("muckrake")
34
+
35
+
36
+ def _logging_level(verbose: int) -> int:
37
+ if verbose <= 0:
38
+ return logging.WARNING
39
+ if verbose == 1:
40
+ return logging.INFO
41
+ return logging.DEBUG
42
+
43
+
44
+ class MuckrakeGroup(click.Group):
45
+ COMMAND_GROUPS = [
46
+ ("List all available datasets", ["list"]),
47
+ ("Crawl and extract", ["crawl"]),
48
+ ("Named-entity recognition", ["ner-extract", "ner-review"]),
49
+ (
50
+ "Deduplicate",
51
+ [
52
+ "xref",
53
+ "xref-prune",
54
+ "dedupe",
55
+ "dedupe-manual",
56
+ "dedupe-explode",
57
+ "dedupe-edges",
58
+ ],
59
+ ),
60
+ ("Build releases", ["release-build", "release-list", "release-publish"]),
61
+ ("Load to database", ["load", "export"]),
62
+ ("Inspect and edit entities", ["add", "get", "search", "update"]),
63
+ ]
64
+
65
+ def list_commands(self, ctx):
66
+ ordered = []
67
+ seen = set()
68
+ for _, commands in self.COMMAND_GROUPS:
69
+ for command in commands:
70
+ if command in self.commands and command not in seen:
71
+ ordered.append(command)
72
+ seen.add(command)
73
+
74
+ for command in sorted(self.commands):
75
+ if command not in seen:
76
+ ordered.append(command)
77
+
78
+ return ordered
79
+
80
+ def format_commands(self, ctx, formatter):
81
+ seen = set()
82
+ for heading, commands in self.COMMAND_GROUPS:
83
+ rows = []
84
+ for command in commands:
85
+ cmd = self.get_command(ctx, command)
86
+ if cmd is None or cmd.hidden:
87
+ continue
88
+ rows.append((command, cmd.get_short_help_str(formatter.width)))
89
+ seen.add(command)
90
+
91
+ if rows:
92
+ with formatter.section(heading):
93
+ formatter.write_dl(rows)
94
+
95
+ other_rows = []
96
+ for command in sorted(self.commands):
97
+ if command in seen:
98
+ continue
99
+ cmd = self.get_command(ctx, command)
100
+ if cmd is None or cmd.hidden:
101
+ continue
102
+ other_rows.append((command, cmd.get_short_help_str(formatter.width)))
103
+
104
+ if other_rows:
105
+ with formatter.section("Other commands"):
106
+ formatter.write_dl(other_rows)
107
+
108
+
109
+ @click.group(cls=MuckrakeGroup)
110
+ @click.option(
111
+ "--verbose",
112
+ "-v",
113
+ count=True,
114
+ help="Increase logging verbosity. Repeat for debug output.",
115
+ )
116
+ def cli(verbose):
117
+ """Muckrake: A minimal FtM data processing framework."""
118
+ configure_logging(level=_logging_level(verbose))
119
+
120
+
121
+ @cli.command()
122
+ @click.argument("dataset_name", required=False)
123
+ @click.option("--output", "-o", type=click.Path(), help="Override output path")
124
+ @click.option(
125
+ "--clear",
126
+ "-c",
127
+ is_flag=True,
128
+ default=False,
129
+ help="Clear dataset data before crawling",
130
+ )
131
+ def crawl(dataset_name, output, clear):
132
+ """Crawl one or all datasets.
133
+
134
+ DATASET_NAME should be the dataset name from config.yml (e.g., gb_political_finance).
135
+ If not provided, crawls all datasets.
136
+ """
137
+ configs = find_datasets(dataset_name)
138
+
139
+ if dataset_name and not configs:
140
+ click.echo(f"Error: Dataset '{dataset_name}' not found", err=True)
141
+ click.echo("\nAvailable datasets:", err=True)
142
+ for ds in list_datasets():
143
+ click.echo(f" - {ds.name}", err=True)
144
+ sys.exit(1)
145
+
146
+ for config in configs:
147
+ ds = load_config(config)
148
+ quiet_loggers = {}
149
+ if ds.name == "meetings":
150
+ for logger_name in (
151
+ "muckrake.dataset",
152
+ "muckrake.crawl",
153
+ "muckrake.extract.fetch",
154
+ ):
155
+ logger = logging.getLogger(logger_name)
156
+ quiet_loggers[logger_name] = logger.level
157
+ logger.setLevel(logging.WARNING)
158
+
159
+ try:
160
+ if clear:
161
+ clear_dataset(ds.name)
162
+ run_crawl(config, output)
163
+ finally:
164
+ for logger_name, level in quiet_loggers.items():
165
+ logging.getLogger(logger_name).setLevel(level)
166
+
167
+
168
+ @cli.command("list")
169
+ def list_cmd():
170
+ """List all available datasets."""
171
+ datasets = list_datasets()
172
+ if not datasets:
173
+ click.echo("No datasets found")
174
+ return
175
+
176
+ click.echo("Available datasets:")
177
+ for ds in datasets:
178
+ title = ds.to_dict().get("title", "")
179
+ click.echo(f" {ds.name:<30} {title}")
180
+
181
+
182
+ def _emit_json(payload, pretty: bool) -> None:
183
+ if pretty:
184
+ click.echo(json.dumps(payload, indent=2, sort_keys=True))
185
+ else:
186
+ click.echo(json.dumps(payload, sort_keys=True))
187
+
188
+
189
+ def _working_uri() -> str:
190
+ return get_working_sql_uri()
191
+
192
+
193
+ @cli.command("add")
194
+ @click.option("--schema", "schema_name", required=True, help="FtM schema name")
195
+ @click.option("--dataset", required=True, help="Dataset name used for provenance")
196
+ @click.option("--source", "source_ref", required=True, help="Durable source reference")
197
+ @click.option("--id", "entity_id", help="Explicit FtM entity ID")
198
+ @click.option(
199
+ "--id-part",
200
+ "id_parts",
201
+ multiple=True,
202
+ help="Stable key component used to generate an ID. Repeat as needed.",
203
+ )
204
+ @click.option("--key-prefix", help="Optional FtM key prefix for generated IDs")
205
+ @click.option(
206
+ "--property",
207
+ "property_items",
208
+ multiple=True,
209
+ required=True,
210
+ help="Entity property in KEY=VALUE form. Repeat for more values.",
211
+ )
212
+ @click.option("--pretty", is_flag=True, default=False, help="Pretty-print JSON output")
213
+ def add_cmd(
214
+ schema_name,
215
+ dataset,
216
+ source_ref,
217
+ entity_id,
218
+ id_parts,
219
+ key_prefix,
220
+ property_items,
221
+ pretty,
222
+ ):
223
+ """Add or update one FtM entity in the working database."""
224
+ try:
225
+ spec = build_entity_spec(
226
+ schema_name=schema_name,
227
+ dataset=dataset,
228
+ source_ref=source_ref,
229
+ entity_id=entity_id,
230
+ id_parts=list(id_parts),
231
+ key_prefix=key_prefix,
232
+ property_items=list(property_items),
233
+ )
234
+ _emit_json(run_add_entity(spec, uri=_working_uri()), pretty)
235
+ except Exception as e:
236
+ log.exception(e)
237
+ sys.exit(1)
238
+
239
+
240
+ @cli.command("get")
241
+ @click.argument("entity_id", required=True)
242
+ @click.option("--pretty", is_flag=True, default=False, help="Pretty-print JSON output")
243
+ def get_cmd(entity_id, pretty):
244
+ """Get one FtM entity by canonical ID from the working database."""
245
+ try:
246
+ payload = get_entity_payload(entity_id, uri=_working_uri())
247
+ if payload is None:
248
+ raise ValueError(f"Entity not found: {entity_id}")
249
+ _emit_json({"status": "ok", "entity": payload}, pretty)
250
+ except Exception as e:
251
+ log.exception(e)
252
+ sys.exit(1)
253
+
254
+
255
+ @cli.command("search")
256
+ @click.argument("query", required=False, default="")
257
+ @click.option("--schema", "schemas", multiple=True, help="Filter by FtM schema")
258
+ @click.option("--limit", type=int, default=20, help="Maximum number of results")
259
+ @click.option("--offset", type=int, default=0, help="Result offset")
260
+ @click.option("--pretty", is_flag=True, default=False, help="Pretty-print JSON output")
261
+ def search_cmd(query, schemas, limit, offset, pretty):
262
+ """Search FtM entities in the working database."""
263
+ try:
264
+ limit = max(1, min(limit, 100))
265
+ offset = max(0, offset)
266
+ requested_schema = list(schemas) if schemas else []
267
+ applied_schema = normalize_schema_filter(requested_schema)
268
+ response = search_entity_payload(query.strip(), requested_schema, limit, offset, uri=_working_uri())
269
+ _emit_json(
270
+ {
271
+ "status": "ok",
272
+ "query": query,
273
+ "results": response.results,
274
+ "total": response.total,
275
+ "offset": response.offset,
276
+ "limit": response.limit,
277
+ "has_next": response.has_next,
278
+ "requested_schema": requested_schema,
279
+ "applied_schema": applied_schema,
280
+ },
281
+ pretty,
282
+ )
283
+ except Exception as e:
284
+ log.exception(e)
285
+ sys.exit(1)
286
+
287
+
288
+ @cli.command("update")
289
+ @click.argument("entity_id", required=True)
290
+ @click.option("--schema", "schema_name", help="Optional replacement FtM schema name")
291
+ @click.option("--dataset", help="Replacement dataset name used for rewritten provenance")
292
+ @click.option("--source", "source_ref", help="Replacement source reference for rewritten provenance")
293
+ @click.option(
294
+ "--property",
295
+ "property_items",
296
+ multiple=True,
297
+ required=True,
298
+ help="Entity property in KEY=VALUE form. Repeat for more values.",
299
+ )
300
+ @click.option("--pretty", is_flag=True, default=False, help="Pretty-print JSON output")
301
+ def update_cmd(entity_id, schema_name, dataset, source_ref, property_items, pretty):
302
+ """Update one FtM entity in the working database by ID."""
303
+ try:
304
+ _emit_json(
305
+ run_update_entity(
306
+ entity_id,
307
+ property_items=list(property_items),
308
+ dataset=dataset,
309
+ source_ref=source_ref,
310
+ schema_name=schema_name,
311
+ uri=_working_uri(),
312
+ ),
313
+ pretty,
314
+ )
315
+ except Exception as e:
316
+ log.exception(e)
317
+ sys.exit(1)
318
+
319
+
320
+ @cli.command()
321
+ @click.option(
322
+ "--output", "-o", type=click.Path(), required=True, help="Output file path"
323
+ )
324
+ @click.option("--dataset", "-d", help="Filter by dataset")
325
+ def export(output, dataset):
326
+ """Export entities to FtM JSON."""
327
+ try:
328
+ from muckrake.export import run_export_ftm
329
+
330
+ run_export_ftm(Path(output), dataset)
331
+ except Exception as e:
332
+ log.exception(e)
333
+ sys.exit(1)
334
+
335
+
336
+ @cli.command()
337
+ @click.option("--limit", "-l", type=int, default=50000, help="Candidate limit")
338
+ @click.option("--threshold", "-t", type=float, help="Auto-merge threshold")
339
+ @click.option("--algorithm", "-a", default=DefaultAlgorithm.NAME, help="Algorithm")
340
+ @click.option("--schema", "-s", help="Filter by schema")
341
+ @click.option("--focus-dataset", "-f", "focus_dataset", help="Focus on a dataset")
342
+ def xref(limit, threshold, algorithm, schema, focus_dataset):
343
+ """Generate deduplication candidates."""
344
+ try:
345
+ run_xref(
346
+ limit=limit,
347
+ threshold=threshold,
348
+ algorithm=algorithm,
349
+ schema=schema,
350
+ focus_dataset=focus_dataset,
351
+ )
352
+ except Exception as e:
353
+ log.exception(e)
354
+ sys.exit(1)
355
+
356
+
357
+ @cli.command()
358
+ def dedupe():
359
+ """Interactively judge candidates."""
360
+ try:
361
+ run_dedupe()
362
+ except Exception as e:
363
+ log.exception(e)
364
+ sys.exit(1)
365
+
366
+
367
+ @cli.command("dedupe-manual")
368
+ @click.argument("entity_ids", nargs=-1, required=True)
369
+ @click.option("--force", "-f", is_flag=True, default=False, help="Force merge")
370
+ def dedupe_manual(entity_ids, force):
371
+ """Manually merge entities as duplicates."""
372
+ try:
373
+ run_merge(entity_ids, force=force)
374
+ except ValueError as ve:
375
+ click.echo(f"Error: {ve}", err=True)
376
+ sys.exit(1)
377
+ except Exception as e:
378
+ log.exception(e)
379
+ sys.exit(1)
380
+
381
+
382
+ @cli.command("dedupe-explode")
383
+ @click.argument("entity_id", required=True)
384
+ def dedupe_explode(entity_id):
385
+ """Undo deduplication by exploding a merged cluster."""
386
+ try:
387
+ run_dedupe_explode(entity_id)
388
+ except Exception as e:
389
+ log.exception(e)
390
+ sys.exit(1)
391
+
392
+
393
+ @cli.command("xref-prune")
394
+ def xref_prune():
395
+ """Remove dedupe candidates from the resolver."""
396
+ try:
397
+ run_prune()
398
+ except Exception as e:
399
+ log.exception(e)
400
+ sys.exit(1)
401
+
402
+
403
+ @cli.command("dedupe-edges")
404
+ @click.argument("dataset_name", required=False)
405
+ @click.option(
406
+ "--max-gap-days",
407
+ type=int,
408
+ default=1,
409
+ show_default=True,
410
+ help="Maximum allowed gap days between adjacent edges",
411
+ )
412
+ @click.option("--dry-run", is_flag=True, default=False, help="Show changes only")
413
+ def dedupe_edges(dataset_name, max_gap_days, dry_run):
414
+ """Deduplicate Representation edges across datasets in resolver."""
415
+ try:
416
+ run_dedupe_edges(
417
+ dataset_name=dataset_name,
418
+ max_gap_days=max_gap_days,
419
+ dry_run=dry_run,
420
+ )
421
+ except Exception as e:
422
+ log.exception(e)
423
+ sys.exit(1)
424
+
425
+
426
+ @cli.command()
427
+ @click.argument("dataset_name", required=False)
428
+ @click.option("--run-id", type=int, help="Load statements from a specific dataset run")
429
+ def load(dataset_name, run_id):
430
+ """Load statements into the database.
431
+
432
+ DATASET_NAME should be the dataset name from config.yml (e.g., gb_political_finance).
433
+ If not provided, loads all datasets.
434
+ """
435
+ try:
436
+ run_load(dataset_name, run_id=run_id)
437
+ except Exception as e:
438
+ log.exception(e)
439
+ sys.exit(1)
440
+
441
+ @cli.command("ner-extract")
442
+ @click.argument("dataset_name", required=False)
443
+ @click.option("--limit", "limit", type=int, default=None, help="Max candidate rows")
444
+ @click.option("--entity-id", "entity_id", help="Extract only for one entity ID")
445
+ @click.option(
446
+ "--extractor",
447
+ "extractor_name",
448
+ type=click.Choice(list_extractors()),
449
+ default="llm",
450
+ show_default=True,
451
+ help="Extraction strategy",
452
+ )
453
+ def ner_extract(dataset_name, limit, entity_id, extractor_name):
454
+ """Extract named entities from statement text fields."""
455
+ try:
456
+ run_ner_extract(
457
+ dataset_name=dataset_name,
458
+ limit=limit,
459
+ entity_id=entity_id,
460
+ extractor_name=extractor_name,
461
+ )
462
+ except Exception as e:
463
+ log.exception(e)
464
+ sys.exit(1)
465
+
466
+
467
+ @cli.command("ner-review")
468
+ @click.argument("dataset_name", required=False)
469
+ @click.option("--limit", "limit", type=int, default=None, help="Max pending candidates")
470
+ def ner_review(dataset_name, limit):
471
+ """Review pending NER extraction candidates."""
472
+ try:
473
+ run_ner_review(dataset_name=dataset_name, limit=limit)
474
+ except Exception as e:
475
+ log.exception(e)
476
+ sys.exit(1)
477
+
478
+
479
+ @cli.command("release-build")
480
+ @click.argument("dataset_name", nargs=-1, required=False)
481
+ @click.option("--notes", help="Optional release notes")
482
+ def release_build(dataset_name, notes):
483
+ """Build an immutable release artifact from dataset runs."""
484
+ try:
485
+ release_id = run_release_build(dataset_name or None, notes=notes)
486
+ click.echo(f"Built release {release_id}")
487
+ except Exception as e:
488
+ log.exception(e)
489
+ sys.exit(1)
490
+
491
+
492
+ @cli.command("release-publish")
493
+ @click.argument("release_id", type=int)
494
+ def release_publish(release_id):
495
+ """Publish a built release into the read-only serving database."""
496
+ try:
497
+ run_release_publish(release_id)
498
+ except Exception as e:
499
+ log.exception(e)
500
+ sys.exit(1)
501
+
502
+
503
+ @cli.command("release-list")
504
+ @click.option("--limit", type=int, default=20, show_default=True, help="Max releases")
505
+ def release_list(limit):
506
+ """List recent releases and their statuses."""
507
+ try:
508
+ releases = list_releases(limit=limit)
509
+ if not releases:
510
+ click.echo("No releases found")
511
+ return
512
+ for release in releases:
513
+ click.echo(
514
+ f"{release.id}\t{release.status}\tcreated={release.created_at}\tpublished={release.published_at or '-'}"
515
+ )
516
+ except Exception as e:
517
+ log.exception(e)
518
+ sys.exit(1)
519
+
520
+
521
+ if __name__ == "__main__":
522
+ cli()