linker.py
5.76 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
"""问句 → 本体概念 / 对象实例 / 时间 的链接。不调 LLM,毫秒级。
做法是最长匹配:把所有已发布概念的名称、显示名、同义词,以及对象实例名录做成词表,
在问句里从长到短找,命中的片段不再参与更短词的匹配(「交付目标达成率」不会再拆出「达成率」)。
中文没有空格,最长匹配比分词后再对齐更稳;认不出的词交给后面的 LLM 规划去理解。
"""
from __future__ import annotations
import re
import threading
import time
from ..core import envs, identity
from . import calendar as cal
from . import objects, schema, service
_cache: dict[str, tuple[float, list[tuple[str, dict]]]] = {}
_lock = threading.Lock()
_TTL = 60.0
_ID_ONLY = re.compile(r"[\d\s·\-_/.#]+") # 纯数字 / 编号拼出来的「名字」
_ASCII = re.compile(r"[a-z0-9_\-]+")
_ALNUM = re.compile(r"[a-z0-9]")
def invalidate() -> None:
with _lock:
_cache.clear()
def _lexicon(ws: str) -> list[tuple[str, dict]]:
key = f"{envs.current()}:{ws}" + ("#draft" if service.in_draft_mode() else "")
with _lock:
hit = _cache.get(key)
if hit and time.time() - hit[0] < _TTL:
return hit[1]
terms: list[tuple[str, dict]] = []
for c in service.runtime(ws).values():
# 术语就是同义词:名称、显示名、同义词都链接到同一个元素
for name in {c["name"], c.get("display_name") or "", *(c.get("synonyms") or [])}:
if name and len(name.strip()) >= 2:
terms.append((name.strip(), {"type": "concept", "id": c["id"], "kind": c["kind"],
"type_key": schema.type_key(c), "name": c["name"]}))
if c["kind"] == "object_type":
# 状态属性的别名是一类记录的叫法(「超时工单」= 工单里 is_overdue 为是的):链到对象,并带上筛选的意思
for p in (c.get("spec") or {}).get("properties") or []:
for name in p.get("synonyms") or []:
if name and len(name.strip()) >= 2:
terms.append((name.strip(), {"type": "concept", "id": c["id"], "kind": c["kind"],
"type_key": schema.type_key(c), "name": c["name"],
"property": p["name"],
"means": f"{c['name']}里「{p.get('display_name') or p['name']}」"
f"({p['name']})为是的那些"}))
try:
for inst in objects.instances(ws):
# 对象没有名称列时「名字」就是主键或一串数字:这种不进词表 ——
# 否则问句里的「前 10」「2026」会被认成某个库存行、某张单子
if inst["label"] and len(inst["label"]) >= 2 and not _looks_like_id(inst["label"], inst["key"]):
ot = service.runtime(ws).get(inst["concept_id"])
if ot:
terms.append((inst["label"], {"type": "instance", "concept_id": ot["id"],
"type_name": ot["name"], "key": inst["key"],
"label": inst["label"]}))
except Exception: # noqa: BLE001
pass
terms.sort(key=lambda t: -len(t[0]))
with _lock:
_cache[key] = (time.time(), terms)
return terms
def _looks_like_id(label: str, key: str) -> bool:
text = str(label).strip()
return text == str(key).strip() or bool(_ID_ONLY.fullmatch(text))
def _bounded(low: str, start: int, end: int) -> bool:
"""英文字母 / 数字组成的词要独立成词才算命中:「S003」不该在「PS0031」里命中,「10」不该在「2026-10-12」里命中。"""
t = low[start:end]
if not _ASCII.fullmatch(t):
return True
before = low[start - 1] if start > 0 else ""
after = low[end] if end < len(low) else ""
return not (_ALNUM.match(before) or _ALNUM.match(after)
or (before and before in "-/.") or (after and after in "-/."))
def link(question: str) -> dict:
ws = identity.current().workspace
q = question or ""
low = q.lower()
taken = [False] * len(q)
concepts: dict[str, dict] = {}
instances: dict[tuple[str, str], dict] = {}
for term, target in _lexicon(ws):
t = term.lower()
start = low.find(t)
while start != -1:
end = start + len(t)
if not any(taken[start:end]) and _bounded(low, start, end):
for i in range(start, end):
taken[i] = True
if target["type"] == "concept":
base = {k: v for k, v in target.items() if k not in ("property", "means")}
hit = concepts.setdefault(target["id"], {**base, "matched": []})
if term not in hit["matched"]:
hit["matched"].append(term)
if target.get("property"):
hit.setdefault("subsets", []).append({"term": term, "property": target["property"],
"means": target["means"]})
else:
instances.setdefault((target["concept_id"], target["key"]),
{**target, "matched": term})
start = low.find(t, end)
time_hint = cal.parse_time_phrase(q)
by_kind: dict[str, list[dict]] = {} # 键是细分类型:object_type / aggregate / rule / action …
for c in concepts.values():
by_kind.setdefault(c["type_key"], []).append(c)
return {"concepts": list(concepts.values()), "by_kind": by_kind,
"instances": list(instances.values()), "time": time_hint}