graphlink.py 2.11 KB
"""文档图谱 ↔ 本体概念。

图谱降级为「知识 / 证据层」:图里的实体是概念的提及。这里按名称 / 同义词把实体挂到概念上
(节点属性 `concept_id`),同时把实体的原文出处作为概念的证据。
"""
from __future__ import annotations

from ..store.graph_store import GraphStore
from . import service


def link_graph(graph: GraphStore) -> dict:
    concepts = service.list_concepts(limit=5000)
    names: dict[str, str] = {}
    for c in concepts:
        for n in [c["name"], c.get("display_name") or "", *(c.get("synonyms") or [])]:
            if n:
                names.setdefault(n.strip().lower(), c["id"])
    linked = 0
    evidence: dict[str, list[dict]] = {}
    with graph._lock:
        for nid, nd in graph.g.nodes(data=True):
            cands = [nd.get("label") or nid, *(nd.get("aliases") or [])]
            cid = next((names[x.strip().lower()] for x in cands if x and x.strip().lower() in names), "")
            if cid:
                if nd.get("concept_id") != cid:
                    nd["concept_id"] = cid
                    linked += 1
                for src in (nd.get("sources") or [])[:5]:
                    evidence.setdefault(cid, []).append(
                        {"chunk_id": src.get("chunk_id", ""), "doc_id": src.get("doc_id", 0),
                         "heading": src.get("heading", ""), "snippet": src.get("snippet", ""),
                         "graph_entity_id": ""})
            elif nd.get("concept_id"):
                nd.pop("concept_id", None)
    for cid, items in evidence.items():
        service.add_evidence(cid, items)
    if linked:
        graph.persist()
    return {"linked": linked, "concepts_with_evidence": len(evidence)}


def entities_of(graph: GraphStore, concept_id: str, limit: int = 30) -> list[dict]:
    out = []
    for nid, nd in graph.g.nodes(data=True):
        if nd.get("concept_id") == concept_id:
            out.append({"id": nid, "label": nd.get("label") or nid, "type": nd.get("type", ""),
                        "degree": graph.g.degree(nid)})
    out.sort(key=lambda x: -x["degree"])
    return out[:limit]