-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathauto_weekly.py
More file actions
2203 lines (1799 loc) · 82.8 KB
/
auto_weekly.py
File metadata and controls
2203 lines (1799 loc) · 82.8 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
完全自动化的周报生成工具
1. 从git历史生成周报文件(基于gen_weekly.py)
2. 自动获取GitHub内容
3. 使用AI生成中文描述
4. 更新周报文件
"""
import re
import os
import sys
import json
import time
import logging
import subprocess
import requests
import functools
from pathlib import Path
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from json import JSONDecodeError
from typing import Dict, List, Optional, Tuple, Callable, Any
from urllib.parse import urlparse
from collections import defaultdict
# ============ 日志配置 ============
def setup_logging(log_file: Optional[str] = None, level: int = logging.INFO):
"""配置日志系统"""
handlers = []
# 控制台处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(level)
console_format = logging.Formatter('%(message)s')
console_handler.setFormatter(console_format)
handlers.append(console_handler)
# 文件处理器(可选)
if log_file:
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_format)
handlers.append(file_handler)
logging.basicConfig(level=level, handlers=handlers)
return logging.getLogger(__name__)
logger = setup_logging()
# ============ 重试装饰器 ============
def retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0,
exceptions: tuple = (requests.RequestException,)):
"""
重试装饰器
Args:
max_attempts: 最大重试次数
delay: 初始延迟(秒)
backoff: 延迟倍数(每次重试后延迟乘以此值)
exceptions: 需要重试的异常类型
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
current_delay = delay
last_exception = None
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
if attempt < max_attempts:
logger.warning(f" ⚠️ 第 {attempt} 次尝试失败: {e}")
logger.info(f" ⏳ {current_delay:.1f}秒后重试...")
time.sleep(current_delay)
current_delay *= backoff
else:
logger.error(f" ✗ 已重试 {max_attempts} 次,放弃")
raise last_exception
return wrapper
return decorator
# ============ 配置管理 ============
@dataclass
class Config:
"""配置类"""
# AI接口配置
ai_base_url: str = "https://api.anthropic.com"
ai_api_key: str = ""
ai_auth_token: str = ""
ai_model: str = "claude-sonnet-4-5-20250929"
# 路径配置
repo_path: Path = field(default_factory=Path.cwd)
weekly_dir: Path = field(default=None)
cache_dir: Path = field(default=None)
# 处理配置
max_links_per_week: int = 50
request_delay: float = 1.0
cache_save_interval: int = 5
# 重试配置
retry_max_attempts: int = 3
retry_delay: float = 1.0
retry_backoff: float = 2.0
def __post_init__(self):
"""初始化后处理"""
if self.weekly_dir is None:
self.weekly_dir = self.repo_path / "weekly"
if self.cache_dir is None:
self.cache_dir = self.repo_path / "links_cache"
@property
def ai_api_url(self) -> str:
"""获取完整的AI API URL"""
base = self.ai_base_url.rstrip("/")
if base.endswith("/messages"):
return base
elif base.endswith("/v1"):
return base + "/messages"
else:
return base + "/v1/messages"
@classmethod
def from_env(cls, repo_path: Optional[Path] = None) -> "Config":
"""从环境变量加载配置"""
if repo_path is None:
repo_path = Path.cwd()
return cls(
ai_base_url=os.getenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com"),
ai_api_key=os.getenv("ANTHROPIC_API_KEY", ""),
ai_auth_token=os.getenv("ANTHROPIC_AUTH_TOKEN", ""),
ai_model=os.getenv("AI_MODEL", "claude-sonnet-4-5-20250929"),
repo_path=repo_path,
max_links_per_week=int(os.getenv("MAX_LINKS_PER_WEEK", "50")),
request_delay=float(os.getenv("REQUEST_DELAY", "1.0")),
)
@classmethod
def from_file(cls, config_file: Path, repo_path: Optional[Path] = None) -> "Config":
"""从配置文件加载配置"""
if repo_path is None:
repo_path = Path.cwd()
config_data = {}
if config_file.exists():
try:
with open(config_file, 'r', encoding='utf-8') as f:
if config_file.suffix in ('.yaml', '.yml'):
try:
import yaml
config_data = yaml.safe_load(f) or {}
except ImportError:
logger.warning("未安装 PyYAML,使用环境变量配置")
elif config_file.suffix == '.json':
config_data = json.load(f)
except Exception as e:
logger.warning(f"读取配置文件失败: {e},使用默认配置")
# 合并环境变量(环境变量优先级更高)
return cls(
ai_base_url=os.getenv("ANTHROPIC_BASE_URL", config_data.get("ai_base_url", "https://api.anthropic.com")),
ai_api_key=os.getenv("ANTHROPIC_API_KEY", config_data.get("ai_api_key", "")),
ai_auth_token=os.getenv("ANTHROPIC_AUTH_TOKEN", config_data.get("ai_auth_token", "")),
ai_model=os.getenv("AI_MODEL", config_data.get("ai_model", "claude-sonnet-4-5-20250929")),
repo_path=repo_path,
max_links_per_week=int(os.getenv("MAX_LINKS_PER_WEEK", config_data.get("max_links_per_week", 50))),
request_delay=float(os.getenv("REQUEST_DELAY", config_data.get("request_delay", 1.0))),
retry_max_attempts=config_data.get("retry_max_attempts", 3),
retry_delay=config_data.get("retry_delay", 1.0),
retry_backoff=config_data.get("retry_backoff", 2.0),
)
# 全局配置(延迟初始化)
_config: Optional[Config] = None
def get_config() -> Config:
"""获取全局配置"""
global _config
if _config is None:
repo_path = Path.cwd()
config_file = repo_path / "config.yaml"
if config_file.exists():
_config = Config.from_file(config_file, repo_path)
else:
_config = Config.from_env(repo_path)
return _config
def set_config(config: Config):
"""设置全局配置"""
global _config
_config = config
# ============ 进度显示 ============
class ProgressBar:
"""简单的进度条显示"""
def __init__(self, total: int, desc: str = "", width: int = 40):
self.total = total
self.current = 0
self.desc = desc
self.width = width
self.start_time = time.time()
def update(self, n: int = 1):
"""更新进度"""
self.current += n
self._display()
def set(self, n: int):
"""设置当前进度"""
self.current = n
self._display()
def _display(self):
"""显示进度条"""
if self.total == 0:
return
percent = self.current / self.total
filled = int(self.width * percent)
bar = '█' * filled + '░' * (self.width - filled)
elapsed = time.time() - self.start_time
if self.current > 0:
eta = elapsed / self.current * (self.total - self.current)
eta_str = format_duration(eta)
else:
eta_str = "--"
# 使用 \r 回到行首,覆盖之前的输出
sys.stdout.write(f'\r{self.desc} |{bar}| {self.current}/{self.total} ({percent:.0%}) ETA: {eta_str}')
sys.stdout.flush()
def finish(self):
"""完成进度条"""
self.current = self.total
self._display()
print() # 换行
def format_duration(seconds: float) -> str:
"""格式化时间为可读字符串"""
if seconds < 60:
return f"{seconds:.1f}秒"
elif seconds < 3600:
minutes = int(seconds // 60)
secs = seconds % 60
return f"{minutes}分{secs:.0f}秒"
else:
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
return f"{hours}小时{minutes}分"
# ================================
def is_meaningful_description(desc: str, url: str) -> bool:
"""
判断描述是否有意义(不仅仅是URL路径名)
无意义的描述包括:
- 空字符串
- URL路径名(如 weaponized-in-china-deployed-in-india)
- URL的一部分
- 太短的文本(少于5个字符)
- 文件名后缀(如 .html)
- 纯数字(如 3453)
"""
if not desc:
return False
desc_lower = desc.lower().strip()
# 从URL提取路径名
url_name = url.rstrip('/').split('/')[-1]
url_name_lower = url_name.lower()
# 如果描述就是URL路径名,不算有效描述
if desc_lower == url_name_lower:
return False
# 移除常见后缀后再比较
for suffix in ['.html', '.htm', '.md', '.php', '.asp', '.aspx']:
if url_name_lower.endswith(suffix):
url_name_no_ext = url_name_lower[:-len(suffix)]
if desc_lower == url_name_no_ext:
return False
# 如果描述是URL路径的变体(将-替换为空格等)
url_name_normalized = url_name_lower.replace('-', ' ').replace('_', ' ')
desc_normalized = desc_lower.replace('-', ' ').replace('_', ' ')
if desc_normalized == url_name_normalized:
return False
# 如果描述是纯数字(如 seebug 的 3453)
if desc.strip().isdigit():
return False
# 如果描述太短(少于5个字符),不算有效描述
if len(desc.strip()) < 5:
return False
# 如果描述只是URL的路径部分
try:
parsed = urlparse(url)
path_parts = [p for p in parsed.path.split('/') if p]
for part in path_parts:
part_lower = part.lower()
if desc_lower == part_lower:
return False
# 移除后缀后比较
for suffix in ['.html', '.htm', '.md']:
if part_lower.endswith(suffix):
if desc_lower == part_lower[:-len(suffix)]:
return False
except Exception:
pass
return True
def _run_git(repo_path: Path, args: List[str], *, check: bool = True) -> subprocess.CompletedProcess:
return subprocess.run(
['git', '-C', str(repo_path), *args],
capture_output=True,
text=True,
encoding='utf-8',
errors='ignore',
check=check,
)
class WeeklyGenerator:
"""周报生成器 - 从git历史生成周报文件"""
def __init__(self, repo_path: str):
self.repo_path = Path(repo_path)
self.weekly_dir = self.repo_path / "weekly"
self.weekly_dir.mkdir(exist_ok=True)
# 文件类型到分类的映射
self.category_map = {
'README.md': '📦 收集的项目',
'tools.md': '🔧 收集的工具',
'BOF.md': '🎯 BOF工具',
'skills-ai.md': '🤖 AI使用技巧',
'docs.md': '📚 收集的文章',
'free.md': '🎁 免费资源',
'pico.md': '🔌 PICO工具',
'C2.md': '🎮 C2框架'
}
def get_week_range(self, date_str: str) -> Tuple[str, str]:
"""获取日期所在周的周一到周日"""
date = datetime.strptime(date_str, "%Y-%m-%d")
monday = date - timedelta(days=date.weekday())
sunday = monday + timedelta(days=6)
return monday.strftime("%Y-%m-%d"), sunday.strftime("%Y-%m-%d")
def get_git_log(self, since_date: str = None) -> List[Dict]:
"""获取git提交日志"""
args = ['log', '--pretty=format:%H|%ad|%s', '--date=format:%Y-%m-%d']
if since_date:
args.extend(['--since', since_date])
try:
result = _run_git(self.repo_path, args, check=True)
except subprocess.CalledProcessError as e:
print(f"? git log ??: {e}")
if e.stderr:
print(f" stderr: {e.stderr.strip()[:200]}")
return []
commits = []
for line in result.stdout.strip().split('\n'):
if not line:
continue
parts = line.split('|', 2)
if len(parts) == 3:
commits.append({
'hash': parts[0],
'date': parts[1],
'message': parts[2]
})
return commits
def extract_links_from_diff(self, commit_hash: str) -> Dict[str, List[Dict]]:
"""从提交diff中提取链接,按文件分类(排除weekly目录)
处理逻辑:
- GitHub链接:desc留空,后续用AI生成
- 非GitHub链接:使用标题行作为desc
"""
try:
result = _run_git(self.repo_path, ['show', commit_hash, '--format=', '--unified=0'], check=True)
except subprocess.CalledProcessError as e:
print(f"? git show ??: {commit_hash}: {e}")
if e.stderr:
print(f" stderr: {e.stderr.strip()[:200]}")
return {}
links_by_file = defaultdict(list)
current_file = None
last_title = "" # 保存上一行的标题(用于非GitHub链接)
for line in result.stdout.split('\n'):
# 检测文件名
if line.startswith('diff --git'):
match = re.search(r'b/(.+)$', line)
if match:
current_file = match.group(1)
last_title = ""
continue
# 只处理新增的行
if not line.startswith('+') or line.startswith('+++'):
continue
# 去掉开头的+号
content = line[1:]
# 排除weekly目录下的文件
if not current_file or current_file not in self.category_map:
continue
if current_file.startswith('weekly/'):
continue
# 检测标题行 (#### 标题 或 ### 标题 等)
title_match = re.match(r'^#{1,6}\s+(.+)$', content)
if title_match:
last_title = title_match.group(1).strip()
continue
# 1. 匹配markdown链接格式: [text](https://...)
markdown_pattern = r'\[([^\]]+)\]\((https?://[^\)]+)\)'
markdown_matches = re.findall(markdown_pattern, content)
for text, url in markdown_matches:
if 'github.com' in url:
# GitHub链接:desc留空,后续用AI生成
links_by_file[current_file].append({'url': url, 'desc': ''})
else:
# 非GitHub链接:使用markdown中的text作为desc
links_by_file[current_file].append({'url': url, 'desc': text})
# 2. 匹配纯URL格式: https://...
markdown_urls = [m[1] for m in markdown_matches]
url_pattern = r'https?://[^\s\)\]>]+'
url_matches = re.findall(url_pattern, content)
for url in url_matches:
if url not in markdown_urls:
if 'github.com' in url:
# GitHub链接:desc留空,后续用AI生成
links_by_file[current_file].append({'url': url, 'desc': ''})
else:
# 非GitHub链接:使用上一行的标题作为desc
links_by_file[current_file].append({'url': url, 'desc': last_title})
last_title = "" # 使用后清空
# 如果这行不是标题也不是链接,清空last_title
if not title_match and not url_matches and not markdown_matches:
if content.strip(): # 非空行
last_title = ""
return dict(links_by_file)
def get_weekly_commits(self, week_start: str, week_end: str) -> Dict:
"""获取指定周的提交记录"""
args = [
'log',
'--pretty=format:%H|%ad|%s',
'--date=format:%Y-%m-%d',
f'--since={week_start}',
f'--until={week_end} 23:59:59',
]
try:
result = _run_git(self.repo_path, args, check=True)
except subprocess.CalledProcessError as e:
print(f"? git log ??: {e}")
if e.stderr:
print(f" stderr: {e.stderr.strip()[:200]}")
return {'commits': []}
commits = []
for line in result.stdout.strip().split('\n'):
if not line:
continue
parts = line.split('|', 2)
if len(parts) == 3:
commits.append({
'hash': parts[0],
'date': parts[1],
'message': parts[2]
})
return {'commits': commits}
def extract_links_from_diffs(self, commits: List[Dict]) -> Dict[str, List[Dict]]:
"""从多个提交的diff中提取链接(排除weekly目录)"""
all_links = defaultdict(list)
for commit in commits:
links_by_file = self.extract_links_from_diff(commit['hash'])
for file, links in links_by_file.items():
all_links[file].extend(links)
return dict(all_links)
def generate_markdown(self, week_start: str, week_end: str, weekly_data: Dict, links_by_file: Dict[str, List[Dict]]) -> str:
"""生成周报的markdown内容"""
content = f"# 本周更新 ({week_start} ~ {week_end})\n\n"
# 去重并按分类组织链接
unique_links = {}
for file, links in links_by_file.items():
category = self.category_map.get(file, '📦 其他')
if category not in unique_links:
unique_links[category] = {}
# 使用url作为key去重,保留desc
for link in links:
url = link['url']
desc = link['desc']
if url not in unique_links[category]:
unique_links[category][url] = desc
elif not unique_links[category][url] and desc:
# 如果已有url但没有desc,更新desc
unique_links[category][url] = desc
# 按分类输出
for category in sorted(unique_links.keys()):
links_dict = unique_links[category]
if links_dict:
content += f"\n## {category}\n\n"
content += "| 项目 | 说明 |\n"
content += "|------|------|\n"
for url, desc in links_dict.items():
# 从URL提取项目名
name = url.rstrip('/').split('/')[-1]
# 如果desc是项目名本身,清空它让AI生成
if desc and desc.lower() != name.lower():
content += f"| [{name}]({url}) | {desc} |\n"
else:
content += f"| [{name}]({url}) | |\n"
# 统计信息
total_commits = len(weekly_data['commits'])
total_links = sum(len(links) for links in unique_links.values())
content += f"\n---\n\n"
content += f"**统计:** 本周共 {total_commits} 次提交,新增 {total_links} 个链接。\n"
return content
def generate_weekly_files(self, start_date: str = "2025-07-21") -> List[str]:
"""生成所有周报文件"""
print("\n" + "="*60)
print("📅 第一步:从Git历史生成周报文件")
print("="*60)
# 获取提交记录
commits = self.get_git_log(start_date)
if not commits:
print("⚠️ 未找到提交记录")
return []
# 按周分组
weeks = defaultdict(lambda: {'commits': [], 'links': defaultdict(list)})
for commit in commits:
monday, sunday = self.get_week_range(commit['date'])
week_key = f"{monday}_{sunday}"
weeks[week_key]['commits'].append(commit)
# 提取该提交的链接
links_by_file = self.extract_links_from_diff(commit['hash'])
for file, links in links_by_file.items():
weeks[week_key]['links'][file].extend(links)
# 生成周报文件
generated_files = []
for week_key in sorted(weeks.keys()):
week_data = weeks[week_key]
monday, sunday = week_key.split('_')
filename = f"weekly-{week_key}.md"
filepath = self.weekly_dir / filename
# 检查文件是否已存在
if filepath.exists():
print(f"⏭️ 跳过已存在: {filename}")
generated_files.append(filename)
continue
# 生成内容
content = f"# 本周更新 ({monday} ~ {sunday})\n\n"
# 去重链接(使用字典,url为key,desc为value)
unique_links = {}
for file, links in week_data['links'].items():
category = self.category_map.get(file, '📦 其他')
if category not in unique_links:
unique_links[category] = {}
for link in links:
url = link['url']
desc = link['desc']
if url not in unique_links[category]:
unique_links[category][url] = desc
elif not unique_links[category][url] and desc:
unique_links[category][url] = desc
# 按分类输出
for category in sorted(unique_links.keys()):
links_dict = unique_links[category]
if links_dict:
content += f"\n## {category}\n\n"
content += "| 项目 | 说明 |\n"
content += "|------|------|\n"
for url, desc in links_dict.items():
name = url.rstrip('/').split('/')[-1]
if desc and desc.lower() != name.lower():
content += f"| [{name}]({url}) | {desc} |\n"
else:
content += f"| [{name}]({url}) | |\n"
# 统计信息
total_commits = len(week_data['commits'])
total_links = sum(len(links) for links in unique_links.values())
content += f"\n---\n\n"
content += f"**统计:** 本周共 {total_commits} 次提交,新增 {total_links} 个链接。\n"
# 写入文件
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✅ 生成: {filename} ({total_links} 个链接)")
generated_files.append(filename)
print(f"\n📊 共生成 {len(generated_files)} 个周报文件")
return generated_files
class DescriptionGenerator:
"""描述生成器 - 使用AI生成项目描述"""
@dataclass(frozen=True)
class GithubFetchResult:
status: str # ok | not_found | error | invalid
content: Optional[str] = None
http_status: Optional[int] = None
error: Optional[str] = None
@dataclass(frozen=True)
class WebFetchResult:
status: str # ok | not_found | error
content: Optional[str] = None
http_status: Optional[int] = None
error: Optional[str] = None
def __init__(self, cache_dir: Path, config: Optional[Config] = None):
self.cache_dir = cache_dir
self.cache_dir.mkdir(exist_ok=True)
self.cache_file = self.cache_dir / 'descriptions_cache.json'
self.cache = self.load_cache()
self.dirty = False # 标记缓存是否被修改
self.config = config or get_config()
def load_cache(self) -> Dict:
if self.cache_file.exists():
try:
with open(self.cache_file, 'r', encoding='utf-8') as f:
return json.load(f)
except JSONDecodeError:
backup = self.cache_file.with_suffix(f".corrupt.{int(time.time())}.json")
try:
self.cache_file.rename(backup)
except OSError:
pass
logger.warning(f"缓存文件 JSON 解析失败,已备份: {backup.name}")
return {}
def save_cache(self):
"""保存缓存(只在有修改时才写入文件)"""
if not self.dirty:
return # 没有修改,跳过写入
with open(self.cache_file, 'w', encoding='utf-8') as f:
json.dump(self.cache, f, ensure_ascii=False, indent=2)
self.dirty = False
@staticmethod
def _parse_github_repo(url: str) -> Optional[Tuple[str, str]]:
try:
parsed = urlparse(url)
except Exception:
return None
if parsed.scheme.lower() != 'https':
return None
netloc = (parsed.netloc or '').lower()
if netloc != 'github.com':
return None
parts = [p for p in (parsed.path or '').split('/') if p]
if len(parts) < 2:
return None
owner = parts[0].strip()
repo = parts[1].strip()
if repo.endswith('.git'):
repo = repo[:-4]
if not owner or not repo:
return None
return owner, repo
def is_github_url(self, url: str) -> bool:
"""判断是否为GitHub URL"""
try:
parsed = urlparse(url)
return parsed.netloc.lower() == 'github.com'
except Exception:
return False
def _fetch_with_retry(self, url: str, headers: dict, timeout: int = 10) -> requests.Response:
"""带重试的HTTP请求"""
config = self.config
current_delay = config.retry_delay
for attempt in range(1, config.retry_max_attempts + 1):
try:
response = requests.get(url, headers=headers, timeout=timeout)
return response
except requests.RequestException as e:
if attempt < config.retry_max_attempts:
logger.warning(f" ⚠️ 请求失败 (第{attempt}次): {e}")
logger.info(f" ⏳ {current_delay:.1f}秒后重试...")
time.sleep(current_delay)
current_delay *= config.retry_backoff
else:
raise
def fetch_github_content(self, url: str) -> "DescriptionGenerator.GithubFetchResult":
"""获取GitHub仓库的README内容(使用raw.githubusercontent.com,无API限制)"""
repo_info = self._parse_github_repo(url)
if not repo_info:
return self.GithubFetchResult(status="invalid")
owner, repo = repo_info
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
repo_page_url = f"https://github.com/{owner}/{repo}"
try:
page_response = self._fetch_with_retry(repo_page_url, headers, timeout=10)
except requests.RequestException as e:
return self.GithubFetchResult(status="error", error=str(e))
if page_response.status_code == 404:
return self.GithubFetchResult(status="not_found", http_status=404)
description = ""
if page_response.status_code == 200:
desc_match = re.search(
r'<meta\s+property="og:description"\s+content="([^"]*)"\s*/?>',
page_response.text,
flags=re.IGNORECASE,
)
if desc_match:
description = desc_match.group(1)
readme_content = ""
readme_files = ['README.md', 'readme.md', 'README.MD', 'README', 'README.txt']
for branch in ("main", "master"):
for readme_name in readme_files:
raw_url = f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/{readme_name}"
try:
readme_response = self._fetch_with_retry(raw_url, headers, timeout=15)
except requests.RequestException:
continue
if readme_response.status_code == 200:
readme_content = readme_response.text[:3000]
break
if readme_content:
break
if readme_content or description:
content = f"Repository: {owner}/{repo}\n"
if description:
content += f"Description: {description}\n"
if readme_content:
content += f"\nREADME (excerpt):\n{readme_content}"
return self.GithubFetchResult(status="ok", content=content, http_status=page_response.status_code)
if page_response.status_code >= 400:
return self.GithubFetchResult(
status="error",
http_status=page_response.status_code,
error=(page_response.text or "")[:200],
)
return self.GithubFetchResult(status="error", http_status=page_response.status_code, error="No description/README found")
def fetch_web_content(self, url: str) -> "DescriptionGenerator.WebFetchResult":
"""获取非GitHub网页内容"""
fetcher = WebContentFetcher(self.config)
result = fetcher.fetch_web_content(url)
return self.WebFetchResult(
status=result.status,
content=result.content,
http_status=result.http_status,
error=result.error
)
def _call_ai_with_retry(self, payload: dict, headers: dict) -> requests.Response:
"""带重试的AI API请求"""
config = self.config
current_delay = config.retry_delay
for attempt in range(1, config.retry_max_attempts + 1):
try:
response = requests.post(
config.ai_api_url,
json=payload,
headers=headers,
timeout=30
)
# 如果是速率限制错误,也需要重试
if response.status_code == 429:
raise requests.RequestException(f"Rate limited: {response.status_code}")
return response
except requests.RequestException as e:
if attempt < config.retry_max_attempts:
logger.warning(f" ⚠️ AI请求失败 (第{attempt}次): {e}")
logger.info(f" ⏳ {current_delay:.1f}秒后重试...")
time.sleep(current_delay)
current_delay *= config.retry_backoff
else:
raise
def call_ai_for_summary(self, url: str, content: str) -> Optional[str]:
"""调用AI接口生成中文摘要"""
config = self.config
try:
prompt = f"""请为以下GitHub项目生成一个简洁的中文描述(15-30个汉字)。
要求:
1. 突出项目的核心功能
2. 使用专业技术术语
3. 简洁明了,便于快速理解
项目链接: {url}
项目信息:
{content}
请只返回中文描述,不要包含其他内容。"""
headers = {
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.20"
}
parsed = urlparse(config.ai_api_url)
path = (parsed.path or "").lower().rstrip("/")
is_anthropic_format = path.endswith("/v1/messages") or path.endswith("/messages")
# 根据不同的AI接口格式调整请求
if is_anthropic_format:
payload = {
"model": config.ai_model,
"max_tokens": 100,
"messages": [{"role": "user", "content": prompt}]
}
headers["anthropic-version"] = "2023-06-01"
# 优先使用 AUTH_TOKEN (OAuth),否则使用 API_KEY
if config.ai_auth_token:
headers["Authorization"] = f"Bearer {config.ai_auth_token}"
elif config.ai_api_key:
headers["x-api-key"] = config.ai_api_key
elif "ollama" in config.ai_api_url.lower():
payload = {
"model": config.ai_model,
"messages": [{"role": "user", "content": prompt}],
"stream": False
}
else:
payload = {
"model": config.ai_model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
"max_tokens": 100
}
if config.ai_auth_token:
headers["Authorization"] = f"Bearer {config.ai_auth_token}"
elif config.ai_api_key:
headers["Authorization"] = f"Bearer {config.ai_api_key}"
response = self._call_ai_with_retry(payload, headers)
if response.status_code == 200:
result = response.json()
if is_anthropic_format:
description = result.get('content', [{}])[0].get('text', '').strip()
elif "ollama" in config.ai_api_url.lower():
description = result.get('message', {}).get('content', '').strip()
else:
description = result.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
description = description.strip('"\'').strip()
return description
else:
logger.error(f" ✗ AI API 错误: HTTP {response.status_code}")
logger.debug(f" ✗ 响应内容: {response.text[:200]}")
return None
except Exception as e:
logger.error(f" ✗ AI API 异常: {e}")
return None
def is_cached(self, url: str) -> bool:
"""检查URL是否已缓存"""
return url in self.cache
def get_cached(self, url: str) -> Optional[str]:
"""获取缓存的描述"""
return self.cache.get(url)
def generate_description(self, url: str) -> Optional[str]:
"""生成单个URL的描述(带缓存)- 支持GitHub和普通网页
返回值:
- 字符串: 正常描述
- "__DELETED__": 链接404/不可用,应从文件中删除
- None: 生成失败但可以重试
"""
# 检查缓存
if url in self.cache:
return self.cache[url]
# 根据URL类型选择抓取方式
if self.is_github_url(url):
fetch_result = self.fetch_github_content(url)
else:
fetch_result = self.fetch_web_content(url)
if fetch_result.status == "not_found":
self.cache[url] = "__DELETED__"
self.dirty = True
return "__DELETED__"
if fetch_result.status != "ok" or not fetch_result.content:
return None
# 调用AI生成描述
description = self.call_ai_for_summary(url, fetch_result.content)
if description and len(description) > 5:
self.cache[url] = description
self.dirty = True # 标记缓存已修改
return description
return None
class WebContentFetcher:
"""网页内容抓取器 - 智能提取非GitHub网页的正文内容"""
@dataclass(frozen=True)
class FetchResult:
status: str # ok | not_found | error
content: Optional[str] = None
http_status: Optional[int] = None
error: Optional[str] = None
def __init__(self, config: Optional[Config] = None):
self.config = config or get_config()
# 需要移除的标签
self._remove_tags = {'script', 'style', 'nav', 'header', 'footer', 'aside', 'noscript', 'iframe'}
# 正文容器优先级
self._content_selectors = ['article', 'main', '.post-content', '.article-content', '.entry-content', '#content']