dsh-auto-ontology 0.0.1 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vicfei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,9 +1,26 @@
1
1
  # dsh-auto-ontology
2
2
 
3
- > Auto ontology construction, natively on DeepSeek Harness: feed documents, get a typed ontology (TBox + ABox) where **every entity and relation carries its source quote.** No evidence, no assertion; unknown types flagged, never silently dropped.
4
- >
5
- > Implements the concept of [NVIDIA/auto-ontology](https://github.com/NVIDIA/auto-ontology); independent community project, not affiliated.
3
+ **Auto ontology construction with evidence, for DeepSeek Harness** — feed it
4
+ documents, get a typed ontology (TBox + ABox) where every entity and relation
5
+ carries its source quote. No evidence, no assertion; unknown types are flagged,
6
+ never silently dropped.
6
7
 
7
- **Status: name reserved — first release in development.**
8
+ ```bash
9
+ npm i -g dsh-auto-ontology
10
+ auto-ontology build --docs ~/my-corpus/*.md --domain "internal design docs" --save
11
+ ```
8
12
 
9
- Engine and docs: https://github.com/vicfei/dsh-auto-ontology
13
+ - Zero-infra: `python3` (stdlib) + a DeepSeek key you already have. No Docker,
14
+ no database — the deliberate opposite of the enterprise-metadata stacks.
15
+ - Two-pass pipeline: TBox schema from corpus samples → per-document ABox
16
+ assertions, each with an evidence span.
17
+ - Outputs: typed JSON (every assertion + evidence), zero-dep SVG cluster graph,
18
+ markdown digest.
19
+ - Register the DSH skill:
20
+ `ln -s "$(npm root -g)/dsh-auto-ontology/skills/dsh-auto-ontology" ~/.dsh/skills/dsh-auto-ontology`
21
+
22
+ Implements the concept of [NVIDIA/auto-ontology](https://github.com/NVIDIA/auto-ontology)
23
+ (13.3k★, Apache-2.0) natively for DSH — clean-room, zero upstream code, not
24
+ affiliated. **Not investment/enterprise advice.**
25
+
26
+ Full docs: [github.com/vicfei/dsh-auto-ontology](https://github.com/vicfei/dsh-auto-ontology)
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ // dsh-auto-ontology CLI — a JS shell spawning the bundled Python engine
3
+ // (the dsh-laya sidecar precedent, proven across the family).
4
+ //
5
+ // auto-ontology build --docs <dir-or-glob> --domain "..." --save [--lang zh]
6
+ // auto-ontology --docs ... (build is the default subcommand)
7
+ import { spawnSync } from "node:child_process";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const argv = process.argv.slice(2);
13
+ const [cmd, ...rest] = argv;
14
+
15
+ let pass;
16
+ if (cmd === "build") {
17
+ pass = rest;
18
+ } else {
19
+ pass = argv; // engine args pass through verbatim (build is the default)
20
+ }
21
+
22
+ // Artifacts land in the caller's cwd (the engine reads ONTOLOGY_HOME).
23
+ const env = {
24
+ ...process.env,
25
+ ONTOLOGY_HOME: path.join(process.cwd(), "ontologies"),
26
+ };
27
+
28
+ const r = spawnSync("python3", [path.join(root, "scripts", "build_ontology.py"), ...pass], {
29
+ stdio: "inherit",
30
+ env,
31
+ });
32
+ process.exit(r.status ?? 1);
package/build.mjs ADDED
@@ -0,0 +1,14 @@
1
+ // prepack: stage the engine from the repo (npm/ never commits staged copies —
2
+ // publish always picks up the current tree; sweep __pycache__ like the family recipe)
3
+ import { cpSync, rmSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const here = path.dirname(fileURLToPath(import.meta.url));
8
+ const repo = path.resolve(here, "..");
9
+
10
+ rmSync(path.join(here, "scripts"), { recursive: true, force: true });
11
+ cpSync(path.join(repo, "scripts"), path.join(here, "scripts"), { recursive: true });
12
+ cpSync(path.join(repo, "LICENSE"), path.join(here, "LICENSE"));
13
+ rmSync(path.join(here, "scripts", "__pycache__"), { recursive: true, force: true });
14
+ console.log("staged scripts/ LICENSE from repo root");
@@ -0,0 +1,12 @@
1
+ # dsh-auto-ontology bundle layer.
2
+ #
3
+ # Deliberately inserts no plugin entry: this bundle is a distribution vehicle —
4
+ # a skill (skills/dsh-auto-ontology/SKILL.md, discovered by @deepseek-ai/dsh-skill-filesystem
5
+ # from ~/.dsh/skills/ or <project>/.dsh/skills/) and a CLI (`auto-ontology`, npm bin)
6
+ # that spawns the bundled Python engine. A cordis plugin import would fail: the
7
+ # package ships no plugin module (typed-tools lands in the 0.2.0 track, issue #11).
8
+ #
9
+ # Install:
10
+ # npm i -g dsh-auto-ontology
11
+ # ln -s "$(npm root -g)/dsh-auto-ontology/skills/dsh-auto-ontology" ~/.dsh/skills/dsh-auto-ontology
12
+ []
package/package.json CHANGED
@@ -1,10 +1,49 @@
1
1
  {
2
2
  "name": "dsh-auto-ontology",
3
- "version": "0.0.1",
4
- "description": "Auto ontology construction for DeepSeek Harness — two-pass LLM pipeline (TBox schema from corpus, ABox assertions per document) with evidence quotes on every entity/relation and type-guard against silent drops. Implements the concept of NVIDIA/auto-ontology. Name reserved; first release in development.",
5
- "keywords": ["deepseek-harness", "dsh", "dsh-plugin", "auto-ontology", "ontology", "knowledge-graph", "llm-extraction", "evidence-grounding"],
6
- "repository": {"type": "git", "url": "git+https://github.com/vicfei/dsh-auto-ontology.git"},
3
+ "version": "0.1.0",
4
+ "description": "Auto ontology construction for DeepSeek Harness — two-pass LLM pipeline (TBox schema from corpus, ABox assertions per document) with an evidence quote on every entity/relation and a type guard against silent drops. Zero-infra stdlib CLI; implements the concept of NVIDIA/auto-ontology, not affiliated.",
5
+ "type": "module",
6
+ "bin": {
7
+ "auto-ontology": "bin/auto-ontology.js"
8
+ },
9
+ "scripts": {
10
+ "prepack": "node build.mjs"
11
+ },
12
+ "engines": {
13
+ "node": "^20.19.0 || >=22.0.0"
14
+ },
15
+ "dsh": {
16
+ "bundle": {
17
+ "patch": "./cordis.patch.yml"
18
+ },
19
+ "manifestVersion": 1
20
+ },
21
+ "files": [
22
+ "bin",
23
+ "skills",
24
+ "scripts",
25
+ "cordis.patch.yml",
26
+ "build.mjs",
27
+ "LICENSE"
28
+ ],
29
+ "keywords": [
30
+ "deepseek-harness",
31
+ "dsh",
32
+ "dsh-plugin",
33
+ "auto-ontology",
34
+ "ontology",
35
+ "knowledge-graph",
36
+ "llm-extraction",
37
+ "evidence-grounding"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/vicfei/dsh-auto-ontology.git"
42
+ },
7
43
  "homepage": "https://github.com/vicfei/dsh-auto-ontology#readme",
44
+ "bugs": {
45
+ "url": "https://github.com/vicfei/dsh-auto-ontology/issues"
46
+ },
8
47
  "license": "MIT",
9
48
  "author": "vicfei"
10
49
  }
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python3
2
+ """自动本体构建引擎(NVIDIA auto-ontology 概念位 M0)
3
+
4
+ 上游 auto-ontology(13.3k★,Apache-2.0)= 从非结构化数据自动构建语义图
5
+ 本体。本插件原生实现其双 pass 管线,家族差异=**证据溯源**:每条实体/关系
6
+ 带原文引文跨度(evidence span),无证据的断言不落库;类型守卫:实例类型
7
+ 必须 ∈ 第一 pass 抽取的 TBox,未知类型标注不静默丢弃(对拍血统)。
8
+
9
+ 管线(2 类 LLM 调用,temperature=0):
10
+ Pass1 schema:从文档样本抽候选实体类型+关系类型(TBox)
11
+ Pass2 assert:逐文档抽实体/关系实例(ABox),每条带 evidence 原文引用
12
+ 合并:类型守卫 + 去重 → ontology JSON + 环形布局 SVG 图 + markdown 摘要
13
+
14
+ 用法:
15
+ python3 scripts/build_ontology.py --docs <dir_or_glob> --domain "description" --save [--lang zh]
16
+ """
17
+ import argparse, datetime as dt, glob, json, math, os, re, subprocess, sys
18
+
19
+ KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+
21
+ # Output language: English by default (international-first), --lang zh / ONTOLOGY_LANG for Chinese
22
+ LANG = os.environ.get("ONTOLOGY_LANG") or "en"
23
+ # npm CLI form lands artifacts in the caller's cwd via ONTOLOGY_HOME (repo default unchanged)
24
+ OUTDIR = os.environ.get("ONTOLOGY_HOME") or os.path.join(KIT, "ontologies")
25
+ def tt(en, zh):
26
+ return en if LANG == "en" else zh
27
+
28
+
29
+ def llm(sysmsg, user, json_out=True):
30
+ key = subprocess.run(["bash", "-c", 'grep -m1 "^export DEEPSEEK_API_KEY=" ~/.bashrc | cut -d= -f2'],
31
+ capture_output=True, text=True).stdout.strip().strip('"')
32
+ body = {"model": "deepseek-chat", "temperature": 0,
33
+ "messages": [{"role": "system", "content": sysmsg}, {"role": "user", "content": user}]}
34
+ if json_out:
35
+ body["response_format"] = {"type": "json_object"}
36
+ r = subprocess.run(["curl", "-s", "-m", "180", "https://api.deepseek.com/chat/completions",
37
+ "-H", f"Authorization: Bearer {key}", "-H", "Content-Type: application/json",
38
+ "-d", json.dumps(body)], capture_output=True, text=True)
39
+ txt = json.loads(r.stdout)["choices"][0]["message"]["content"]
40
+ return json.loads(re.sub(r"^```(json)?|```$", "", txt.strip(), flags=re.M).strip()) if json_out else txt
41
+
42
+
43
+ def main():
44
+ global LANG
45
+ ap = argparse.ArgumentParser()
46
+ ap.add_argument("--docs", required=True, help="目录或 glob,如 '~/dsh-*/README.md'")
47
+ ap.add_argument("--domain", required=True, help="语料领域描述(喂给 schema pass)")
48
+ ap.add_argument("--save", action="store_true")
49
+ ap.add_argument("--lang", choices=("en", "zh"), default=LANG, help="output language (default en)")
50
+ args = ap.parse_args()
51
+ LANG = args.lang
52
+ paths = sorted(glob.glob(os.path.expanduser(args.docs))) if "*" in args.docs else \
53
+ sorted(glob.glob(os.path.join(args.docs, "*")))
54
+ docs = []
55
+ for p in paths:
56
+ try:
57
+ docs.append({"path": os.path.basename(os.path.dirname(p)) or p, "text": open(p).read()[:6000]})
58
+ except Exception:
59
+ pass
60
+ if not docs:
61
+ sys.exit(tt("no documents matched", "无文档"))
62
+ print(tt(f"corpus: {len(docs)} doc(s) · domain: {args.domain}", f"语料:{len(docs)} 篇 · 领域:{args.domain}"), file=sys.stderr)
63
+
64
+ sample = "\n\n".join(d["text"][:1500] for d in docs[:4])
65
+ tbox = llm(
66
+ tt("You are an ontology engineer. Extract the ontology schema (TBox) from the corpus sample. Output JSON: "
67
+ '{"entity_types":[{"name":"...","desc":"..."}],"relation_types":[{"name":"...","domains":"TypeA","ranges":"TypeB","desc":"..."}]}. '
68
+ "Type names in English snake_case; write every desc in English. Extract only what the corpus genuinely supports — prefer fewer, truer types.",
69
+ "你是本体工程师。从语料样本抽取本体模式(TBox)。输出 JSON:"
70
+ '{"entity_types":[{"name":"...","desc":"..."}],"relation_types":[{"name":"...","domains":"类型A","ranges":"类型B","desc":"..."}]}'
71
+ "。类型名用英文 snake_case,desc 用中文。只抽取语料真实支撑的,宁缺毋滥。"),
72
+ tt(f"Domain: {args.domain}\nCorpus sample:\n{sample}", f"领域:{args.domain}\n语料样本:\n{sample}"))
73
+
74
+ etypes = {e["name"] for e in tbox.get("entity_types", [])}
75
+ abox, flagged = [], []
76
+ for d in docs:
77
+ out = llm(
78
+ tt("You are an ontology instance extractor. From the document, extract entity and relation instances (ABox) based on the given TBox. "
79
+ "Discipline: every instance must carry evidence=a verbatim quote from the document (<=40 chars); types must come from the TBox; "
80
+ "when unsure, do not extract. Output JSON: "
81
+ '{"entities":[{"name":"...","type":"...","evidence":"..."}],'
82
+ '"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}',
83
+ "你是本体实例抽取器。基于给定 TBox 从文档抽取实体与关系实例(ABox)。"
84
+ "**纪律**:每条实例必须附 evidence=文档原文引文(不超过40字);类型必须取自 TBox;"
85
+ "不确定的不抽。输出 JSON:"
86
+ '{"entities":[{"name":"...","type":"...","evidence":"..."}],'
87
+ '"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
88
+ tt(f"TBox:\n{json.dumps(tbox, ensure_ascii=False)}\n\nDocument ({d['path']}):\n{d['text']}",
89
+ f"TBox:{json.dumps(tbox, ensure_ascii=False)}\n\n文档({d['path']}):\n{d['text']}"))
90
+ for e in out.get("entities", []):
91
+ if e.get("name"):
92
+ (abox if e.get("type") in etypes else flagged).append({**e, "doc": d["path"]})
93
+ for r in out.get("relations", []):
94
+ abox.append({**r, "doc": d["path"]})
95
+ ent_names = {e["name"] for e in abox if "type" in e}
96
+ rels = [r for r in abox if "predicate" in r and r["subject"] in ent_names and r["object"] in ent_names]
97
+
98
+ ontology = {"domain": args.domain, "built_at": dt.datetime.now().isoformat(timespec="seconds"),
99
+ "tbox": tbox, "abox": {"entities": [e for e in abox if "type" in e], "relations": rels},
100
+ "flagged_unknown_types": flagged,
101
+ "stats": {"docs": len(docs), "entities": len(abox) - len(rels), "relations": len(rels),
102
+ "flagged": len(flagged)}}
103
+ print(f"\n## 本体构建 · {args.domain}\n")
104
+ print(tt(f"- Entity types {len(tbox.get('entity_types', []))} · relation types {len(tbox.get('relation_types', []))} · "
105
+ f"entities {ontology['stats']['entities']} · relations {len(rels)} · unknown types flagged {len(flagged)}",
106
+ f"- 实体类型 {len(tbox.get('entity_types', []))} · 关系类型 {len(tbox.get('relation_types', []))} · "
107
+ f"实体 {ontology['stats']['entities']} · 关系 {len(rels)} · 未知类型被拦 {len(flagged)}"))
108
+ for e in tbox.get("entity_types", [])[:8]:
109
+ print(f" - T: {e['name']} — {e.get('desc', '')[:40]}")
110
+ for r in rels[:12]:
111
+ print(f" - R: ({r['subject']}) -[{r['predicate']}]-> ({r['object']}) | ev: {r.get('evidence', '')[:40]}")
112
+ if flagged:
113
+ print(tt(f" ⚠ {len(flagged)} instance(s) with unknown types NOT stored (type guard — flagged, never silently dropped)",
114
+ f" ⚠ 未入库的未知类型实例 {len(flagged)} 条(类型守卫,不静默丢弃)"))
115
+
116
+ if args.save:
117
+ os.makedirs(OUTDIR, exist_ok=True)
118
+ base = os.path.join(OUTDIR, dt.datetime.now().strftime("%Y%m%d-%H%M"))
119
+ json.dump(ontology, open(base + ".json", "w"), ensure_ascii=False, indent=1)
120
+ # 环形布局 SVG(类型分簇)
121
+ ents = ontology["abox"]["entities"]
122
+ by_type = {}
123
+ for e in ents:
124
+ by_type.setdefault(e["type"], []).append(e)
125
+ colors = ["#2456c4", "#c23531", "#2f8a4c", "#8a5fc2", "#b07a2a", "#2a8a8a"]
126
+ nodes, cx, cy, W, H = [], 400, 340, 860, 700
127
+ clusters = list(by_type.items())[:6]
128
+ for ci, (t, es) in enumerate(clusters):
129
+ r0, ang0 = 60 + ci * 45, ci * 2 * math.pi / max(len(clusters), 1)
130
+ gx, gy = cx + r0 * 1.9 * math.cos(ang0), cy + r0 * 1.5 * math.sin(ang0)
131
+ for i, e in enumerate(es[:10]):
132
+ a = 2 * math.pi * i / max(len(es[:10]), 1)
133
+ nodes.append((e["name"][:14], gx + 52 * math.cos(a), gy + 40 * math.sin(a), colors[ci % 6]))
134
+ svg = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" font-family="monospace">',
135
+ f'<text x="10" y="16" font-size="13">{args.domain} · {len(ents)} entities / {len(rels)} relations</text>']
136
+ for r in rels:
137
+ nm = {n[0]: (n[1], n[2]) for n in nodes}
138
+ if r["subject"] in nm and r["object"] in nm:
139
+ x1, y1 = nm[r["subject"]]; x2, y2 = nm[r["object"]]
140
+ svg.append(f'<line x1="{x1:.0f}" y1="{y1:.0f}" x2="{x2:.0f}" y2="{y2:.0f}" stroke="#99a" stroke-width="0.7"/>')
141
+ for name, x, y, c in nodes:
142
+ svg.append(f'<circle cx="{x:.0f}" cy="{y:.0f}" r="4" fill="{c}"/>'
143
+ f'<text x="{x + 6:.0f}" y="{y + 3:.0f}" font-size="9" fill="#345">{name}</text>')
144
+ svg.append("</svg>")
145
+ open(base + ".svg", "w").write("".join(svg))
146
+ open(base + ".md", "w").write(tt(
147
+ f"# Ontology · {args.domain}\n\nEntities {len(ents)} · relations {len(rels)} · "
148
+ f"evidence lives in the JSON (ontologies/*.json); unknown types flagged: {len(flagged)}.\n",
149
+ f"# 本体 · {args.domain}\n\n实体 {len(ents)} · 关系 {len(rels)} · "
150
+ f"证据随 JSON(ontologies/*.json);未知类型拦截 {len(flagged)} 条。\n"))
151
+ print(f"\n→ {base}.json / .svg / .md", file=sys.stderr)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: dsh-auto-ontology
3
+ description: Auto ontology construction for DeepSeek Harness — two-pass LLM pipeline (TBox schema from corpus, ABox assertions per document) with an evidence quote on every entity/relation and a type guard against silent drops. English-first, --lang zh for Chinese.
4
+ ---
5
+
6
+ Use this skill when asked to turn a document corpus into a knowledge graph /
7
+ ontology ("extract a knowledge graph from these docs", "build an ontology").
8
+ **Evidence is the contract** — no assertion lands without its source quote, and
9
+ unknown types are flagged, never silently dropped.
10
+
11
+ ## Run
12
+
13
+ `auto-ontology` must be on PATH (`npm i -g dsh-auto-ontology`).
14
+
15
+ ```bash
16
+ auto-ontology build --docs <dir-or-glob> --domain "<description>" --save # typed JSON + SVG cluster graph + md digest
17
+ auto-ontology build --docs '*.md' --domain "..." --lang zh # Chinese prompts/artifacts
18
+ ```
19
+
20
+ Requires `python3` (stdlib only) and a `DEEPSEEK_API_KEY` in `~/.bashrc`.
21
+ Artifacts land in `./ontologies/` (relative to where you invoke); the SVG is
22
+ the shareable overview, the JSON carries every assertion with its evidence span.
23
+
24
+ ## Discipline
25
+
26
+ - Every entity/relation must carry `evidence` = a verbatim quote (≤40 chars);
27
+ the engine rejects no-evidence assertions.
28
+ - Instance types must come from the extracted TBox; unknown types are recorded
29
+ in `flagged_unknown_types`, never silently dropped.
30
+ - Artifacts are append-only in spirit: a new run writes new files; it never
31
+ edits a prior ontology.