templates.py
6.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""本体即代码:YAML 导入导出 + 行业模板包。
YAML 里概念之间用名称引用(`@指标名` 或直接写名称),导入时解析成 id,
这样模板可读、可 diff、可在客户之间复用。能力(技能/动作)与 SOP 也可以放在同一份 YAML 里,
由各自模块注册的 section handler 处理。
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable
import yaml
from fastapi import HTTPException
from ..governance import audit
from . import schema, service
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates"
# 其他 section(capabilities / sops)的导入导出由对应模块注册
_import_sections: dict[str, Callable[[list[dict]], dict]] = {}
_export_sections: dict[str, Callable[[], list[dict]]] = {}
def register_section(name: str, importer: Callable[[list[dict]], dict],
exporter: Callable[[], list[dict]]) -> None:
_import_sections[name] = importer
_export_sections[name] = exporter
_REF_FIELDS = {"metric": ("calibre_rule", "calendar", "object_type"),
"link_type": ("from_type", "to_type"), "dimension": ("object_type",),
"term": ("refers_to",)}
def export_yaml(include_drafts: bool = True) -> str:
items = service.list_concepts(status="" if include_drafts else "published")
id2name = {c["id"]: c["name"] for c in items}
concepts = []
for brief in items:
c = service.get_concept(brief["id"])
spec = dict(c.get("spec") or {})
for f in _REF_FIELDS.get(c["kind"], ()):
if spec.get(f) in id2name:
spec[f] = "@" + id2name[spec[f]]
entry: dict[str, Any] = {"kind": c["kind"], "name": c["name"]}
for k in ("display_name", "description"):
if c.get(k):
entry[k] = c[k]
if c.get("synonyms"):
entry["synonyms"] = c["synonyms"]
if spec:
entry["spec"] = spec
if c.get("bindings"):
entry["bindings"] = [{"ds_id": b["ds_id"], "target_kind": b["target_kind"],
"ref": b["ref"]} for b in c["bindings"]]
concepts.append(entry)
doc: dict[str, Any] = {"version": 1, "concepts": concepts}
for name, fn in _export_sections.items():
try:
doc[name] = fn()
except Exception: # noqa: BLE001
doc[name] = []
return yaml.safe_dump(doc, allow_unicode=True, sort_keys=False, width=120)
def _deref(v: Any) -> Any:
if isinstance(v, str) and v.startswith("@"):
found = service.find(v[1:])
return found["id"] if found else v[1:]
return v
def import_yaml(text: str, *, ds_map: dict[int, int] | None = None, overwrite: bool = False,
with_bindings: bool = True) -> dict:
"""导入。已存在的同名同类概念默认跳过(overwrite=True 时覆盖)。
ds_map:模板里的数据源编号 → 本地数据源编号。模板通常不带绑定,带了也要映射。
"""
try:
doc = yaml.safe_load(text) or {}
except yaml.YAMLError as e:
raise HTTPException(422, f"YAML 解析失败:{e}") from e
if not isinstance(doc, dict):
raise HTTPException(422, "YAML 顶层必须是对象")
items = doc.get("concepts") or []
created, updated, skipped, errors = [], [], [], []
# 两遍:先建全部概念(引用可能指向后面的),再回填引用
pending_refs: list[tuple[str, str, dict]] = []
for it in items:
kind, name = it.get("kind"), str(it.get("name") or "").strip()
if kind not in schema.KINDS or not name:
errors.append(f"无效条目:{it!r}"[:200])
continue
spec = dict(it.get("spec") or {})
raw_refs = {f: spec.get(f) for f in _REF_FIELDS.get(kind, ()) if spec.get(f)}
for f in raw_refs:
spec[f] = ""
existing = service.find(name, kind)
try:
if existing and not overwrite:
skipped.append(name)
continue
if existing:
c = service.update_concept(existing["id"], display_name=it.get("display_name"),
description=it.get("description"),
synonyms=it.get("synonyms"), spec=spec)
updated.append(name)
else:
c = service.create_concept(kind, name, display_name=it.get("display_name", ""),
description=it.get("description", ""),
synonyms=it.get("synonyms"), spec=spec,
origin="template")
created.append(name)
if with_bindings:
for b in it.get("bindings") or []:
ds = int(b.get("ds_id") or 0)
ds = (ds_map or {}).get(ds, ds)
if ds:
service.set_binding(c["id"], ds, b["target_kind"], b.get("ref") or {})
if raw_refs:
pending_refs.append((c["id"], kind, raw_refs))
except HTTPException as e:
errors.append(f"{name}:{e.detail}")
for cid, kind, refs in pending_refs:
c = service.get_concept(cid)
spec = dict(c.get("spec") or {})
for f, v in refs.items():
spec[f] = _deref(v if str(v).startswith("@") else "@" + str(v))
service.update_concept(cid, spec=spec)
extra = {}
for name, fn in _import_sections.items():
if doc.get(name):
try:
extra[name] = fn(doc[name])
except HTTPException as e:
errors.append(f"{name}:{e.detail}")
audit.record("ontology.import", "ontology", "", f"导入 YAML:新增 {len(created)},"
f"更新 {len(updated)},跳过 {len(skipped)},错误 {len(errors)}")
return {"created": created, "updated": updated, "skipped": skipped, "errors": errors,
"sections": extra}
def list_templates() -> list[dict]:
out = []
for p in sorted(TEMPLATE_DIR.glob("*.yaml")):
try:
doc = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
except Exception: # noqa: BLE001
continue
out.append({"id": p.stem, "name": doc.get("name") or p.stem,
"description": doc.get("description") or "",
"concepts": len(doc.get("concepts") or []),
"capabilities": len(doc.get("capabilities") or []),
"sops": len(doc.get("sops") or [])})
return out
def apply_template(template_id: str, overwrite: bool = False) -> dict:
p = TEMPLATE_DIR / f"{template_id}.yaml"
if not p.exists() or p.parent != TEMPLATE_DIR:
raise HTTPException(404, "模板不存在")
return import_yaml(p.read_text(encoding="utf-8"), overwrite=overwrite, with_bindings=False)