extract_cli.py
4.08 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
"""本地调试:不开 UI,直接对文档跑完整抽取流水线。
用法(在项目根目录):
python scripts/extract_cli.py "需求文档-xxx.md"
python scripts/extract_cli.py doc.md --no-resolve --no-community # 跳过耗时步骤
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
# Windows 控制台默认是 GBK,直接 print 乱码字符串会抛 UnicodeEncodeError,
# 反而让"修乱码"的脚本自己先挂掉。这里强制 UTF-8 输出。
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
from app.core import db # noqa: E402
from app.core.config import get_settings # noqa: E402
from app.extract import pipeline # noqa: E402
from app.extract.community import CommunityStore # noqa: E402
from app.ingest.filename import sanitize_display_name, stored_name # noqa: E402
from app.store.graph_store import GraphStore # noqa: E402
from app.store.vector_store import HybridIndex # noqa: E402
def main() -> None:
ap = argparse.ArgumentParser(description="命令行跑抽取流水线")
ap.add_argument("path", help="文档路径")
ap.add_argument("--no-resolve", action="store_true", help="跳过实体消歧")
ap.add_argument("--no-community", action="store_true", help="跳过社区检测")
ap.add_argument("--no-gleaning", action="store_true", help="关闭补抽(最省额度)")
args = ap.parse_args()
src = Path(args.path)
if not src.exists():
print("文件不存在:", src)
sys.exit(1)
db.init_db()
overrides = {}
if args.no_resolve:
overrides["RESOLVE_ENABLED"] = "0"
if args.no_community:
overrides["COMMUNITY_ENABLED"] = "0"
if args.no_gleaning:
overrides["GLEANING_ROUNDS"] = "0"
if overrides:
db.set_config(overrides)
print("已临时调整配置:", overrides)
settings = get_settings()
data = settings.data_path
graph = GraphStore(data / "graph.json")
index = HybridIndex(data / "index")
communities = CommunityStore(data / "communities.json")
import hashlib
raw = src.read_bytes()
file_hash = hashlib.sha256(raw).hexdigest()[:16]
display = sanitize_display_name(src.name)
existing = db.find_document_by_hash(file_hash)
if existing:
doc_id = existing["id"]
target = Path(existing["stored_path"])
print(f"文档已登记,复用 id={doc_id}({existing['filename']})")
else:
target = data / "uploads" / stored_name(display, file_hash)
target.write_bytes(raw)
doc_id = db.create_document(display, str(target), len(raw), file_hash, target.name)
print(f"文档已登记 id={doc_id}:{display}")
started = time.time()
for ev in pipeline.run_extract(doc_id, str(target), graph, index, communities):
stage = ev.get("stage")
if stage == "extract" and "i" in ev:
print(f"[{ev['i']}/{ev['total']}] {(ev.get('heading') or '')[-40:]} "
f"+实体{ev.get('new_entities', 0)} +关系{ev.get('new_relations', 0)} "
f"累计 {ev.get('cum_entities', 0)}/{ev.get('cum_relations', 0)}")
elif ev.get("error"):
print(" ! 错误:", ev["error"])
else:
print("·", ev.get("message", stage))
st = graph.stats()
print(f"\n=== 统计(耗时 {time.time() - started:.1f}s)===")
print(f"实体 {st['entity_count']} · 关系 {st['relation_count']} · "
f"社区 {st['community_count']} · 平均度 {st['avg_degree']}")
print(f"孤立点 {st['isolated']} · 度=1 叶子 {st['leaf']}({st['leaf_ratio'] * 100:.1f}%)")
print("类型分布:", st["type_dist"])
print("图谱已保存到:", data / "graph.json")
print("\n跑一份质量对比:python scripts/quality_report.py")
if __name__ == "__main__":
main()