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
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
import sys
|
|
5
|
+
import textwrap
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
from rich.console import Group, RenderableType
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
from rich.text import Text
|
|
14
|
+
from sqlalchemy.engine import Connection, RowMapping
|
|
15
|
+
from textual.app import App, ComposeResult
|
|
16
|
+
from textual.containers import Horizontal, VerticalScroll
|
|
17
|
+
from textual.widgets import Footer, Static
|
|
18
|
+
|
|
19
|
+
from .storage import (
|
|
20
|
+
get_candidate,
|
|
21
|
+
get_connection,
|
|
22
|
+
init_db,
|
|
23
|
+
list_candidates,
|
|
24
|
+
review_candidate,
|
|
25
|
+
update_candidate_extraction,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
ACTION_TO_STATUS = {
|
|
31
|
+
"x": "approved",
|
|
32
|
+
"n": "rejected",
|
|
33
|
+
"e": None,
|
|
34
|
+
"u": None,
|
|
35
|
+
"q": None,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class ReviewEvent:
|
|
41
|
+
candidate_id: int
|
|
42
|
+
action: str
|
|
43
|
+
schema: str
|
|
44
|
+
when: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _collect_highlight_terms(entity: dict[str, Any]) -> list[str]:
|
|
48
|
+
props = entity.get("properties", {})
|
|
49
|
+
if not isinstance(props, dict):
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
terms: list[str] = []
|
|
53
|
+
for prop_name in ("name", "alias", "abbreviation"):
|
|
54
|
+
for value in props.get(prop_name, []):
|
|
55
|
+
if isinstance(value, str) and value.strip():
|
|
56
|
+
terms.append(value.strip())
|
|
57
|
+
return terms
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _entity_name(entity: dict[str, Any]) -> str:
|
|
61
|
+
props = entity.get("properties", {})
|
|
62
|
+
if not isinstance(props, dict):
|
|
63
|
+
return "-"
|
|
64
|
+
|
|
65
|
+
names = [v for v in props.get("name", []) if isinstance(v, str) and v.strip()]
|
|
66
|
+
if names:
|
|
67
|
+
return names[0]
|
|
68
|
+
return "-"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _highlight_terms(text: str, terms: list[str]) -> str:
|
|
72
|
+
if not text or not terms:
|
|
73
|
+
return text
|
|
74
|
+
|
|
75
|
+
spans: list[tuple[int, int]] = []
|
|
76
|
+
seen_terms: set[str] = set()
|
|
77
|
+
for term in sorted(terms, key=len, reverse=True):
|
|
78
|
+
normalized = term.strip().lower()
|
|
79
|
+
if not normalized or normalized in seen_terms:
|
|
80
|
+
continue
|
|
81
|
+
seen_terms.add(normalized)
|
|
82
|
+
for match in re.finditer(re.escape(term), text, flags=re.IGNORECASE):
|
|
83
|
+
spans.append((match.start(), match.end()))
|
|
84
|
+
|
|
85
|
+
if not spans:
|
|
86
|
+
return text
|
|
87
|
+
|
|
88
|
+
spans.sort()
|
|
89
|
+
merged: list[list[int]] = []
|
|
90
|
+
for start, end in spans:
|
|
91
|
+
if not merged or start > merged[-1][1]:
|
|
92
|
+
merged.append([start, end])
|
|
93
|
+
continue
|
|
94
|
+
merged[-1][1] = max(merged[-1][1], end)
|
|
95
|
+
|
|
96
|
+
chunks: list[str] = []
|
|
97
|
+
cursor = 0
|
|
98
|
+
for start, end in merged:
|
|
99
|
+
if start > cursor:
|
|
100
|
+
chunks.append(text[cursor:start])
|
|
101
|
+
chunks.append(click.style(text[start:end], fg="yellow", bold=True))
|
|
102
|
+
cursor = end
|
|
103
|
+
|
|
104
|
+
if cursor < len(text):
|
|
105
|
+
chunks.append(text[cursor:])
|
|
106
|
+
return "".join(chunks)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _highlight_text(text: str, terms: list[str]) -> Text:
|
|
110
|
+
rendered = Text(text)
|
|
111
|
+
if not text or not terms:
|
|
112
|
+
return rendered
|
|
113
|
+
|
|
114
|
+
spans: list[tuple[int, int]] = []
|
|
115
|
+
seen_terms: set[str] = set()
|
|
116
|
+
for term in sorted(terms, key=len, reverse=True):
|
|
117
|
+
normalized = term.strip().lower()
|
|
118
|
+
if not normalized or normalized in seen_terms:
|
|
119
|
+
continue
|
|
120
|
+
seen_terms.add(normalized)
|
|
121
|
+
for match in re.finditer(re.escape(term), text, flags=re.IGNORECASE):
|
|
122
|
+
spans.append((match.start(), match.end()))
|
|
123
|
+
|
|
124
|
+
if not spans:
|
|
125
|
+
return rendered
|
|
126
|
+
|
|
127
|
+
spans.sort()
|
|
128
|
+
merged: list[tuple[int, int]] = []
|
|
129
|
+
for start, end in spans:
|
|
130
|
+
if not merged or start > merged[-1][1]:
|
|
131
|
+
merged.append((start, end))
|
|
132
|
+
continue
|
|
133
|
+
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
|
134
|
+
|
|
135
|
+
for start, end in merged:
|
|
136
|
+
rendered.stylize("bold yellow", start, end)
|
|
137
|
+
return rendered
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _join_values(values: list[str], max_items: int = 3) -> str:
|
|
141
|
+
cleaned = [v for v in values if isinstance(v, str) and v.strip()]
|
|
142
|
+
if not cleaned:
|
|
143
|
+
return "-"
|
|
144
|
+
if len(cleaned) <= max_items:
|
|
145
|
+
return " | ".join(cleaned)
|
|
146
|
+
return " | ".join(cleaned[:max_items]) + f" (+{len(cleaned) - max_items})"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _split_refs(values: list[str]) -> tuple[list[str], list[str]]:
|
|
150
|
+
refs: list[str] = []
|
|
151
|
+
plain: list[str] = []
|
|
152
|
+
for value in values:
|
|
153
|
+
if value.startswith("$ref:"):
|
|
154
|
+
refs.append(value)
|
|
155
|
+
continue
|
|
156
|
+
plain.append(value)
|
|
157
|
+
return refs, plain
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _parse_entities(row: RowMapping) -> list[dict[str, Any]]:
|
|
161
|
+
entities = json.loads(row["extraction_json"])
|
|
162
|
+
if not isinstance(entities, list):
|
|
163
|
+
raise ValueError(f"Candidate {row['id']} has invalid extraction payload")
|
|
164
|
+
return entities
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _validate_entities_payload(payload: Any) -> None:
|
|
168
|
+
if not isinstance(payload, list):
|
|
169
|
+
raise ValueError("Extraction must be a JSON array")
|
|
170
|
+
|
|
171
|
+
for index, entity in enumerate(payload, start=1):
|
|
172
|
+
if not isinstance(entity, dict):
|
|
173
|
+
raise ValueError(f"Entity #{index} must be an object")
|
|
174
|
+
|
|
175
|
+
schema = entity.get("schema")
|
|
176
|
+
if not isinstance(schema, str) or not schema.strip():
|
|
177
|
+
raise ValueError(f"Entity #{index} is missing a string 'schema'")
|
|
178
|
+
|
|
179
|
+
props = entity.get("properties")
|
|
180
|
+
if not isinstance(props, dict):
|
|
181
|
+
raise ValueError(f"Entity #{index} is missing an object 'properties'")
|
|
182
|
+
|
|
183
|
+
for prop_name, values in props.items():
|
|
184
|
+
if not isinstance(prop_name, str):
|
|
185
|
+
raise ValueError(f"Entity #{index} has non-string property name")
|
|
186
|
+
if not isinstance(values, list):
|
|
187
|
+
raise ValueError(
|
|
188
|
+
f"Entity #{index} property '{prop_name}' must be an array"
|
|
189
|
+
)
|
|
190
|
+
for value in values:
|
|
191
|
+
if not isinstance(value, str):
|
|
192
|
+
raise ValueError(
|
|
193
|
+
f"Entity #{index} property '{prop_name}' values must be strings"
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _edit_entities_in_editor(entities: list[Any]) -> list[dict[str, Any]] | None:
|
|
198
|
+
initial = json.dumps(entities, indent=2, sort_keys=True) + "\n"
|
|
199
|
+
edited = click.edit(initial, extension=".json")
|
|
200
|
+
if edited is None:
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
payload = json.loads(edited)
|
|
204
|
+
_validate_entities_payload(payload)
|
|
205
|
+
return payload
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _render_candidate(row: RowMapping, index: int, total: int) -> RenderableType:
|
|
209
|
+
entities = _parse_entities(row)
|
|
210
|
+
terms: list[str] = []
|
|
211
|
+
for entity in entities:
|
|
212
|
+
if isinstance(entity, dict):
|
|
213
|
+
terms.extend(_collect_highlight_terms(entity))
|
|
214
|
+
|
|
215
|
+
header = Text.assemble(
|
|
216
|
+
(f"Candidate #{row['id']}", "bold white"),
|
|
217
|
+
(f" [{index}/{total}]", "bright_black"),
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
meta = Table.grid(expand=True)
|
|
221
|
+
meta.add_column(style="bright_black", width=12)
|
|
222
|
+
meta.add_column(style="white")
|
|
223
|
+
meta.add_row("dataset", str(row["dataset"]))
|
|
224
|
+
meta.add_row("entity", str(row["entity_id"]))
|
|
225
|
+
meta.add_row("field", str(row["property_name"]))
|
|
226
|
+
|
|
227
|
+
source = _highlight_text(str(row["source_text"]), terms)
|
|
228
|
+
|
|
229
|
+
entities_table = Table(expand=True, box=None)
|
|
230
|
+
entities_table.add_column("#", style="bright_black", width=3)
|
|
231
|
+
entities_table.add_column("Schema", style="green", width=14)
|
|
232
|
+
entities_table.add_column("Name", style="bold")
|
|
233
|
+
entities_table.add_column("Alias", style="cyan")
|
|
234
|
+
entities_table.add_column("Abbr", style="magenta", width=14)
|
|
235
|
+
entities_table.add_column("Refs", style="yellow", width=14)
|
|
236
|
+
entities_table.add_column("Other", style="white")
|
|
237
|
+
|
|
238
|
+
if not entities:
|
|
239
|
+
entities_table.add_row("-", "-", "(none)", "-", "-", "-", "-")
|
|
240
|
+
else:
|
|
241
|
+
for entity_idx, entity in enumerate(entities, start=1):
|
|
242
|
+
if not isinstance(entity, dict):
|
|
243
|
+
entities_table.add_row(
|
|
244
|
+
str(entity_idx), "invalid", "-", "-", "-", "-", str(entity)
|
|
245
|
+
)
|
|
246
|
+
continue
|
|
247
|
+
|
|
248
|
+
props = entity.get("properties", {})
|
|
249
|
+
if not isinstance(props, dict):
|
|
250
|
+
props = {}
|
|
251
|
+
|
|
252
|
+
aliases = [v for v in props.get("alias", []) if isinstance(v, str)]
|
|
253
|
+
abbreviations = [
|
|
254
|
+
v for v in props.get("abbreviation", []) if isinstance(v, str)
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
refs: list[str] = []
|
|
258
|
+
other_parts: list[str] = []
|
|
259
|
+
for prop_name in sorted(props.keys()):
|
|
260
|
+
if prop_name in {"name", "alias", "abbreviation"}:
|
|
261
|
+
continue
|
|
262
|
+
values = [v for v in props.get(prop_name, []) if isinstance(v, str)]
|
|
263
|
+
if not values:
|
|
264
|
+
continue
|
|
265
|
+
prop_refs, prop_plain = _split_refs(values)
|
|
266
|
+
refs.extend(prop_refs)
|
|
267
|
+
if prop_plain:
|
|
268
|
+
other_parts.append(
|
|
269
|
+
f"{prop_name}={_join_values(prop_plain, max_items=2)}"
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
entities_table.add_row(
|
|
273
|
+
str(entity_idx),
|
|
274
|
+
str(entity.get("schema", "Unknown")),
|
|
275
|
+
_entity_name(entity),
|
|
276
|
+
_join_values(aliases),
|
|
277
|
+
_join_values(abbreviations),
|
|
278
|
+
_join_values(refs),
|
|
279
|
+
_join_values(other_parts, max_items=3),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
return Group(
|
|
283
|
+
header,
|
|
284
|
+
"",
|
|
285
|
+
meta,
|
|
286
|
+
"",
|
|
287
|
+
Text("Source text", style="bold bright_black"),
|
|
288
|
+
source,
|
|
289
|
+
"",
|
|
290
|
+
Text(f"Extracted entities ({len(entities)})", style="bold bright_black"),
|
|
291
|
+
entities_table,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class NERReviewState:
|
|
296
|
+
def __init__(self, conn: Connection, rows: list[RowMapping]):
|
|
297
|
+
self.conn = conn
|
|
298
|
+
self.rows = rows
|
|
299
|
+
self.index = 0
|
|
300
|
+
self.approved = 0
|
|
301
|
+
self.rejected = 0
|
|
302
|
+
self.skipped = 0
|
|
303
|
+
self.events: list[ReviewEvent] = []
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def total(self) -> int:
|
|
307
|
+
return len(self.rows)
|
|
308
|
+
|
|
309
|
+
@property
|
|
310
|
+
def current(self) -> Optional[RowMapping]:
|
|
311
|
+
if self.index >= self.total:
|
|
312
|
+
return None
|
|
313
|
+
return self.rows[self.index]
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def done(self) -> bool:
|
|
317
|
+
return self.current is None
|
|
318
|
+
|
|
319
|
+
def decide(self, action: str) -> None:
|
|
320
|
+
row = self.current
|
|
321
|
+
if row is None:
|
|
322
|
+
return
|
|
323
|
+
|
|
324
|
+
status = ACTION_TO_STATUS.get(action)
|
|
325
|
+
if status == "approved":
|
|
326
|
+
review_candidate(self.conn, row["id"], status=status)
|
|
327
|
+
self.approved += 1
|
|
328
|
+
elif status == "rejected":
|
|
329
|
+
review_candidate(self.conn, row["id"], status=status)
|
|
330
|
+
self.rejected += 1
|
|
331
|
+
else:
|
|
332
|
+
self.skipped += 1
|
|
333
|
+
|
|
334
|
+
self.events.append(
|
|
335
|
+
ReviewEvent(
|
|
336
|
+
candidate_id=row["id"],
|
|
337
|
+
action=action,
|
|
338
|
+
schema=str(row["schema"]),
|
|
339
|
+
when=datetime.now(UTC).strftime("%H:%M:%S"),
|
|
340
|
+
)
|
|
341
|
+
)
|
|
342
|
+
self.index += 1
|
|
343
|
+
|
|
344
|
+
def summary(self) -> dict[str, int]:
|
|
345
|
+
return {
|
|
346
|
+
"approved": self.approved,
|
|
347
|
+
"rejected": self.rejected,
|
|
348
|
+
"skipped": self.skipped,
|
|
349
|
+
"remaining": max(0, self.total - self.index),
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
def edit_current(self, extraction: list[dict[str, Any]]) -> None:
|
|
353
|
+
row = self.current
|
|
354
|
+
if row is None:
|
|
355
|
+
return
|
|
356
|
+
|
|
357
|
+
update_candidate_extraction(self.conn, row["id"], extraction)
|
|
358
|
+
refreshed = get_candidate(self.conn, row["id"])
|
|
359
|
+
if refreshed is not None:
|
|
360
|
+
self.rows[self.index] = refreshed
|
|
361
|
+
|
|
362
|
+
self.events.append(
|
|
363
|
+
ReviewEvent(
|
|
364
|
+
candidate_id=row["id"],
|
|
365
|
+
action="e",
|
|
366
|
+
schema=str(row["schema"]),
|
|
367
|
+
when=datetime.now(UTC).strftime("%H:%M:%S"),
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class ReviewWidget(Static):
|
|
373
|
+
def on_mount(self) -> None:
|
|
374
|
+
self.reload()
|
|
375
|
+
|
|
376
|
+
def reload(self) -> None:
|
|
377
|
+
app = self.app
|
|
378
|
+
assert isinstance(app, NERReviewApp)
|
|
379
|
+
if app.state.done:
|
|
380
|
+
self.update(Text("No pending candidates.", justify="center"))
|
|
381
|
+
return
|
|
382
|
+
row = app.state.current
|
|
383
|
+
assert row is not None
|
|
384
|
+
self.update(_render_candidate(row, app.state.index + 1, app.state.total))
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class HistoryWidget(Static):
|
|
388
|
+
is_visible = False
|
|
389
|
+
|
|
390
|
+
def on_mount(self) -> None:
|
|
391
|
+
self.border_title = "History"
|
|
392
|
+
self._apply_visibility()
|
|
393
|
+
self.reload()
|
|
394
|
+
|
|
395
|
+
def toggle_visible(self) -> None:
|
|
396
|
+
self.is_visible = not self.is_visible
|
|
397
|
+
self._apply_visibility()
|
|
398
|
+
|
|
399
|
+
def _apply_visibility(self) -> None:
|
|
400
|
+
self.styles.display = "block" if self.is_visible else "none"
|
|
401
|
+
|
|
402
|
+
def reload(self) -> None:
|
|
403
|
+
app = self.app
|
|
404
|
+
assert isinstance(app, NERReviewApp)
|
|
405
|
+
|
|
406
|
+
table = Table(expand=True, box=None)
|
|
407
|
+
table.add_column("When", style="bright_black", width=9)
|
|
408
|
+
table.add_column("ID", style="white", width=7)
|
|
409
|
+
table.add_column("Action", width=8)
|
|
410
|
+
table.add_column("Schema", style="bright_black")
|
|
411
|
+
|
|
412
|
+
action_style = {"x": "green", "n": "red", "u": "yellow", "e": "cyan"}
|
|
413
|
+
action_label = {"x": "approve", "n": "reject", "u": "skip", "e": "edit"}
|
|
414
|
+
|
|
415
|
+
for event in app.state.events[-25:]:
|
|
416
|
+
table.add_row(
|
|
417
|
+
event.when,
|
|
418
|
+
str(event.candidate_id),
|
|
419
|
+
Text(
|
|
420
|
+
action_label.get(event.action, event.action),
|
|
421
|
+
style=action_style.get(event.action, "white"),
|
|
422
|
+
),
|
|
423
|
+
event.schema,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
if not app.state.events:
|
|
427
|
+
table.add_row("-", "-", "-", "No actions yet")
|
|
428
|
+
self.update(table)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
class NERReviewApp(App[dict[str, int]]):
|
|
432
|
+
CSS = """
|
|
433
|
+
Screen {
|
|
434
|
+
layout: vertical;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
#main {
|
|
438
|
+
layout: horizontal;
|
|
439
|
+
height: 1fr;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
VerticalScroll {
|
|
443
|
+
width: 1fr;
|
|
444
|
+
border: solid white;
|
|
445
|
+
padding: 1;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
ReviewWidget {
|
|
449
|
+
width: 1fr;
|
|
450
|
+
height: auto;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
HistoryWidget {
|
|
454
|
+
width: 52;
|
|
455
|
+
border: solid white;
|
|
456
|
+
padding: 1;
|
|
457
|
+
}
|
|
458
|
+
"""
|
|
459
|
+
|
|
460
|
+
BINDINGS = [
|
|
461
|
+
("x", "approve", "Approve"),
|
|
462
|
+
("n", "reject", "Reject"),
|
|
463
|
+
("e", "edit", "Edit JSON"),
|
|
464
|
+
("u", "skip", "Skip"),
|
|
465
|
+
("h", "history", "Toggle History"),
|
|
466
|
+
("q", "quit_review", "Quit"),
|
|
467
|
+
]
|
|
468
|
+
|
|
469
|
+
def __init__(self, state: NERReviewState):
|
|
470
|
+
super().__init__()
|
|
471
|
+
self.state = state
|
|
472
|
+
|
|
473
|
+
def compose(self) -> ComposeResult:
|
|
474
|
+
self.title = "NER Review"
|
|
475
|
+
yield Horizontal(
|
|
476
|
+
VerticalScroll(ReviewWidget(), id="review"),
|
|
477
|
+
HistoryWidget(),
|
|
478
|
+
id="main",
|
|
479
|
+
)
|
|
480
|
+
yield Footer()
|
|
481
|
+
|
|
482
|
+
def _refresh(self) -> None:
|
|
483
|
+
review = self.query_one(ReviewWidget)
|
|
484
|
+
review.reload()
|
|
485
|
+
self.query_one("#review", VerticalScroll).scroll_home(animate=False)
|
|
486
|
+
history = self.query_one(HistoryWidget)
|
|
487
|
+
history.reload()
|
|
488
|
+
history.refresh(layout=True)
|
|
489
|
+
|
|
490
|
+
def _advance(self, action: str) -> None:
|
|
491
|
+
self.state.decide(action)
|
|
492
|
+
if self.state.done:
|
|
493
|
+
self.exit(self.state.summary())
|
|
494
|
+
return
|
|
495
|
+
self._refresh()
|
|
496
|
+
|
|
497
|
+
async def action_approve(self) -> None:
|
|
498
|
+
self._advance("x")
|
|
499
|
+
|
|
500
|
+
async def action_reject(self) -> None:
|
|
501
|
+
self._advance("n")
|
|
502
|
+
|
|
503
|
+
async def action_skip(self) -> None:
|
|
504
|
+
self._advance("u")
|
|
505
|
+
|
|
506
|
+
async def action_edit(self) -> None:
|
|
507
|
+
row = self.state.current
|
|
508
|
+
if row is None:
|
|
509
|
+
return
|
|
510
|
+
|
|
511
|
+
with self.suspend():
|
|
512
|
+
try:
|
|
513
|
+
entities = _parse_entities(row)
|
|
514
|
+
edited = _edit_entities_in_editor(entities)
|
|
515
|
+
except Exception as exc:
|
|
516
|
+
click.echo(click.style(f"Edit failed: {exc}", fg="red"))
|
|
517
|
+
return
|
|
518
|
+
|
|
519
|
+
if edited is None:
|
|
520
|
+
return
|
|
521
|
+
self.state.edit_current(edited)
|
|
522
|
+
self._refresh()
|
|
523
|
+
|
|
524
|
+
async def action_history(self) -> None:
|
|
525
|
+
history = self.query_one(HistoryWidget)
|
|
526
|
+
history.toggle_visible()
|
|
527
|
+
self._refresh()
|
|
528
|
+
|
|
529
|
+
async def action_quit_review(self) -> None:
|
|
530
|
+
self.exit(self.state.summary())
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _style_label(label: str) -> str:
|
|
534
|
+
return click.style(label, fg="bright_black", bold=True)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _print_entity(entity: dict[str, Any], index: int) -> None:
|
|
538
|
+
schema = entity.get("schema", "Unknown")
|
|
539
|
+
key = entity.get("key")
|
|
540
|
+
props = entity.get("properties", {})
|
|
541
|
+
if not isinstance(props, dict):
|
|
542
|
+
props = {}
|
|
543
|
+
|
|
544
|
+
heading = click.style(f"#{index} {schema}", fg="green", bold=True)
|
|
545
|
+
if key:
|
|
546
|
+
heading = f"{heading} {click.style(f'key={key}', fg='cyan')}"
|
|
547
|
+
click.echo(f" {heading}")
|
|
548
|
+
|
|
549
|
+
names = [v for v in props.get("name", []) if isinstance(v, str)]
|
|
550
|
+
aliases = [v for v in props.get("alias", []) if isinstance(v, str)]
|
|
551
|
+
abbreviations = [v for v in props.get("abbreviation", []) if isinstance(v, str)]
|
|
552
|
+
|
|
553
|
+
if names:
|
|
554
|
+
click.echo(f" {_style_label('name')} {_join_values(names)}")
|
|
555
|
+
if aliases:
|
|
556
|
+
click.echo(
|
|
557
|
+
f" {_style_label('alias')} {click.style(_join_values(aliases), fg='bright_cyan')}"
|
|
558
|
+
)
|
|
559
|
+
if abbreviations:
|
|
560
|
+
click.echo(
|
|
561
|
+
f" {_style_label('abbr')} {click.style(_join_values(abbreviations), fg='magenta')}"
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
for prop_name in sorted(props):
|
|
565
|
+
if prop_name in {"name", "alias", "abbreviation"}:
|
|
566
|
+
continue
|
|
567
|
+
values = [v for v in props.get(prop_name, []) if isinstance(v, str)]
|
|
568
|
+
if not values:
|
|
569
|
+
continue
|
|
570
|
+
refs, plain = _split_refs(values)
|
|
571
|
+
if refs:
|
|
572
|
+
click.echo(
|
|
573
|
+
f" {_style_label(prop_name)} {click.style(_join_values(refs), fg='yellow')}"
|
|
574
|
+
)
|
|
575
|
+
if plain:
|
|
576
|
+
click.echo(f" {_style_label(prop_name)} {_join_values(plain)}")
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _print_candidate(row: RowMapping, index: int, total: int) -> None:
|
|
580
|
+
entities = _parse_entities(row)
|
|
581
|
+
terms: list[str] = []
|
|
582
|
+
for entity in entities:
|
|
583
|
+
if isinstance(entity, dict):
|
|
584
|
+
terms.extend(_collect_highlight_terms(entity))
|
|
585
|
+
|
|
586
|
+
click.echo("\n" + click.style("=" * 88, fg="bright_black"))
|
|
587
|
+
click.echo(
|
|
588
|
+
click.style(f"[{index}/{total}] Candidate #{row['id']}", fg="white", bold=True)
|
|
589
|
+
+ f" {_style_label('dataset')} {row['dataset']}"
|
|
590
|
+
)
|
|
591
|
+
click.echo(
|
|
592
|
+
f"{_style_label('source')} {row['entity_id']}"
|
|
593
|
+
f" {_style_label('field')} {row['property_name']}"
|
|
594
|
+
)
|
|
595
|
+
click.echo(_style_label("source text"))
|
|
596
|
+
source_text = _highlight_terms(str(row["source_text"]), terms)
|
|
597
|
+
for line in textwrap.wrap(source_text, width=88, break_long_words=False):
|
|
598
|
+
click.echo(f" {line}")
|
|
599
|
+
|
|
600
|
+
click.echo(
|
|
601
|
+
f"{_style_label('extracted entities')} {click.style(str(len(entities)), fg='green', bold=True)}"
|
|
602
|
+
)
|
|
603
|
+
if not entities:
|
|
604
|
+
click.echo(" - (none)")
|
|
605
|
+
return
|
|
606
|
+
|
|
607
|
+
for entity_idx, entity in enumerate(entities, start=1):
|
|
608
|
+
if isinstance(entity, dict):
|
|
609
|
+
_print_entity(entity, entity_idx)
|
|
610
|
+
else:
|
|
611
|
+
click.echo(f" {entity_idx}. {entity}")
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _run_prompt_review(conn: Connection, rows: list[RowMapping]) -> dict[str, int]:
|
|
615
|
+
approved = 0
|
|
616
|
+
rejected = 0
|
|
617
|
+
skipped = 0
|
|
618
|
+
total = len(rows)
|
|
619
|
+
|
|
620
|
+
idx = 0
|
|
621
|
+
while idx < total:
|
|
622
|
+
row = rows[idx]
|
|
623
|
+
_print_candidate(row, idx + 1, total)
|
|
624
|
+
action = click.prompt(
|
|
625
|
+
"Action: [x] approve, [n] reject, [e] edit, [u] skip, [q] quit",
|
|
626
|
+
type=click.Choice(sorted(ACTION_TO_STATUS), case_sensitive=False),
|
|
627
|
+
default="x",
|
|
628
|
+
show_choices=False,
|
|
629
|
+
).lower()
|
|
630
|
+
|
|
631
|
+
if action == "q":
|
|
632
|
+
break
|
|
633
|
+
|
|
634
|
+
if action == "e":
|
|
635
|
+
entities = _parse_entities(row)
|
|
636
|
+
try:
|
|
637
|
+
edited = _edit_entities_in_editor(entities)
|
|
638
|
+
except Exception as exc:
|
|
639
|
+
click.echo(click.style(f"Edit failed: {exc}", fg="red"))
|
|
640
|
+
continue
|
|
641
|
+
|
|
642
|
+
if edited is None:
|
|
643
|
+
continue
|
|
644
|
+
|
|
645
|
+
update_candidate_extraction(conn, row["id"], edited)
|
|
646
|
+
refreshed = get_candidate(conn, row["id"])
|
|
647
|
+
if refreshed is not None:
|
|
648
|
+
rows[idx] = refreshed
|
|
649
|
+
click.echo(click.style("Saved edited extraction.", fg="green"))
|
|
650
|
+
continue
|
|
651
|
+
|
|
652
|
+
status = ACTION_TO_STATUS[action]
|
|
653
|
+
if status == "approved":
|
|
654
|
+
review_candidate(conn, row["id"], status=status)
|
|
655
|
+
approved += 1
|
|
656
|
+
elif status == "rejected":
|
|
657
|
+
review_candidate(conn, row["id"], status=status)
|
|
658
|
+
rejected += 1
|
|
659
|
+
else:
|
|
660
|
+
skipped += 1
|
|
661
|
+
idx += 1
|
|
662
|
+
|
|
663
|
+
return {
|
|
664
|
+
"approved": approved,
|
|
665
|
+
"rejected": rejected,
|
|
666
|
+
"skipped": skipped,
|
|
667
|
+
"remaining": max(0, total - (approved + rejected + skipped)),
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _run_tui_review(conn: Connection, rows: list[RowMapping]) -> dict[str, int]:
|
|
672
|
+
state = NERReviewState(conn, rows)
|
|
673
|
+
app = NERReviewApp(state)
|
|
674
|
+
result = app.run()
|
|
675
|
+
if result is None:
|
|
676
|
+
return state.summary()
|
|
677
|
+
return result
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def run_ner_review(
|
|
681
|
+
dataset_name: Optional[str] = None, limit: Optional[int] = None
|
|
682
|
+
) -> None:
|
|
683
|
+
conn = get_connection()
|
|
684
|
+
init_db(conn)
|
|
685
|
+
rows = list_candidates(
|
|
686
|
+
conn, dataset_name=dataset_name, status="pending", limit=limit
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
if not rows:
|
|
690
|
+
click.echo("No pending NER candidates to review.")
|
|
691
|
+
conn.close()
|
|
692
|
+
return
|
|
693
|
+
|
|
694
|
+
if sys.stdout.isatty() and sys.stdin.isatty():
|
|
695
|
+
summary = _run_tui_review(conn, rows)
|
|
696
|
+
else:
|
|
697
|
+
summary = _run_prompt_review(conn, rows)
|
|
698
|
+
|
|
699
|
+
conn.close()
|
|
700
|
+
click.echo(
|
|
701
|
+
"\nReview complete. "
|
|
702
|
+
f"approved={summary['approved']} "
|
|
703
|
+
f"rejected={summary['rejected']} "
|
|
704
|
+
f"skipped={summary['skipped']} "
|
|
705
|
+
f"remaining={summary['remaining']}"
|
|
706
|
+
)
|