summarize.py 3.62 KB
"""描述归并。

v1 的做法是"同一实体在不同片段里的描述,只留最长的那条"(graph_store.py 里
`if len(description) > len(nd["description"])`)。跨片段的信息因此全部丢失 ——
一个实体可能在第 3 块讲它怎么算、第 17 块讲它归谁管,最后只剩其中一句。

这里把累积的多条描述交给模型合并成一段,保留全部信息点。
只对累积条数达到阈值的对象做,控制调用量。
"""
from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed

from ..core import llm
from ..store.graph_store import GraphStore
from .prompts import SUMMARY_SYSTEM, SUMMARY_USER

log = logging.getLogger(__name__)

MAX_LEN = 180


def _summarize_one(name: str, kind: str, descriptions: list[str]) -> str:
    listing = "\n".join(f"{i + 1}. {d}" for i, d in enumerate(descriptions))
    try:
        out = llm.chat([{"role": "system", "content": SUMMARY_SYSTEM},
                        {"role": "user", "content": SUMMARY_USER.format(
                            name=name, kind=kind, descriptions=listing, limit=MAX_LEN)}],
                       temperature=0.2)
        return (out or "").strip().strip('"')
    except Exception as e:  # noqa: BLE001
        log.warning("描述归并失败(%s):%s", name, str(e)[:120])
        return ""


def summarize_graph(graph: GraphStore, threshold: int = 4, concurrency: int = 8,
                    progress=None) -> dict:
    """把 descriptions 条数 ≥ threshold 的节点/边归并成一段 description。"""
    node_jobs: list[tuple[str, str, list[str]]] = []
    edge_jobs: list[tuple[tuple[str, str, str], str, list[str]]] = []

    with graph._lock:  # noqa: SLF001 —— 同包内的一致性读,避免中途被抽取线程改写
        for n, d in graph.g.nodes(data=True):
            descs = [x for x in (d.get("descriptions") or []) if x]
            if len(descs) >= threshold:
                node_jobs.append((n, d.get("type") or "实体", descs))
        for s, t, k, d in graph.g.edges(keys=True, data=True):
            descs = [x for x in (d.get("descriptions") or []) if x]
            if len(descs) >= threshold:
                edge_jobs.append(((s, t, k), f"{s}→{t} 的「{d.get('relation', k)}」关系", descs))

    total = len(node_jobs) + len(edge_jobs)
    if not total:
        return {"summarized_entities": 0, "summarized_relations": 0}
    if progress:
        progress(f"描述归并:{len(node_jobs)} 个实体 / {len(edge_jobs)} 条关系")

    done_n = done_e = 0
    with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool:
        futs = {}
        for nid, kind, descs in node_jobs:
            futs[pool.submit(_summarize_one, nid, kind, descs)] = ("node", nid)
        for ekey, kind, descs in edge_jobs:
            futs[pool.submit(_summarize_one, ekey[0] + "→" + ekey[1], kind, descs)] = ("edge", ekey)
        for fut in as_completed(futs):
            what, ref = futs[fut]
            try:
                text = fut.result()
            except Exception:  # noqa: BLE001
                continue
            if not text:
                continue
            with graph._lock:  # noqa: SLF001
                if what == "node" and graph.g.has_node(ref):
                    graph.g.nodes[ref]["description"] = text
                    done_n += 1
                elif what == "edge":
                    s, t, k = ref
                    if graph.g.has_edge(s, t, key=k):
                        graph.g.edges[s, t, k]["description"] = text
                        done_e += 1
    return {"summarized_entities": done_n, "summarized_relations": done_e}