dsh-auto-ontology 0.2.2 → 0.3.0
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.
- package/README.md +11 -0
- package/bin/auto-ontology.js +7 -1
- package/lib/index.js +66 -14
- package/package.json +2 -2
- package/scripts/adversarial_cases.json +119 -0
- package/scripts/build_ontology.py +788 -133
- package/scripts/eval_evidence.py +309 -58
- package/scripts/grounding.py +198 -0
- package/scripts/trajectory.py +148 -0
- package/scripts/validate_format.py +69 -12
- package/scripts/weknora_bridge.py +11 -3
- package/skills/dsh-auto-ontology/SKILL.md +23 -3
|
@@ -19,15 +19,24 @@ coreference, and conflicts (issues #5 #6 #7 #8):
|
|
|
19
19
|
is never edited or dropped (append-only across runs)
|
|
20
20
|
cost: per-call usage accounting + --max-calls hard cap; every artifact
|
|
21
21
|
carries provenance (model/temp/elapsed/calls/tokens)
|
|
22
|
+
kb: --kb reads a WeKnora knowledge base instead of files — one chunk is
|
|
23
|
+
one document, and every quote carries its chunk id (#56)
|
|
22
24
|
|
|
23
25
|
Usage:
|
|
24
26
|
python3 scripts/build_ontology.py --docs <dir_or_glob> --domain "..." --save [--lang zh]
|
|
27
|
+
python3 scripts/build_ontology.py --kb <weknora-kb-id> --domain "..." --save [--limit N]
|
|
25
28
|
python3 scripts/build_ontology.py --docs <new> --domain "..." --merge ontologies/old.json --save
|
|
26
29
|
python3 scripts/build_ontology.py --query "WrenAI" [--from ontologies/x.json]
|
|
30
|
+
python3 scripts/build_ontology.py --trajectory [--from ontologies/x.json] [more.json ...] [--out traj.ndjson]
|
|
31
|
+
python3 scripts/build_ontology.py --proposals run.proposals.json --actor agent:NAME [--from ontologies/x.json]
|
|
27
32
|
"""
|
|
28
|
-
import argparse, datetime as dt, glob, json, math, os, re,
|
|
33
|
+
import argparse, concurrent.futures as cf, datetime as dt, glob, json, math, os, re, sys, threading, time
|
|
34
|
+
import urllib.error, urllib.request
|
|
35
|
+
from xml.sax.saxutils import escape
|
|
29
36
|
|
|
30
37
|
KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
38
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
39
|
+
import grounding
|
|
31
40
|
|
|
32
41
|
# Output language: English by default (international-first), --lang zh / ONTOLOGY_LANG for Chinese
|
|
33
42
|
LANG = os.environ.get("ONTOLOGY_LANG") or "en"
|
|
@@ -37,42 +46,57 @@ def tt(en, zh):
|
|
|
37
46
|
# npm CLI form lands artifacts in the caller's cwd via ONTOLOGY_HOME (repo default unchanged)
|
|
38
47
|
OUTDIR = os.environ.get("ONTOLOGY_HOME") or os.path.join(KIT, "ontologies")
|
|
39
48
|
|
|
49
|
+
|
|
50
|
+
def newest_artifact():
|
|
51
|
+
"""The newest artifact in OUTDIR — a plain message when there is none, not a traceback."""
|
|
52
|
+
files = sorted(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
|
|
53
|
+
if not files:
|
|
54
|
+
sys.exit(tt(f"no ontology artifact in {OUTDIR} — pass --from, or build one first",
|
|
55
|
+
f"{OUTDIR} 里没有本体工件——请用 --from 指定,或先构建"))
|
|
56
|
+
return files[-1]
|
|
57
|
+
|
|
40
58
|
COST = {"calls": 0, "in": 0, "out": 0}
|
|
41
59
|
MAX_CALLS = None
|
|
60
|
+
_LOCK = threading.Lock() # the judge calls run concurrently; the ledger and the guard do not race
|
|
42
61
|
|
|
43
62
|
|
|
44
63
|
def _key(s):
|
|
45
|
-
"""Name-matching key: case/punctuation-insensitive
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
64
|
+
"""Name-matching key: case/punctuation/whitespace-insensitive, script-agnostic
|
|
65
|
+
(ASCII-only stripping used to drop CJK-named entities and collapse CJK relations)."""
|
|
66
|
+
return re.sub(r"[\W_]+", "", str(s).lower())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
MODEL = os.environ.get("ONTOLOGY_MODEL") or "deepseek-chat"
|
|
70
|
+
JUDGE_MODEL = MODEL # set by --judge-model / ONTOLOGY_JUDGE_MODEL in main()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _reserved_usage(u):
|
|
74
|
+
"""Token accounting for a call whose `calls` slot llm() reserved before it started."""
|
|
75
|
+
with _LOCK:
|
|
76
|
+
COST["in"] += int(u.get("prompt_tokens") or 0)
|
|
77
|
+
COST["out"] += int(u.get("completion_tokens") or 0)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def llm(sysmsg, user, json_out=True, model=None):
|
|
81
|
+
"""Every LLM request of a run goes through here: cost guard first — the call is reserved
|
|
82
|
+
under the lock, so concurrent judge calls cannot overshoot the cap — then one retried
|
|
83
|
+
call; each answered attempt lands its tokens in the ledger."""
|
|
84
|
+
with _LOCK:
|
|
85
|
+
if MAX_CALLS is not None and COST["calls"] >= MAX_CALLS:
|
|
86
|
+
raise SystemExit(f"cost guard: {MAX_CALLS} LLM calls reached (--max-calls)")
|
|
87
|
+
COST["calls"] += 1
|
|
88
|
+
out, _ = grounding.complete(model or MODEL, [{"role": "system", "content": sysmsg},
|
|
89
|
+
{"role": "user", "content": user}],
|
|
90
|
+
json_out=json_out, account=_reserved_usage)
|
|
91
|
+
return out
|
|
68
92
|
|
|
69
93
|
|
|
70
94
|
# ── the fold store (pure; unit-tested in CI) ────────────────────────────────
|
|
71
95
|
|
|
72
96
|
def new_store(domain):
|
|
73
97
|
return {"domain": domain, "entities": {}, "relations": {}, "conflicts": [],
|
|
74
|
-
"flagged": [], "tbox_types": set(), "tbox_relations": {}, "merge_log": [],
|
|
75
|
-
"certifications": {}, "suppressed": 0}
|
|
98
|
+
"flagged": [], "tbox_types": set(), "type_descs": {}, "tbox_relations": {}, "merge_log": [],
|
|
99
|
+
"certifications": {}, "suppressed": 0, "flagged_ungrounded": []}
|
|
76
100
|
|
|
77
101
|
|
|
78
102
|
def load_store(o):
|
|
@@ -80,6 +104,7 @@ def load_store(o):
|
|
|
80
104
|
st = new_store(o.get("domain", "?"))
|
|
81
105
|
for t in o.get("tbox", {}).get("entity_types", []):
|
|
82
106
|
st["tbox_types"].add(t["name"])
|
|
107
|
+
st["type_descs"][t["name"]] = t.get("desc", "")
|
|
83
108
|
for r in o.get("tbox", {}).get("relation_types", []):
|
|
84
109
|
st["tbox_relations"][(r.get("name"), r.get("domains"), r.get("ranges"))] = r
|
|
85
110
|
for e in o.get("abox", {}).get("entities", []):
|
|
@@ -90,6 +115,10 @@ def load_store(o):
|
|
|
90
115
|
"docs": sorted(docs), "evidences": []}
|
|
91
116
|
for ev in evs:
|
|
92
117
|
_fold_ev(st["entities"][_key(e["name"])]["evidences"], ev)
|
|
118
|
+
# a writer that flagged the assertion but not its evidences keeps its verdict on reload
|
|
119
|
+
if e.get("type_grounding") is False and not any("grounded" in x for x in st["entities"][_key(e["name"])]["evidences"]):
|
|
120
|
+
for x in st["entities"][_key(e["name"])]["evidences"]:
|
|
121
|
+
x["grounded"] = False
|
|
93
122
|
for r in o.get("abox", {}).get("relations", []):
|
|
94
123
|
evs = r.get("evidences") or [{"quote": r.get("evidence", ""), "doc": r.get("doc", "?")}]
|
|
95
124
|
docs = set(r.get("docs", [])) | ({r["doc"]} if r.get("doc") and r["doc"] != "?" else set())
|
|
@@ -98,14 +127,19 @@ def load_store(o):
|
|
|
98
127
|
"docs": sorted(docs), "evidences": []}
|
|
99
128
|
for ev in evs:
|
|
100
129
|
_fold_ev(st["relations"][k]["evidences"], ev)
|
|
130
|
+
if r.get("grounding") is False and not any("grounded" in x for x in st["relations"][k]["evidences"]):
|
|
131
|
+
for x in st["relations"][k]["evidences"]:
|
|
132
|
+
x["grounded"] = False
|
|
101
133
|
st["conflicts"] = list(o.get("conflicts", []))
|
|
102
134
|
st["flagged"] = list(o.get("flagged_unknown_types", []))
|
|
135
|
+
st["flagged_ungrounded"] = list(o.get("flagged_ungrounded", []))
|
|
103
136
|
st["merge_log"] = list(o.get("merge_log", []))
|
|
104
|
-
|
|
137
|
+
# re-key by the certified name so a key-scheme change never orphans a verdict
|
|
138
|
+
st["certifications"] = {_key(c.get("name", k)): c for k, c in o.get("certifications", {}).items()}
|
|
105
139
|
st["suppressed"] = 0
|
|
106
140
|
return st
|
|
107
141
|
|
|
108
|
-
def certify(o, name, verdict, note=""):
|
|
142
|
+
def certify(o, name, verdict, note="", actor=None):
|
|
109
143
|
"""Human verdict on an entity (issue #13, the upstream Learn pillar,
|
|
110
144
|
evidence-first version): record travels WITH the ontology (portable artifact).
|
|
111
145
|
rejected — the (name, type) pair is suppressed in every later fold; the
|
|
@@ -113,64 +147,203 @@ def certify(o, name, verdict, note=""):
|
|
|
113
147
|
type re-asserting the same name is a NEW assertion and re-enters (the
|
|
114
148
|
rejection was about that typing, not the string).
|
|
115
149
|
accepted — the entity is marked trusted; conflicts against it still get
|
|
116
|
-
recorded (they are never silently resolved), the mark is the human word.
|
|
150
|
+
recorded (they are never silently resolved), the mark is the human word.
|
|
151
|
+
`actor` names who issued the verdict — an agent applying one must say so."""
|
|
117
152
|
st = load_store(o)
|
|
118
153
|
k = _key(name)
|
|
119
154
|
e = st["entities"].get(k)
|
|
120
155
|
if e is None:
|
|
121
156
|
raise SystemExit(tt(f"no such entity: {name}", f"无此实体:{name}"))
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
157
|
+
rec = {"name": e["name"], "type": e["type"], "verdict": verdict, "at":
|
|
158
|
+
dt.datetime.now().isoformat(timespec="seconds"), "note": note,
|
|
159
|
+
"evidence": _strongest(e["evidences"])[0] if e["evidences"] else {}}
|
|
160
|
+
if actor:
|
|
161
|
+
rec["actor"] = actor
|
|
162
|
+
o.setdefault("certifications", {})[k] = rec
|
|
126
163
|
if verdict == "reject":
|
|
127
164
|
del st["entities"][k]
|
|
128
165
|
st["relations"] = {rk: r for rk, r in st["relations"].items()
|
|
129
166
|
if _key(r["subject"]) != k and _key(r["object"]) != k}
|
|
130
|
-
o
|
|
131
|
-
"relations": sorted(st["relations"].values(),
|
|
132
|
-
key=lambda r: (r["subject"].lower(), r["predicate"]))}
|
|
133
|
-
o["stats"]["entities"] = len(st["entities"])
|
|
134
|
-
o["stats"]["relations"] = len(st["relations"])
|
|
167
|
+
_refresh(o, st)
|
|
135
168
|
return o
|
|
136
169
|
|
|
137
170
|
|
|
171
|
+
def apply_proposals(o, doc, actor=None):
|
|
172
|
+
"""Re-type entities from a judge's grounded proposals — the trip back from
|
|
173
|
+
dsh-EvoOntology's adapter. `doc` is its runs/<run>.proposals.json ({run_id,
|
|
174
|
+
judge_model, proposals: [...]}) or a bare proposal list. Recorded, never a
|
|
175
|
+
silent edit:
|
|
176
|
+
• only a proposal marked grounded is applied; the rest are counted;
|
|
177
|
+
• a stale one (entity gone, typed differently since) is skipped and counted;
|
|
178
|
+
• a type outside the TBox is never asserted — skipped and counted;
|
|
179
|
+
• an entity whose latest certification was not issued by an agent is not
|
|
180
|
+
touched — a human verdict is not overwritten by a machine's;
|
|
181
|
+
• applied = a reject certification on the OLD typing (actor, note, and
|
|
182
|
+
`retyped_to` naming the new type and the quote) + a NEW assertion of the
|
|
183
|
+
new type carrying the one quote the judge grounded — with the judge's
|
|
184
|
+
name and reason on it; the entity's other quotes follow unjudged (their
|
|
185
|
+
verdicts were about the old typing); every relation it endpoints is
|
|
186
|
+
folded back exactly as it was;
|
|
187
|
+
• a name re-typed a second time keeps rejecting its first typing too
|
|
188
|
+
(`also_rejects`): one certification per name would otherwise let that
|
|
189
|
+
typing back in on the next fold.
|
|
190
|
+
-> (o, report)"""
|
|
191
|
+
st = load_store(o)
|
|
192
|
+
meta = doc if isinstance(doc, dict) else {}
|
|
193
|
+
props = (doc.get("proposals") or []) if isinstance(doc, dict) else doc
|
|
194
|
+
rep = {"applied": [], "stale": [], "human_certified": [], "off_tbox": [], "not_grounded": 0}
|
|
195
|
+
for p in props:
|
|
196
|
+
if p.get("grounded") is not True:
|
|
197
|
+
rep["not_grounded"] += 1
|
|
198
|
+
continue
|
|
199
|
+
k = _key(p.get("name"))
|
|
200
|
+
e = st["entities"].get(k)
|
|
201
|
+
if e is None or e["type"] != p.get("from_type") or not p.get("quote"):
|
|
202
|
+
rep["stale"].append(p.get("name"))
|
|
203
|
+
continue
|
|
204
|
+
if p.get("to_type") not in st["tbox_types"]:
|
|
205
|
+
rep["off_tbox"].append(e["name"])
|
|
206
|
+
continue
|
|
207
|
+
cert = st.get("certifications", {}).get(k)
|
|
208
|
+
if cert and not str(cert.get("actor", "")).startswith("agent"):
|
|
209
|
+
rep["human_certified"].append(e["name"])
|
|
210
|
+
continue
|
|
211
|
+
old_type, to = e["type"], p["to_type"]
|
|
212
|
+
# a second re-typing: the certification being replaced rejected the typing the name has now
|
|
213
|
+
chain = ([cert["type"], *cert.get("also_rejects", [])]
|
|
214
|
+
if cert and cert.get("verdict") == "reject" and (cert.get("retyped_to") or {}).get("type") == old_type
|
|
215
|
+
else [])
|
|
216
|
+
olds = [dict(x) for x in e["evidences"]]
|
|
217
|
+
aliases, docs = list(e.get("aliases", [])), list(e.get("docs", []))
|
|
218
|
+
rels = [(r["subject"], r["predicate"], r["object"], [dict(x) for x in r["evidences"]], list(r.get("docs", [])))
|
|
219
|
+
for rk, r in st["relations"].items() if k in (rk[0], rk[2])]
|
|
220
|
+
judge = p.get("judge") or meta.get("judge_model") or "?"
|
|
221
|
+
judge_reason = p.get("judge_reason") or p.get("reason")
|
|
222
|
+
rec = {
|
|
223
|
+
"name": e["name"], "type": old_type, "verdict": "reject",
|
|
224
|
+
"at": dt.datetime.now().isoformat(timespec="seconds"),
|
|
225
|
+
"note": f"re-typed as {to}: judge {judge} grounded another quote",
|
|
226
|
+
"evidence": dict(_strongest(olds)[0]) if olds else {},
|
|
227
|
+
**({"actor": actor} if actor else {}),
|
|
228
|
+
"retyped_to": {"type": to, "quote": p["quote"], "doc": p.get("doc", "?"), "judge": judge,
|
|
229
|
+
**({"run": meta["run_id"]} if meta.get("run_id") else {}),
|
|
230
|
+
**({"reason": judge_reason} if judge_reason else {}),
|
|
231
|
+
**({"chunk_id": p["chunk_id"]} if p.get("chunk_id") else {})},
|
|
232
|
+
**({"also_rejects": chain} if chain else {})}
|
|
233
|
+
st["certifications"][k] = o.setdefault("certifications", {})[k] = rec # the artifact carries the verdict
|
|
234
|
+
for rk in [rk for rk in st["relations"] if k in (rk[0], rk[2])]:
|
|
235
|
+
del st["relations"][rk]
|
|
236
|
+
del st["entities"][k]
|
|
237
|
+
fold_entity(st, e["name"], to, p["quote"], p.get("doc", "?"), grounded=True, reason=judge_reason,
|
|
238
|
+
judge=None if judge == "?" else judge, chunk_id=p.get("chunk_id"))
|
|
239
|
+
new = st["entities"][k]
|
|
240
|
+
for x in olds:
|
|
241
|
+
if x["quote"] != p["quote"]:
|
|
242
|
+
_fold_ev(new["evidences"], {a: x[a] for a in ("quote", "doc", "chunk_id") if a in x})
|
|
243
|
+
new["aliases"], new["docs"] = aliases, sorted(set(docs) | set(new["docs"]))
|
|
244
|
+
for sub, pred, obj, evs, rdocs in rels:
|
|
245
|
+
for x in evs:
|
|
246
|
+
fold_relation(st, sub, pred, obj, x["quote"], x["doc"],
|
|
247
|
+
**{a: x[a] for a in ("grounded", "reason", "judge", "chunk_id") if a in x})
|
|
248
|
+
st["relations"][_key(sub), pred, _key(obj)]["docs"] = rdocs
|
|
249
|
+
rep["applied"].append({"name": e["name"], "from_type": old_type, "to_type": to,
|
|
250
|
+
"quote": p["quote"], "relations": len(rels)})
|
|
251
|
+
if rep["applied"]:
|
|
252
|
+
_refresh(o, st)
|
|
253
|
+
return o, rep
|
|
254
|
+
|
|
255
|
+
|
|
138
256
|
def _fold_ev(evs, ev):
|
|
139
257
|
if isinstance(ev, str):
|
|
140
258
|
ev = {"quote": ev, "doc": "?"}
|
|
141
259
|
q, d = ev.get("quote", ""), ev.get("doc", "?")
|
|
142
260
|
if q and not any(e["quote"] == q for e in evs):
|
|
143
|
-
|
|
261
|
+
item = {"quote": q, "doc": d}
|
|
262
|
+
for k in ("grounded", "reason", "judge", "chunk_id"):
|
|
263
|
+
if k in ev:
|
|
264
|
+
item[k] = ev[k]
|
|
265
|
+
evs.append(item)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _flag(evs):
|
|
269
|
+
"""The grounding flag of an assertion, derived from its evidences: True — some
|
|
270
|
+
carried quote grounds the claim; False — judged, and none does; None — never judged."""
|
|
271
|
+
if any(e.get("grounded") is True for e in evs):
|
|
272
|
+
return True
|
|
273
|
+
if evs and all(e.get("grounded") is False for e in evs):
|
|
274
|
+
return False
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _strongest(evs):
|
|
279
|
+
"""Presentation order — stable, so fold order holds inside each class: a grounded
|
|
280
|
+
quote first, an unjudged one next, an ungrounded one last. Nothing is edited or
|
|
281
|
+
dropped; evidences[0] is simply the best quote the assertion carries."""
|
|
282
|
+
return sorted(evs, key=lambda e: {True: 0, None: 1, False: 2}[e.get("grounded")])
|
|
283
|
+
|
|
144
284
|
|
|
285
|
+
def _flag_ungrounded(st, cur, etype, quote, doc, chunk_id=None):
|
|
286
|
+
"""A different-type challenger whose own quote does not ground it is no evidence
|
|
287
|
+
of a conflict — it is a guess. Kept and flagged, never promoted on its own."""
|
|
288
|
+
if not any(f["entity"] == cur["name"] and f["asserted_type"] == etype and f["evidence"]["quote"] == quote
|
|
289
|
+
for f in st["flagged_ungrounded"]):
|
|
290
|
+
st["flagged_ungrounded"].append({"entity": cur["name"], "existing_type": cur["type"],
|
|
291
|
+
"asserted_type": etype,
|
|
292
|
+
"evidence": {"quote": quote, "doc": doc, **({"chunk_id": chunk_id} if chunk_id else {})}})
|
|
145
293
|
|
|
146
|
-
|
|
294
|
+
|
|
295
|
+
def _ev(quote, doc, grounded=None, reason=None, judge=None, chunk_id=None):
|
|
296
|
+
"""A fold's evidence: the build's verdict rides on it when one was given. The build
|
|
297
|
+
keeps a judge's reason only for a quote it rejected; `judge` is set by the one path
|
|
298
|
+
that folds a quote judged outside a build (`apply --proposals`), which keeps the
|
|
299
|
+
reason for a grounded quote too. `chunk_id` is where a --kb build read the quote."""
|
|
300
|
+
ev = {"quote": quote, "doc": doc}
|
|
301
|
+
if grounded is not None:
|
|
302
|
+
ev["grounded"] = grounded
|
|
303
|
+
if reason and (grounded is False or judge):
|
|
304
|
+
ev["reason"] = reason
|
|
305
|
+
if judge:
|
|
306
|
+
ev["judge"] = judge
|
|
307
|
+
if chunk_id:
|
|
308
|
+
ev["chunk_id"] = chunk_id
|
|
309
|
+
return ev
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def fold_entity(st, name, etype, quote, doc, grounded=None, reason=None, judge=None, chunk_id=None):
|
|
147
313
|
"""Append-only entity fold; the same name under a different type => conflict
|
|
148
314
|
holding BOTH evidences — recorded, never silently resolved. A rejected
|
|
149
|
-
certification suppresses the (name, type) pair — counted, never re-asserted
|
|
315
|
+
certification suppresses the (name, type) pair — counted, never re-asserted,
|
|
316
|
+
and a re-typed name's earlier typings with it (`also_rejects`).
|
|
317
|
+
`grounded` is the build's verdict on this quote (None = never judged); `judge`
|
|
318
|
+
and `chunk_id` ride onto the evidence (_ev)."""
|
|
150
319
|
k = _key(name)
|
|
151
320
|
if not k:
|
|
152
321
|
return
|
|
153
322
|
cert = st.get("certifications", {}).get(k)
|
|
154
|
-
if cert and cert.get("verdict") == "reject" and cert.get("type") == etype:
|
|
323
|
+
if cert and cert.get("verdict") == "reject" and (cert.get("type") == etype or etype in (cert.get("also_rejects") or [])):
|
|
155
324
|
st["suppressed"] = st.get("suppressed", 0) + 1
|
|
156
325
|
return
|
|
157
326
|
cur = st["entities"].get(k)
|
|
327
|
+
ev = _ev(quote, doc, grounded, reason, judge, chunk_id)
|
|
158
328
|
if cur is None:
|
|
159
329
|
st["entities"][k] = {"name": name, "type": etype, "aliases": [],
|
|
160
|
-
"docs": [doc] if doc != "?" else [],
|
|
161
|
-
"evidences": [{"quote": quote, "doc": doc}]}
|
|
330
|
+
"docs": [doc] if doc != "?" else [], "evidences": [ev]}
|
|
162
331
|
return
|
|
163
332
|
if cur["type"] != etype:
|
|
333
|
+
if grounded is False:
|
|
334
|
+
_flag_ungrounded(st, cur, etype, quote, doc, chunk_id)
|
|
335
|
+
return
|
|
164
336
|
st["conflicts"].append({"entity": cur["name"], "types": {
|
|
165
|
-
cur["type"]: cur["evidences"][0] if cur["evidences"] else {"quote": "", "doc": "?"},
|
|
166
|
-
etype:
|
|
337
|
+
cur["type"]: dict(_strongest(cur["evidences"])[0]) if cur["evidences"] else {"quote": "", "doc": "?"},
|
|
338
|
+
etype: dict(ev)}})
|
|
167
339
|
return
|
|
168
|
-
_fold_ev(cur["evidences"],
|
|
340
|
+
_fold_ev(cur["evidences"], ev)
|
|
169
341
|
if doc != "?":
|
|
170
342
|
cur["docs"] = sorted(set(cur["docs"]) | {doc})
|
|
171
343
|
|
|
172
344
|
|
|
173
|
-
def fold_relation(st, subject, predicate, obj, quote, doc, alias_map=None
|
|
345
|
+
def fold_relation(st, subject, predicate, obj, quote, doc, alias_map=None, grounded=None, reason=None, judge=None,
|
|
346
|
+
chunk_id=None):
|
|
174
347
|
if alias_map: # canonicalize endpoints through the coref result before folding
|
|
175
348
|
subject = alias_map.get(_key(subject), subject)
|
|
176
349
|
obj = alias_map.get(_key(obj), obj)
|
|
@@ -178,12 +351,12 @@ def fold_relation(st, subject, predicate, obj, quote, doc, alias_map=None):
|
|
|
178
351
|
return
|
|
179
352
|
k = (_key(subject), predicate, _key(obj))
|
|
180
353
|
cur = st["relations"].get(k)
|
|
354
|
+
ev = _ev(quote, doc, grounded, reason, judge, chunk_id)
|
|
181
355
|
if cur is None:
|
|
182
356
|
st["relations"][k] = {"subject": subject, "predicate": predicate, "object": obj,
|
|
183
|
-
"docs": [doc] if doc != "?" else [],
|
|
184
|
-
"evidences": [{"quote": quote, "doc": doc}]}
|
|
357
|
+
"docs": [doc] if doc != "?" else [], "evidences": [ev]}
|
|
185
358
|
return
|
|
186
|
-
_fold_ev(cur["evidences"],
|
|
359
|
+
_fold_ev(cur["evidences"], ev)
|
|
187
360
|
if doc != "?":
|
|
188
361
|
cur["docs"] = sorted(set(cur["docs"]) | {doc})
|
|
189
362
|
|
|
@@ -236,18 +409,32 @@ def query_ontology(o, term):
|
|
|
236
409
|
return hits
|
|
237
410
|
|
|
238
411
|
|
|
412
|
+
def _mark(x, key):
|
|
413
|
+
"""Digest marker of an assertion's grounding flag: ✓ grounded · ⚠ ungrounded · none = never judged."""
|
|
414
|
+
return {True: " ✓", False: " ⚠"}.get(x.get(key), "")
|
|
415
|
+
|
|
416
|
+
|
|
239
417
|
def to_markdown(o):
|
|
240
418
|
"""Ontology v2 -> shareable markdown digest (issue #12): stats + provenance,
|
|
241
419
|
conflicts table, entities by type, relations with evidence quotes."""
|
|
242
420
|
from collections import defaultdict
|
|
243
421
|
st = o.get("stats", {})
|
|
244
422
|
prov = o.get("provenance", {})
|
|
423
|
+
kb = prov.get("kb") or {}
|
|
245
424
|
L = [f"# Ontology · {o.get('domain', '?')}", "",
|
|
246
425
|
f"- **{st.get('entities', 0)} entities · {st.get('relations', 0)} relations · "
|
|
247
426
|
f"{st.get('conflicts', 0)} conflicts · {st.get('flagged', 0)} unknown types flagged**",
|
|
248
427
|
f"- provenance: {prov.get('model', '?')} · {prov.get('calls', '?')} calls · "
|
|
249
428
|
f"{prov.get('tokens_in', 0):,} in / {prov.get('tokens_out', 0):,} out tokens · "
|
|
250
|
-
f"{prov.get('elapsed_s', '?')}s · built {o.get('built_at', '?')}"
|
|
429
|
+
f"{prov.get('elapsed_s', '?')}s · built {o.get('built_at', '?')}"
|
|
430
|
+
+ (f" · knowledge base {kb['id']}: {kb['chunks']} chunk(s) of {kb['documents']} document(s)" if kb else "")]
|
|
431
|
+
if sum(st.get(k, 0) for k in ("entities_grounded", "entities_ungrounded",
|
|
432
|
+
"relations_grounded", "relations_ungrounded")):
|
|
433
|
+
L.append(f"- type grounding (judged at build time): entities {st.get('entities_grounded', 0)} grounded · "
|
|
434
|
+
f"{st.get('entities_ungrounded', 0)} ungrounded; relations {st.get('relations_grounded', 0)} grounded · "
|
|
435
|
+
f"{st.get('relations_ungrounded', 0)} ungrounded — ✓ the best carried quote grounds the claim; "
|
|
436
|
+
"⚠ no carried quote grounds it (kept and flagged, never dropped)")
|
|
437
|
+
L.append("")
|
|
251
438
|
if o.get("conflicts"):
|
|
252
439
|
L += ["## Conflicts (both evidences kept, awaiting review)", "",
|
|
253
440
|
"| Entity | Types | Evidence A | Evidence B |", "|---|---|---|---|"]
|
|
@@ -257,6 +444,14 @@ def to_markdown(o):
|
|
|
257
444
|
f"\"{t1[1].get('quote', '')[:50]}\" ({t1[1].get('doc', '?')}) | "
|
|
258
445
|
f"\"{t2[1].get('quote', '')[:50]}\" ({t2[1].get('doc', '?')}) |")
|
|
259
446
|
L.append("")
|
|
447
|
+
if o.get("flagged_ungrounded"):
|
|
448
|
+
L += ["## Ungrounded type clashes (kept, not conflicts)", "",
|
|
449
|
+
"| Entity | Typed as | Challenged as | Challenger's quote |", "|---|---|---|---|"]
|
|
450
|
+
for c in o["flagged_ungrounded"][:20]:
|
|
451
|
+
L.append(f"| {c['entity']} | {c['existing_type']} | {c['asserted_type']} | "
|
|
452
|
+
f"\"{c['evidence'].get('quote', '')[:50]}\" ({c['evidence'].get('doc', '?')}) |")
|
|
453
|
+
L += ["", "> A different type asserted with a quote that does not ground it is a guess, not a "
|
|
454
|
+
"conflict; it becomes one only when a grounded quote says so.", ""]
|
|
260
455
|
by_type = defaultdict(list)
|
|
261
456
|
for e in o.get("abox", {}).get("entities", []):
|
|
262
457
|
by_type[e["type"]].append(e)
|
|
@@ -266,11 +461,11 @@ def to_markdown(o):
|
|
|
266
461
|
for e in es[:40]:
|
|
267
462
|
al = f" · aka {', '.join(e['aliases'])}" if e.get("aliases") else ""
|
|
268
463
|
ev = e["evidences"][0]["quote"] if e.get("evidences") else ""
|
|
269
|
-
L.append(f"- **{e['name']}**{al} — \"{ev[:70]}\" ({', '.join(e.get('docs', [])[:3])})")
|
|
464
|
+
L.append(f"- **{e['name']}**{al}{_mark(e, 'type_grounding')} — \"{ev[:70]}\" ({', '.join(e.get('docs', [])[:3])})")
|
|
270
465
|
L += ["", "## Relations", "", "| Subject | Predicate | Object | Evidence |", "|---|---|---|---|"]
|
|
271
466
|
for r in o.get("abox", {}).get("relations", [])[:200]:
|
|
272
467
|
ev = r["evidences"][0]["quote"] if r.get("evidences") else ""
|
|
273
|
-
L.append(f"| {r['subject']} | {r['predicate']} | {r['object']} | \"{ev[:50]}\" |")
|
|
468
|
+
L.append(f"| {r['subject']} | {r['predicate']} | {r['object']}{_mark(r, 'grounding')} | \"{ev[:50]}\" |")
|
|
274
469
|
L += ["", "> Every assertion carries its evidence span in the JSON; this page is the digest. "
|
|
275
470
|
"Not investment/enterprise advice."]
|
|
276
471
|
return "\n".join(L)
|
|
@@ -350,34 +545,77 @@ def to_jsonld(o):
|
|
|
350
545
|
"evidence": {"@id": "https://dsh-auto-ontology.dev/vocab/evidence", "@container": "@list"}}
|
|
351
546
|
graph = []
|
|
352
547
|
for e in o.get("abox", {}).get("entities", []):
|
|
353
|
-
|
|
354
|
-
|
|
548
|
+
node = {"@id": eid(e["name"]), "@type": e["type"], "name": e["name"],
|
|
549
|
+
"aliases": e.get("aliases", []), "evidence": e.get("evidences", [])}
|
|
550
|
+
if "type_grounding" in e:
|
|
551
|
+
node["type_grounding"] = e["type_grounding"]
|
|
552
|
+
graph.append(node)
|
|
355
553
|
for r in o.get("abox", {}).get("relations", []):
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
554
|
+
node = {"@id": rid(r), "@type": r["predicate"],
|
|
555
|
+
"subject": {"@id": eid(r["subject"]), "name": r["subject"]},
|
|
556
|
+
"object": {"@id": eid(r["object"]), "name": r["object"]},
|
|
557
|
+
"evidence": r.get("evidences", [])}
|
|
558
|
+
if "grounding" in r:
|
|
559
|
+
node["grounding"] = r["grounding"]
|
|
560
|
+
graph.append(node)
|
|
360
561
|
return {"@context": ctx, "@graph": graph,
|
|
361
562
|
"dshao:domain": o.get("domain"), "dshao:built_at": o.get("built_at")}
|
|
362
563
|
|
|
363
564
|
|
|
565
|
+
def _abox(st):
|
|
566
|
+
"""The store's ABox in artifact shape — the ONE place entities and relations are
|
|
567
|
+
serialized, so a certification rebuild keeps every derived flag."""
|
|
568
|
+
ents, rels = [], []
|
|
569
|
+
for e in sorted(st["entities"].values(), key=lambda x: x["name"].lower()):
|
|
570
|
+
f = _flag(e["evidences"])
|
|
571
|
+
ents.append(dict(e, evidences=_strongest(e["evidences"]), **({"type_grounding": f} if f is not None else {})))
|
|
572
|
+
for r in sorted(st["relations"].values(), key=lambda r: (r["subject"].lower(), r["predicate"])):
|
|
573
|
+
f = _flag(r["evidences"])
|
|
574
|
+
rels.append(dict(r, evidences=_strongest(r["evidences"]), **({"grounding": f} if f is not None else {})))
|
|
575
|
+
return {"entities": ents, "relations": rels}
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _refresh(o, st):
|
|
579
|
+
"""Rebuild the ABox and every count the stats block derives from it — the one
|
|
580
|
+
place a certification or a re-typing leaves an artifact consistent (a reject
|
|
581
|
+
used to lower the entity count and leave the grounded/ungrounded counts stale)."""
|
|
582
|
+
abox = _abox(st)
|
|
583
|
+
o["abox"] = abox
|
|
584
|
+
n = lambda kind, key, f: sum(1 for x in abox[kind] if x.get(key) is f)
|
|
585
|
+
o.setdefault("stats", {}).update({
|
|
586
|
+
"entities": len(abox["entities"]), "relations": len(abox["relations"]),
|
|
587
|
+
"entities_grounded": n("entities", "type_grounding", True),
|
|
588
|
+
"entities_ungrounded": n("entities", "type_grounding", False),
|
|
589
|
+
"relations_grounded": n("relations", "grounding", True),
|
|
590
|
+
"relations_ungrounded": n("relations", "grounding", False)})
|
|
591
|
+
|
|
592
|
+
|
|
364
593
|
def store_to_ontology(st, new_type_descs, provenance):
|
|
365
|
-
|
|
366
|
-
|
|
594
|
+
descs = st["type_descs"] if "type_descs" in st else new_type_descs
|
|
595
|
+
abox = _abox(st)
|
|
596
|
+
|
|
597
|
+
def n(kind, key, f):
|
|
598
|
+
return sum(1 for x in abox[kind] if x.get(key) is f)
|
|
367
599
|
return {
|
|
368
600
|
"domain": st["domain"], "built_at": dt.datetime.now().isoformat(timespec="seconds"),
|
|
369
601
|
"provenance": provenance,
|
|
370
|
-
"tbox": {"entity_types": [{"name": t, "desc":
|
|
602
|
+
"tbox": {"entity_types": [{"name": t, "desc": descs.get(t, "")}
|
|
371
603
|
for t in sorted(st["tbox_types"])],
|
|
372
604
|
"relation_types": list(st["tbox_relations"].values())},
|
|
373
|
-
"abox":
|
|
605
|
+
"abox": abox,
|
|
374
606
|
"conflicts": st["conflicts"],
|
|
375
607
|
"flagged_unknown_types": st["flagged"],
|
|
608
|
+
"flagged_ungrounded": st["flagged_ungrounded"],
|
|
376
609
|
"merge_log": st["merge_log"],
|
|
377
610
|
"certifications": st.get("certifications", {}),
|
|
378
|
-
"stats": {"entities": len(
|
|
611
|
+
"stats": {"entities": len(abox["entities"]), "relations": len(abox["relations"]),
|
|
379
612
|
"conflicts": len(st["conflicts"]), "flagged": len(st["flagged"]),
|
|
380
|
-
"suppressed_by_certification": st.get("suppressed", 0)
|
|
613
|
+
"suppressed_by_certification": st.get("suppressed", 0),
|
|
614
|
+
"entities_grounded": n("entities", "type_grounding", True),
|
|
615
|
+
"entities_ungrounded": n("entities", "type_grounding", False),
|
|
616
|
+
"relations_grounded": n("relations", "grounding", True),
|
|
617
|
+
"relations_ungrounded": n("relations", "grounding", False),
|
|
618
|
+
"ungrounded_type_clashes": len(st["flagged_ungrounded"])},
|
|
381
619
|
}
|
|
382
620
|
|
|
383
621
|
|
|
@@ -391,18 +629,6 @@ P_TBOX = {
|
|
|
391
629
|
'{"entity_types":[{"name":"...","desc":"..."}],"relation_types":[{"name":"...","domains":"类型A","ranges":"类型B","desc":"..."}]}'
|
|
392
630
|
"。类型名用英文 snake_case,desc 用中文。只抽取语料真实支撑的,宁缺毋滥。"),
|
|
393
631
|
}
|
|
394
|
-
P_ABOX = {
|
|
395
|
-
"en": ("You are an ontology instance extractor. From the document, extract entity and relation instances (ABox) based on the given TBox. "
|
|
396
|
-
"Discipline: every instance must carry evidence=a verbatim quote from the document (<=40 chars); types must come from the TBox; "
|
|
397
|
-
"when unsure, do not extract. Output JSON: "
|
|
398
|
-
'{"entities":[{"name":"...","type":"...","evidence":"..."}],'
|
|
399
|
-
'"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
|
|
400
|
-
"zh": ("你是本体实例抽取器。基于给定 TBox 从文档抽取实体与关系实例(ABox)。"
|
|
401
|
-
"**纪律**:每条实例必须附 evidence=文档原文引文(不超过40字);类型必须取自 TBox;"
|
|
402
|
-
"不确定的不抽。输出 JSON:"
|
|
403
|
-
'{"entities":[{"name":"...","type":"...","evidence":"..."}],'
|
|
404
|
-
'"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
|
|
405
|
-
}
|
|
406
632
|
P_COREF = {
|
|
407
633
|
"en": ("You resolve entity mentions in an ontology. Given entity names (with types), output JSON "
|
|
408
634
|
'{"pairs":[{"canonical":"...","alias":"..."}]} where alias is clearly the SAME real-world '
|
|
@@ -412,33 +638,187 @@ P_COREF = {
|
|
|
412
638
|
'{"pairs":[{"canonical":"...","alias":"..."}]}——alias 与 canonical 须确定是同一现实事物'
|
|
413
639
|
"(缩写/大小写/前缀差异)。只有确定才合并,可争议的不合;不同类型绝不配对。"),
|
|
414
640
|
}
|
|
641
|
+
P_ABOX = {
|
|
642
|
+
"en": ("You are an ontology instance extractor. From the document, extract entity and relation instances (ABox) based on the given TBox. "
|
|
643
|
+
"Discipline: types must come from the TBox; when unsure, do not extract. "
|
|
644
|
+
"EVIDENCE is a verbatim quote copied EXACTLY from the document (up to 200 chars, no paraphrase): "
|
|
645
|
+
"for an entity, the sentence that states what the entity IS - it must contain the entity's name as written; "
|
|
646
|
+
"for a relation, the sentence that names an endpoint and states the relation. "
|
|
647
|
+
"When a line takes its meaning from the list label, heading or table header above it, "
|
|
648
|
+
"start the quote at that label. "
|
|
649
|
+
"If the document only mentions a name without saying what it is, quote the sentence that mentions it. "
|
|
650
|
+
"Output JSON: "
|
|
651
|
+
'{"entities":[{"name":"...","type":"...","evidence":"..."}],'
|
|
652
|
+
'"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
|
|
653
|
+
"zh": ("你是本体实例抽取器。基于给定 TBox 从文档抽取实体与关系实例(ABox)。"
|
|
654
|
+
"**纪律**:类型必须取自 TBox;不确定的不抽。"
|
|
655
|
+
"evidence 必须是**逐字**复制的原文引文(不超过 200 字,不得改写):"
|
|
656
|
+
"实体——说明该实体**是什么**的那句话,且必须包含实体名原文;"
|
|
657
|
+
"关系——点出关系一端并陈述该关系的那句话。"
|
|
658
|
+
"当某一行的含义来自其上方的列表标签、标题或表头时,引文从该标签开始。"
|
|
659
|
+
"若文档只是提及名字而未说明其为何物,则引用提及它的那句话。"
|
|
660
|
+
"输出 JSON:"
|
|
661
|
+
'{"entities":[{"name":"...","type":"...","evidence":"..."}],'
|
|
662
|
+
'"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
|
|
663
|
+
}
|
|
664
|
+
P_REGROUND = {
|
|
665
|
+
"en": ("You repair evidence quotes for ontology assertions. For each numbered claim, find in the document the "
|
|
666
|
+
"contiguous span that STATES the claim and copy it exactly (up to 200 chars). The span may start at the "
|
|
667
|
+
"list label, heading or table header that gives a line its meaning (for example \"Family: [X] - [Y]\" "
|
|
668
|
+
"before a link). An entity quote must contain the entity's name as written and say what the entity is; "
|
|
669
|
+
"a relation quote must name an endpoint and state the relation. If the document does not state the "
|
|
670
|
+
"claim, set quote to null - never paraphrase, never stitch together sentences that are not adjacent. "
|
|
671
|
+
'Output JSON: {"repairs":[{"i":1,"quote":"... or null"}]} - exactly one entry per item, same numbering.'),
|
|
672
|
+
"zh": ("你为 ontology 断言修复证据引文。对每条编号断言,在文档中找到**陈述**该断言的连续原文片段并逐字复制"
|
|
673
|
+
"(不超过 200 字)。片段可以从赋予该行含义的列表标签、标题或表头开始(例如链接之前的“Family: [X] · [Y]”)。"
|
|
674
|
+
"实体引文必须包含实体名原文并说明该实体是什么;关系引文必须点出一个端点并陈述该关系。"
|
|
675
|
+
"若文档并未陈述该断言,quote 置为 null——不得改写、不得拼接不相邻的句子。"
|
|
676
|
+
'输出 JSON:{"repairs":[{"i":1,"quote":"... 或 null"}]}——每项恰好一条,编号一致。'),
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
JUDGE_JOBS = int(os.environ.get("ONTOLOGY_JUDGE_JOBS") or 8) # concurrent single-item judge calls
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def _doc_label(d):
|
|
683
|
+
"""How a prompt names the text a model is reading: the document's path — or, for a
|
|
684
|
+
chunk read from a knowledge base, its place in its document."""
|
|
685
|
+
return d.get("label") or d["path"]
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _reject_reason(x, text):
|
|
689
|
+
"""Why an extracted quote can never ground its claim — None when it may be judged.
|
|
690
|
+
|
|
691
|
+
The one check the judge cannot make: it sees the quote, not the document, so only a
|
|
692
|
+
verbatim span of the document is evidence. A quote that does not spell the entity's
|
|
693
|
+
name or a relation's endpoint is still JUDGED. (Until 2026-11-25 that was a
|
|
694
|
+
pre-reject; on the published before-artifact it would have turned away 30 ungrounded
|
|
695
|
+
assertions and 9 grounded ones — "payload" for market_data_payload, a plugin typed
|
|
696
|
+
from its own title line. A quote about ANOTHER instance of the type stays rejected by
|
|
697
|
+
the judge: the adversarial set pins it.)"""
|
|
698
|
+
q = x.get("evidence", "")
|
|
699
|
+
if not q or not grounding.is_verbatim(q, text):
|
|
700
|
+
return tt("quote is not verbatim in the source document", "引文并非文档原文")
|
|
701
|
+
return None
|
|
415
702
|
|
|
416
703
|
|
|
417
|
-
def
|
|
704
|
+
def _item(kind, x, doc, descs):
|
|
705
|
+
tname = x["type"] if kind == "entity" else x["predicate"]
|
|
706
|
+
desc = descs.get(tname, "")
|
|
707
|
+
claim = (grounding.entity_claim(x["name"], x["type"]) if kind == "entity"
|
|
708
|
+
else grounding.relation_claim(x.get("subject") or "", x["predicate"], x.get("object") or ""))
|
|
709
|
+
return {"kind": kind, "type_name": tname, "type_desc": desc, "claim": claim, "quote": x["evidence"], "doc": doc}
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _judge(cands, doc, descs):
|
|
713
|
+
"""-> verdicts in the same order: the shared judge, ONE call per item — the protocol the
|
|
714
|
+
eval and the adversarial set use (a hand audit found batched verdicts less accurate).
|
|
715
|
+
The items are judged concurrently; the order of the verdicts is the order of the input."""
|
|
716
|
+
items = [_item(k, x, doc, descs) for k, x in cands]
|
|
717
|
+
if not items:
|
|
718
|
+
return []
|
|
719
|
+
with cf.ThreadPoolExecutor(max_workers=min(JUDGE_JOBS, len(items))) as ex:
|
|
720
|
+
return list(ex.map(lambda it: grounding.judge([it], JUDGE_MODEL, call=_judge_call)[0], items))
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def _judge_call(sysmsg, user):
|
|
724
|
+
"""A judge call: through the cost guard AND through --judge-model. grounding.judge()
|
|
725
|
+
hands `call` no model, so a bare llm() here judged with the build model while the
|
|
726
|
+
provenance named the judge model."""
|
|
727
|
+
return llm(sysmsg, user, model=JUDGE_MODEL)
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def _reground(d, failed, descs):
|
|
731
|
+
"""-> a replacement quote (or None) per failed assertion, from ONE call."""
|
|
732
|
+
L = [tt(f"Document ({_doc_label(d)}):", f"文档({_doc_label(d)}):"), d["text"], "", tt("Claims:", "断言:")]
|
|
733
|
+
for i, (kind, x) in enumerate(failed, 1):
|
|
734
|
+
L.append(f"{i}. {_item(kind, x, d['path'], descs)['claim']}\n "
|
|
735
|
+
+ tt("rejected quote", "被否决的引文") + f": {json.dumps(x['evidence'], ensure_ascii=False)}")
|
|
736
|
+
out = llm(P_REGROUND[LANG], "\n".join(L))
|
|
737
|
+
got = {}
|
|
738
|
+
for r in out.get("repairs", []):
|
|
739
|
+
try:
|
|
740
|
+
got[int(r.get("i", 0))] = r.get("quote")
|
|
741
|
+
except (AttributeError, TypeError, ValueError):
|
|
742
|
+
continue
|
|
743
|
+
return [got.get(i) for i in range(1, len(failed) + 1)]
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def ground_doc(d, out, known, descs, reground=True):
|
|
747
|
+
"""The grounding pass for ONE document, in place on the extracted assertions: every
|
|
748
|
+
(claim, quote) leaves with `grounded` True / False, or untouched when it never had a
|
|
749
|
+
quote to judge. Order: the verbatim gate (no LLM — a span not in the document is not
|
|
750
|
+
evidence), one judge call per verbatim quote, then — only if something failed — one
|
|
751
|
+
re-ground call and a re-judge of every repaired quote. Nothing is dropped: an
|
|
752
|
+
ungrounded assertion is folded like any other and flagged.
|
|
753
|
+
-> {entities: [grounded, ungrounded], relations: [...], regrounded}"""
|
|
754
|
+
cands = [("entity", e) for e in out.get("entities", []) if e.get("name") and e.get("type") in known]
|
|
755
|
+
cands += [("relation", r) for r in out.get("relations", [])]
|
|
756
|
+
todo = []
|
|
757
|
+
for kind, x in cands:
|
|
758
|
+
why = _reject_reason(x, d["text"])
|
|
759
|
+
if why is None:
|
|
760
|
+
todo.append((kind, x))
|
|
761
|
+
else:
|
|
762
|
+
x["grounded"], x["judge_reason"] = False, why
|
|
763
|
+
for (kind, x), v in zip(todo, _judge(todo, d["path"], descs)):
|
|
764
|
+
x["grounded"], x["judge_reason"] = v["grounded"], v["reason"]
|
|
765
|
+
failed = [(k, x) for k, x in cands if x.get("evidence") and x.get("grounded") is False]
|
|
766
|
+
repaired = []
|
|
767
|
+
if reground and failed:
|
|
768
|
+
for (kind, x), q in zip(failed, _reground(d, failed, descs)):
|
|
769
|
+
if q and _reject_reason(dict(x, evidence=q), d["text"]) is None:
|
|
770
|
+
x["evidence"], x["regrounded"] = q, True
|
|
771
|
+
repaired.append((kind, x))
|
|
772
|
+
for (kind, x), v in zip(repaired, _judge(repaired, d["path"], descs)):
|
|
773
|
+
x["grounded"], x["judge_reason"] = v["grounded"], v["reason"]
|
|
774
|
+
return {"entities": [sum(1 for k, x in cands if k == "entity" and x.get("grounded") is True),
|
|
775
|
+
sum(1 for k, x in cands if k == "entity" and x.get("grounded") is False)],
|
|
776
|
+
"relations": [sum(1 for k, x in cands if k == "relation" and x.get("grounded") is True),
|
|
777
|
+
sum(1 for k, x in cands if k == "relation" and x.get("grounded") is False)],
|
|
778
|
+
"regrounded": len(repaired)}
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def build(docs, domain, base=None, sample=4, ground=True, reground=True):
|
|
418
782
|
st = base if base is not None else new_store(domain)
|
|
783
|
+
# a knowledge-base build samples DOCUMENTS, not chunks: the first chunk of each carries the opening
|
|
784
|
+
pool = [d for d in docs if d.get("schema_text")] or docs
|
|
419
785
|
tbox = llm(P_TBOX[LANG],
|
|
420
|
-
tt(f"Domain: {domain}\nCorpus sample:\n" + "\n\n".join(d["text"][:1500] for d in
|
|
421
|
-
f"领域:{domain}\n语料样本:\n" + "\n\n".join(d["text"][:1500] for d in
|
|
786
|
+
tt(f"Domain: {domain}\nCorpus sample:\n" + "\n\n".join((d.get("schema_text") or d["text"])[:1500] for d in pool[:sample]),
|
|
787
|
+
f"领域:{domain}\n语料样本:\n" + "\n\n".join((d.get("schema_text") or d["text"])[:1500] for d in pool[:sample])))
|
|
422
788
|
known = {e["name"] for e in tbox.get("entity_types", [])}
|
|
423
|
-
|
|
424
|
-
|
|
789
|
+
# a definition the base artifact carried stays (its assertions were judged against it); this
|
|
790
|
+
# run's pass fills a blank and names what is new — a merge used to bring them all back empty
|
|
791
|
+
kept = st.setdefault("type_descs", {})
|
|
792
|
+
new_type_descs = {e["name"]: e.get("desc") or kept.get(e["name"], "")
|
|
793
|
+
for e in tbox.get("entity_types", []) if not kept.get(e["name"])}
|
|
794
|
+
kept.update(new_type_descs)
|
|
425
795
|
st["tbox_types"] |= known
|
|
426
796
|
for r in tbox.get("relation_types", []):
|
|
427
797
|
st["tbox_relations"][(r.get("name"), r.get("domains"), r.get("ranges"))] = r
|
|
798
|
+
descs = {t["name"]: t.get("desc", "") for t in tbox.get("entity_types", [])}
|
|
799
|
+
descs.update({r.get("name"): r.get("desc", "") for r in tbox.get("relation_types", [])})
|
|
428
800
|
|
|
429
|
-
per_doc = []
|
|
801
|
+
per_doc, tally, quoteless = [], {"entities": [0, 0], "relations": [0, 0], "regrounded": 0}, 0
|
|
430
802
|
for d in docs:
|
|
431
803
|
out = llm(P_ABOX[LANG],
|
|
432
|
-
tt(f"TBox:\n{json.dumps(tbox, ensure_ascii=False)}\n\nDocument ({d
|
|
433
|
-
f"TBox:{json.dumps(tbox, ensure_ascii=False)}\n\n文档({d
|
|
804
|
+
tt(f"TBox:\n{json.dumps(tbox, ensure_ascii=False)}\n\nDocument ({_doc_label(d)}):\n{d['text']}",
|
|
805
|
+
f"TBox:{json.dumps(tbox, ensure_ascii=False)}\n\n文档({_doc_label(d)}):\n{d['text']}"))
|
|
806
|
+
if ground:
|
|
807
|
+
g = ground_doc(d, out, known, descs, reground=reground)
|
|
808
|
+
for k in ("entities", "relations"):
|
|
809
|
+
tally[k] = [a + b for a, b in zip(tally[k], g[k])]
|
|
810
|
+
tally["regrounded"] += g["regrounded"]
|
|
434
811
|
per_doc.append((d, out))
|
|
435
812
|
for e in out.get("entities", []):
|
|
436
813
|
if not e.get("name"):
|
|
437
814
|
continue
|
|
438
|
-
if e.get("
|
|
439
|
-
|
|
815
|
+
if not e.get("evidence"):
|
|
816
|
+
quoteless += 1
|
|
817
|
+
elif e.get("type") in known:
|
|
818
|
+
fold_entity(st, e["name"], e["type"], e["evidence"], d["path"], grounded=e.get("grounded"),
|
|
819
|
+
reason=e.get("judge_reason"), chunk_id=d.get("chunk_id"))
|
|
440
820
|
else:
|
|
441
|
-
st["flagged"].append({**e, "doc": d["path"]}) # type guard — never silently dropped
|
|
821
|
+
st["flagged"].append({**e, "doc": d["path"], **({"chunk_id": d["chunk_id"]} if d.get("chunk_id") else {})}) # type guard — never silently dropped
|
|
442
822
|
|
|
443
823
|
merged_aliases, alias_map = [], {}
|
|
444
824
|
names = [f"{e['name']} ({e['type']})" for e in st["entities"].values()]
|
|
@@ -450,9 +830,131 @@ def build(docs, domain, base=None, sample=4):
|
|
|
450
830
|
if p.get("canonical") and p.get("alias")])
|
|
451
831
|
for d, out in per_doc: # relations fold AFTER coref so endpoints are canonical
|
|
452
832
|
for r in out.get("relations", []):
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
833
|
+
if not r.get("evidence"):
|
|
834
|
+
quoteless += 1
|
|
835
|
+
continue
|
|
836
|
+
fold_relation(st, r.get("subject"), r.get("predicate"), r.get("object"), r["evidence"], d["path"],
|
|
837
|
+
alias_map=alias_map, grounded=r.get("grounded"), reason=r.get("judge_reason"),
|
|
838
|
+
chunk_id=d.get("chunk_id"))
|
|
839
|
+
if quoteless:
|
|
840
|
+
print(tt(f"{quoteless} extracted assertion(s) arrived without a quote — not folded (no evidence, no assertion)",
|
|
841
|
+
f"{quoteless} 条抽取结果未带引文——不予并入(无证据,无断言)"), file=sys.stderr)
|
|
842
|
+
return st, new_type_descs, merged_aliases, tally
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
# ── a WeKnora knowledge base as documents (O5.2, issue #56) ──────────────────
|
|
846
|
+
|
|
847
|
+
WK_PAGE = 100 # rows per page on a WeKnora list endpoint
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def _wk_get(method, path, body=None):
|
|
851
|
+
"""One WeKnora API call with the family's auth convention (the bridge's): env
|
|
852
|
+
WEKNORA_URL / WEKNORA_API_KEY / WEKNORA_TENANT_ID. -> (status, parsed)"""
|
|
853
|
+
hdr = {"Content-Type": "application/json", "X-API-Key": os.environ.get("WEKNORA_API_KEY", "")}
|
|
854
|
+
if os.environ.get("WEKNORA_TENANT_ID"):
|
|
855
|
+
hdr["X-Tenant-ID"] = os.environ["WEKNORA_TENANT_ID"]
|
|
856
|
+
req = urllib.request.Request(os.environ.get("WEKNORA_URL", "").rstrip("/") + path,
|
|
857
|
+
data=json.dumps(body).encode() if body is not None else None,
|
|
858
|
+
method=method, headers=hdr)
|
|
859
|
+
try:
|
|
860
|
+
with urllib.request.urlopen(req, timeout=60) as r:
|
|
861
|
+
return r.status, json.load(r)
|
|
862
|
+
except urllib.error.HTTPError as e:
|
|
863
|
+
return e.code, e.read().decode(errors="ignore")[:300]
|
|
864
|
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
|
865
|
+
return 0, f"{type(e).__name__}: {e}"
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
def _wk_rows(get, path):
|
|
869
|
+
"""Every row of a paged WeKnora list endpoint — it answers {success, data, page,
|
|
870
|
+
page_size, total}. A page that repeats rows already read ends the walk: an
|
|
871
|
+
endpoint that ignores `page` must not be walked forever."""
|
|
872
|
+
rows, seen, page = [], set(), 1
|
|
873
|
+
while True:
|
|
874
|
+
status, out = get("GET", f"{path}{'&' if '?' in path else '?'}page={page}&page_size={WK_PAGE}")
|
|
875
|
+
if status != 200 or not isinstance(out, dict) or out.get("success") is False or not isinstance(out.get("data"), list):
|
|
876
|
+
sys.exit(tt(f"WeKnora answered {status} on {path.split('?')[0]}: {str(out)[:200]} — check WEKNORA_URL / "
|
|
877
|
+
f"WEKNORA_API_KEY / WEKNORA_TENANT_ID (family config: ~/.config/weknora-ops/config)",
|
|
878
|
+
f"WeKnora 在 {path.split('?')[0]} 返回 {status}:{str(out)[:200]}——请检查 WEKNORA_URL / "
|
|
879
|
+
f"WEKNORA_API_KEY / WEKNORA_TENANT_ID(家族配置:~/.config/weknora-ops/config)"))
|
|
880
|
+
fresh = [r for r in out["data"] if isinstance(r, dict) and r.get("id") not in seen]
|
|
881
|
+
rows += fresh
|
|
882
|
+
seen |= {r["id"] for r in fresh}
|
|
883
|
+
if not fresh or len(out["data"]) < WK_PAGE or page * WK_PAGE >= int(out.get("total") or 0):
|
|
884
|
+
return rows
|
|
885
|
+
page += 1
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def kb_chunks(kb, limit=None, get=None):
|
|
889
|
+
"""A WeKnora knowledge base as the documents of a build: ONE CHUNK IS ONE DOCUMENT,
|
|
890
|
+
read whole — chunk-level evidence is the point. -> (docs, info)
|
|
891
|
+
|
|
892
|
+
Reading order is deterministic — documents by title, a document's chunks by
|
|
893
|
+
index — so a `limit` reads the same chunks every time. Only a document whose
|
|
894
|
+
parse completed is read; the others are counted in `info` and skipped (a
|
|
895
|
+
document still parsing has nothing to quote). Only text chunks are read: a
|
|
896
|
+
generated summary is not a source. An evidence's `doc` is the document's
|
|
897
|
+
TITLE — the name a person knows the source by, what a file build records —
|
|
898
|
+
and `chunk_id` says which chunk the quote was read from. `label` tells the
|
|
899
|
+
prompts they are reading a fragment. The schema pass samples DOCUMENTS: the
|
|
900
|
+
first chunk of each carries the document's opening as chunked
|
|
901
|
+
(`schema_text`), which is what a file build's sample reads.
|
|
902
|
+
|
|
903
|
+
get(method, path, body) -> (status, parsed) is the transport — stdlib urllib
|
|
904
|
+
against WEKNORA_URL unless a test hands in its own. A read scope is enough:
|
|
905
|
+
the build never writes to the knowledge base."""
|
|
906
|
+
if get is None:
|
|
907
|
+
if not (os.environ.get("WEKNORA_URL") and os.environ.get("WEKNORA_API_KEY")):
|
|
908
|
+
sys.exit(tt("WEKNORA_URL / WEKNORA_API_KEY not set (family config: ~/.config/weknora-ops/config)",
|
|
909
|
+
"未设置 WEKNORA_URL / WEKNORA_API_KEY(家族配置:~/.config/weknora-ops/config)"))
|
|
910
|
+
get = _wk_get
|
|
911
|
+
docs = []
|
|
912
|
+
info = {"id": kb, "limit": limit, "skipped_documents": {}}
|
|
913
|
+
know = _wk_rows(get, f"/api/v1/knowledge-bases/{kb}/knowledge")
|
|
914
|
+
for k in sorted(know, key=lambda k: (k.get("title") or "", k.get("id") or "")):
|
|
915
|
+
if k.get("parse_status") != "completed":
|
|
916
|
+
why = k.get("parse_status") or "unknown"
|
|
917
|
+
info["skipped_documents"][why] = info["skipped_documents"].get(why, 0) + 1
|
|
918
|
+
continue
|
|
919
|
+
title = k.get("title") or k["id"]
|
|
920
|
+
group, opening = [], []
|
|
921
|
+
for c in sorted(_wk_rows(get, f"/api/v1/chunks/{k['id']}"), key=lambda c: c.get("chunk_index") or 0):
|
|
922
|
+
if (not (c.get("content") or "").strip() or c.get("chunk_type") not in (None, "text")
|
|
923
|
+
or c.get("is_enabled") is False):
|
|
924
|
+
continue
|
|
925
|
+
if limit is not None and len(docs) + len(group) >= limit:
|
|
926
|
+
break
|
|
927
|
+
group.append({"path": title, "text": c["content"].strip(), "chunk_id": c.get("id"),
|
|
928
|
+
"label": f"{title} · chunk {c.get('chunk_index') or 0} — a fragment of that document"})
|
|
929
|
+
if len("\n\n".join(opening)) < 1500:
|
|
930
|
+
opening.append(group[-1]["text"])
|
|
931
|
+
if group:
|
|
932
|
+
group[0]["schema_text"] = "\n\n".join(opening)
|
|
933
|
+
docs += group
|
|
934
|
+
if limit is not None and len(docs) >= limit:
|
|
935
|
+
break
|
|
936
|
+
info["documents"], info["chunks"] = len({d["path"] for d in docs}), len(docs)
|
|
937
|
+
return docs, info
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def file_docs(target):
|
|
941
|
+
"""The documents a --docs target names: each file read up to the engine's 6000
|
|
942
|
+
characters, named by its parent directory (a README's repository)."""
|
|
943
|
+
paths = (sorted(glob.glob(target)) if "*" in target else
|
|
944
|
+
[target] if os.path.isfile(target) else sorted(glob.glob(os.path.join(target, "*"))))
|
|
945
|
+
docs = []
|
|
946
|
+
for p in paths:
|
|
947
|
+
try:
|
|
948
|
+
docs.append({"path": os.path.basename(os.path.dirname(p)) or p,
|
|
949
|
+
"text": open(p, errors="ignore").read()[:6000]})
|
|
950
|
+
except OSError:
|
|
951
|
+
pass
|
|
952
|
+
return docs
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def _text_w(s, fs):
|
|
956
|
+
"""Approximate rendered width in px: a monospace cell is ~0.6 em, a CJK cell ~1 em."""
|
|
957
|
+
return fs * sum(1.0 if ord(c) > 0x2E80 else 0.6 for c in s)
|
|
456
958
|
|
|
457
959
|
|
|
458
960
|
def _write_svg(path, o, domain):
|
|
@@ -469,8 +971,31 @@ def _write_svg(path, o, domain):
|
|
|
469
971
|
for i, e in enumerate(es[:10]):
|
|
470
972
|
a = 2 * math.pi * i / max(len(es[:10]), 1)
|
|
471
973
|
nodes.append((e["name"][:14], gx + 52 * math.cos(a), gy + 40 * math.sin(a), colors[ci % 6]))
|
|
472
|
-
|
|
473
|
-
|
|
974
|
+
# the title takes two lines and the graph is shifted so that no label leaves the canvas:
|
|
975
|
+
# with six type clusters the outer rings used to put labels above y=0 and left of x=0
|
|
976
|
+
title = domain
|
|
977
|
+
while title and _text_w(title, 13) > 840:
|
|
978
|
+
title = title[:-1]
|
|
979
|
+
if title != domain:
|
|
980
|
+
title += "…"
|
|
981
|
+
st = o.get("stats") or {}
|
|
982
|
+
line2 = f"{len(ents)} entities / {len(rels)} relations"
|
|
983
|
+
if "entities_grounded" in st:
|
|
984
|
+
ok = st["entities_grounded"] + st["relations_grounded"]
|
|
985
|
+
line2 += f" · {ok} judged grounded · {len(ents) + len(rels) - ok} not grounded, kept and flagged"
|
|
986
|
+
TOP, PAD, W, H = 48, 8, 860, 700
|
|
987
|
+
tx = ty = 0.0
|
|
988
|
+
if nodes:
|
|
989
|
+
x0 = min(n[1] for n in nodes) - 4
|
|
990
|
+
x1 = max(n[1] + 6 + _text_w(n[0], 9) for n in nodes)
|
|
991
|
+
y0 = min(n[2] for n in nodes) - 7
|
|
992
|
+
y1 = max(n[2] for n in nodes) + 4
|
|
993
|
+
W, H = max(W, math.ceil(x1 - x0) + 2 * PAD), max(H, math.ceil(y1 - y0) + TOP + PAD)
|
|
994
|
+
tx, ty = (W - (x1 - x0)) / 2 - x0, TOP - y0
|
|
995
|
+
svg = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" font-family="monospace">',
|
|
996
|
+
f'<text x="10" y="16" font-size="13">{escape(title)}</text>',
|
|
997
|
+
f'<text x="10" y="33" font-size="13">{escape(line2)}</text>',
|
|
998
|
+
f'<g transform="translate({tx:.0f} {ty:.0f})">']
|
|
474
999
|
nm = {n[0]: (n[1], n[2]) for n in nodes}
|
|
475
1000
|
for r in rels:
|
|
476
1001
|
if r["subject"][:14] in nm and r["object"][:14] in nm:
|
|
@@ -479,15 +1004,34 @@ def _write_svg(path, o, domain):
|
|
|
479
1004
|
svg.append(f'<line x1="{x1:.0f}" y1="{y1:.0f}" x2="{x2:.0f}" y2="{y2:.0f}" stroke="#99a" stroke-width="0.7"/>')
|
|
480
1005
|
for name, x, y, c in nodes:
|
|
481
1006
|
svg.append(f'<circle cx="{x:.0f}" cy="{y:.0f}" r="4" fill="{c}"/>'
|
|
482
|
-
f'<text x="{x + 6:.0f}" y="{y + 3:.0f}" font-size="9" fill="#345">{name}</text>')
|
|
483
|
-
svg.append("</svg>")
|
|
1007
|
+
f'<text x="{x + 6:.0f}" y="{y + 3:.0f}" font-size="9" fill="#345">{escape(name)}</text>')
|
|
1008
|
+
svg.append("</g></svg>")
|
|
484
1009
|
open(path, "w").write("".join(svg))
|
|
485
1010
|
|
|
486
1011
|
|
|
1012
|
+
def _where(ev):
|
|
1013
|
+
"""Query-output locator of an evidence read from a knowledge base: its chunk id."""
|
|
1014
|
+
return f" · chunk {ev['chunk_id']}" if ev.get("chunk_id") else ""
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
def _ev_mark(ev):
|
|
1018
|
+
"""Query-output marker of one evidence: its verdict, and why when it failed."""
|
|
1019
|
+
if ev.get("grounded") is True:
|
|
1020
|
+
return " ✓"
|
|
1021
|
+
if ev.get("grounded") is False:
|
|
1022
|
+
return " ⚠" + (f" — {ev['reason']}" if ev.get("reason") else "")
|
|
1023
|
+
return ""
|
|
1024
|
+
|
|
1025
|
+
|
|
487
1026
|
def main():
|
|
488
|
-
global LANG, MAX_CALLS
|
|
1027
|
+
global LANG, MAX_CALLS, JUDGE_MODEL
|
|
489
1028
|
ap = argparse.ArgumentParser()
|
|
490
|
-
ap.add_argument("--docs", default=None, help="directory or
|
|
1029
|
+
ap.add_argument("--docs", default=None, help="directory, glob or single file, e.g. '~/dsh-*/README.md'")
|
|
1030
|
+
ap.add_argument("--kb", default=None, metavar="ID",
|
|
1031
|
+
help="build from a WeKnora knowledge base instead of --docs: one chunk is one document and every "
|
|
1032
|
+
"evidence carries its chunk_id (env WEKNORA_URL / WEKNORA_API_KEY / WEKNORA_TENANT_ID)")
|
|
1033
|
+
ap.add_argument("--limit", type=int, default=None,
|
|
1034
|
+
help="with --kb: read at most this many chunks, in reading order (default: the whole base)")
|
|
491
1035
|
ap.add_argument("--domain", default=None, help="corpus domain description (schema pass)")
|
|
492
1036
|
ap.add_argument("--merge", default=None, help="existing ontology JSON to fold into (append-only)")
|
|
493
1037
|
ap.add_argument("--query", default=None, help="query mode: every assertion about X, with evidence")
|
|
@@ -497,16 +1041,33 @@ def main():
|
|
|
497
1041
|
help="certification mode: --certify NAME --verdict accept|reject [--note ...] [--from x.json]")
|
|
498
1042
|
ap.add_argument("--verdict", choices=("accept", "reject"), default=None, help="verdict for --certify")
|
|
499
1043
|
ap.add_argument("--note", default="", help="optional note recorded with a certification")
|
|
1044
|
+
ap.add_argument("--actor", default=None,
|
|
1045
|
+
help="who issues a --certify verdict, recorded with it (env ONTOLOGY_ACTOR; "
|
|
1046
|
+
"an agent applying a verdict must name itself)")
|
|
1047
|
+
ap.add_argument("--proposals", default=None, metavar="FILE",
|
|
1048
|
+
help="apply mode: re-type entities from a judge's grounded proposals "
|
|
1049
|
+
"(a dsh-EvoOntology runs/<run>.proposals.json); requires --actor")
|
|
500
1050
|
ap.add_argument("--jsonld", action="store_true", help="export the ontology as JSON-LD 1.1 (with --from, or the newest artifact)")
|
|
501
1051
|
ap.add_argument("--html", action="store_true", help="render the ontology as a single-file HTML digest (with --save, or --from standalone)")
|
|
502
|
-
ap.add_argument("--from", dest="frm", default=None,
|
|
1052
|
+
ap.add_argument("--from", dest="frm", default=None,
|
|
1053
|
+
help="ontology file for --query / --jsonld / --html / --trajectory (default: newest in outdir)")
|
|
1054
|
+
ap.add_argument("--trajectory", action="store_true",
|
|
1055
|
+
help="export mode: the artifact as an ao-trajectory/0.1 event stream, one JSON event per line")
|
|
1056
|
+
ap.add_argument("artifacts", nargs="*",
|
|
1057
|
+
help="artifact files for --trajectory (default: --from, or the newest in outdir)")
|
|
1058
|
+
ap.add_argument("--out", default=None, help="with --trajectory: write the stream here instead of stdout")
|
|
503
1059
|
ap.add_argument("--sample", type=int, default=4, help="docs sampled for the TBox schema pass")
|
|
504
1060
|
ap.add_argument("--max-calls", type=int, default=None, help="cost guard: abort beyond this many LLM calls")
|
|
1061
|
+
ap.add_argument("--no-ground", action="store_true",
|
|
1062
|
+
help="skip the type-grounding judge (no assertion gets a grounding flag)")
|
|
1063
|
+
ap.add_argument("--judge-model", default=None,
|
|
1064
|
+
help="model for the grounding judge (default: the build model; env ONTOLOGY_JUDGE_MODEL)")
|
|
505
1065
|
ap.add_argument("--save", action="store_true")
|
|
506
1066
|
ap.add_argument("--lang", choices=("en", "zh"), default=LANG, help="output language (default en)")
|
|
507
1067
|
args = ap.parse_args()
|
|
508
1068
|
LANG = args.lang
|
|
509
1069
|
MAX_CALLS = args.max_calls
|
|
1070
|
+
JUDGE_MODEL = args.judge_model or os.environ.get("ONTOLOGY_JUDGE_MODEL") or MODEL
|
|
510
1071
|
t0 = time.time()
|
|
511
1072
|
|
|
512
1073
|
if args.diff:
|
|
@@ -514,63 +1075,145 @@ def main():
|
|
|
514
1075
|
print(render_diff(diff_ontologies(a, b)))
|
|
515
1076
|
return
|
|
516
1077
|
|
|
1078
|
+
if args.artifacts and not args.trajectory:
|
|
1079
|
+
ap.error("artifact files are read only with --trajectory")
|
|
1080
|
+
if args.trajectory:
|
|
1081
|
+
import trajectory
|
|
1082
|
+
if args.artifacts and args.frm:
|
|
1083
|
+
ap.error("--trajectory takes artifact files or --from, not both")
|
|
1084
|
+
paths = args.artifacts or ([args.frm] if args.frm else
|
|
1085
|
+
sorted(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)[-1:])
|
|
1086
|
+
if not paths:
|
|
1087
|
+
sys.exit(tt(f"no ontology artifact under {OUTDIR}", f"{OUTDIR} 下没有本体文件"))
|
|
1088
|
+
for p in paths:
|
|
1089
|
+
if not os.path.isfile(p):
|
|
1090
|
+
sys.exit(tt(f"no such ontology artifact: {p}", f"没有这个本体文件:{p}"))
|
|
1091
|
+
events = [e for p in paths for e in trajectory.export_events(json.load(open(p)), os.path.basename(p))]
|
|
1092
|
+
for i, e in enumerate(events): # one stream: positions run on across artifacts
|
|
1093
|
+
e["seq"] = i
|
|
1094
|
+
lines = trajectory.render(events)
|
|
1095
|
+
if args.out:
|
|
1096
|
+
open(args.out, "w", encoding="utf-8").write("\n".join(lines) + "\n")
|
|
1097
|
+
print(f"trajectory: {trajectory.tally(events)} -> {args.out}")
|
|
1098
|
+
else:
|
|
1099
|
+
try:
|
|
1100
|
+
print("\n".join(lines))
|
|
1101
|
+
except BrokenPipeError: # the reader went away (| head): a closed pipe, not a failure
|
|
1102
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
1103
|
+
return
|
|
1104
|
+
print(f"trajectory: {trajectory.tally(events)}", file=sys.stderr)
|
|
1105
|
+
return
|
|
1106
|
+
|
|
517
1107
|
if args.certify:
|
|
518
1108
|
if not args.verdict:
|
|
519
1109
|
sys.exit("--certify needs --verdict accept|reject")
|
|
520
|
-
path = args.frm or
|
|
521
|
-
|
|
1110
|
+
path = args.frm or newest_artifact()
|
|
1111
|
+
actor = args.actor or os.environ.get("ONTOLOGY_ACTOR") or "unspecified"
|
|
1112
|
+
o = certify(json.load(open(path)), args.certify, args.verdict, note=args.note, actor=actor)
|
|
1113
|
+
os.makedirs(OUTDIR, exist_ok=True) # --from may point at an artifact outside OUTDIR
|
|
522
1114
|
out = os.path.join(OUTDIR, dt.datetime.now().strftime("%Y%m%d-%H%M%S") + "-certified.json")
|
|
523
1115
|
json.dump(o, open(out, "w"), ensure_ascii=False, indent=1)
|
|
524
1116
|
print(f"{args.certify} {args.verdict} -> {out}")
|
|
525
1117
|
return
|
|
526
1118
|
|
|
1119
|
+
if args.proposals:
|
|
1120
|
+
actor = args.actor or os.environ.get("ONTOLOGY_ACTOR")
|
|
1121
|
+
if not actor:
|
|
1122
|
+
sys.exit(tt("--proposals needs --actor: an agent applying a verdict must name itself",
|
|
1123
|
+
"--proposals 需要 --actor:agent 应用裁决必须署名"))
|
|
1124
|
+
if not actor.startswith("agent"):
|
|
1125
|
+
sys.exit(tt("--proposals: --actor must start with 'agent' (agent:<name>) — this path applies a "
|
|
1126
|
+
"machine's proposals; a person's verdict is --certify",
|
|
1127
|
+
"--proposals:--actor 须以 'agent' 开头(agent:<名字>)——此路径应用的是机器的提议;"
|
|
1128
|
+
"人工裁决请用 --certify"))
|
|
1129
|
+
if not os.path.isfile(args.proposals):
|
|
1130
|
+
sys.exit(tt(f"no such proposals file: {args.proposals}", f"没有这个提议文件:{args.proposals}"))
|
|
1131
|
+
path = args.frm or newest_artifact()
|
|
1132
|
+
if not os.path.isfile(path):
|
|
1133
|
+
sys.exit(tt(f"no such ontology artifact: {path}", f"没有这个本体文件:{path}"))
|
|
1134
|
+
o, rep = apply_proposals(json.load(open(path)), json.load(open(args.proposals)), actor=actor)
|
|
1135
|
+
for a in rep["applied"]:
|
|
1136
|
+
print(f" - {a['name']}: {a['from_type']} → {a['to_type']} — \"{a['quote'][:70]}\" · "
|
|
1137
|
+
f"{a['relations']} relation(s) kept")
|
|
1138
|
+
print(tt(f"re-typed {len(rep['applied'])} entit(y/ies) from {args.proposals} · {rep['not_grounded']} not grounded "
|
|
1139
|
+
f"(skipped) · {len(rep['stale'])} stale · {len(rep['human_certified'])} human-certified (not touched) · "
|
|
1140
|
+
f"{len(rep['off_tbox'])} outside the TBox",
|
|
1141
|
+
f"改型 {len(rep['applied'])} 个实体,来自 {args.proposals} · {rep['not_grounded']} 条未过判官(跳过)· "
|
|
1142
|
+
f"{len(rep['stale'])} 条已过期 · {len(rep['human_certified'])} 条人工认证(未动)· "
|
|
1143
|
+
f"{len(rep['off_tbox'])} 条类型不在 TBox"))
|
|
1144
|
+
for key in ("stale", "human_certified", "off_tbox"):
|
|
1145
|
+
if rep[key]:
|
|
1146
|
+
print(f" · {key.replace('_', ' ')}: {', '.join(map(str, rep[key]))}")
|
|
1147
|
+
if rep["applied"]:
|
|
1148
|
+
os.makedirs(OUTDIR, exist_ok=True) # --from may point at an artifact outside OUTDIR
|
|
1149
|
+
out = os.path.join(OUTDIR, dt.datetime.now().strftime("%Y%m%d-%H%M%S") + "-retyped.json")
|
|
1150
|
+
json.dump(o, open(out, "w"), ensure_ascii=False, indent=1)
|
|
1151
|
+
print(f"-> {out}")
|
|
1152
|
+
return
|
|
1153
|
+
|
|
527
1154
|
if args.html and not args.docs:
|
|
528
1155
|
import render_html
|
|
529
|
-
path = args.frm or
|
|
1156
|
+
path = args.frm or newest_artifact()
|
|
530
1157
|
out = os.path.splitext(path)[0] + ".html"
|
|
531
1158
|
open(out, "w", encoding="utf-8").write(render_html.render(to_markdown(json.load(open(path)))))
|
|
532
1159
|
print(f"html -> {out}")
|
|
533
1160
|
return
|
|
534
1161
|
|
|
535
1162
|
if args.jsonld:
|
|
536
|
-
path = args.frm or
|
|
1163
|
+
path = args.frm or newest_artifact()
|
|
537
1164
|
out = os.path.splitext(path)[0] + ".jsonld"
|
|
538
1165
|
json.dump(to_jsonld(json.load(open(path))), open(out, "w"), ensure_ascii=False, indent=1)
|
|
539
1166
|
print(f"jsonld -> {out}")
|
|
540
1167
|
return
|
|
541
1168
|
|
|
542
1169
|
if args.query:
|
|
543
|
-
path = args.frm or
|
|
544
|
-
|
|
1170
|
+
path = args.frm or newest_artifact()
|
|
1171
|
+
o = json.load(open(path))
|
|
1172
|
+
hits = query_ontology(o, args.query)
|
|
545
1173
|
print(f"# {args.query} — {path}")
|
|
546
1174
|
for e in hits["entities"]:
|
|
547
1175
|
print(f"\n[{e['type']}] {e['name']}" +
|
|
548
|
-
(f" (aliases: {', '.join(e['aliases'])})" if e.get("aliases") else ""))
|
|
1176
|
+
(f" (aliases: {', '.join(e['aliases'])})" if e.get("aliases") else "") + _mark(e, "type_grounding"))
|
|
549
1177
|
for ev in e.get("evidences", []):
|
|
550
|
-
print(f' | {ev["doc"]}: "{ev["quote"]}"')
|
|
1178
|
+
print(f' | {ev["doc"]}{_where(ev)}: "{ev["quote"]}"' + _ev_mark(ev))
|
|
551
1179
|
for r in hits["relations"]:
|
|
552
|
-
print(f"\n({r['subject']}) -[{r['predicate']}]-> ({r['object']})")
|
|
1180
|
+
print(f"\n({r['subject']}) -[{r['predicate']}]-> ({r['object']})" + _mark(r, "grounding"))
|
|
553
1181
|
for ev in r.get("evidences", []):
|
|
554
|
-
print(f' | {ev["doc"]}: "{ev["quote"]}"')
|
|
1182
|
+
print(f' | {ev["doc"]}{_where(ev)}: "{ev["quote"]}"' + _ev_mark(ev))
|
|
555
1183
|
if not hits["entities"] and not hits["relations"]:
|
|
556
1184
|
print(tt("no assertions matched", "无匹配断言"))
|
|
1185
|
+
elif any("type_grounding" in e for e in hits["entities"]) or any("grounding" in r for r in hits["relations"]):
|
|
1186
|
+
print("\n" + tt("✓ the quote grounds the claim · ⚠ no carried quote grounds it (kept and flagged)",
|
|
1187
|
+
"✓ 引文支撑断言 · ⚠ 现有引文均不支撑(保留并标记)"))
|
|
557
1188
|
return
|
|
558
1189
|
|
|
559
|
-
if not args.
|
|
560
|
-
sys.exit(tt("--docs and --domain are required for a build
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
1190
|
+
if not args.domain or not (args.docs or args.kb):
|
|
1191
|
+
sys.exit(tt("--docs and --domain are required for a build (--kb reads a WeKnora knowledge base)",
|
|
1192
|
+
"构建需要 --docs 与 --domain(--kb 读取 WeKnora 知识库)"))
|
|
1193
|
+
if args.docs and args.kb:
|
|
1194
|
+
ap.error("--docs and --kb name two corpora: one source per build")
|
|
1195
|
+
if args.limit is not None and not args.kb:
|
|
1196
|
+
ap.error("--limit applies to --kb (how many chunks to read)")
|
|
1197
|
+
if args.limit is not None and args.limit < 1:
|
|
1198
|
+
ap.error("--limit must be at least 1")
|
|
1199
|
+
kb_info = None
|
|
1200
|
+
if args.kb:
|
|
1201
|
+
docs, kb_info = kb_chunks(args.kb, limit=args.limit)
|
|
1202
|
+
skipped = kb_info["skipped_documents"]
|
|
1203
|
+
corpus = tt(f"corpus: {len(docs)} chunk(s) of {kb_info['documents']} document(s) in knowledge base {args.kb}"
|
|
1204
|
+
+ (f" — {sum(skipped.values())} not read: " + ", ".join(f"{v} {k}" for k, v in sorted(skipped.items()))
|
|
1205
|
+
if skipped else ""),
|
|
1206
|
+
f"语料:知识库 {args.kb} 的 {kb_info['documents']} 篇文档共 {len(docs)} 个分块"
|
|
1207
|
+
+ (f"——{sum(skipped.values())} 篇未读:" + "、".join(f"{v} 篇 {k}" for k, v in sorted(skipped.items()))
|
|
1208
|
+
if skipped else ""))
|
|
1209
|
+
else:
|
|
1210
|
+
docs = file_docs(os.path.expanduser(args.docs))
|
|
1211
|
+
corpus = tt(f"corpus: {len(docs)} doc(s)", f"语料:{len(docs)} 篇")
|
|
570
1212
|
if not docs:
|
|
571
|
-
sys.exit(tt("no
|
|
572
|
-
|
|
573
|
-
|
|
1213
|
+
sys.exit(tt(f"knowledge base {args.kb} holds no readable chunk (no completed document, or an empty base)"
|
|
1214
|
+
if args.kb else "no documents matched",
|
|
1215
|
+
f"知识库 {args.kb} 没有可读分块(没有解析完成的文档,或库为空)" if args.kb else "无文档"))
|
|
1216
|
+
print(corpus + tt(f" · domain: {args.domain}", f" · 领域:{args.domain}"), file=sys.stderr)
|
|
574
1217
|
|
|
575
1218
|
base, prior_stats = None, None
|
|
576
1219
|
if args.merge:
|
|
@@ -578,7 +1221,8 @@ def main():
|
|
|
578
1221
|
prior_stats = {k: len(base[k]) for k in ("entities", "relations", "conflicts")}
|
|
579
1222
|
print(tt(f"merging into {args.merge} (append-only)", f"增量并入 {args.merge}(append-only)"), file=sys.stderr)
|
|
580
1223
|
|
|
581
|
-
st, new_type_descs, corefed = build(docs, args.domain, base=base, sample=max(1, args.sample)
|
|
1224
|
+
st, new_type_descs, corefed, tally = build(docs, args.domain, base=base, sample=max(1, args.sample),
|
|
1225
|
+
ground=not args.no_ground)
|
|
582
1226
|
if corefed:
|
|
583
1227
|
st["merge_log"].append({"ran_at": dt.datetime.now().isoformat(timespec="seconds"),
|
|
584
1228
|
"coref_merges": corefed})
|
|
@@ -588,18 +1232,35 @@ def main():
|
|
|
588
1232
|
"added_docs": len(docs),
|
|
589
1233
|
"entities_before": prior_stats["entities"],
|
|
590
1234
|
"entities_after": len(st["entities"])})
|
|
591
|
-
prov = {"model":
|
|
1235
|
+
prov = {"model": MODEL, "temperature": 0, "elapsed_s": round(time.time() - t0),
|
|
592
1236
|
"calls": COST["calls"], "tokens_in": COST["in"], "tokens_out": COST["out"],
|
|
593
|
-
"docs_this_run": len(docs), "merged_from": bool(args.merge)
|
|
1237
|
+
"docs_this_run": len(docs), "merged_from": bool(args.merge),
|
|
1238
|
+
"judge_model": JUDGE_MODEL, "grounding_pass": not args.no_ground,
|
|
1239
|
+
**({"kb": kb_info} if kb_info else {})}
|
|
594
1240
|
o = store_to_ontology(st, new_type_descs, prov)
|
|
595
1241
|
|
|
596
1242
|
print(f"\n## Ontology build · {args.domain}\n")
|
|
1243
|
+
if kb_info:
|
|
1244
|
+
print(tt(f"- source: WeKnora knowledge base {kb_info['id']} — {kb_info['chunks']} chunk(s) of "
|
|
1245
|
+
f"{kb_info['documents']} document(s), every evidence carrying its chunk_id",
|
|
1246
|
+
f"- 来源:WeKnora 知识库 {kb_info['id']}——{kb_info['documents']} 篇文档的 {kb_info['chunks']} 个分块,"
|
|
1247
|
+
f"每条证据都带 chunk_id"))
|
|
597
1248
|
print(tt(f"- Entity types {len(o['tbox']['entity_types'])} · entities {o['stats']['entities']} · "
|
|
598
1249
|
f"relations {o['stats']['relations']} · conflicts {o['stats']['conflicts']} · "
|
|
599
1250
|
f"unknown types flagged {o['stats']['flagged']}",
|
|
600
1251
|
f"- 实体类型 {len(o['tbox']['entity_types'])} · 实体 {o['stats']['entities']} · "
|
|
601
1252
|
f"关系 {o['stats']['relations']} · 冲突 {o['stats']['conflicts']} · "
|
|
602
1253
|
f"未知类型拦截 {o['stats']['flagged']}"))
|
|
1254
|
+
if not args.no_ground:
|
|
1255
|
+
s = o["stats"]
|
|
1256
|
+
print(tt(f"- type grounding (judge {JUDGE_MODEL}): entities {s['entities_grounded']} grounded · "
|
|
1257
|
+
f"{s['entities_ungrounded']} ungrounded; relations {s['relations_grounded']} grounded · "
|
|
1258
|
+
f"{s['relations_ungrounded']} ungrounded; {tally['regrounded']} quote(s) re-grounded · "
|
|
1259
|
+
f"{s['ungrounded_type_clashes']} ungrounded type clash(es) kept out of conflicts",
|
|
1260
|
+
f"- 类型接地(判官 {JUDGE_MODEL}):实体 {s['entities_grounded']} 接地 · "
|
|
1261
|
+
f"{s['entities_ungrounded']} 未接地;关系 {s['relations_grounded']} 接地 · "
|
|
1262
|
+
f"{s['relations_ungrounded']} 未接地;{tally['regrounded']} 条引文重取 · "
|
|
1263
|
+
f"{s['ungrounded_type_clashes']} 条未接地类型冲突未计入 conflicts"))
|
|
603
1264
|
print(tt(f"- provenance: {prov['calls']} calls · {prov['tokens_in']:,} in / {prov['tokens_out']:,} out tokens · {prov['elapsed_s']}s",
|
|
604
1265
|
f"- 溯源:{prov['calls']} 次调用 · {prov['tokens_in']:,} 入 / {prov['tokens_out']:,} 出 · {prov['elapsed_s']}s"))
|
|
605
1266
|
for c in o["conflicts"][:6]:
|
|
@@ -620,13 +1281,7 @@ def main():
|
|
|
620
1281
|
open(base_path + ".html", "w", encoding="utf-8").write(render_html.render(to_markdown(o)))
|
|
621
1282
|
except Exception as exc:
|
|
622
1283
|
print(f"⚠ html render skipped ({type(exc).__name__})", file=sys.stderr)
|
|
623
|
-
open(base_path + ".md", "w").write(
|
|
624
|
-
f"# Ontology · {args.domain}\n\nEntities {o['stats']['entities']} · relations {o['stats']['relations']} · "
|
|
625
|
-
f"conflicts {o['stats']['conflicts']} · unknown types flagged {o['stats']['flagged']}.\n"
|
|
626
|
-
f"Evidence lives in the JSON; provenance: {prov['calls']} calls, {prov['elapsed_s']}s.\n",
|
|
627
|
-
f"# 本体 · {args.domain}\n\n实体 {o['stats']['entities']} · 关系 {o['stats']['relations']} · "
|
|
628
|
-
f"冲突 {o['stats']['conflicts']} · 未知类型拦截 {o['stats']['flagged']}。\n"
|
|
629
|
-
f"证据随 JSON;溯源:{prov['calls']} 次调用,{prov['elapsed_s']}s。\n"))
|
|
1284
|
+
open(base_path + ".md", "w", encoding="utf-8").write(to_markdown(o))
|
|
630
1285
|
print(f"\n→ {base_path}.json / .svg / .md", file=sys.stderr)
|
|
631
1286
|
|
|
632
1287
|
|