typing_pass.py 5.92 KB
"""类型补全:给抽取完还停留在「其他」的节点补上业务类型。

为什么会有一批无类型节点:关系里出现、但模型没把它单独列进 entities 的端点,
`add_relation` 只能先把它建成 `其他`。实测一份需求文档里这样的节点有一百多个,
占到全部实体的两成 —— 图谱按类型着色时它们全是一片灰,过滤器也筛不出来。

做法:把「名称 + 描述 + 它参与的关系」拼成一段上下文,和本体类型做向量最近邻。
只有相似度足够高才落定,够不着就老实留在「其他」,不硬猜。
"""
from __future__ import annotations
import logging

import numpy as np

from ..core import llm
from ..core.ontology import entity_type_block
from ..store.graph_store import GraphStore

log = logging.getLogger(__name__)

FALLBACK = "其他"
MAX_CONTEXT_RELATIONS = 4


def _context_of(graph: GraphStore, nid: str) -> str:
    with graph._lock:  # noqa: SLF001
        d = graph.g.nodes[nid]
        parts = [nid]
        if d.get("description"):
            parts.append(d["description"][:120])
        rels = []
        for _, t, k, ed in graph.g.out_edges(nid, keys=True, data=True):
            rels.append(f"{nid} {ed.get('relation', k)} {t}")
            if len(rels) >= MAX_CONTEXT_RELATIONS:
                break
        for s, _, k, ed in graph.g.in_edges(nid, keys=True, data=True):
            if len(rels) >= MAX_CONTEXT_RELATIONS:
                break
            rels.append(f"{s} {ed.get('relation', k)} {nid}")
        parts.extend(rels)
    return ";".join(parts)


def complete_types(graph: GraphStore, entity_types: list[str], threshold: float = 0.42,
                   progress=None) -> dict:
    """返回 {"candidates": n, "typed": m}。"""
    targets = [n for n, d in graph.g.nodes(data=True) if (d.get("type") or FALLBACK) == FALLBACK]
    candidates = [t for t in entity_types if t != FALLBACK]
    if not targets or not candidates:
        return {"candidates": len(targets), "typed": 0}
    if progress:
        progress(f"类型补全:{len(targets)} 个未分类实体待归类")

    # 用带说明和正例的类型描述做向量,比只用类型名两个字准得多
    type_docs = [line for line in entity_type_block(candidates).splitlines() if line.strip()]
    if len(type_docs) != len(candidates):
        type_docs = candidates

    try:
        type_emb = llm.embed(type_docs)
        node_emb = llm.embed([_context_of(graph, n) for n in targets])
    except Exception as e:  # noqa: BLE001
        log.warning("类型补全失败,全部保留为「其他」:%s", str(e)[:150])
        return {"candidates": len(targets), "typed": 0}

    sims = node_emb @ type_emb.T
    typed = 0
    for i, nid in enumerate(targets):
        j = int(np.argmax(sims[i]))
        if float(sims[i][j]) < threshold:
            continue
        graph.g.nodes[nid]["type"] = candidates[j]
        typed += 1
    return {"candidates": len(targets), "typed": typed}


DESCRIBE_SYSTEM = "你是业务知识库编辑,根据一个实体在图谱中的关系,写出它的业务含义。"

DESCRIBE_USER = """实体:{name}

它在知识图谱中的关系:
{relations}

请用**一句话**(40 字以内)说明这个实体在业务中是什么。
只依据上面的关系,不要编造;关系信息不足以判断就输出"—"。
直接输出这句话,不要任何前缀。"""


def describe_orphans(graph: GraphStore, concurrency: int = 8, limit: int = 300,
                     progress=None) -> dict:
    """给"只在关系里出现、因而没有描述"的节点补一句业务含义。

    这批节点是 add_relation 隐式建出来的,属性上只有一个名字。留着不管的话,
    详情面板里有近两成实体显示"(无描述)",实体向量也少了一大块可检索的信息。
    描述完全由它自己的关系推出,不引入外部臆测。
    """
    from concurrent.futures import ThreadPoolExecutor, as_completed

    targets = [n for n, d in graph.g.nodes(data=True)
               if not (d.get("description") or "").strip() and graph.g.degree(n) > 0]
    targets = sorted(targets, key=lambda n: -graph.g.degree(n))[:limit]
    if not targets:
        return {"candidates": 0, "described": 0}
    if progress:
        progress(f"描述补全:{len(targets)} 个只在关系中出现的实体待补")

    def _one(nid: str) -> tuple[str, str]:
        with graph._lock:  # noqa: SLF001
            lines = []
            for _, t, k, ed in graph.g.out_edges(nid, keys=True, data=True):
                lines.append(f"- {nid} —[{ed.get('relation', k)}]→ {t}"
                             + (f":{ed.get('description', '')[:60]}" if ed.get("description") else ""))
            for s, _, k, ed in graph.g.in_edges(nid, keys=True, data=True):
                lines.append(f"- {s} —[{ed.get('relation', k)}]→ {nid}"
                             + (f":{ed.get('description', '')[:60]}" if ed.get("description") else ""))
        try:
            out = llm.chat([{"role": "system", "content": DESCRIBE_SYSTEM},
                            {"role": "user", "content": DESCRIBE_USER.format(
                                name=nid, relations="\n".join(lines[:8]))}], temperature=0.2)
        except Exception as e:  # noqa: BLE001
            log.debug("描述补全失败 %s:%s", nid, e)
            return nid, ""
        text = (out or "").strip().strip('"')
        return nid, "" if text in ("", "—", "-") else text[:120]

    described = 0
    with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool:
        futs = [pool.submit(_one, n) for n in targets]
        for fut in as_completed(futs):
            try:
                nid, text = fut.result()
            except Exception:  # noqa: BLE001
                continue
            if text and graph.g.has_node(nid):
                graph.g.nodes[nid]["description"] = text
                described += 1
    return {"candidates": len(targets), "described": described}