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,210 @@
1
+ # Entity Extraction (Prototype)
2
+
3
+ This package contains a minimal, extensible named-entity extraction pipeline.
4
+
5
+ The goal is to support multiple extraction strategies behind one interface.
6
+ Implemented now:
7
+
8
+ - `delimiter` (deterministic splitter)
9
+ - `llm` (basic OpenRouter-powered extractor via PydanticAI)
10
+
11
+ ## What exists now
12
+
13
+ - CLI command: `muckrake ner-extract`
14
+ - Strategy registry under `src/muckrake/extract/ner/engines/`
15
+ - Implemented strategies: `delimiter`, `llm`
16
+ - Candidate persistence into `data/muckrake.db` table: `ner_candidates`
17
+
18
+ Code locations:
19
+
20
+ - pipeline: `src/muckrake/extract/ner/pipeline.py`
21
+ - engines registry: `src/muckrake/extract/ner/engines/__init__.py`
22
+ - delimiter engine: `src/muckrake/extract/ner/engines/delimited.py`
23
+ - storage: `src/muckrake/extract/ner/storage.py`
24
+
25
+ ## Input model
26
+
27
+ Extraction runs over normalized crawler output (`statements.pack.csv`), not raw source files.
28
+
29
+ Currently selected statement fields:
30
+
31
+ - `LegalEntity.name`
32
+ - `Organization.name`
33
+ - `Company.name`
34
+ - `Person.name`
35
+
36
+ This keeps the process format-agnostic across CSV/JSON/HTML-backed datasets.
37
+
38
+ ## Current strategy: `delimiter`
39
+
40
+ - Splits candidate text on commas and semicolons.
41
+ - Emits a list of FtM-aligned entity fragments.
42
+
43
+ Each extracted entity is stored as an FtM-style JSON fragment without `id`:
44
+
45
+ ```json
46
+ {
47
+ "schema": "LegalEntity",
48
+ "properties": {
49
+ "name": ["Example Name"]
50
+ }
51
+ }
52
+ ```
53
+
54
+ Using `LegalEntity` is deliberate at this stage because delimiter splitting alone
55
+ cannot reliably distinguish `Person` vs `Organization`.
56
+
57
+ ## LLM strategy: `llm` (basic)
58
+
59
+ - Uses `pydantic-ai` with OpenRouter.
60
+ - Reads `OPENROUTER_API_KEY` and `LLM_MODEL` (from environment, with `.env` fallback).
61
+ `LLM_MODEL` can be either `stepfun/step-3.5-flash:free` or `openrouter:stepfun/step-3.5-flash:free`.
62
+ - Produces FtM-style fragments in the same `entities` format as delimiter.
63
+ - Supports relation links via local keys and `$ref:<key>` values in extracted properties
64
+ (for example `Employment.employee -> "$ref:p1"`).
65
+ - Validates output against FollowTheMoney schemata/properties and retries the model on errors.
66
+ - Centralized Logfire tracing (`configure_logging(app=...)`).
67
+ Set `LOGFIRE_TOKEN` to send traces to Logfire.
68
+
69
+ Prompt configuration:
70
+
71
+ - Default prompt is in `src/muckrake/extract/ner/engines/llm_prompt.py`.
72
+ - You can override prompt text with `NER_LLM_PROMPT_FILE=/path/to/prompt.txt`.
73
+
74
+ ## Storage
75
+
76
+ Candidates are stored in `data/muckrake.db`, table `ner_candidates`.
77
+
78
+ Main columns:
79
+
80
+ - `dataset`, `entity_id`, `schema`, `property_name`
81
+ - `source_text`, `fingerprint`
82
+ - `extractor`
83
+ - `status` (`pending`, `approved`, `rejected`)
84
+ - `reviewer`, `reviewed_at`
85
+ - `extraction_json`, `created_at`, `updated_at`
86
+
87
+ `extractor_version` still exists internally in the table for compatibility,
88
+ but it is fixed by the app and not exposed in CLI.
89
+
90
+ Uniqueness key:
91
+
92
+ - `(dataset, entity_id, property_name, fingerprint, extractor, extractor_version)`
93
+
94
+ So reruns with unchanged input + extractor configuration are idempotent.
95
+
96
+ ## Load-time import
97
+
98
+ `muckrake load` and `muckrake xref` both read `ner_candidates` and apply matching extractions before materializing statements:
99
+
100
+ - if a candidate matches `(entity_id, property_name, fingerprint)`, the original source entity is skipped,
101
+ - extracted fragments from `extraction_json` are materialized as new FtM entities,
102
+ - references to the original entity ID are rewritten to the extracted entity IDs,
103
+ - generated IDs use source dataset prefix + extracted `name` (for example `gb-meet-...`),
104
+ - if there is no matching candidate, loading behaves exactly as before.
105
+
106
+ Only candidates with `status = approved` are applied.
107
+
108
+ This mirrors the dedupe philosophy: extraction decisions alter load-time materialization.
109
+ Current implementation applies the latest approved matching candidate.
110
+
111
+ ## Usage
112
+
113
+ Run for one dataset:
114
+
115
+ ```bash
116
+ uv run muckrake ner-extract open_access
117
+ ```
118
+
119
+ Choose extractor:
120
+
121
+ ```bash
122
+ uv run muckrake ner-extract open_access --extractor delimiter --limit 20
123
+
124
+ # basic LLM extraction
125
+ uv run muckrake ner-extract open_access --extractor llm --limit 20
126
+ ```
127
+
128
+ Extract a single source entity:
129
+
130
+ ```bash
131
+ uv run muckrake ner-extract open_access --entity-id gb-meetings-12345 --extractor llm
132
+ ```
133
+
134
+ Run across all datasets:
135
+
136
+ ```bash
137
+ uv run muckrake ner-extract
138
+ ```
139
+
140
+ Review pending candidates:
141
+
142
+ ```bash
143
+ # One dataset
144
+ uv run muckrake ner-review open_access
145
+
146
+ # All datasets
147
+ uv run muckrake ner-review
148
+ ```
149
+
150
+ Review controls:
151
+
152
+ - `x` approve candidate
153
+ - `n` reject candidate
154
+ - `e` edit extracted JSON in your `$EDITOR`
155
+ - `u` skip candidate
156
+ - `q` quit review
157
+
158
+ When you press `e`, Muckrake opens a temporary JSON file in your terminal editor.
159
+ How to exit depends on the editor:
160
+
161
+ - Vim/Vi: press `Esc`, type `:wq`, press `Enter` (save + exit)
162
+ - Vim/Vi without saving: `Esc`, `:q!`, `Enter`
163
+ - Nano: `Ctrl+X`, then `Y` + `Enter` to save (or `N` to discard)
164
+
165
+ Tip: set an editor you are comfortable with before review:
166
+
167
+ ```bash
168
+ export EDITOR=nano
169
+ # or
170
+ export EDITOR=vim
171
+ ```
172
+
173
+ ## Quick test
174
+
175
+ 1. Crawl a dataset so statements exist:
176
+
177
+ ```bash
178
+ uv run muckrake crawl open_access
179
+ ```
180
+
181
+ 2. Run extraction:
182
+
183
+ ```bash
184
+ uv run muckrake ner-extract open_access --limit 20
185
+ ```
186
+
187
+ 3. Review and approve a few candidates:
188
+
189
+ ```bash
190
+ uv run muckrake ner-review open_access --limit 20
191
+ ```
192
+
193
+ 4. Load dataset and verify approved candidates are applied:
194
+
195
+ ```bash
196
+ uv run muckrake load open_access
197
+ ```
198
+
199
+ 5. Run extraction again with same options and confirm no new rows are inserted.
200
+
201
+ 6. Check row count:
202
+
203
+ ```bash
204
+ uv run python -c "from sqlalchemy import create_engine, text; from muckrake.settings import SQL_URI; e=create_engine(SQL_URI); print(e.connect().execute(text('select count(*) from ner_candidates')).scalar())"
205
+ ```
206
+
207
+ ## Next planned pieces
208
+
209
+ - Add additional extraction engines to `ner/engines/`.
210
+ - Load only approved candidates into FtM entities.
@@ -0,0 +1,4 @@
1
+ from .pipeline import run_ner_extract
2
+ from .review import run_ner_review
3
+
4
+ __all__ = ["run_ner_extract", "run_ner_review"]
@@ -0,0 +1,32 @@
1
+ from collections.abc import Callable
2
+
3
+ from .base import Extractor
4
+ from .delimited import DelimitedExtractor
5
+
6
+
7
+ def _load_delimiter() -> Extractor:
8
+ return DelimitedExtractor()
9
+
10
+
11
+ def _load_llm() -> Extractor:
12
+ from .llm import LLMExtractor
13
+
14
+ return LLMExtractor()
15
+
16
+
17
+ EXTRACTORS: dict[str, Callable[[], Extractor]] = {
18
+ "delimiter": _load_delimiter,
19
+ "llm": _load_llm,
20
+ }
21
+
22
+
23
+ def get_extractor(name: str) -> Extractor:
24
+ factory = EXTRACTORS.get(name)
25
+ if factory is None:
26
+ available = ", ".join(sorted(EXTRACTORS.keys()))
27
+ raise ValueError(f"Unknown extractor '{name}'. Available: {available}")
28
+ return factory()
29
+
30
+
31
+ def list_extractors() -> list[str]:
32
+ return sorted(EXTRACTORS.keys())
@@ -0,0 +1,14 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any
3
+
4
+
5
+ class RecoverableExtractionError(Exception):
6
+ pass
7
+
8
+
9
+ class Extractor(ABC):
10
+ name: str
11
+
12
+ @abstractmethod
13
+ def extract(self, text: str) -> list[dict[str, Any]]:
14
+ raise NotImplementedError
@@ -0,0 +1,39 @@
1
+ import re
2
+ from typing import Any
3
+
4
+ from .base import Extractor
5
+
6
+
7
+ class DelimitedExtractor(Extractor):
8
+ name = "delimiter"
9
+
10
+ @staticmethod
11
+ def _normalize(segment: str) -> str:
12
+ return " ".join(segment.strip().split())
13
+
14
+ def extract(self, text: str) -> list[dict[str, Any]]:
15
+ parts = re.split(r"[;,]", text)
16
+ entities: list[dict[str, Any]] = []
17
+ for part in parts:
18
+ seg = self._normalize(part)
19
+ if len(seg) < 3:
20
+ continue
21
+ entities.append(
22
+ {
23
+ "schema": "LegalEntity",
24
+ "properties": {
25
+ "name": [seg],
26
+ },
27
+ }
28
+ )
29
+
30
+ unique_entities: list[dict[str, Any]] = []
31
+ seen_names: set[str] = set()
32
+ for entity in entities:
33
+ name = entity["properties"]["name"][0]
34
+ if name in seen_names:
35
+ continue
36
+ seen_names.add(name)
37
+ unique_entities.append(entity)
38
+
39
+ return unique_entities
@@ -0,0 +1,164 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Any
4
+
5
+ from followthemoney import model
6
+ from pydantic import BaseModel, Field
7
+
8
+ from muckrake.logging import configure_logging
9
+
10
+ from .base import Extractor, RecoverableExtractionError
11
+ from .llm_prompt import DEFAULT_SYSTEM_PROMPT, build_user_prompt
12
+
13
+
14
+ def _get_system_prompt() -> str:
15
+ prompt_path = os.getenv("NER_LLM_PROMPT_FILE")
16
+ if prompt_path:
17
+ path = Path(prompt_path)
18
+ if path.exists():
19
+ return path.read_text(encoding="utf-8").strip()
20
+ return DEFAULT_SYSTEM_PROMPT
21
+
22
+
23
+ class LLMEntity(BaseModel):
24
+ key: str | None = None
25
+ schema_: str = Field(alias="schema")
26
+ properties: dict[str, list[str]] = Field(default_factory=dict)
27
+
28
+
29
+ class LLMExtractor(Extractor):
30
+ name = "llm"
31
+
32
+ def __init__(self) -> None:
33
+ configure_logging(enable_logfire=True)
34
+
35
+ model_name = os.getenv("LLM_MODEL")
36
+ if not model_name:
37
+ raise RuntimeError("LLM_MODEL is not set")
38
+
39
+ from pydantic_ai import Agent
40
+ from pydantic_ai import ModelRetry
41
+
42
+ model_name = self._normalize_model_name(model_name)
43
+
44
+ self._agent = Agent(
45
+ model_name,
46
+ output_type=list[LLMEntity],
47
+ system_prompt=_get_system_prompt(),
48
+ output_retries=3,
49
+ )
50
+
51
+ @self._agent.output_validator
52
+ def _validate_output(entities: list[LLMEntity]) -> list[LLMEntity]:
53
+ try:
54
+ self._validate_extraction_output(entities)
55
+ except ValueError as exc:
56
+ raise ModelRetry(str(exc)) from exc
57
+ return entities
58
+
59
+ @staticmethod
60
+ def _normalize_model_name(model_name: str) -> str:
61
+ return model_name.strip()
62
+
63
+ @staticmethod
64
+ def _validate_extraction_output(entities: list[LLMEntity]) -> None:
65
+ key_to_schema: dict[str, str] = {}
66
+
67
+ if not entities:
68
+ raise ValueError(
69
+ "No entities extracted. Return at least one entity when text contains named actors."
70
+ )
71
+
72
+ for entity in entities:
73
+ if entity.key:
74
+ key_to_schema[entity.key] = entity.schema_
75
+
76
+ schema_name = entity.schema_
77
+ schema = model.get(schema_name)
78
+ if schema is None:
79
+ raise ValueError(f"Unknown schema '{schema_name}'.")
80
+
81
+ if not entity.properties:
82
+ raise ValueError(f"Entity '{schema_name}' has no properties.")
83
+
84
+ for prop_name, values in entity.properties.items():
85
+ if prop_name not in schema.properties:
86
+ available = ", ".join(sorted(schema.properties.keys()))
87
+ raise ValueError(
88
+ f"Property '{prop_name}' is not valid for entity '{schema_name}'. "
89
+ f"Available properties: [{available}]"
90
+ )
91
+
92
+ if not isinstance(values, list) or not values:
93
+ raise ValueError(
94
+ f"Property '{prop_name}' on '{schema_name}' must be a non-empty list of strings."
95
+ )
96
+
97
+ prop = schema.get(prop_name)
98
+ if prop is None:
99
+ available = ", ".join(sorted(schema.properties.keys()))
100
+ raise ValueError(
101
+ f"Property '{prop_name}' is not valid for entity '{schema_name}'. "
102
+ f"Available properties: [{available}]"
103
+ )
104
+ assert prop is not None
105
+ for value in values:
106
+ if not isinstance(value, str):
107
+ raise ValueError(
108
+ f"Property '{prop_name}' on '{schema_name}' must contain strings only."
109
+ )
110
+
111
+ if value.startswith("$ref:"):
112
+ if prop.type.name != "entity":
113
+ raise ValueError(
114
+ f"Property '{prop_name}' on '{schema_name}' cannot use $ref values."
115
+ )
116
+ continue
117
+
118
+ cleaned = prop.type.clean(value)
119
+ if cleaned is None:
120
+ raise ValueError(
121
+ f"Invalid value '{value}' for property '{prop_name}' on '{schema_name}'."
122
+ )
123
+
124
+ for entity in entities:
125
+ schema = model.get(entity.schema_)
126
+ if schema is None:
127
+ raise ValueError(f"Unknown schema '{entity.schema_}'.")
128
+ for prop_name, values in entity.properties.items():
129
+ prop = schema.get(prop_name)
130
+ if prop is None:
131
+ raise ValueError(
132
+ f"Property '{prop_name}' is not valid for entity '{entity.schema_}'."
133
+ )
134
+ if prop.type.name != "entity":
135
+ continue
136
+
137
+ for value in values:
138
+ if not value.startswith("$ref:"):
139
+ continue
140
+ ref_key = value[5:]
141
+ ref_schema_name = key_to_schema.get(ref_key)
142
+ if ref_schema_name is None:
143
+ raise ValueError(
144
+ f"Unknown entity reference key '{ref_key}' for property '{prop_name}'."
145
+ )
146
+ ref_schema = model.get(ref_schema_name)
147
+ if ref_schema is None:
148
+ raise ValueError(
149
+ f"Unknown schema '{ref_schema_name}' for ref '{ref_key}'."
150
+ )
151
+ if prop.range is not None and not ref_schema.is_a(prop.range):
152
+ raise ValueError(
153
+ f"Reference '$ref:{ref_key}' has schema '{ref_schema_name}', "
154
+ f"but property '{entity.schema_}.{prop_name}' expects '{prop.range.name}'."
155
+ )
156
+
157
+ def extract(self, text: str) -> list[dict[str, Any]]:
158
+ from pydantic_ai.exceptions import UnexpectedModelBehavior
159
+
160
+ try:
161
+ result = self._agent.run_sync(build_user_prompt(text))
162
+ except UnexpectedModelBehavior as exc:
163
+ raise RecoverableExtractionError(str(exc)) from exc
164
+ return [e.model_dump(exclude_none=True, by_alias=True) for e in result.output]
@@ -0,0 +1,44 @@
1
+ DEFAULT_SYSTEM_PROMPT = """
2
+ You extract FollowTheMoney-style entity fragments from a single text field.
3
+
4
+ Rules:
5
+ - You return only entities directly supported by the text. Do not infer or guess anything, even if it seems obvious.
6
+ - Use the following FollowTheMoney schemata:
7
+ - Person (individuals)
8
+ - Company (commercial entities)
9
+ - PublicBody (government departments, local councils)
10
+ - Organization (for non-commercial entities such as NGOs, associations, trade groups, etc., or if you are not sure about the legal form of an entity)
11
+ - LegalEntity (where you don't know if it's a person, company, public body or organization)
12
+ - Employment (to describe employment relationships between people and companies, organizations)
13
+ - Ownership (to describe ownership relationships between people and companies, organizations)
14
+ - Every entity must include a schema and properties (all property values as arrays of strings)
15
+ - Use optional entity key values so relation entities can refer to participants.
16
+ - For relation references, set property values as "$ref:<key>".
17
+
18
+ If an entity has an alternate name, include it as a "alias" property. If it is an abbreviation, include it as an "abbreviation" property. Don't include the abbreviation in the name (unless the full name is not provided). Don't include the same name twice (e.g., as both "name" and "abbreviation").
19
+
20
+ Where relevant, keep honorifics and titles as part of the name, as they will help with entity disambiguation. For companies, keep the legal form (e.g., "Ltd", "Plc") as part of the name. Note that these are not abbreviations.
21
+
22
+ Be aware of context! For example, if the source text is "Families of those injured and affected by the Southport attack", then it would be wrong to extract "Southport" as an organization, as they mean different things. Instead, extract the full "Families of those injured and affected by the Southport attack" as an Organization.
23
+
24
+ Reference example:
25
+
26
+ Input: Victoria Newton, Editor of The Sun
27
+ Output: [{"key": "p1", "properties": {"name": ["Victoria Newton"]}, "schema": "Person"}, {"key": "c1", "properties": {"name": ["The Sun"]}, "schema": "Company"}, {"key": "e1", "properties": {"employee": ["$ref:p1"], "employer": ["$ref:c1"], "role": ["Editor"]}, "schema": "Employment"}]
28
+
29
+ Input: GMB union members and Camell Laird workers
30
+ Output: [{"key": "o1", "properties": {"name": ["GMB"]}, "schema": "Organization"}, {"key": "c1", "properties": {"name": ["Camell Laird"]}, "schema": "Company"}]
31
+
32
+ Only extract meaningful entities. Things like "family", "members", "legal team" are not meaningful on their own, unless they are part of the entity name.
33
+
34
+ Input: Lady Julia Amess, Katie Amess and legal team
35
+ Output: [{"key": "p1", "properties": {"name": ["Lady Julia Amess"]}, "schema": "Person"}, {"key": "p2", "properties": {"name": ["Katie Amess"]}, "schema": "Person"}]
36
+ """.strip()
37
+
38
+
39
+ def build_user_prompt(text: str) -> str:
40
+ return (
41
+ "Extract FollowTheMoney entity fragments from this text. "
42
+ "Return structured data only.\n\n"
43
+ f"Text:\n{text}"
44
+ )