linker.py 3.45 KB
"""问句 → 本体概念 / 对象实例 / 时间 的链接。不调 LLM,毫秒级。

做法是最长匹配:把所有已发布概念的名称、显示名、同义词,以及对象实例名录做成词表,
在问句里从长到短找,命中的片段不再参与更短词的匹配(「交付目标达成率」不会再拆出「达成率」)。
中文没有空格,最长匹配比分词后再对齐更稳;认不出的词交给后面的 LLM 规划去理解。
"""
from __future__ import annotations

import threading
import time

from ..core import identity
from . import calendar as cal
from . import objects, service

_cache: dict[str, tuple[float, list[tuple[str, dict]]]] = {}
_lock = threading.Lock()
_TTL = 60.0


def invalidate() -> None:
    with _lock:
        _cache.clear()


def _lexicon(ws: str) -> list[tuple[str, dict]]:
    key = ws + ("#draft" if service._draft_mode.get() 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():
        target = c
        if c["kind"] == "term":          # 术语指向真正的概念
            ref = service.rt_get((c.get("spec") or {}).get("refers_to") or "")
            if ref:
                target = ref
        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": target["id"],
                                             "kind": target["kind"], "name": target["name"]}))
    try:
        for inst in objects.instances(ws):
            if inst["label"] and len(inst["label"]) >= 2:
                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 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]):
                for i in range(start, end):
                    taken[i] = True
                if target["type"] == "concept":
                    hit = concepts.setdefault(target["id"], {**target, "matched": []})
                    if term not in hit["matched"]:
                        hit["matched"].append(term)
                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]] = {}
    for c in concepts.values():
        by_kind.setdefault(c["kind"], []).append(c)
    return {"concepts": list(concepts.values()), "by_kind": by_kind,
            "instances": list(instances.values()), "time": time_hint}