pipeline.py
13.1 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
"""抽取流水线:解析 → 分块 → 并发抽取(自适应补抽) → 归一化入图 → 消歧 →
描述归并 → 社区检测 → 重建索引。
生成器,逐步 yield 进度事件;由 jobs/queue.py 放到后台线程跑并广播给 SSE。
"""
from __future__ import annotations
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from ..core import db, llm
from ..core.ontology import default_ontology
from ..ingest import chunk as chunk_mod
from ..ingest.parse import parse_file
from ..store.graph_store import GraphStore
from ..store.vector_store import HybridIndex
from . import (community as community_mod, resolve as resolve_mod, summarize as summarize_mod,
typing_pass)
from .normalize import TypeNormalizer, is_noise_entity
from .prompts import (COMPLETE, GLEANING_USER, IF_LOOP_USER, build_extract_messages,
parse_json_fallback, parse_records)
log = logging.getLogger(__name__)
def _extract_chunk(ch: dict, onto: dict, max_gleaning: int) -> tuple[list[dict], list[dict], int]:
"""单块抽取 + 自适应补抽。返回 (entities, relations, llm_calls)。
v1 无条件跑固定轮数的 gleaning,等于每块都多花一倍调用。这里先问模型
"还有遗漏吗"(输出只有一个字,很便宜),答"是"才继续补抽。
"""
msgs = build_extract_messages(ch["text"], ch.get("heading", ""), onto)
raw = llm.chat(msgs, temperature=0.1)
calls = 1
ents, rels = parse_records(raw)
if not ents and not rels:
ents, rels = parse_json_fallback(raw) # 模型偶尔无视格式改吐 JSON
history = msgs + [{"role": "assistant", "content": raw}]
for _ in range(max(0, max_gleaning)):
try:
verdict = llm.chat(history + [{"role": "user", "content": IF_LOOP_USER}],
temperature=0.0)
calls += 1
except Exception: # noqa: BLE001
break
if (verdict or "").strip().startswith("是"):
break
more_raw = llm.chat(history + [{"role": "user", "content": GLEANING_USER}],
temperature=0.1)
calls += 1
if COMPLETE in (more_raw or "") and len((more_raw or "").strip()) < len(COMPLETE) + 8:
break
e2, r2 = parse_records(more_raw)
if not e2 and not r2:
break
ents += e2
rels += r2
history = history + [{"role": "user", "content": GLEANING_USER},
{"role": "assistant", "content": more_raw}]
return ents, rels, calls
def run_extract(doc_id: int, path: str, graph: GraphStore, index: HybridIndex,
communities: community_mod.CommunityStore):
cfg = db.get_all_config()
onto = json.loads(cfg["ONTOLOGY"]) if cfg.get("ONTOLOGY") else default_ontology()
concurrency = max(1, int(cfg.get("EXTRACT_CONCURRENCY", "8")))
max_gleaning = int(cfg.get("GLEANING_ROUNDS", "2"))
min_conf = float(cfg.get("MIN_ENTITY_CONFIDENCE", "0.3"))
noise_filter = cfg.get("NOISE_FILTER", "1") == "1"
# --- 解析 ---
yield {"stage": "parse", "message": "正在解析文档…"}
db.update_document(doc_id, status="parsing", error="")
parsed = parse_file(path)
if parsed.warnings:
for w in parsed.warnings:
yield {"stage": "parse", "level": "warn", "message": w}
db.update_document(doc_id, encoding=parsed.encoding,
parse_warning=";".join(parsed.warnings)[:2000])
# --- 分块 ---
chunks = chunk_mod.chunk_text(
parsed.text, doc_id,
chunk_tokens=int(cfg.get("CHUNK_TOKENS", "600")),
overlap_tokens=int(cfg.get("CHUNK_OVERLAP_TOKENS", "80")),
min_tokens=int(cfg.get("MIN_CHUNK_TOKENS", "120")))
total = len(chunks)
if not total:
raise RuntimeError("文档分块结果为空,无法抽取")
avg_tok = sum(c["tokens"] for c in chunks) // total
yield {"stage": "chunk", "total": total,
"message": f"已切分为 {total} 个片段(平均 {avg_tok} token,编码 {parsed.encoding})"}
db.update_document(doc_id, status="extracting", chunk_count=total)
# --- 重抽幂等:先回收这篇文档上一次的贡献 ---
purged = graph.delete_document(doc_id)
if purged["removed_entities"] or purged["removed_relations"]:
yield {"stage": "chunk", "message":
f"检测到历史抽取结果,已回收该文档独有的 "
f"{purged['removed_entities']} 个实体 / {purged['removed_relations']} 条关系"}
# --- 并发抽取 ---
normalizer = TypeNormalizer(onto.get("entity_types"), onto.get("relation_types"))
done = 0
llm_calls = 0
dropped_noise = 0
dropped_lowconf = 0
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futs = {pool.submit(_extract_chunk, ch, onto, max_gleaning): ch for ch in chunks}
for fut in as_completed(futs):
ch = futs[fut]
done += 1
source = {"chunk_id": ch["id"], "doc_id": doc_id,
"heading": ch.get("heading", ""), "snippet": ch["text"][:200]}
try:
raw_ents, raw_rels, calls = fut.result()
llm_calls += calls
except Exception as e: # noqa: BLE001
yield {"stage": "extract", "i": done, "total": total, "error": str(e)[:200],
"heading": ch.get("heading", "")}
continue
new_e = new_r = 0
for e in raw_ents:
name = (e.get("name") or "").strip()
conf = float(e.get("confidence", 0.8) or 0.8)
if not name:
continue
if conf < min_conf:
dropped_lowconf += 1
continue
if noise_filter and is_noise_entity(name, e.get("type", ""), e.get("description", "")):
dropped_noise += 1
continue
before = graph.has_node(name)
graph.add_entity(name, normalizer.entity_type(e.get("type", "")),
e.get("description", ""), source, doc_id, conf)
if not before:
new_e += 1
for r in raw_rels:
s, t = (r.get("source") or "").strip(), (r.get("target") or "").strip()
conf = float(r.get("confidence", 0.8) or 0.8)
if not s or not t or conf < min_conf:
continue
if noise_filter and (is_noise_entity(s) or is_noise_entity(t)):
dropped_noise += 1
continue
rel, _raw = normalizer.relation_type(r.get("relation", "关联"))
if graph.add_relation(s, t, rel, r.get("description", ""), source, doc_id, conf):
new_r += 1
yield {"stage": "extract", "i": done, "total": total, "heading": ch.get("heading", ""),
"new_entities": new_e, "new_relations": new_r,
"cum_entities": graph.g.number_of_nodes(),
"cum_relations": graph.g.number_of_edges()}
yield {"stage": "extract_done", "message":
f"抽取完成:{llm_calls} 次 LLM 调用;过滤噪声实体 {dropped_noise} 个、"
f"低置信 {dropped_lowconf} 个"}
graph.persist()
# --- 实体消歧 ---
resolve_stats = {}
if cfg.get("RESOLVE_ENABLED", "1") == "1":
yield {"stage": "resolve", "message": "正在做实体消歧(归一化 / 向量 / 大模型裁决)…"}
msgs: list[str] = []
resolve_stats = resolve_mod.resolve_entities(
graph,
sim_threshold=float(cfg.get("SIM_THRESHOLD", "0.88")),
review_low=float(cfg.get("SIM_REVIEW_LOW", "0.78")),
ngram_thr=float(cfg.get("NGRAM_JACCARD", "0.65")),
progress=msgs.append)
for m in msgs:
yield {"stage": "resolve", "message": m}
yield {"stage": "resolve", "message":
f"消歧完成:候选 {resolve_stats.get('candidates', 0)} 组,"
f"自动合并 {resolve_stats.get('auto_merged', 0)},"
f"大模型判定合并 {resolve_stats.get('llm_merged', 0)},"
f"实际合并节点 {resolve_stats.get('merged', 0)} 个",
"stats": resolve_stats}
graph.persist()
# --- 类型补全 ---
type_stats = {}
if cfg.get("TYPE_COMPLETION", "1") == "1":
yield {"stage": "typing", "message": "正在给未分类实体补全业务类型…"}
msgs = []
type_stats = typing_pass.complete_types(
graph, onto.get("entity_types") or [],
threshold=float(cfg.get("TYPE_COMPLETION_THRESHOLD", "0.42")),
progress=msgs.append)
for m in msgs:
yield {"stage": "typing", "message": m}
yield {"stage": "typing", "stats": type_stats, "message":
f"类型补全:{type_stats.get('candidates', 0)} 个未分类实体中,"
f"归类了 {type_stats.get('typed', 0)} 个"}
desc_stats = typing_pass.describe_orphans(graph, concurrency=concurrency,
progress=msgs.append)
type_stats["describe"] = desc_stats
yield {"stage": "typing", "message":
f"描述补全:{desc_stats.get('candidates', 0)} 个无描述实体中,"
f"补上了 {desc_stats.get('described', 0)} 条"}
graph.persist()
# --- 描述归并 ---
yield {"stage": "summarize", "message": "正在归并跨片段的实体描述…"}
msgs = []
sum_stats = summarize_mod.summarize_graph(
graph, threshold=int(cfg.get("SUMMARY_SOURCE_THRESHOLD", "4")),
concurrency=concurrency, progress=msgs.append)
for m in msgs:
yield {"stage": "summarize", "message": m}
yield {"stage": "summarize", "message":
f"已归并 {sum_stats['summarized_entities']} 个实体 / "
f"{sum_stats['summarized_relations']} 条关系的描述", "stats": sum_stats}
graph.persist()
# --- 社区 ---
comm_stats = {}
if cfg.get("COMMUNITY_ENABLED", "1") == "1":
yield {"stage": "community", "message": "正在做社区检测…"}
msgs = []
comm_stats = community_mod.build(
graph, communities,
min_size=int(cfg.get("COMMUNITY_MIN_SIZE", "4")),
make_report=cfg.get("COMMUNITY_REPORT", "1") == "1",
concurrency=concurrency, progress=msgs.append)
for m in msgs:
yield {"stage": "community", "message": m}
yield {"stage": "community", "message":
f"社区 {comm_stats.get('communities', 0)} 个,"
f"已生成报告 {comm_stats.get('reports', 0)} 份", "stats": comm_stats}
graph.persist()
# --- 索引 ---
yield {"stage": "index", "message": "正在建立 chunk / 实体 / 关系 三套混合索引…"}
index.upsert_chunks(doc_id, chunks) # 增量:不再抹掉其他文档的证据
index.rebuild_entities(graph.all_entities())
index.rebuild_relations(graph.all_relations())
stats = graph.stats()
mine = graph.doc_stats(doc_id) # 本文档的贡献,不是全库计数
db.update_document(doc_id, status="done", entity_count=mine["entity_count"],
relation_count=mine["relation_count"], error="")
yield {"stage": "done", "message": "抽取完成", "stats": stats, "doc_stats": mine,
"quality": {
"chunks": total, "avg_chunk_tokens": avg_tok, "llm_calls": llm_calls,
"dropped_noise": dropped_noise, "dropped_lowconf": dropped_lowconf,
"unmapped_types": normalizer.unmapped_types,
"unmapped_relations": normalizer.unmapped_relations,
"resolve": resolve_stats, "typing": type_stats,
"summarize": sum_stats, "community": comm_stats,
"index": index.stats()}}
def delete_document_data(doc_id: int, graph: GraphStore, index: HybridIndex,
communities: community_mod.CommunityStore) -> dict:
"""删除某篇文档:回收它独有的实体/关系 + 它的 chunk 索引。
v1 没有这个能力 —— 文档删了,它贡献的节点和边永远留在图里。
"""
purged = graph.delete_document(doc_id)
removed_chunks = index.delete_doc(doc_id)
index.rebuild_entities(graph.all_entities())
index.rebuild_relations(graph.all_relations())
# 图结构变了,社区要重算。这里只跑 Louvain 不生成报告(不花 LLM 额度):
# 否则节点上还留着旧的 community 标记、报告却被清空,头部显示"17 社区"
# 而社区面板说"还没有社区",前后自相矛盾。摘要留到下次抽取时重建。
cfg = db.get_all_config()
if cfg.get("COMMUNITY_ENABLED", "1") == "1" and graph.g.number_of_nodes():
community_mod.build(graph, communities,
min_size=int(cfg.get("COMMUNITY_MIN_SIZE", "4")),
make_report=False)
else:
graph.set_communities({})
communities.clear()
graph.persist()
return {**purged, "removed_chunks": removed_chunks}