graph_store.py 23.9 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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
"""NetworkX 知识图谱存储:增量写入、按文档溯源与删除、邻域查询、导出给 Sigma。

v2 关键变化:
- 节点/边都带 `doc_ids`,所以文档删除时能精确回收它独有的实体与关系(v1 做不到,
  删文档等于把垃圾永久留在图里)。
- 边带 `occurrence`(被多少个片段佐证),既用于图上线宽,也用于检索排序 ——
  v1 所有边一视同仁,检索时只能盲截。
- 节点带 `aliases`(实体消歧合并进来的别名)和 `community`。
- persist() 改原子写。v1 直接 write_text,写到一半崩溃就毁掉整个 2.7MB 图谱。
"""
from __future__ import annotations
import json
import logging
import os
import re
import threading
from pathlib import Path

import networkx as nx

log = logging.getLogger(__name__)

_WS = re.compile(r"\s+")
# 全角 → 半角(数字、字母、常见标点),统一引号书名号
_FULLWIDTH = {ord(c): ord(c) - 0xFEE0 for c in
              "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
              "abcdefghijklmnopqrstuvwxyz()%+-/:"}
_QUOTES = {ord("“"): '"', ord("”"): '"', ord("‘"): "'", ord("’"): "'",
           ord("《"): "", ord("》"): "", ord("「"): "", ord("」"): ""}
MAX_SOURCES = 12
MAX_DESCRIPTIONS = 12


def norm_name(name: str) -> str:
    """实体名归一化:去首尾空白、压缩内部空白。作为图节点 id。"""
    return _WS.sub(" ", (name or "").strip())


def canon_key(name: str) -> str:
    """更激进的归一化键,仅用于找重复候选,不作为 id。

    直接消灭实测到的 11 组纯空格/标点差异重复:
    `盯防周期T` vs `盯防周期 T`、`5分钟` vs `5 分钟`、`生态+自然` vs `生态 + 自然`。
    """
    s = (name or "").strip().lower()
    s = s.translate(_FULLWIDTH).translate(_QUOTES)
    s = re.sub(r"[\s\-_·、,,/\\()()\[\]【】\"']", "", s)
    return s


class GraphStore:
    def __init__(self, path: Path):
        self.path = path
        self.g = nx.MultiDiGraph()
        self._lock = threading.RLock()
        if path.exists():
            self.load()

    # ---------- 写入 ----------
    def add_entity(self, name: str, etype: str, description: str = "",
                   source: dict | None = None, doc_id: int | None = None,
                   confidence: float = 1.0) -> str:
        nid = norm_name(name)
        if not nid:
            return ""
        with self._lock:
            if not self.g.has_node(nid):
                self.g.add_node(nid, label=nid, type=etype or "其他", description=description,
                                descriptions=[], aliases=[], sources=[], doc_ids=[],
                                occurrence=0, confidence=confidence, verified=False)
            nd = self.g.nodes[nid]
            nd["occurrence"] = nd.get("occurrence", 0) + 1
            if etype and (not nd.get("type") or nd["type"] == "其他"):
                nd["type"] = etype
            if description:
                descs = nd.setdefault("descriptions", [])
                if description not in descs and len(descs) < MAX_DESCRIPTIONS:
                    descs.append(description)
                # 未归纳前先用最长的一条兜底展示
                if len(description) > len(nd.get("description", "")):
                    nd["description"] = description
            nd["confidence"] = max(float(nd.get("confidence", 0)), float(confidence))
            if doc_id is not None and doc_id not in nd.setdefault("doc_ids", []):
                nd["doc_ids"].append(doc_id)
            if source:
                self._merge_source(nd.setdefault("sources", []), source)
        return nid

    def add_relation(self, source_name: str, target_name: str, relation: str,
                     description: str = "", source: dict | None = None,
                     doc_id: int | None = None, confidence: float = 1.0) -> bool:
        s, t = norm_name(source_name), norm_name(target_name)
        if not s or not t or s == t:
            return False
        rel = norm_name(relation) or "关联"
        with self._lock:
            for endpoint in (s, t):
                if not self.g.has_node(endpoint):
                    self.g.add_node(endpoint, label=endpoint, type="其他", description="",
                                    descriptions=[], aliases=[], sources=[],
                                    doc_ids=[] if doc_id is None else [doc_id],
                                    occurrence=1, confidence=confidence, verified=False)
                elif doc_id is not None and doc_id not in self.g.nodes[endpoint].setdefault("doc_ids", []):
                    self.g.nodes[endpoint]["doc_ids"].append(doc_id)
            if not self.g.has_edge(s, t, key=rel):
                self.g.add_edge(s, t, key=rel, relation=rel, description=description,
                                descriptions=[], sources=[], doc_ids=[], occurrence=0,
                                confidence=confidence, verified=False)
            ed = self.g.edges[s, t, rel]
            ed["occurrence"] = ed.get("occurrence", 0) + 1
            if description:
                descs = ed.setdefault("descriptions", [])
                if description not in descs and len(descs) < MAX_DESCRIPTIONS:
                    descs.append(description)
                if len(description) > len(ed.get("description", "")):
                    ed["description"] = description
            ed["confidence"] = max(float(ed.get("confidence", 0)), float(confidence))
            if doc_id is not None and doc_id not in ed.setdefault("doc_ids", []):
                ed["doc_ids"].append(doc_id)
            if source:
                self._merge_source(ed.setdefault("sources", []), source)
        return True

    @staticmethod
    def _merge_source(sources: list, source: dict) -> None:
        cid = source.get("chunk_id")
        if cid and any(x.get("chunk_id") == cid for x in sources):
            return
        if len(sources) < MAX_SOURCES:
            sources.append(source)

    # ---------- 实体消歧:合并节点 ----------
    def merge_nodes(self, keep: str, drop: str) -> bool:
        """把 drop 合并进 keep:属性合并、边重定向、drop 记为别名。"""
        keep, drop = norm_name(keep), norm_name(drop)
        if keep == drop:
            return False
        with self._lock:
            if not (self.g.has_node(keep) and self.g.has_node(drop)):
                return False
            k, d = self.g.nodes[keep], self.g.nodes[drop]
            aliases = k.setdefault("aliases", [])
            for a in [d.get("label", drop)] + list(d.get("aliases") or []):
                if a and a != keep and a not in aliases:
                    aliases.append(a)
            for fld in ("descriptions", "sources"):
                cur = k.setdefault(fld, [])
                for item in d.get(fld) or []:
                    if item not in cur and len(cur) < (MAX_DESCRIPTIONS if fld == "descriptions" else MAX_SOURCES):
                        cur.append(item)
            for doc in d.get("doc_ids") or []:
                if doc not in k.setdefault("doc_ids", []):
                    k["doc_ids"].append(doc)
            k["occurrence"] = k.get("occurrence", 0) + d.get("occurrence", 0)
            if len(d.get("description", "")) > len(k.get("description", "")):
                k["description"] = d["description"]
            if (not k.get("type") or k["type"] == "其他") and d.get("type"):
                k["type"] = d["type"]

            # 边重定向(含累加 occurrence),自环丢弃
            for _, tgt, key, ed in list(self.g.out_edges(drop, keys=True, data=True)):
                if tgt != keep:
                    self._absorb_edge(keep, tgt, key, ed)
            for src, _, key, ed in list(self.g.in_edges(drop, keys=True, data=True)):
                if src != keep:
                    self._absorb_edge(src, keep, key, ed)
            self.g.remove_node(drop)
        return True

    def _absorb_edge(self, s: str, t: str, key: str, ed: dict) -> None:
        if not self.g.has_edge(s, t, key=key):
            self.g.add_edge(s, t, key=key, **{k: (list(v) if isinstance(v, list) else v)
                                              for k, v in ed.items()})
            return
        cur = self.g.edges[s, t, key]
        cur["occurrence"] = cur.get("occurrence", 0) + ed.get("occurrence", 0)
        for fld, cap in (("descriptions", MAX_DESCRIPTIONS), ("sources", MAX_SOURCES)):
            lst = cur.setdefault(fld, [])
            for item in ed.get(fld) or []:
                if item not in lst and len(lst) < cap:
                    lst.append(item)
        for doc in ed.get("doc_ids") or []:
            if doc not in cur.setdefault("doc_ids", []):
                cur["doc_ids"].append(doc)
        if len(ed.get("description", "")) > len(cur.get("description", "")):
            cur["description"] = ed["description"]

    def remove_nodes(self, names: list[str]) -> int:
        with self._lock:
            gone = 0
            for n in names:
                nid = norm_name(n)
                if self.g.has_node(nid):
                    self.g.remove_node(nid)
                    gone += 1
            return gone

    # ---------- 按文档删除 ----------
    def delete_document(self, doc_id: int) -> dict:
        """回收该文档贡献的实体与关系;被多篇文档共同支撑的保留。"""
        with self._lock:
            dropped_edges = 0
            for s, t, k, ed in list(self.g.edges(keys=True, data=True)):
                docs = ed.get("doc_ids") or []
                if doc_id in docs:
                    docs.remove(doc_id)
                    ed["sources"] = [x for x in (ed.get("sources") or [])
                                     if x.get("doc_id") != doc_id]
                    if not docs:
                        self.g.remove_edge(s, t, key=k)
                        dropped_edges += 1
            dropped_nodes = 0
            for n, nd in list(self.g.nodes(data=True)):
                docs = nd.get("doc_ids") or []
                if doc_id in docs:
                    docs.remove(doc_id)
                    nd["sources"] = [x for x in (nd.get("sources") or [])
                                     if x.get("doc_id") != doc_id]
                    if not docs:
                        self.g.remove_node(n)
                        dropped_nodes += 1
        self.persist()
        return {"removed_entities": dropped_nodes, "removed_relations": dropped_edges}

    # ---------- 持久化 ----------
    def persist(self) -> None:
        with self._lock:
            data = nx.node_link_data(self.g, edges="links")
        self.path.parent.mkdir(parents=True, exist_ok=True)
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
        os.replace(tmp, self.path)  # 原子替换,杜绝写一半损坏

    def load(self) -> None:
        try:
            data = json.loads(self.path.read_text(encoding="utf-8"))
            self.g = nx.node_link_graph(data, directed=True, multigraph=True, edges="links")
        except Exception as e:  # noqa: BLE001
            log.error("图谱文件损坏,以空图启动:%s", e)
            self.g = nx.MultiDiGraph()

    def clear(self) -> None:
        with self._lock:
            self.g = nx.MultiDiGraph()
        self.persist()

    # ---------- 统计 ----------
    def stats(self) -> dict:
        with self._lock:
            type_dist: dict[str, int] = {}
            for _, d in self.g.nodes(data=True):
                t = d.get("type") or "其他"
                type_dist[t] = type_dist.get(t, 0) + 1
            rel_dist: dict[str, int] = {}
            for _, _, d in self.g.edges(data=True):
                r = d.get("relation") or "关联"
                rel_dist[r] = rel_dist.get(r, 0) + 1
            degrees = [d for _, d in self.g.degree()]
            isolated = sum(1 for d in degrees if d == 0)
            leaf = sum(1 for d in degrees if d == 1)
            n = self.g.number_of_nodes()
            communities = len({d.get("community") for _, d in self.g.nodes(data=True)
                               if d.get("community") is not None})
            return {
                "entity_count": n,
                "relation_count": self.g.number_of_edges(),
                "type_dist": dict(sorted(type_dist.items(), key=lambda x: -x[1])),
                "relation_dist": dict(sorted(rel_dist.items(), key=lambda x: -x[1])),
                "community_count": communities,
                "isolated": isolated,
                "leaf": leaf,
                "leaf_ratio": round(leaf / n, 4) if n else 0.0,
                "avg_degree": round(sum(degrees) / n, 2) if n else 0.0,
            }

    # ---------- 导出给前端 ----------
    def _node_payload(self, n: str, d: dict, deg: int) -> dict:
        return {"key": n, "attributes": {
            "label": d.get("label", n), "type": d.get("type") or "其他",
            "degree": deg, "size": 4 + min(deg, 26) ** 0.85,
            "community": d.get("community"),
            "occurrence": d.get("occurrence", 1),
            "doc_ids": d.get("doc_ids") or [],
            "verified": bool(d.get("verified"))}}

    def export_sigma(self, type_filter: list[str] | None = None, keyword: str = "",
                     limit: int = 500, relation_filter: list[str] | None = None,
                     doc_id: int | None = None, min_degree: int = 0) -> dict:
        """按度数取最核心的 limit 个节点。密集图上保证可读与性能。"""
        with self._lock:
            kw = (keyword or "").strip().lower()
            candidates = []
            for n, d in self.g.nodes(data=True):
                if type_filter and (d.get("type") or "其他") not in type_filter:
                    continue
                if doc_id is not None and doc_id not in (d.get("doc_ids") or []):
                    continue
                deg = self.g.degree(n)
                if deg < min_degree:
                    continue
                if kw and kw not in n.lower() and kw not in (d.get("description") or "").lower() \
                        and not any(kw in a.lower() for a in (d.get("aliases") or [])):
                    continue
                candidates.append((n, d, deg))
            candidates.sort(key=lambda x: -x[2])
            nodes, keep = [], set()
            for n, d, deg in candidates[:limit]:
                nodes.append(self._node_payload(n, d, deg))
                keep.add(n)
            edges = self._edges_between(keep, relation_filter, doc_id)
            return {"nodes": nodes, "edges": edges,
                    "truncated": len(candidates) > limit, "total_matched": len(candidates)}

    def _edges_between(self, keep: set[str], relation_filter: list[str] | None = None,
                       doc_id: int | None = None) -> list[dict]:
        edges, seen = [], set()
        for s, t, k, d in self.g.edges(keys=True, data=True):
            if s not in keep or t not in keep:
                continue
            rel = d.get("relation") or k
            if relation_filter and rel not in relation_filter:
                continue
            if doc_id is not None and doc_id not in (d.get("doc_ids") or []):
                continue
            eid = f"{s}__{k}__{t}"
            if eid in seen:
                continue
            seen.add(eid)
            edges.append({"key": eid, "source": s, "target": t, "attributes": {
                "label": rel, "relation": rel,
                "occurrence": d.get("occurrence", 1),
                "size": 0.8 + min(d.get("occurrence", 1), 8) * 0.25,
                "verified": bool(d.get("verified"))}})
        return edges

    def ego(self, node_id: str, hops: int = 1, limit: int = 300) -> dict:
        """以某节点为中心按 BFS 展开 hops 跳。支撑"按需展开"式浏览 ——
        LightRAG 是一次性全量加载再截断,大图上没法用。"""
        nid = norm_name(node_id)
        with self._lock:
            if not self.g.has_node(nid):
                return {"nodes": [], "edges": [], "truncated": False, "total_matched": 0}
            keep = {nid}
            layer = {nid}
            for _ in range(max(1, hops)):
                nxt = set()
                # 每层按邻居度数排序,优先保留信息量大的枢纽
                for n in layer:
                    nbrs = set(self.g.successors(n)) | set(self.g.predecessors(n))
                    for m in sorted(nbrs, key=lambda x: -self.g.degree(x)):
                        if m not in keep:
                            nxt.add(m)
                        if len(keep) + len(nxt) >= limit:
                            break
                    if len(keep) + len(nxt) >= limit:
                        break
                keep |= nxt
                layer = nxt
                if not layer or len(keep) >= limit:
                    break
            nodes = [self._node_payload(n, self.g.nodes[n], self.g.degree(n)) for n in keep]
            return {"nodes": nodes, "edges": self._edges_between(keep),
                    "truncated": len(keep) >= limit, "total_matched": len(keep), "center": nid}

    def subgraph_payload(self, node_ids: list[str]) -> dict:
        with self._lock:
            keep = {norm_name(n) for n in node_ids if self.g.has_node(norm_name(n))}
            nodes = [self._node_payload(n, self.g.nodes[n], self.g.degree(n)) for n in keep]
            return {"nodes": nodes, "edges": self._edges_between(keep)}

    # ---------- 详情 ----------
    def node_detail(self, node_id: str) -> dict | None:
        nid = norm_name(node_id)
        with self._lock:
            if not self.g.has_node(nid):
                return None
            d = self.g.nodes[nid]
            out_edges, in_edges = [], []
            for _, t, k, ed in self.g.out_edges(nid, keys=True, data=True):
                out_edges.append({"relation": ed.get("relation", k), "target": t,
                                  "description": ed.get("description", ""),
                                  "target_type": self.g.nodes[t].get("type", ""),
                                  "occurrence": ed.get("occurrence", 1),
                                  "sources": ed.get("sources", [])})
            for s, _, k, ed in self.g.in_edges(nid, keys=True, data=True):
                in_edges.append({"relation": ed.get("relation", k), "source": s,
                                 "description": ed.get("description", ""),
                                 "source_type": self.g.nodes[s].get("type", ""),
                                 "occurrence": ed.get("occurrence", 1),
                                 "sources": ed.get("sources", [])})
            out_edges.sort(key=lambda e: -e["occurrence"])
            in_edges.sort(key=lambda e: -e["occurrence"])
            return {"id": nid, "label": d.get("label", nid), "type": d.get("type") or "其他",
                    "description": d.get("description", ""),
                    "aliases": d.get("aliases") or [], "doc_ids": d.get("doc_ids") or [],
                    "occurrence": d.get("occurrence", 1), "community": d.get("community"),
                    "verified": bool(d.get("verified")), "degree": self.g.degree(nid),
                    "sources": d.get("sources", []),
                    "out_edges": out_edges, "in_edges": in_edges}

    def edge_detail(self, s: str, t: str, rel: str) -> dict | None:
        s, t, rel = norm_name(s), norm_name(t), norm_name(rel)
        with self._lock:
            if not self.g.has_edge(s, t, key=rel):
                return None
            ed = self.g.edges[s, t, rel]
            return {"source": s, "target": t, "relation": rel,
                    "description": ed.get("description", ""),
                    "occurrence": ed.get("occurrence", 1),
                    "doc_ids": ed.get("doc_ids") or [],
                    "verified": bool(ed.get("verified")),
                    "sources": ed.get("sources", [])}

    def update_node(self, node_id: str, **fields) -> bool:
        nid = norm_name(node_id)
        with self._lock:
            if not self.g.has_node(nid):
                return False
            for k, v in fields.items():
                if k in ("type", "description", "verified", "label"):
                    self.g.nodes[nid][k] = v
        return True

    def update_edge(self, s: str, t: str, rel: str, **fields) -> bool:
        s, t, rel = norm_name(s), norm_name(t), norm_name(rel)
        with self._lock:
            if not self.g.has_edge(s, t, key=rel):
                return False
            for k, v in fields.items():
                if k in ("description", "verified"):
                    self.g.edges[s, t, rel][k] = v
        return True

    # ---------- 供检索 ----------
    def neighbors(self, node_id: str, max_degree: int = 0) -> list[dict]:
        """返回邻边,按 occurrence 降序。max_degree>0 时只取权重最高的前 N 条,
        避免 `门店`(度110) 这类枢纽节点把整轮扩展淹没。"""
        nid = norm_name(node_id)
        res: list[dict] = []
        with self._lock:
            if not self.g.has_node(nid):
                return res
            for _, t, k, ed in self.g.out_edges(nid, keys=True, data=True):
                res.append({"from": nid, "to": t, "relation": ed.get("relation", k),
                            "description": ed.get("description", ""),
                            "occurrence": ed.get("occurrence", 1), "dir": "out"})
            for s, _, k, ed in self.g.in_edges(nid, keys=True, data=True):
                res.append({"from": s, "to": nid, "relation": ed.get("relation", k),
                            "description": ed.get("description", ""),
                            "occurrence": ed.get("occurrence", 1), "dir": "in"})
        res.sort(key=lambda e: -e["occurrence"])
        return res[:max_degree] if max_degree > 0 else res

    def has_node(self, node_id: str) -> bool:
        return self.g.has_node(norm_name(node_id))

    def degree(self, node_id: str) -> int:
        nid = norm_name(node_id)
        return self.g.degree(nid) if self.g.has_node(nid) else 0

    def all_entities(self) -> list[dict]:
        with self._lock:
            return [{"id": n, "label": d.get("label", n), "type": d.get("type") or "其他",
                     "description": d.get("description", ""),
                     "aliases": d.get("aliases") or [],
                     "doc_ids": d.get("doc_ids") or [],
                     "community": d.get("community"),
                     "degree": self.g.degree(n)}
                    for n, d in self.g.nodes(data=True)]

    def all_relations(self) -> list[dict]:
        with self._lock:
            out = []
            for s, t, k, d in self.g.edges(keys=True, data=True):
                rel = d.get("relation") or k
                out.append({"id": f"{s}__{k}__{t}", "source": s, "target": t, "relation": rel,
                            "description": d.get("description", ""),
                            "occurrence": d.get("occurrence", 1),
                            "doc_ids": d.get("doc_ids") or [],
                            "sources": d.get("sources", [])})
            return out

    def doc_stats(self, doc_id: int) -> dict:
        """该文档贡献了多少实体/关系。文档列表要显示的是这个,
        而不是整库的全局计数 —— 否则每篇文档都显示同一个数字,毫无意义。"""
        with self._lock:
            ents = sum(1 for _, d in self.g.nodes(data=True)
                       if doc_id in (d.get("doc_ids") or []))
            rels = sum(1 for _, _, d in self.g.edges(data=True)
                       if doc_id in (d.get("doc_ids") or []))
            return {"entity_count": ents, "relation_count": rels}

    def node_types(self) -> list[str]:
        with self._lock:
            return sorted({(d.get("type") or "其他") for _, d in self.g.nodes(data=True)})

    def set_communities(self, mapping: dict[str, int]) -> None:
        with self._lock:
            for n, c in mapping.items():
                if self.g.has_node(n):
                    self.g.nodes[n]["community"] = int(c)