-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgetnote_manager.py
More file actions
executable file
·229 lines (188 loc) · 7.09 KB
/
getnote_manager.py
File metadata and controls
executable file
·229 lines (188 loc) · 7.09 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
#!/usr/bin/env python3
"""
Get 笔记知识库管理工具
提供交互式界面查看和搜索知识库内容
"""
import os
import sys
from pathlib import Path
# 加载环境变量
config_dir = Path(__file__).parent / "config"
getnote_env = config_dir / "getnote.env"
if getnote_env.exists():
with open(getnote_env, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
from mcp_tools.getnote import GetNoteAPI
class GetNoteManager:
"""Get 笔记知识库管理器"""
def __init__(self):
self.client = GetNoteAPI()
self.common_topics = [
'提示词', 'AI工具', 'Claude', '时间管理',
'学习方法', '沟通技巧', '职场', '创业',
'写作', '效率', '思维', '产品'
]
def show_overview(self):
"""显示知识库概览"""
print("\n" + "=" * 70)
print("📚 Get 笔记知识库概览")
print("=" * 70)
print()
total_count = 0
for topic in self.common_topics:
materials = self.client.recall(topic, top_k=3)
if materials:
total_count += len(materials)
print(f'【{topic}】找到 {len(materials)} 条')
for i, m in enumerate(materials[:2], 1): # 只显示前2条
title = m.get('title', '无标题')[:50]
mtype = m.get('type', '未知')
score = m.get('score', 0)
print(f' {i}. [{mtype}] {title}... ({score:.3f})')
print()
print("=" * 70)
print(f"✅ 已扫描 {len(self.common_topics)} 个主题")
print("=" * 70)
def search_by_keyword(self, keyword: str, top_k: int = 5, show_content: bool = True):
"""按关键词搜索"""
print("\n" + "=" * 70)
print(f"🔍 搜索: {keyword}")
print("=" * 70)
print()
materials = self.client.recall(keyword, top_k=top_k)
if not materials:
print("❌ 未找到相关内容")
return []
print(f"✅ 找到 {len(materials)} 条相关素材:\n")
for i, m in enumerate(materials, 1):
title = m.get('title', '无标题')
mtype = m.get('type', '未知')
score = m.get('score', 0)
print(f"\n{i}. {title}")
print(f" 类型: {mtype} | 相关度: {score:.4f}")
if show_content:
content = m.get('content', '')
if content:
preview = content[:300].replace('\n', ' ')
print(f" 内容: {preview}...")
print("\n" + "=" * 70)
return materials
def show_material_detail(self, material: dict):
"""显示素材详情"""
print("\n" + "=" * 70)
print(f"📄 {material.get('title', '无标题')}")
print("=" * 70)
print()
print(f"类型: {material.get('type', '未知')}")
print(f"ID: {material.get('id', 'N/A')}")
print(f"相关度: {material.get('score', 0):.4f}")
print()
print("内容:")
print("-" * 70)
print(material.get('content', '无内容'))
print("-" * 70)
def analyze_topics(self):
"""分析知识库主题分布"""
print("\n" + "=" * 70)
print("📊 知识库主题分析")
print("=" * 70)
print()
topic_scores = {}
for topic in self.common_topics:
materials = self.client.recall(topic, top_k=1)
if materials:
avg_score = sum(m.get('score', 0) for m in materials) / len(materials)
topic_scores[topic] = {
'count': len(materials),
'avg_score': avg_score
}
# 按相关度排序
sorted_topics = sorted(
topic_scores.items(),
key=lambda x: x[1]['avg_score'],
reverse=True
)
print("主题相关度排名:\n")
for i, (topic, data) in enumerate(sorted_topics, 1):
score = data['avg_score']
bar = '█' * int(score * 20)
print(f"{i:2d}. {topic:12s} {bar:20s} {score:.3f}")
print("\n" + "=" * 70)
def interactive_menu(self):
"""交互式菜单"""
while True:
print("\n" + "=" * 70)
print("📚 Get 笔记知识库管理")
print("=" * 70)
print("\n选项:")
print(" 1. 查看知识库概览")
print(" 2. 搜索关键词")
print(" 3. 主题分布分析")
print(" 4. 查看常见主题")
print(" 0. 退出")
print()
choice = input("请选择 [0-4]: ").strip()
if choice == '0':
print("\n👋 再见!")
break
elif choice == '1':
self.show_overview()
elif choice == '2':
keyword = input("\n请输入关键词: ").strip()
if keyword:
top_k = input("返回数量 [默认5]: ").strip() or "5"
try:
top_k = int(top_k)
self.search_by_keyword(keyword, top_k)
except ValueError:
print("❌ 数量必须是数字")
elif choice == '3':
self.analyze_topics()
elif choice == '4':
print("\n常见主题:")
for i, topic in enumerate(self.common_topics, 1):
print(f" {i}. {topic}")
else:
print("❌ 无效选择")
input("\n按 Enter 继续...")
def main():
"""主函数"""
import argparse
parser = argparse.ArgumentParser(
description='Get 笔记知识库管理工具'
)
parser.add_argument('keyword', nargs='?', help='搜索关键词')
parser.add_argument('-n', '--number', type=int, default=5, help='返回数量')
parser.add_argument('-o', '--overview', action='store_true', help='显示概览')
parser.add_argument('-a', '--analyze', action='store_true', help='分析主题分布')
parser.add_argument('-i', '--interactive', action='store_true', help='交互式模式')
args = parser.parse_args()
manager = GetNoteManager()
try:
if args.interactive:
# 交互式模式
manager.interactive_menu()
elif args.overview:
# 显示概览
manager.show_overview()
elif args.analyze:
# 分析主题
manager.analyze_topics()
elif args.keyword:
# 搜索关键词
manager.search_by_keyword(args.keyword, args.number)
else:
# 默认显示概览
manager.show_overview()
except KeyboardInterrupt:
print("\n\n👋 已取消")
sys.exit(0)
except Exception as e:
print(f"\n❌ 错误: {e}")
sys.exit(1)
if __name__ == "__main__":
main()