-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgetnote_view.py
More file actions
executable file
·435 lines (360 loc) · 15.6 KB
/
getnote_view.py
File metadata and controls
executable file
·435 lines (360 loc) · 15.6 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python3
"""
Get 笔记知识库查看工具
支持查看完整内容和公众号文章适配性评估
用法: python3 getnote_view.py [序号]
"""
import os
import sys
import json
from pathlib import Path
from typing import List, Dict
from datetime import datetime
# 加载环境变量
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 GetNoteViewer:
"""Get 笔记查看器"""
def __init__(self):
self.client = GetNoteAPI()
self.all_notes = []
self.all_files = {}
self.used_materials_file = Path(__file__).parent / "config" / "used_materials.json"
self.used_materials = self._load_used_materials()
def _load_used_materials(self) -> Dict:
"""加载已使用素材记录"""
if self.used_materials_file.exists():
try:
with open(self.used_materials_file, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return {"used_articles": []}
return {"used_articles": []}
def _is_used(self, title: str) -> bool:
"""检查素材是否已使用"""
for used in self.used_materials.get("used_articles", []):
if used.get("title") == title:
return True
return False
def _get_used_info(self, title: str) -> Dict:
"""获取已使用素材的详细信息"""
for used in self.used_materials.get("used_articles", []):
if used.get("title") == title:
return used
return {}
def fetch_all_content(self):
"""获取所有知识库内容"""
print("🔍 正在获取知识库全部内容...\n")
# 方法1: 使用空查询或通用查询获取所有内容
all_items = {}
# 先尝试使用最通用的查询
try:
# 使用空格作为查询,Get笔记会返回所有相关内容
materials = self.client.recall(" ", top_k=100)
for m in materials:
item_id = m.get('id')
if item_id:
all_items[item_id] = m
except:
pass
# 方法2: 使用广泛关键词补充(确保覆盖所有内容)
keywords = ['文章', '教程', '指南', 'AI', '开发', '学习', '技术', '工具',
'方法', '实践', '应用', '经验', '分享', '代码', '效率', '管理',
'提示词', 'Claude', 'Cursor', '烟花', '企业', '日记', '小程序',
'Transformer', '沟通', '教育', '范式', '系统']
for kw in keywords:
try:
materials = self.client.recall(kw, top_k=100)
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()
# 统计已使用和未使用的数量
used_count = sum(1 for note in self.all_notes if self._is_used(note.get('title', '')))
unused_count = len(self.all_notes) - used_count
print(f"📝 笔记(NOTE): {len(self.all_notes)} 条")
print(f" ✅ 已使用: {used_count} 条")
print(f" 🆕 未使用: {unused_count} 条\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 ''
# 检查是否已使用
is_used = self._is_used(title)
used_mark = "✅ " if is_used else "🆕 "
print(f"{used_mark}{i:2d}. {title}")
if url:
print(f" 🔗 {url}")
# 如果已使用,显示使用信息
if is_used:
used_info = self._get_used_info(title)
if used_info:
print(f" 📅 已于 {used_info.get('used_date')} 改编为《{used_info.get('generated_title', '未知标题')}》")
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):
is_used = self._is_used(title)
used_mark = "✅ " if is_used else "🆕 "
print(f"{used_mark}{i:2d}. {title}")
print(f" (共 {len(fragments)} 个片段)")
if is_used:
used_info = self._get_used_info(title)
if used_info:
print(f" 📅 已于 {used_info.get('used_date')} 改编")
print()
print("=" * 70)
print(f"\n💡 使用方法: python3 getnote_view.py <序号>")
print(f" 例如: python3 getnote_view.py 8")
print(f"\n💡 提示: ✅ = 已使用 🆕 = 未使用(推荐优先选择)")
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)
# 评估结果
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 main():
"""主函数"""
viewer = GetNoteViewer()
try:
print("🔍 正在加载知识库内容...\n")
viewer.fetch_all_content()
# 如果没有提供参数,显示列表
if len(sys.argv) == 1:
viewer.show_all_titles()
return
# 获取用户输入的序号
try:
index = int(sys.argv[1])
except ValueError:
print("❌ 错误: 请提供有效的数字序号")
print(f"\n用法: python3 {sys.argv[0]} <序号>")
sys.exit(1)
max_index = len(viewer.all_notes) + len(viewer.all_files)
if index < 1 or index > max_index:
print(f"❌ 错误: 序号必须在 1-{max_index} 之间")
sys.exit(1)
# 获取完整内容
content_data = viewer.get_full_content(index)
if not content_data:
print("❌ 获取内容失败")
sys.exit(1)
# 评估适配性
evaluation = viewer.evaluate_for_wechat(content_data)
# 显示结果
print()
viewer.show_content_and_evaluation(content_data, evaluation)
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()