community.py
7.07 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
"""社区检测与社区报告(v1 完全没有)。
两个用途:
1. **图谱**:按社区着色 / 画凸包 / 折叠成超级节点。989 个节点按 41 种类型着色是
一团乱麻,按 8~15 个社区着色才看得出结构。
2. **检索**:主题类、概览类问题("这套体系整体怎么运转")在纯实体/关系检索下
无解 —— 没有任何单个三元组能回答它。社区报告提供了这一层抽象。
Louvain 用 networkx 自带实现(3.x 起内置 louvain_communities),没有额外依赖。
"""
from __future__ import annotations
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import networkx as nx
from ..core import llm
from ..store.graph_store import GraphStore
from .prompts import COMMUNITY_SYSTEM, COMMUNITY_USER
log = logging.getLogger(__name__)
MAX_ENTITIES_IN_PROMPT = 30
MAX_RELATIONS_IN_PROMPT = 40
def detect(graph: GraphStore, min_size: int = 4) -> dict[str, int]:
"""Louvain 分区。边权用 occurrence(被多少片段佐证),比无权更贴业务。"""
with graph._lock: # noqa: SLF001
ug = nx.Graph()
ug.add_nodes_from(graph.g.nodes())
for s, t, d in graph.g.edges(data=True):
w = float(d.get("occurrence", 1))
if ug.has_edge(s, t):
ug[s][t]["weight"] += w
else:
ug.add_edge(s, t, weight=w)
if ug.number_of_nodes() == 0:
return {}
try:
parts = nx.community.louvain_communities(ug, weight="weight", seed=42)
except Exception as e: # noqa: BLE001
log.warning("Louvain 不可用,退回连通分量:%s", str(e)[:150])
parts = list(nx.connected_components(ug))
parts = sorted(parts, key=len, reverse=True)
mapping: dict[str, int] = {}
cid = 0
for part in parts:
if len(part) < min_size:
continue # 太小的簇不单独成社区,留空
for n in part:
mapping[n] = cid
cid += 1
return mapping
def _build_prompt(graph: GraphStore, members: list[str]) -> tuple[str, str]:
with graph._lock: # noqa: SLF001
ranked = sorted(members, key=lambda n: -graph.g.degree(n))[:MAX_ENTITIES_IN_PROMPT]
ent_lines = []
for n in ranked:
d = graph.g.nodes[n]
desc = (d.get("description") or "")[:90]
ent_lines.append(f"- {n}({d.get('type') or '其他'})" + (f":{desc}" if desc else ""))
member_set = set(members)
rel_lines = []
for s, t, k, d in graph.g.edges(keys=True, data=True):
if s in member_set and t in member_set:
desc = (d.get("description") or "")[:70]
rel_lines.append(f"- {s} —[{d.get('relation', k)}]→ {t}" + (f":{desc}" if desc else ""))
if len(rel_lines) >= MAX_RELATIONS_IN_PROMPT:
break
return "\n".join(ent_lines), "\n".join(rel_lines) or "(无)"
def _report_one(graph: GraphStore, cid: int, members: list[str]) -> dict:
ents, rels = _build_prompt(graph, members)
try:
out = llm.chat_json([{"role": "system", "content": COMMUNITY_SYSTEM},
{"role": "user", "content": COMMUNITY_USER.format(
entities=ents, relations=rels)}], temperature=0.2)
except Exception as e: # noqa: BLE001
log.warning("社区 %s 报告生成失败:%s", cid, str(e)[:120])
out = {}
with graph._lock: # noqa: SLF001
top = sorted(members, key=lambda n: -graph.g.degree(n))[:10]
return {
"id": cid,
"title": (out.get("title") or f"社区 {cid}")[:40] if isinstance(out, dict) else f"社区 {cid}",
"summary": (out.get("summary") or "") if isinstance(out, dict) else "",
"keywords": (out.get("keywords") or []) if isinstance(out, dict) else [],
"size": len(members),
"members": members,
"top_entities": top,
}
class CommunityStore:
"""社区报告落盘,检索时按需读取。"""
def __init__(self, path: Path):
self.path = path
self.reports: list[dict] = []
self.load()
def load(self) -> None:
if self.path.exists():
try:
self.reports = json.loads(self.path.read_text(encoding="utf-8"))
except Exception:
self.reports = []
def save(self) -> None:
import os
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps(self.reports, ensure_ascii=False), encoding="utf-8")
os.replace(tmp, self.path)
def clear(self) -> None:
self.reports = []
self.save()
def by_id(self, cid: int) -> dict | None:
for r in self.reports:
if r["id"] == cid:
return r
return None
def search(self, query: str, k: int = 3) -> list[dict]:
"""社区报告检索。数量少(十几个),直接向量全比即可。"""
if not self.reports:
return []
try:
texts = [f"{r['title']} {r['summary']} {' '.join(r.get('keywords') or [])}"
for r in self.reports]
emb = llm.embed(texts)
q = llm.embed([query])[0]
sims = emb @ q
order = sims.argsort()[::-1][:k]
out = []
for i in order:
r = dict(self.reports[int(i)])
r["score"] = round(float(sims[int(i)]), 4)
out.append(r)
return out
except Exception as e: # noqa: BLE001
log.warning("社区检索失败:%s", str(e)[:120])
return self.reports[:k]
def build(graph: GraphStore, store: CommunityStore, min_size: int = 4,
make_report: bool = True, concurrency: int = 6, progress=None) -> dict:
mapping = detect(graph, min_size=min_size)
graph.set_communities(mapping)
groups: dict[int, list[str]] = {}
for n, c in mapping.items():
groups.setdefault(c, []).append(n)
if progress:
progress(f"社区检测:{len(groups)} 个社区,覆盖 {len(mapping)} 个实体")
if not make_report or not groups:
store.reports = [{"id": c, "title": f"社区 {c}", "summary": "", "keywords": [],
"size": len(m), "members": m,
"top_entities": sorted(m, key=lambda n: -graph.degree(n))[:10]}
for c, m in groups.items()]
store.save()
return {"communities": len(groups), "reports": 0}
reports: list[dict] = []
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool:
futs = {pool.submit(_report_one, graph, c, m): c for c, m in groups.items()}
for fut in as_completed(futs):
try:
reports.append(fut.result())
except Exception as e: # noqa: BLE001
log.warning("社区报告任务异常:%s", str(e)[:120])
reports.sort(key=lambda r: -r["size"])
store.reports = reports
store.save()
return {"communities": len(groups), "reports": len(reports)}