muckrake 0.2.1__tar.gz → 0.3.0__tar.gz

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 (53) hide show
  1. {muckrake-0.2.1 → muckrake-0.3.0}/PKG-INFO +17 -3
  2. {muckrake-0.2.1 → muckrake-0.3.0}/README.md +15 -1
  3. muckrake-0.3.0/pyproject.toml +84 -0
  4. muckrake-0.3.0/pyproject.toml.orig +79 -0
  5. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/artifacts.py +13 -14
  6. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/cli.py +72 -18
  7. muckrake-0.3.0/src/muckrake/crawl.py +311 -0
  8. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dataset.py +79 -37
  9. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/db.py +60 -55
  10. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/cluster.py +43 -49
  11. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/dedupe.py +5 -8
  12. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/dedupe_edges.py +10 -15
  13. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/review.py +24 -24
  14. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/entity_query.py +5 -4
  15. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/entity_write.py +8 -7
  16. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/export.py +8 -8
  17. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/fetch.py +99 -33
  18. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/README.md +31 -4
  19. muckrake-0.3.0/src/muckrake/extract/ner/__init__.py +4 -0
  20. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/engines/base.py +4 -0
  21. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/engines/llm.py +18 -9
  22. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/materialize.py +4 -7
  23. muckrake-0.3.0/src/muckrake/extract/ner/pipeline.py +172 -0
  24. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/review.py +19 -21
  25. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/storage.py +132 -24
  26. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/load.py +9 -16
  27. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/logging.py +3 -3
  28. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/release.py +135 -31
  29. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/runs.py +58 -20
  30. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/search.py +9 -5
  31. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/serialize.py +7 -15
  32. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/settings.py +8 -2
  33. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/store.py +49 -11
  34. muckrake-0.3.0/src/muckrake/units.py +124 -0
  35. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/util.py +5 -4
  36. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/utils/__init__.py +8 -1
  37. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/utils/dates.py +66 -41
  38. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/utils/gb_coh.py +2 -3
  39. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/view.py +5 -5
  40. muckrake-0.2.1/pyproject.toml +0 -40
  41. muckrake-0.2.1/src/muckrake/crawl.py +0 -223
  42. muckrake-0.2.1/src/muckrake/extract/ner/__init__.py +0 -4
  43. muckrake-0.2.1/src/muckrake/extract/ner/pipeline.py +0 -151
  44. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/__init__.py +0 -0
  45. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/README.md +0 -0
  46. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/dedupe/__init__.py +5 -5
  47. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/env.py +0 -0
  48. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/__init__.py +0 -0
  49. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/engines/__init__.py +0 -0
  50. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/engines/delimited.py +0 -0
  51. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/extract/ner/engines/llm_prompt.py +0 -0
  52. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/id.py +0 -0
  53. {muckrake-0.2.1 → muckrake-0.3.0}/src/muckrake/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: muckrake
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: A framework for creating and storing FollowTheMoney entities, used by OpenLobbying.
5
5
  Author: Nicu Calcea
6
6
  Author-email: Nicu Calcea <mail@nicu.md>
@@ -13,7 +13,7 @@ Requires-Dist: lxml>=6.0.2
13
13
  Requires-Dist: nomenklatura>=4.4.1
14
14
  Requires-Dist: openpyxl>=3.1.5
15
15
  Requires-Dist: pandas>=2.3.3
16
- Requires-Dist: pydantic-ai-slim[google,openrouter]>=1.0.0
16
+ Requires-Dist: pydantic-ai-slim[anthropic,google,openrouter]>=1.0.0,<2
17
17
  Requires-Dist: psycopg[binary]>=3.2.12
18
18
  Requires-Dist: plyvel>=1.5.1
19
19
  Requires-Dist: pyyaml>=6.0.3
@@ -53,6 +53,16 @@ To crawl a dataset, run `uv run muckrake crawl {dataset_name}`. Run `uv run muck
53
53
 
54
54
  Each crawl now creates a `dataset_runs` record in Postgres and stores immutable artifacts under `MUCKRAKE_ARTIFACT_PATH` (defaults to `data/artifacts`). The latest successful run remains mirrored into `data/datasets/{name}/statements.pack.csv` for local compatibility.
55
55
 
56
+ #### Units of work and `--retry-failed`
57
+
58
+ A crawler can split its work into independently retryable units (one source file, one page, one record) by wrapping each in `dataset.run_unit(key, func, *args)`. A unit's statements reach the pack only if `func` returns. If it raises, the unit is recorded as failed, nothing from it is emitted, and the crawl carries on. A crawl that completes with failed units finishes as `partial`: its output is usable by `load` and `release-build`, and the failures are counted by error type in the run's stats and the end-of-crawl log. Errors outside a unit still fail the whole crawl.
59
+
60
+ Each run writes a `units.jsonl` ledger next to its pack, recording where every succeeded unit sits in the pack. `uv run muckrake crawl {dataset_name} --retry-failed` copies the units that succeeded in the dataset's latest crawl into a new run and re-runs everything else. That covers both retrying failures (e.g. after a parser fix) and resuming a crawl that crashed or was killed partway. Pack and ledger are written in place under the run's artifact directory as the crawl goes, so even a killed crawl leaves its completed units behind.
61
+
62
+ #### Completeness warnings
63
+
64
+ When a crawler knows its output is missing something (a pagination cap was hit, an API returned fewer items than it reported, a linked file has gone), it records it with `dataset.warn_incomplete(reason, **context)` rather than only logging it. Keep `reason` a fixed phrase and put the specifics in `context`. The run finishes as `partial`, the warnings are counted by reason in the end-of-crawl log and listed in the run's stats, and warnings raised inside a unit are carried over by `--retry-failed`. `release-build` logs every `partial` input and records what it's missing (failed units and warnings by reason) in the release manifest.
65
+
56
66
  ### AI-based NER
57
67
 
58
68
  Many data sources have [composite fields that contain multiple entities](https://openaccess.transparency.org.uk/?meeting=10088). We use LLMs to extract unique entities and relationships from these fields, and store them as candidates in the database for review and approval. See [NER docs](/src/muckrake/extract/ner/README.md) for details.
@@ -87,6 +97,8 @@ uv run muckrake dedupe-edges
87
97
 
88
98
  Statements are loaded into Postgres with `uv run muckrake load`. This reads the statements CSV files and applies any approved NER candidates before materialising entities and relationships.
89
99
 
100
+ A load is atomic: every dataset in it is cleared and reloaded in a single transaction, so a load that fails partway leaves the previously loaded statements in place. A dataset with no statements pack is skipped with a warning, and its loaded statements are kept.
101
+
90
102
  To load from a specific immutable crawl snapshot instead of the local workspace copy:
91
103
 
92
104
  ```bash
@@ -100,6 +112,8 @@ uv run muckrake release-build
100
112
  uv run muckrake release-publish 1
101
113
  ```
102
114
 
115
+ Publishing is atomic: the new release is written in a single transaction, so readers keep seeing the previous release until it commits, and a failed publish leaves it in place. On Postgres, the release is loaded with `COPY` into a new statement table, indexed and given its own search view, then swapped in with renames, so readers only wait for the swap. A full release of ~5M statements publishes in minutes. On SQLite, the published statements are cleared and rewritten row by row.
116
+
103
117
 
104
118
  ## OpenLobbying
105
119
 
@@ -123,7 +137,7 @@ The primary user of Muckrake data is [OpenLobbying](https://openlobbying.org/),
123
137
  - `MUCKRAKE_FTM_SCHEMA_PATHS`
124
138
  - `MUCKRAKE_ENV_FILE`
125
139
  - `FTM_MODEL_PATH` if you need to override the merged FollowTheMoney model entirely
126
- - `OPENROUTER_API_KEY`, `LLM_MODEL`, `NER_LLM_PROMPT_FILE`, `LOGFIRE_TOKEN`
140
+ - `LLM_MODEL`, `OPENROUTER_API_KEY` or `ANTHROPIC_API_KEY`, `NER_LLM_PROMPT_FILE`, `LOGFIRE_TOKEN`
127
141
  - Example:
128
142
 
129
143
  ```bash
@@ -27,6 +27,16 @@ To crawl a dataset, run `uv run muckrake crawl {dataset_name}`. Run `uv run muck
27
27
 
28
28
  Each crawl now creates a `dataset_runs` record in Postgres and stores immutable artifacts under `MUCKRAKE_ARTIFACT_PATH` (defaults to `data/artifacts`). The latest successful run remains mirrored into `data/datasets/{name}/statements.pack.csv` for local compatibility.
29
29
 
30
+ #### Units of work and `--retry-failed`
31
+
32
+ A crawler can split its work into independently retryable units (one source file, one page, one record) by wrapping each in `dataset.run_unit(key, func, *args)`. A unit's statements reach the pack only if `func` returns. If it raises, the unit is recorded as failed, nothing from it is emitted, and the crawl carries on. A crawl that completes with failed units finishes as `partial`: its output is usable by `load` and `release-build`, and the failures are counted by error type in the run's stats and the end-of-crawl log. Errors outside a unit still fail the whole crawl.
33
+
34
+ Each run writes a `units.jsonl` ledger next to its pack, recording where every succeeded unit sits in the pack. `uv run muckrake crawl {dataset_name} --retry-failed` copies the units that succeeded in the dataset's latest crawl into a new run and re-runs everything else. That covers both retrying failures (e.g. after a parser fix) and resuming a crawl that crashed or was killed partway. Pack and ledger are written in place under the run's artifact directory as the crawl goes, so even a killed crawl leaves its completed units behind.
35
+
36
+ #### Completeness warnings
37
+
38
+ When a crawler knows its output is missing something (a pagination cap was hit, an API returned fewer items than it reported, a linked file has gone), it records it with `dataset.warn_incomplete(reason, **context)` rather than only logging it. Keep `reason` a fixed phrase and put the specifics in `context`. The run finishes as `partial`, the warnings are counted by reason in the end-of-crawl log and listed in the run's stats, and warnings raised inside a unit are carried over by `--retry-failed`. `release-build` logs every `partial` input and records what it's missing (failed units and warnings by reason) in the release manifest.
39
+
30
40
  ### AI-based NER
31
41
 
32
42
  Many data sources have [composite fields that contain multiple entities](https://openaccess.transparency.org.uk/?meeting=10088). We use LLMs to extract unique entities and relationships from these fields, and store them as candidates in the database for review and approval. See [NER docs](/src/muckrake/extract/ner/README.md) for details.
@@ -61,6 +71,8 @@ uv run muckrake dedupe-edges
61
71
 
62
72
  Statements are loaded into Postgres with `uv run muckrake load`. This reads the statements CSV files and applies any approved NER candidates before materialising entities and relationships.
63
73
 
74
+ A load is atomic: every dataset in it is cleared and reloaded in a single transaction, so a load that fails partway leaves the previously loaded statements in place. A dataset with no statements pack is skipped with a warning, and its loaded statements are kept.
75
+
64
76
  To load from a specific immutable crawl snapshot instead of the local workspace copy:
65
77
 
66
78
  ```bash
@@ -74,6 +86,8 @@ uv run muckrake release-build
74
86
  uv run muckrake release-publish 1
75
87
  ```
76
88
 
89
+ Publishing is atomic: the new release is written in a single transaction, so readers keep seeing the previous release until it commits, and a failed publish leaves it in place. On Postgres, the release is loaded with `COPY` into a new statement table, indexed and given its own search view, then swapped in with renames, so readers only wait for the swap. A full release of ~5M statements publishes in minutes. On SQLite, the published statements are cleared and rewritten row by row.
90
+
77
91
 
78
92
  ## OpenLobbying
79
93
 
@@ -97,7 +111,7 @@ The primary user of Muckrake data is [OpenLobbying](https://openlobbying.org/),
97
111
  - `MUCKRAKE_FTM_SCHEMA_PATHS`
98
112
  - `MUCKRAKE_ENV_FILE`
99
113
  - `FTM_MODEL_PATH` if you need to override the merged FollowTheMoney model entirely
100
- - `OPENROUTER_API_KEY`, `LLM_MODEL`, `NER_LLM_PROMPT_FILE`, `LOGFIRE_TOKEN`
114
+ - `LLM_MODEL`, `OPENROUTER_API_KEY` or `ANTHROPIC_API_KEY`, `NER_LLM_PROMPT_FILE`, `LOGFIRE_TOKEN`
101
115
  - Example:
102
116
 
103
117
  ```bash
@@ -0,0 +1,84 @@
1
+ [project]
2
+ name = "muckrake"
3
+ version = "0.3.0"
4
+ description = "A framework for creating and storing FollowTheMoney entities, used by OpenLobbying."
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = [
8
+ "beautifulsoup4>=4.14.3",
9
+ "click>=8.3.1",
10
+ "datapatch>=1.2.4",
11
+ "followthemoney>=4.4.0",
12
+ "org-id>=0.1.0",
13
+ "lxml>=6.0.2",
14
+ "nomenklatura>=4.4.1",
15
+ "openpyxl>=3.1.5",
16
+ "pandas>=2.3.3",
17
+ "pydantic-ai-slim[anthropic,google,openrouter]>=1.0.0,<2",
18
+ "psycopg[binary]>=3.2.12",
19
+ "plyvel>=1.5.1",
20
+ "pyyaml>=6.0.3",
21
+ "requests>=2.32.5",
22
+ "xlrd>=2.0.2",
23
+ "logfire[httpx,sqlalchemy]>=4.24.0",
24
+ "odfpy>=1.4.1",
25
+ ]
26
+
27
+ [[project.authors]]
28
+ name = "Nicu Calcea"
29
+ email = "mail@nicu.md"
30
+
31
+ [project.scripts]
32
+ muckrake = "muckrake.cli:cli"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.9.17,<0.10.0"]
36
+ build-backend = "uv_build"
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=9.0.3",
41
+ "ruff>=0.15",
42
+ "mypy>=1.19",
43
+ "pre-commit>=4.0",
44
+ "types-requests>=2.32",
45
+ "types-pyyaml>=6.0",
46
+ ]
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
50
+
51
+ [tool.ruff]
52
+ line-length = 100
53
+ target-version = "py313"
54
+ extend-exclude = ["datasets_to_do"]
55
+
56
+ [tool.ruff.lint]
57
+ select = [
58
+ "E",
59
+ "F",
60
+ "I",
61
+ "UP",
62
+ "B",
63
+ ]
64
+
65
+ [tool.ruff.lint.per-file-ignores]
66
+ "src/muckrake/extract/ner/engines/llm_prompt.py" = ["E501"]
67
+
68
+ [tool.mypy]
69
+ python_version = "3.13"
70
+ check_untyped_defs = true
71
+ warn_unused_ignores = true
72
+
73
+ [[tool.mypy.overrides]]
74
+ module = [
75
+ "banal.*",
76
+ "datapatch.*",
77
+ "plyvel.*",
78
+ "org_id.*",
79
+ "xlrd.*",
80
+ "odf.*",
81
+ "lxml.*",
82
+ "bs4.*",
83
+ ]
84
+ ignore_missing_imports = true
@@ -0,0 +1,79 @@
1
+ [project]
2
+ name = "muckrake"
3
+ version = "0.3.0"
4
+ description = "A framework for creating and storing FollowTheMoney entities, used by OpenLobbying."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Nicu Calcea", email = "mail@nicu.md" }
8
+ ]
9
+ requires-python = ">=3.13"
10
+ dependencies = [
11
+ "beautifulsoup4>=4.14.3",
12
+ "click>=8.3.1",
13
+ "datapatch>=1.2.4",
14
+ "followthemoney>=4.4.0",
15
+ "org-id>=0.1.0",
16
+ "lxml>=6.0.2",
17
+ "nomenklatura>=4.4.1",
18
+ "openpyxl>=3.1.5",
19
+ "pandas>=2.3.3",
20
+ "pydantic-ai-slim[anthropic,google,openrouter]>=1.0.0,<2",
21
+ "psycopg[binary]>=3.2.12",
22
+ "plyvel>=1.5.1",
23
+ "pyyaml>=6.0.3",
24
+ "requests>=2.32.5",
25
+ "xlrd>=2.0.2",
26
+ "logfire[httpx,sqlalchemy]>=4.24.0",
27
+ "odfpy>=1.4.1",
28
+ ]
29
+
30
+ [project.scripts]
31
+ muckrake = "muckrake.cli:cli"
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.9.17,<0.10.0"]
35
+ build-backend = "uv_build"
36
+
37
+ [dependency-groups]
38
+ dev = [
39
+ "pytest>=9.0.3",
40
+ "ruff>=0.15",
41
+ "mypy>=1.19",
42
+ "pre-commit>=4.0",
43
+ "types-requests>=2.32",
44
+ "types-pyyaml>=6.0",
45
+ ]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+
50
+ [tool.ruff]
51
+ line-length = 100
52
+ target-version = "py313"
53
+ # Parked, unmaintained crawler stubs from before the openlobbying split.
54
+ extend-exclude = ["datasets_to_do"]
55
+
56
+ [tool.ruff.lint]
57
+ select = ["E", "F", "I", "UP", "B"]
58
+
59
+ [tool.ruff.lint.per-file-ignores]
60
+ # LLM prompt prose; wrapping would change the prompt text.
61
+ "src/muckrake/extract/ner/engines/llm_prompt.py" = ["E501"]
62
+
63
+ [tool.mypy]
64
+ python_version = "3.13"
65
+ check_untyped_defs = true
66
+ warn_unused_ignores = true
67
+
68
+ [[tool.mypy.overrides]]
69
+ module = [
70
+ "banal.*",
71
+ "datapatch.*",
72
+ "plyvel.*",
73
+ "org_id.*",
74
+ "xlrd.*",
75
+ "odf.*",
76
+ "lxml.*",
77
+ "bs4.*",
78
+ ]
79
+ ignore_missing_imports = true
@@ -31,29 +31,28 @@ class LocalArtifactStore:
31
31
  def exists(self, storage_key: str) -> bool:
32
32
  return self.resolve_path(storage_key).exists()
33
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)
34
+ def describe(self, storage_key: str) -> StoredArtifact:
35
+ """Describe an artifact already written in place under ``storage_key``."""
36
+ path = self.resolve_path(storage_key)
38
37
  return StoredArtifact(
39
38
  storage_backend=self.storage_backend,
40
39
  storage_key=storage_key,
41
- absolute_path=target_path,
42
- sha256=file_sha256(target_path),
43
- size_bytes=target_path.stat().st_size,
40
+ absolute_path=path,
41
+ sha256=file_sha256(path),
42
+ size_bytes=path.stat().st_size,
44
43
  )
45
44
 
45
+ def put_file(self, source_path: Path, storage_key: str) -> StoredArtifact:
46
+ target_path = self.resolve_path(storage_key)
47
+ target_path.parent.mkdir(parents=True, exist_ok=True)
48
+ shutil.copy2(source_path, target_path)
49
+ return self.describe(storage_key)
50
+
46
51
  def put_bytes(self, data: bytes, storage_key: str) -> StoredArtifact:
47
52
  target_path = self.resolve_path(storage_key)
48
53
  target_path.parent.mkdir(parents=True, exist_ok=True)
49
54
  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
- )
55
+ return self.describe(storage_key)
57
56
 
58
57
  def put_json(self, payload: dict[str, Any], storage_key: str) -> StoredArtifact:
59
58
  data = json.dumps(payload, indent=2, sort_keys=True).encode("utf-8")
@@ -1,23 +1,21 @@
1
- import logging
2
1
  import json
2
+ import logging
3
3
  import sys
4
4
  from pathlib import Path
5
5
 
6
6
  import click
7
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
8
+
10
9
  from muckrake.crawl import run_crawl
10
+ from muckrake.dataset import clear_dataset, find_datasets, list_datasets, load_config
11
11
  from muckrake.dedupe import (
12
- run_xref,
13
12
  run_dedupe,
13
+ run_dedupe_edges,
14
14
  run_dedupe_explode,
15
15
  run_merge,
16
16
  run_prune,
17
- run_dedupe_edges,
17
+ run_xref,
18
18
  )
19
- from muckrake.extract.ner import run_ner_extract, run_ner_review
20
- from muckrake.extract.ner.engines import list_extractors
21
19
  from muckrake.entity_query import (
22
20
  get_entity_payload,
23
21
  normalize_schema_filter,
@@ -26,7 +24,12 @@ from muckrake.entity_query import (
26
24
  from muckrake.entity_write import add_entity as run_add_entity
27
25
  from muckrake.entity_write import build_entity_spec
28
26
  from muckrake.entity_write import update_entity as run_update_entity
27
+ from muckrake.extract.ner import run_ner_auto_review, run_ner_extract, run_ner_review
28
+ from muckrake.extract.ner.engines import list_extractors
29
+ from muckrake.extract.ner.storage import export_candidates, import_candidates
30
+ from muckrake.extract.ner.storage import get_connection as get_ner_connection
29
31
  from muckrake.load import run_load
32
+ from muckrake.logging import configure_logging
30
33
  from muckrake.release import list_releases, run_release_build, run_release_publish
31
34
  from muckrake.settings import get_working_sql_uri
32
35
 
@@ -128,12 +131,23 @@ def cli(verbose):
128
131
  default=False,
129
132
  help="Clear dataset data before crawling",
130
133
  )
131
- def crawl(dataset_name, output, clear):
134
+ @click.option(
135
+ "--retry-failed",
136
+ is_flag=True,
137
+ default=False,
138
+ help=(
139
+ "Carry over the units that succeeded in the dataset's latest crawl and re-run "
140
+ "the rest (failed units, and any never reached if that crawl crashed)"
141
+ ),
142
+ )
143
+ def crawl(dataset_name, output, clear, retry_failed):
132
144
  """Crawl one or all datasets.
133
145
 
134
146
  DATASET_NAME should be the dataset name from config.yml (e.g., gb_political_finance).
135
147
  If not provided, crawls all datasets.
136
148
  """
149
+ if retry_failed and not dataset_name:
150
+ raise click.UsageError("--retry-failed needs a DATASET_NAME")
137
151
  configs = find_datasets(dataset_name)
138
152
 
139
153
  if dataset_name and not configs:
@@ -159,7 +173,7 @@ def crawl(dataset_name, output, clear):
159
173
  try:
160
174
  if clear:
161
175
  clear_dataset(ds.name)
162
- run_crawl(config, output)
176
+ run_crawl(config, output, retry_failed=retry_failed)
163
177
  finally:
164
178
  for logger_name, level in quiet_loggers.items():
165
179
  logging.getLogger(logger_name).setLevel(level)
@@ -265,7 +279,9 @@ def search_cmd(query, schemas, limit, offset, pretty):
265
279
  offset = max(0, offset)
266
280
  requested_schema = list(schemas) if schemas else []
267
281
  applied_schema = normalize_schema_filter(requested_schema)
268
- response = search_entity_payload(query.strip(), requested_schema, limit, offset, uri=_working_uri())
282
+ response = search_entity_payload(
283
+ query.strip(), requested_schema, limit, offset, uri=_working_uri()
284
+ )
269
285
  _emit_json(
270
286
  {
271
287
  "status": "ok",
@@ -289,7 +305,9 @@ def search_cmd(query, schemas, limit, offset, pretty):
289
305
  @click.argument("entity_id", required=True)
290
306
  @click.option("--schema", "schema_name", help="Optional replacement FtM schema name")
291
307
  @click.option("--dataset", help="Replacement dataset name used for rewritten provenance")
292
- @click.option("--source", "source_ref", help="Replacement source reference for rewritten provenance")
308
+ @click.option(
309
+ "--source", "source_ref", help="Replacement source reference for rewritten provenance"
310
+ )
293
311
  @click.option(
294
312
  "--property",
295
313
  "property_items",
@@ -318,9 +336,7 @@ def update_cmd(entity_id, schema_name, dataset, source_ref, property_items, pret
318
336
 
319
337
 
320
338
  @cli.command()
321
- @click.option(
322
- "--output", "-o", type=click.Path(), required=True, help="Output file path"
323
- )
339
+ @click.option("--output", "-o", type=click.Path(), required=True, help="Output file path")
324
340
  @click.option("--dataset", "-d", help="Filter by dataset")
325
341
  def export(output, dataset):
326
342
  """Export entities to FtM JSON."""
@@ -438,6 +454,7 @@ def load(dataset_name, run_id):
438
454
  log.exception(e)
439
455
  sys.exit(1)
440
456
 
457
+
441
458
  @cli.command("ner-extract")
442
459
  @click.argument("dataset_name", required=False)
443
460
  @click.option("--limit", "limit", type=int, default=None, help="Max candidate rows")
@@ -450,7 +467,10 @@ def load(dataset_name, run_id):
450
467
  show_default=True,
451
468
  help="Extraction strategy",
452
469
  )
453
- def ner_extract(dataset_name, limit, entity_id, extractor_name):
470
+ @click.option(
471
+ "--workers", type=int, default=1, show_default=True, help="Texts extracted concurrently"
472
+ )
473
+ def ner_extract(dataset_name, limit, entity_id, extractor_name, workers):
454
474
  """Extract named entities from statement text fields."""
455
475
  try:
456
476
  run_ner_extract(
@@ -458,6 +478,7 @@ def ner_extract(dataset_name, limit, entity_id, extractor_name):
458
478
  limit=limit,
459
479
  entity_id=entity_id,
460
480
  extractor_name=extractor_name,
481
+ workers=workers,
461
482
  )
462
483
  except Exception as e:
463
484
  log.exception(e)
@@ -467,15 +488,47 @@ def ner_extract(dataset_name, limit, entity_id, extractor_name):
467
488
  @cli.command("ner-review")
468
489
  @click.argument("dataset_name", required=False)
469
490
  @click.option("--limit", "limit", type=int, default=None, help="Max pending candidates")
470
- def ner_review(dataset_name, limit):
491
+ @click.option(
492
+ "--auto",
493
+ is_flag=True,
494
+ default=False,
495
+ help="Approve every pending split without review; reject unsplit extractions",
496
+ )
497
+ def ner_review(dataset_name, limit, auto):
471
498
  """Review pending NER extraction candidates."""
472
499
  try:
473
- run_ner_review(dataset_name=dataset_name, limit=limit)
500
+ if auto:
501
+ run_ner_auto_review(dataset_name=dataset_name)
502
+ else:
503
+ run_ner_review(dataset_name=dataset_name, limit=limit)
474
504
  except Exception as e:
475
505
  log.exception(e)
476
506
  sys.exit(1)
477
507
 
478
508
 
509
+ @cli.command("ner-export")
510
+ @click.argument("path", type=click.Path(dir_okay=False, path_type=Path))
511
+ def ner_export(path):
512
+ """Save all NER candidates and review decisions to a JSON lines file (.gz to compress)."""
513
+ conn = get_ner_connection()
514
+ try:
515
+ click.echo(f"Exported {export_candidates(conn, path)} candidates to {path}")
516
+ finally:
517
+ conn.close()
518
+
519
+
520
+ @cli.command("ner-import")
521
+ @click.argument("path", type=click.Path(exists=True, dir_okay=False, path_type=Path))
522
+ def ner_import(path):
523
+ """Add NER candidates from an export; candidates already present are kept as they are."""
524
+ conn = get_ner_connection()
525
+ try:
526
+ imported, present = import_candidates(conn, path)
527
+ click.echo(f"Imported {imported} candidates; {present} were already present.")
528
+ finally:
529
+ conn.close()
530
+
531
+
479
532
  @cli.command("release-build")
480
533
  @click.argument("dataset_name", nargs=-1, required=False)
481
534
  @click.option("--notes", help="Optional release notes")
@@ -511,7 +564,8 @@ def release_list(limit):
511
564
  return
512
565
  for release in releases:
513
566
  click.echo(
514
- f"{release.id}\t{release.status}\tcreated={release.created_at}\tpublished={release.published_at or '-'}"
567
+ f"{release.id}\t{release.status}\tcreated={release.created_at}"
568
+ f"\tpublished={release.published_at or '-'}"
515
569
  )
516
570
  except Exception as e:
517
571
  log.exception(e)