-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgetnote_interactive.py
More file actions
executable file
·392 lines (322 loc) · 13.5 KB
/
getnote_interactive.py
File metadata and controls
executable file
·392 lines (322 loc) · 13.5 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#!/usr/bin/env python3
"""
Get 笔记知识库交互式浏览工具
支持序号选择、完整内容查看和公众号文章适配性评估
"""
import os
import sys
from pathlib import Path
from typing import List, Dict
# 加载环境变量
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 GetNoteInteractive:
"""Get 笔记交互式浏览器"""
def __init__(self):
self.client = GetNoteAPI()
self.all_notes = []
self.all_files = {}
def fetch_all_content(self):
"""获取所有知识库内容"""
print("🔍 正在加载知识库内容...\n")
keywords = ['文章', '教程', '指南', 'AI', '开发', '学习']
all_items = {}
for kw in keywords:
try:
materials = self.client.recall(kw, top_k=30)
for m in materials:
item_id = m.get('id')
if item_id and item_id not in all_items:
all_items[item_id] = m
except:
continue
# 分类
self.all_notes = [m for m in all_items.values() if m.get('type') == 'NOTE']
self.all_notes.sort(key=lambda x: x.get('title', ''))
for m in all_items.values():
if m.get('type') == 'FILE':
title = m.get('title', '无标题')
if title not in self.all_files:
self.all_files[title] = []
self.all_files[title].append(m)
def show_all_titles(self):
"""显示所有笔记标题"""
print("=" * 70)
print("📚 Get 笔记知识库 - 全部内容")
print("=" * 70)
print()
print(f"📝 笔记(NOTE): {len(self.all_notes)} 条\n")
for i, note in enumerate(self.all_notes, 1):
title = note.get('title', '无标题')
extra = note.get('extra', {})
url = extra.get('url', '') if isinstance(extra, dict) else ''
print(f"{i:2d}. {title}")
if url:
print(f" 🔗 {url}")
if self.all_files:
print(f"\n📄 文档(FILE): {len(self.all_files)} 份\n")
for i, (title, fragments) in enumerate(self.all_files.items(), len(self.all_notes) + 1):
print(f"{i:2d}. {title}")
print(f" (共 {len(fragments)} 个片段)")
print()
print("=" * 70)
def get_full_content(self, index: int) -> Dict:
"""获取完整内容(处理多片段情况)"""
total_notes = len(self.all_notes)
if index <= total_notes:
# 选择的是笔记
note = self.all_notes[index - 1]
title = note.get('title', '无标题')
# 检查是否有多个片段
print(f"\n🔍 正在获取《{title}》的完整内容...\n")
# 搜索同标题的所有片段
all_fragments = self.client.recall(title, top_k=50)
fragments = [f for f in all_fragments if f.get('title') == title]
if len(fragments) > 1:
print(f"✅ 发现 {len(fragments)} 个片段,正在合并...\n")
# 合并内容
full_content = ""
for frag in fragments:
content = frag.get('content', '')
if content and content not in full_content:
full_content += content + "\n\n"
return {
'title': title,
'content': full_content.strip(),
'type': note.get('type'),
'url': note.get('extra', {}).get('url', ''),
'fragments': len(fragments)
}
else:
return {
'title': title,
'content': note.get('content', ''),
'type': note.get('type'),
'url': note.get('extra', {}).get('url', ''),
'fragments': 1
}
else:
# 选择的是文档
file_index = index - total_notes - 1
file_titles = list(self.all_files.keys())
if file_index < len(file_titles):
title = file_titles[file_index]
fragments = self.all_files[title]
print(f"\n🔍 正在合并《{title}》的 {len(fragments)} 个片段...\n")
# 合并所有片段
full_content = ""
for frag in fragments:
content = frag.get('content', '')
if content:
full_content += content + "\n\n"
return {
'title': title,
'content': full_content.strip(),
'type': 'FILE',
'url': '',
'fragments': len(fragments)
}
return None
def evaluate_for_wechat(self, content_data: Dict) -> Dict:
"""评估内容是否适合写公众号文章"""
title = content_data.get('title', '')
content = content_data.get('content', '')
url = content_data.get('url', '')
# 基础指标
word_count = len(content)
has_url = bool(url)
content_type = content_data.get('type', '')
# 评估结果
evaluation = {
'suitable': False,
'score': 0,
'reasons': [],
'suggestions': []
}
# 1. 长度评估
if word_count >= 500:
evaluation['score'] += 25
evaluation['reasons'].append(f"✅ 内容长度充足(约{word_count}字)")
elif word_count >= 300:
evaluation['score'] += 15
evaluation['reasons'].append(f"⚠️ 内容长度适中(约{word_count}字),建议扩充")
else:
evaluation['reasons'].append(f"❌ 内容过短(约{word_count}字),需要大量扩充")
evaluation['suggestions'].append("补充更多案例、故事或实践经验")
# 2. 结构评估
has_structure = any(keyword in content for keyword in ['一、', '二、', '1.', '2.', '##', '###'])
if has_structure:
evaluation['score'] += 20
evaluation['reasons'].append("✅ 内容有清晰结构")
else:
evaluation['reasons'].append("⚠️ 建议添加明确的章节结构")
evaluation['suggestions'].append("使用小标题划分内容层次")
# 3. 实践性评估
practical_keywords = ['方法', '技巧', '步骤', '如何', '实践', '案例', '经验', '教程']
practical_count = sum(1 for kw in practical_keywords if kw in content)
if practical_count >= 3:
evaluation['score'] += 25
evaluation['reasons'].append("✅ 内容具有实践性和可操作性")
elif practical_count >= 1:
evaluation['score'] += 15
evaluation['reasons'].append("⚠️ 有一定实践性,可增强可操作性")
evaluation['suggestions'].append("添加更多具体方法和步骤")
else:
evaluation['reasons'].append("❌ 缺少实践指导")
evaluation['suggestions'].append("补充具体的操作方法和案例")
# 4. 话题热度评估
hot_topics = ['AI', 'Claude', '提示词', '效率', '时间管理', '职场', '创业', '学习']
has_hot_topic = any(topic in title or topic in content[:200] for topic in hot_topics)
if has_hot_topic:
evaluation['score'] += 15
evaluation['reasons'].append("✅ 话题有热度和关注度")
else:
evaluation['reasons'].append("⚠️ 话题可以更贴近热点")
evaluation['suggestions'].append("结合当前热门话题或痛点")
# 5. 原创性评估
if has_url:
evaluation['score'] += 15
evaluation['reasons'].append(f"✅ 有原文链接,可作为参考素材")
else:
evaluation['reasons'].append("⚠️ 无原文链接,注意版权问题")
# 综合评估
if evaluation['score'] >= 75:
evaluation['suitable'] = True
evaluation['level'] = "🌟🌟🌟 强烈推荐"
evaluation['summary'] = "内容质量优秀,非常适合改编为公众号文章"
elif evaluation['score'] >= 60:
evaluation['suitable'] = True
evaluation['level'] = "🌟🌟 推荐"
evaluation['summary'] = "内容基础较好,稍作优化即可发布"
elif evaluation['score'] >= 40:
evaluation['suitable'] = False
evaluation['level'] = "🌟 可考虑"
evaluation['summary'] = "内容有潜力,但需要较多改进和扩充"
else:
evaluation['suitable'] = False
evaluation['level'] = "❌ 不推荐"
evaluation['summary'] = "当前内容不太适合,建议寻找其他素材"
return evaluation
def show_content_and_evaluation(self, content_data: Dict, evaluation: Dict):
"""显示完整内容和评估结果"""
print("=" * 70)
print(f"📄 《{content_data['title']}》")
print("=" * 70)
print()
# 基本信息
print("【基本信息】")
print(f"类型: {content_data.get('type', '未知')}")
if content_data.get('fragments', 1) > 1:
print(f"片段数: {content_data['fragments']} 个")
if content_data.get('url'):
print(f"原文: {content_data['url']}")
print()
# 内容预览
content = content_data.get('content', '')
print("【内容预览】")
print("-" * 70)
# 显示前1000字
preview_length = min(1000, len(content))
print(content[:preview_length])
if len(content) > preview_length:
print(f"\n... (还有 {len(content) - preview_length} 字)")
print("-" * 70)
print()
# 核心摘要
print("【核心摘要】")
# 提取前300字作为摘要
summary = content[:300].replace('\n', ' ')
print(f"{summary}...")
print()
# 公众号适配性评估
print("=" * 70)
print("📊 公众号文章适配性评估")
print("=" * 70)
print()
print(f"【综合评分】{evaluation['score']}/100")
print(f"【推荐等级】{evaluation['level']}")
print(f"【评估结论】{evaluation['summary']}")
print()
print("【详细分析】")
for reason in evaluation['reasons']:
print(f" {reason}")
if evaluation['suggestions']:
print()
print("【优化建议】")
for suggestion in evaluation['suggestions']:
print(f" • {suggestion}")
print()
print("=" * 70)
def run(self):
"""运行交互式流程"""
# 1. 获取所有内容
self.fetch_all_content()
# 2. 显示标题列表
self.show_all_titles()
# 3. 提示用户输入
print()
print("💡 请输入文章序号查看完整内容和评估(输入 0 退出)")
while True:
try:
user_input = input("\n请选择 [0-%d]: " % (len(self.all_notes) + len(self.all_files))).strip()
if not user_input:
continue
choice = int(user_input)
if choice == 0:
print("\n👋 再见!")
break
max_index = len(self.all_notes) + len(self.all_files)
if choice < 1 or choice > max_index:
print(f"❌ 无效选择,请输入 1-{max_index} 之间的数字")
continue
# 4. 获取完整内容
content_data = self.get_full_content(choice)
if not content_data:
print("❌ 获取内容失败")
continue
# 5. 评估适配性
evaluation = self.evaluate_for_wechat(content_data)
# 6. 显示结果
print()
self.show_content_and_evaluation(content_data, evaluation)
# 继续或退出
print()
continue_choice = input("按 Enter 继续选择,输入 q 退出: ").strip().lower()
if continue_choice == 'q':
print("\n👋 再见!")
break
# 重新显示标题列表
print()
self.show_all_titles()
except ValueError:
print("❌ 请输入有效的数字")
except KeyboardInterrupt:
print("\n\n👋 已取消")
break
except Exception as e:
print(f"\n❌ 错误: {e}")
import traceback
traceback.print_exc()
def main():
"""主函数"""
try:
browser = GetNoteInteractive()
browser.run()
except KeyboardInterrupt:
print("\n\n👋 已取消")
sys.exit(0)
except Exception as e:
print(f"\n❌ 程序错误: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()