resolve.py 9.1 KB
"""实体消歧(v1 完全没有这一步)。

v1 图谱实测问题:
- 11 组纯空格/标点差异的重复:`盯防周期T` vs `盯防周期 T`、`5分钟` vs `5 分钟`、
  `生态+自然` vs `生态 + 自然`。
- 137 组包含式别名候选:`主机厂` vs `主机厂侧`、`大模型` vs `大模型总结`。
  其中一部分该合(同一对象的不同说法),一部分不该合(后者是前者的细分),
  纯规则分不开,必须让模型判。

三级策略,越贵的手段用得越少:
1. canon_key 完全相同 → 直接合并,零成本。
2. 向量余弦 ≥ SIM_THRESHOLD 且类型相容 → 自动合并。
3. 落在 [SIM_REVIEW_LOW, SIM_THRESHOLD) 或字面高度重合 → 批量交给 LLM 裁决。
"""
from __future__ import annotations
import logging
from collections import defaultdict

import numpy as np

from ..core import llm
from ..store.graph_store import GraphStore, canon_key
from .prompts import DEDUP_SYSTEM, DEDUP_USER

log = logging.getLogger(__name__)

# 这些类型天然容易"看起来像"但实际是并列的不同对象,合并要更保守
_STRICT_TYPES = {"周期", "口径", "指标"}
MAX_LLM_PAIRS = 120        # 单次抽取最多送多少对去裁决,控成本
LLM_BATCH = 20


def _ngrams(s: str, n: int = 2) -> set[str]:
    s = canon_key(s)
    if len(s) <= n:
        return {s} if s else set()
    return {s[i:i + n] for i in range(len(s) - n + 1)}


def _jaccard(a: set[str], b: set[str]) -> float:
    if not a or not b:
        return 0.0
    inter = len(a & b)
    return inter / (len(a) + len(b) - inter)


class _UnionFind:
    def __init__(self):
        self.parent: dict[str, str] = {}

    def find(self, x: str) -> str:
        self.parent.setdefault(x, x)
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a: str, b: str) -> None:
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[rb] = ra


def _type_compatible(t1: str, t2: str) -> bool:
    if not t1 or not t2 or t1 == t2:
        return True
    return "其他" in (t1, t2)


def _ask_llm(pairs: list[tuple[str, str]]) -> list[bool]:
    """批量裁决。返回与 pairs 等长的布尔列表;任何异常都按"不合并"处理(保守)。"""
    verdicts: list[bool] = []
    for start in range(0, len(pairs), LLM_BATCH):
        batch = pairs[start:start + LLM_BATCH]
        listing = "\n".join(f"{i + 1}. 「{a}」 与 「{b}」" for i, (a, b) in enumerate(batch))
        try:
            out = llm.chat([{"role": "system", "content": DEDUP_SYSTEM},
                            {"role": "user", "content": DEDUP_USER.format(pairs=listing)}],
                           temperature=0.0)
        except Exception as e:  # noqa: BLE001
            log.warning("消歧裁决调用失败,本批按不合并处理:%s", str(e)[:150])
            verdicts.extend([False] * len(batch))
            continue
        got: dict[int, bool] = {}
        for line in (out or "").splitlines():
            line = line.strip()
            if not line or "|" not in line:
                continue
            idx_s, _, ans = line.partition("|")
            try:
                idx = int(idx_s.strip().rstrip(".、")) - 1
            except ValueError:
                continue
            got[idx] = ans.strip().startswith("是")
        verdicts.extend([got.get(i, False) for i in range(len(batch))])
    return verdicts


def find_duplicate_candidates(graph: GraphStore, sim_threshold: float = 0.88,
                              review_low: float = 0.78, ngram_thr: float = 0.65,
                              top_k: int = 5, limit: int = 400) -> list[dict]:
    """找出疑似重复的实体对,供消歧 UI 展示与人工确认。不修改图。"""
    entities = graph.all_entities()
    if len(entities) < 2:
        return []
    labels = [e["label"] for e in entities]
    types = [e.get("type", "") for e in entities]

    pairs: dict[tuple[str, str], dict] = {}

    # 1) canon_key 完全相同
    by_key: dict[str, list[int]] = defaultdict(list)
    for i, lb in enumerate(labels):
        by_key[canon_key(lb)].append(i)
    for idxs in by_key.values():
        if len(idxs) < 2:
            continue
        for a in range(len(idxs)):
            for b in range(a + 1, len(idxs)):
                i, j = idxs[a], idxs[b]
                key = tuple(sorted((labels[i], labels[j])))
                pairs[key] = {"a": key[0], "b": key[1], "reason": "归一化后完全相同",
                              "score": 1.0, "auto": True}

    # 2) 向量近邻
    try:
        texts = [f"{e['label']} {e.get('type', '')} {e.get('description', '')}" for e in entities]
        emb = llm.embed(texts)
        sim = emb @ emb.T
        np.fill_diagonal(sim, -1.0)
        for i in range(len(entities)):
            for j in np.argsort(-sim[i])[:top_k]:
                j = int(j)
                if j <= i:
                    continue
                s = float(sim[i][j])
                if s < review_low:
                    continue
                key = tuple(sorted((labels[i], labels[j])))
                if key in pairs and pairs[key].get("auto"):
                    continue
                strict = types[i] in _STRICT_TYPES or types[j] in _STRICT_TYPES
                auto = (s >= sim_threshold and _type_compatible(types[i], types[j]) and not strict)
                pairs[key] = {"a": key[0], "b": key[1], "score": round(s, 4),
                              "reason": f"向量相似度 {s:.3f}", "auto": auto}
    except Exception as e:  # noqa: BLE001
        log.warning("消歧向量阶段失败,退回纯字面:%s", str(e)[:150])

    # 3) 字面高度重合(含包含关系)
    grams = [_ngrams(lb) for lb in labels]
    bucket: dict[str, list[int]] = defaultdict(list)
    for i, gs in enumerate(grams):
        for g in gs:
            bucket[g].append(i)
    checked: set[tuple[int, int]] = set()
    for idxs in bucket.values():
        if len(idxs) > 60:      # 过于常见的 gram,跳过,避免 O(n^2) 爆炸
            continue
        for a in range(len(idxs)):
            for b in range(a + 1, len(idxs)):
                i, j = idxs[a], idxs[b]
                if (i, j) in checked:
                    continue
                checked.add((i, j))
                jac = _jaccard(grams[i], grams[j])
                ci, cj = canon_key(labels[i]), canon_key(labels[j])
                contained = (ci in cj or cj in ci) and abs(len(ci) - len(cj)) <= 4
                if jac < ngram_thr and not contained:
                    continue
                key = tuple(sorted((labels[i], labels[j])))
                if key in pairs:
                    continue
                pairs[key] = {"a": key[0], "b": key[1], "score": round(jac, 4),
                              "reason": ("疑似别名(包含关系)" if contained
                                         else f"字面重合 {jac:.2f}"),
                              "auto": False}

    out = sorted(pairs.values(), key=lambda x: -x["score"])[:limit]
    deg = {e["label"]: e.get("degree", 0) for e in entities}
    for p in out:
        p["a_degree"] = deg.get(p["a"], 0)
        p["b_degree"] = deg.get(p["b"], 0)
    return out


def resolve_entities(graph: GraphStore, sim_threshold: float = 0.88, review_low: float = 0.78,
                     ngram_thr: float = 0.65, use_llm: bool = True,
                     progress=None) -> dict:
    """执行消歧并就地修改图。返回统计。"""
    cands = find_duplicate_candidates(graph, sim_threshold, review_low, ngram_thr)
    if not cands:
        return {"candidates": 0, "auto_merged": 0, "llm_judged": 0, "llm_merged": 0, "merged": 0}

    auto = [c for c in cands if c.get("auto")]
    review = [c for c in cands if not c.get("auto")][:MAX_LLM_PAIRS]

    uf = _UnionFind()
    for c in auto:
        uf.union(c["a"], c["b"])

    llm_merged = 0
    if use_llm and review:
        if progress:
            progress(f"消歧:{len(review)} 组边界候选交给大模型裁决")
        verdicts = _ask_llm([(c["a"], c["b"]) for c in review])
        for c, ok in zip(review, verdicts):
            if ok:
                uf.union(c["a"], c["b"])
                llm_merged += 1

    # 分组,每组选一个"保留者":优先度数高,其次出现次数多,最后名字短
    groups: dict[str, list[str]] = defaultdict(list)
    for label in set([c["a"] for c in cands] + [c["b"] for c in cands]):
        groups[uf.find(label)].append(label)

    info = {e["label"]: e for e in graph.all_entities()}
    merged = 0
    for members in groups.values():
        members = [m for m in members if m in info]
        if len(members) < 2:
            continue
        members.sort(key=lambda m: (-info[m].get("degree", 0),
                                    -len(info[m].get("description") or ""),
                                    len(m)))
        keep, drops = members[0], members[1:]
        for d in drops:
            if graph.merge_nodes(keep, d):
                merged += 1
    return {"candidates": len(cands), "auto_merged": len(auto),
            "llm_judged": len(review), "llm_merged": llm_merged, "merged": merged}