-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.py
More file actions
812 lines (691 loc) · 32.2 KB
/
main.py
File metadata and controls
812 lines (691 loc) · 32.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SecuriPaperBot - 主启动脚本
一个简化的启动入口,避免复杂的包导入问题
"""
import sys
import os
import argparse
import asyncio
import time
from pathlib import Path
from typing import Optional, Dict, Any
import logging
from paperbot.core.di.bootstrap import bootstrap_dependencies
# 解决 Windows 上 curl_cffi 的兼容性问题
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 添加当前目录和src目录到Python路径,解决导入问题
current_dir = Path(__file__).parent.absolute()
sys.path.insert(0, str(current_dir))
sys.path.insert(0, str(current_dir / "src"))
def check_python_version():
"""检查Python版本"""
if sys.version_info < (3, 8):
print(f"❌ 错误: 需要Python 3.8+,当前版本: {sys.version}")
return False
return True
def check_dependencies():
"""检查必要的依赖"""
required_packages = [
'requests', 'lxml', 'urllib3', 'aiohttp', 'bs4'
]
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"❌ 缺少必要依赖: {', '.join(missing_packages)}")
print("请运行: pip install -r requirements.txt")
return False
return True
async def _sequential_download(downloader, valid_papers):
"""顺序下载论文并显示进度"""
download_results = []
success_count = 0
cached_count = 0
start_time = time.time()
print(f"📄 开始逐个下载 {len(valid_papers)} 篇论文")
for idx, paper in enumerate(valid_papers):
paper_start_time = time.time()
try:
result = await downloader.download_paper(
paper['url'],
paper.get('title', f'paper_{idx}'),
paper_index=idx,
total_papers=len(valid_papers)
)
paper_time = time.time() - paper_start_time
if result and result.get('success'):
if result.get('cached'):
print(f"📋 缓存命中 (耗时: {paper_time:.1f}s)")
cached_count += 1
else:
size_kb = result.get('size', 0) / 1024
print(f"✅ 下载成功 (耗时: {paper_time:.1f}s, 大小: {size_kb:.1f}KB)")
success_count += 1
download_results.append(result)
else:
error_msg = result.get('error', '未知错误') if result else '下载失败'
print(f"❌ 下载失败: {error_msg}")
download_results.append(result or {'success': False})
if idx < len(valid_papers) - 1:
await asyncio.sleep(2) # 避免请求过于频繁
except Exception as e:
print(f"❌ 下载异常: {str(e)}")
download_results.append({'success': False, 'error': str(e)})
total_time = time.time() - start_time
print("\n" + "🎉 下载完成统计:")
print(f"✅ 成功下载: {success_count}/{len(download_results)} 篇论文")
print(f"📋 缓存命中: {cached_count} 篇")
print(f"⏱️ 总耗时: {total_time:.1f} 秒")
print(f"📁 文件存储在: {downloader.download_path}")
if success_count > 0:
avg_time = total_time / success_count
print(f"📊 平均速度: {avg_time:.2f} 秒/篇")
success_rate = (success_count / len(valid_papers)) if valid_papers else 0
print(f"📈 成功率: {success_rate:.1%}")
def simple_paper_download(conference: str, year: str, url: Optional[str] = None, smart_mode: bool = False):
"""
简化的论文下载功能,根据会议类型选择合适的下载器。
- CCS会议使用专用的 `downloader_ccs`。
- 其他会议使用通用的 `downloader`,并支持智能并发模式。
"""
print(f"🚀 开始下载 {conference.upper()} {year} 年论文...")
is_ccs = conference.lower() == 'ccs'
# 根据会议类型选择下载器
if is_ccs:
from paperbot.utils.downloader_ccs import PaperDownloader as DownloaderClass
print("📚 目标会议: CCS (使用专用解析逻辑)")
if smart_mode:
print("ℹ️ CCS 下载目前不支持智能模式,将使用稳定顺序模式。")
smart_mode = False # 强制为顺序模式
else:
from paperbot.agents.conference.agent import ConferenceResearchAgent
async def _run_download():
try:
agent = ConferenceResearchAgent({"download_path": f'./papers/{conference}_{year}'})
result = await agent.process(conference, year)
papers = result.get("papers", [])
print(f"✅ 找到 {len(papers)} 篇论文")
with_pdf = [p for p in papers if p.get("local_path")]
print(f"📝 下载成功 {len(with_pdf)} 篇;含代码链接 {sum(1 for p in papers if p.get('github_links'))}")
except Exception as e:
print(f"❌ 下载过程中出现严重错误: {e}")
try:
asyncio.run(_run_download())
print("✅ 下载任务完成")
except Exception as e:
print(f"❌ 异步执行失败: {e}")
print("💡 请确保您有网络访问权限和正确的会议信息。")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="SecuriPaperBot - 智能论文分析工具")
# 全局
# 添加子命令
subparsers = parser.add_subparsers(dest='command', help='可用命令')
# 下载命令(默认行为)
parser.add_argument('--conference', choices=['ccs', 'sp', 'ndss', 'usenix'],
help='会议名称')
parser.add_argument('--year', help='会议年份 (例如: 23 表示2023年)')
parser.add_argument('--url', help='机构ACM访问URL')
parser.add_argument('--check', action='store_true', help='检查环境配置')
parser.add_argument('--demo', action='store_true', help='运行演示模式')
parser.add_argument('--smart', action='store_true', help='明确启用智能并发下载模式')
parser.add_argument('--no-smart', action='store_true', help='禁用智能模式,使用传统稳定模式')
# 学者追踪命令
track_parser = subparsers.add_parser('track', help='学者追踪功能')
track_parser.add_argument('--config', type=str,
default='config/scholar_subscriptions.yaml',
help='订阅配置文件路径')
track_parser.add_argument('--scholar-id', type=str,
help='仅追踪指定学者 (Semantic Scholar ID)')
track_parser.add_argument('--force', action='store_true',
help='强制重新检测(清除缓存)')
track_parser.add_argument('--dry-run', action='store_true',
help='仅检测新论文,不生成报告')
track_parser.add_argument('--summary', action='store_true',
help='显示追踪状态摘要')
track_parser.add_argument('--dataset-path', type=str,
help='本地数据集路径(覆盖 data_source.dataset_path)')
track_parser.add_argument('--repro', action='store_true',
help='启用可复现性验证(需 Docker)')
# 运行实验(ExperimentRunner)
exp_parser = subparsers.add_parser('run-exp', help='运行实验配置 (ExperimentRunner)')
exp_parser.add_argument('--config', required=True, help='实验配置文件路径 (YAML)')
# 渲染报告(从 meta.json + 模板)
render_parser = subparsers.add_parser('render-report', help='根据 meta.json 渲染报告')
render_parser.add_argument('--meta', required=False, help='pipeline/实验生成的 meta.json 路径,缺省自动选最新')
render_parser.add_argument('--template', default=None, help='报告模板名称,默认使用 meta 或 settings 中配置')
render_parser.add_argument('--output', default=None, help='输出文件路径(可选,默认按论文ID命名写入默认目录)')
# 🆕 深度评审命令
review_parser = subparsers.add_parser('review', help='论文深度评审 (ReviewerAgent)')
review_parser.add_argument('--title', required=True, help='论文标题')
review_parser.add_argument('--abstract', required=True, help='论文摘要')
review_parser.add_argument('--output', default=None, help='输出 JSON 文件路径')
# 🆕 声明验证命令
verify_parser = subparsers.add_parser('verify', help='科学声明验证 (VerificationAgent)')
verify_parser.add_argument('--title', required=True, help='论文标题')
verify_parser.add_argument('--abstract', required=True, help='论文摘要')
verify_parser.add_argument('--num-claims', type=int, default=3, help='提取的声明数量')
verify_parser.add_argument('--output', default=None, help='输出 JSON 文件路径')
# 🆕 Paper2Code 代码生成命令
gencode_parser = subparsers.add_parser('gen-code', help='Paper2Code 代码生成 (ReproAgent)')
gencode_parser.add_argument('--title', required=True, help='论文标题')
gencode_parser.add_argument('--abstract', required=True, help='论文摘要')
gencode_parser.add_argument('--method', default=None, help='方法章节内容(可选)')
gencode_parser.add_argument('--output-dir', default='./generated_code', help='输出目录')
gencode_parser.add_argument('--use-orchestrator', action='store_true',
help='启用多 Agent 协调模式(Blueprint + CodeMemory + RAG)')
gencode_parser.add_argument('--no-rag', action='store_true',
help='禁用 CodeRAG 模式检索')
parser.add_argument('--mode', choices=['production', 'academic'], default=os.getenv("PAPERBOT_MODE", "production"),
help='运行模式 (production/academic)')
parser.add_argument('--report-template', dest='report_template', default=None,
help='覆盖报告模板名称 (如 paper_report.md.j2 / academic_report.md.j2)')
parser.add_argument('--data-source', dest='data_source', default=None,
help='数据源类型覆盖 (api/local/hybrid),local 时需配合 dataset_path/dataset_name')
parser.add_argument('--offline', action='store_true', help='离线/私有模式(优先本地数据源,禁用外部调用)')
return parser
def main():
"""主函数"""
# 设置控制台编码,防止中文乱码
import sys
import io
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# 全局时区/seed/日志
os.environ.setdefault("TZ", "UTC")
try:
time.tzset()
except Exception:
pass
seed = int(os.getenv("PAPERBOT_SEED", "42"))
try:
import random
random.seed(seed)
import numpy as np
np.random.seed(seed)
except Exception:
pass
logging.basicConfig(
level=os.getenv("PAPERBOT_LOG_LEVEL", "INFO"),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
bootstrap_dependencies()
print("=" * 60)
print("🔐 SecuriPaperBot - 智能论文分析框架")
print("=" * 60)
# 检查环境
if not check_python_version():
sys.exit(1)
parser = build_parser()
args = parser.parse_args()
if args.check:
print("🔍 检查环境配置...")
deps_ok = check_dependencies()
if deps_ok:
print("✅ 环境检查通过")
else:
print("❌ 环境检查失败")
return
if args.demo:
print("🎯 运行演示模式...")
print("📋 支持的功能:")
print(" - ACM CCS 论文下载")
print(" - IEEE S&P 论文下载")
print(" - NDSS 论文下载")
print(" - USENIX Security 论文下载")
print(" - 论文代码链接提取")
print(" - 代码质量分析")
print(" - 文档生成")
print("💡 所有功能完全可用!")
return
if not check_dependencies():
print("\n📦 安装依赖:")
print("pip install requests lxml urllib3 aiohttp beautifulsoup4 pdfplumber")
sys.exit(1)
# 处理学者追踪命令
if args.command == 'track':
run_scholar_tracking(args)
return
# 处理实验命令
if args.command == 'run-exp':
run_experiment(args)
return
# 渲染报告
if args.command == 'render-report':
render_report(args)
return
# 🆕 深度评审
if args.command == 'review':
run_review(args)
return
# 🆕 声明验证
if args.command == 'verify':
run_verify(args)
return
# 🆕 Paper2Code 代码生成
if args.command == 'gen-code':
run_gencode(args)
return
if args.conference and args.year:
# 所有会议使用相同的下载逻辑
if args.no_smart:
smart_mode = False # 明确禁用智能模式
elif args.smart:
smart_mode = True # 明确启用智能模式
else:
smart_mode = True # 默认启用智能模式
mode_desc = "智能加速模式" if smart_mode else "传统稳定模式"
print(f"🚀 开始下载 {args.conference.upper()} {args.year} 论文 ({mode_desc})...")
simple_paper_download(args.conference, args.year, args.url, smart_mode)
else:
print("📝 使用帮助:")
print(" 检查环境: python main.py --check")
print(" 查看演示: python main.py --demo")
print(" 下载论文 (默认智能模式):")
print(" CCS: python main.py --conference ccs --year 23")
print(" S&P: python main.py --conference sp --year 23")
print(" NDSS: python main.py --conference ndss --year 23")
print(" USENIX: python main.py --conference usenix --year 23")
print(" 关闭智能模式 (传统稳定模式):")
print(" python main.py --conference ndss --year 23 --no-smart")
print(" 学者追踪:")
print(" python main.py track --summary")
print(" python main.py track")
print(" python main.py track --scholar-id 1741101")
print(" python main.py track --force")
print(" 查看帮助: python main.py --help")
print("💡 注意: 所有会议都使用相同的下载方式,支持不同年份")
print("🤖 智能模式默认启用,提供更快的下载速度和进度显示")
def run_experiment(args):
"""运行 ExperimentRunner 实验"""
from paperbot.utils.experiment_runner import ExperimentRunner
cfg_path = Path(args.config).expanduser()
if not cfg_path.is_absolute():
cfg_path = current_dir / cfg_path
cfg_path = cfg_path.resolve()
if not cfg_path.exists():
print(f"❌ 找不到实验配置文件: {cfg_path}")
return
print(f"🧪 运行实验: {cfg_path}")
runner = ExperimentRunner(str(cfg_path))
runner.run()
print("✅ 实验完成,结果已写入 output/experiments")
def render_report(args):
"""根据 meta.json 渲染报告(paper/academic 模板兼容)"""
import json
from config.settings import settings
from paperbot.presentation.reports.writer import ReportWriter
from paperbot.domain.paper import PaperMeta
from paperbot.domain.influence.result import InfluenceResult
from pathlib import Path
import glob
meta_path = None
if args.meta:
candidate = Path(args.meta).expanduser()
if not candidate.is_absolute():
candidate = current_dir / candidate
if candidate.exists():
meta_path = candidate.resolve()
else:
# 自动发现 output/experiments 下最新 *_meta.json
pattern = current_dir / "output" / "experiments" / "*_meta.json"
metas = glob.glob(str(pattern))
if metas:
metas.sort(key=lambda p: Path(p).stat().st_mtime, reverse=True)
meta_path = Path(metas[0]).resolve()
if not meta_path or not meta_path.exists():
print("❌ 找不到 meta 文件,请使用 --meta 指定或确保 output/experiments 下存在 *_meta.json")
return
try:
meta = json.loads(meta_path.read_text(encoding="utf-8"))
except Exception as e:
print(f"❌ 读取 meta 失败: {e}")
return
# 兼容不同字段命名
paper_dict = meta.get("paper") or meta.get("paper_meta") or {}
influence_dict = meta.get("influence") or meta.get("influence_result") or meta.get("results_summary", [{}])[0].get("influence", {})
research = meta.get("research") or meta.get("research_result") or {}
code_analysis = meta.get("code_analysis") or meta.get("code_analysis_result") or {}
quality = meta.get("quality") or meta.get("quality_result") or {}
scholar_name = meta.get("scholar_name") or meta.get("scholar") or None
try:
paper = PaperMeta.from_dict(paper_dict)
except Exception as e:
print(f"❌ 构造 PaperMeta 失败: {e}")
return
if not influence_dict:
# 最小兜底,避免模板崩溃
influence_dict = {
"total_score": 0.0,
"academic_score": 0.0,
"engineering_score": 0.0,
"explanation": "No influence data provided.",
"metrics_breakdown": {},
"recommendation": "低优先级",
}
influence = InfluenceResult.from_dict(influence_dict)
template_name = (
args.template
or meta.get("template")
or settings.report.get("template", "paper_report.md.j2")
)
writer = ReportWriter(template_name=template_name)
md = writer.render_template(
paper=paper,
influence=influence,
research_result=research,
code_analysis_result=code_analysis,
quality_result=quality,
scholar_name=scholar_name,
)
# 追加复现信息(若 meta 提供)
reproducibility_lines = []
if meta.get("git_commit") or meta.get("pip_freeze"):
reproducibility_lines.append("\n\n---\n## 复现信息")
if meta.get("git_commit"):
reproducibility_lines.append(f"- Git Commit: `{meta['git_commit']}`")
if meta.get("pip_freeze"):
reproducibility_lines.append("- 环境依赖(截断展示):")
for line in meta["pip_freeze"][:20]:
reproducibility_lines.append(f" - {line}")
if reproducibility_lines:
md += "\n".join(reproducibility_lines)
if args.output:
out_path = Path(args.output).expanduser()
if not out_path.is_absolute():
out_path = current_dir / out_path
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(md, encoding="utf-8")
print(f"✅ 报告已写入: {out_path}")
else:
path = writer.write_report(md, paper, scholar_name=scholar_name)
print(f"✅ 报告已写入: {path}")
def run_scholar_tracking(args):
"""运行学者追踪功能"""
print("=" * 60)
print("📚 PaperBot 学者追踪系统")
print("=" * 60)
config_path = Path(args.config).expanduser()
if not config_path.is_absolute():
config_path = current_dir / config_path
config_path = config_path.resolve()
if not config_path.exists():
print(f"❌ 找不到订阅配置文件: {config_path}")
return
async def _run_tracking():
from paperbot.agents.scholar_tracking.paper_tracker_agent import PaperTrackerAgent
from paperbot.agents.scholar_tracking.scholar_profile_agent import ScholarProfileAgent
from paperbot.domain.paper import PaperMeta
from paperbot.application.workflows.scholar_pipeline import ScholarPipeline
from config.settings import settings
from paperbot.repro import ReproAgent
import tempfile, shutil
from git.repo import Repo as GitRepo
from paperbot.infrastructure.event_log.logging_event_log import LoggingEventLog
from paperbot.infrastructure.event_log.composite_event_log import CompositeEventLog
from paperbot.infrastructure.event_log.sqlalchemy_event_log import SqlAlchemyEventLog
from paperbot.application.collaboration.message_schema import new_run_id, new_trace_id
overrides: Dict[str, Any] = {"subscriptions_config_path": str(config_path)}
mode = getattr(args, "mode", None) or getattr(settings, "mode", "production")
overrides["mode"] = mode
overrides["offline"] = args.offline or getattr(settings, "offline", False)
if args.report_template:
overrides["report_template"] = args.report_template
elif mode == "academic":
overrides["report_template"] = "academic_report.md.j2"
if args.data_source:
overrides["data_source"] = {**settings.data_source, "type": args.data_source}
if getattr(args, "dataset_path", None):
ds = overrides.get("data_source", settings.data_source.copy())
ds["dataset_path"] = args.dataset_path
overrides["data_source"] = ds
profile_agent = ScholarProfileAgent(overrides)
# 显示摘要
if args.summary:
print("\n📊 追踪状态摘要:")
print(profile_agent.summary())
return
settings = profile_agent.get_settings()
reporting_cfg = settings.get("reporting", {})
min_score = settings.get("min_influence_score", 0)
tracker_agent = PaperTrackerAgent({**overrides, "api": settings.get("api", {}), "data_source": settings.get("data_source", {})})
pipeline = ScholarPipeline(
{
"output_dir": str(profile_agent.get_output_dir()),
"report_template": reporting_cfg.get(
"template", overrides.get("report_template", "paper_report.md.j2")
),
"use_documentation_agent": False, # 禁用 DocumentationAgent 以避免接口不匹配
"mode": mode,
}
)
# Phase-0: event log + run id for end-to-end traceability
try:
event_log = CompositeEventLog([LoggingEventLog(), SqlAlchemyEventLog()])
except Exception:
event_log = LoggingEventLog()
session_run_id = new_run_id()
# 强制模式
if args.force and args.scholar_id:
print(f"\n🔄 强制重新检测学者: {args.scholar_id}")
profile_agent.clear_scholar_cache(args.scholar_id)
elif args.force:
print("\n🔄 清除所有缓存...")
profile_agent.clear_all_cache()
# 追踪学者
if args.scholar_id:
scholar = profile_agent.get_scholar_by_id(args.scholar_id)
if not scholar:
print(f"❌ 未找到学者: {args.scholar_id}")
return
result = await tracker_agent.track_scholar(scholar, dry_run=args.dry_run)
results = [result]
await tracker_agent.ss_agent.close()
else:
print("\n🔍 开始追踪所有订阅学者...")
results = await tracker_agent.track_all_scholars(dry_run=args.dry_run)
# 显示结果
total_new = 0
for result in results:
scholar_name = result.get("scholar_name", "Unknown")
new_count = result.get("new_papers_count", len(result.get("new_papers", [])))
status = result.get("status", "unknown")
if status == "success":
print(f" ✅ {scholar_name}: 发现 {new_count} 篇新论文")
total_new += new_count
elif status == "error":
print(f" ❌ {scholar_name}: {result.get('error', '未知错误')}")
else:
print(f" ⚠️ {scholar_name}: {status}")
print(f"\n📈 总计发现 {total_new} 篇新论文")
if total_new == 0:
print("\n✅ 学者追踪完成!")
return
persist_reports = not args.dry_run
if args.dry_run:
print("\n🧪 Dry-Run 模式:将运行分析但不写入 Markdown 文件。")
else:
print("\n📝 生成分析报告...")
for result in results:
if result.get("status") != "success":
continue
scholar_name = result.get("scholar_name")
new_papers = result.get("new_papers", [])
if not new_papers:
continue
print(f"\n 处理 {scholar_name} 的 {len(new_papers)} 篇论文...")
papers = [PaperMeta.from_dict(p) for p in new_papers]
processed_records = []
for paper in papers:
try:
report_path, influence, pipeline_data = await pipeline.analyze_paper(
paper,
scholar_name,
persist_report=persist_reports,
event_log=event_log,
run_id=session_run_id,
trace_id=new_trace_id(),
)
pis = f"{influence.total_score:.1f}/100 ({influence.recommendation.value})"
if report_path:
print(f" 📄 {paper.title[:40]}... -> {report_path.name} | PIS {pis}")
else:
print(f" 📄 {paper.title[:40]}... -> (未持久化) | PIS {pis}")
# 可复现性验证(需 repo)
repro_result = {}
if args.repro and (paper.github_url or paper.has_code):
tmp_dir = Path(tempfile.mkdtemp(prefix="paperbot-repro-"))
try:
repo_url = paper.github_url
if repo_url:
print(f" 🔁 Repro: cloning {repo_url}")
GitRepo.clone_from(repo_url, tmp_dir)
repro_agent = ReproAgent({"repro": settings.get("repro", {})})
repro_result = await repro_agent.run(tmp_dir)
else:
repro_result = {"status": "skipped", "reason": "no_repo"}
except Exception as e:
repro_result = {"status": "error", "error": str(e)}
print(f" ⚠️ Repro 失败: {e}")
finally:
try:
shutil.rmtree(tmp_dir)
except Exception:
pass
# 重新渲染报告,写回
try:
if pipeline.report_writer is not None:
md = pipeline.report_writer.render_template(
paper=paper,
influence=influence,
research_result=pipeline_data.get("stages", {}).get("research", {}).get("result", {}),
code_analysis_result=pipeline_data.get("stages", {}).get("code_analysis", {}).get("result", {}),
quality_result=pipeline_data.get("stages", {}).get("quality", {}).get("result", {}),
scholar_name=scholar_name,
repro_result=repro_result,
meta=None,
)
path = pipeline.report_writer.write_report(md, paper, scholar_name)
pipeline_data["report_path"] = str(path)
except Exception as e:
print(f" ⚠️ 重渲染报告失败: {e}")
processed_records.append(
{
"paper_id": paper.paper_id,
"title": paper.title,
"report_path": str(report_path) if report_path else None,
"pis": round(influence.total_score, 2),
"recommendation": influence.recommendation.value,
"status": pipeline_data.get("status", "success"),
}
)
except Exception as e:
print(f" ❌ 处理失败: {paper.title[:40]}... - {e}")
processed_records.append(
{
"paper_id": paper.paper_id,
"title": paper.title,
"status": f"failed: {e}",
}
)
scholar_id = result.get("scholar_id")
if (
processed_records
and scholar_id
and reporting_cfg.get("persist_history", True)
):
profile_agent.record_processed_papers(
scholar_id,
processed_records,
)
print("\n✅ 学者追踪完成!")
try:
asyncio.run(_run_tracking())
except KeyboardInterrupt:
print("\n⚠️ 用户中断")
except Exception as e:
print(f"\n❌ 追踪过程出错: {e}")
import traceback
traceback.print_exc()
def run_review(args):
"""运行论文深度评审 (ReviewerAgent)"""
import json
from paperbot.agents.review.agent import ReviewerAgent
print("📝 论文深度评审...")
print(f" 标题: {args.title}")
async def _run():
agent = ReviewerAgent({})
result = await agent.process(
title=args.title,
abstract=args.abstract
)
return result
result = asyncio.run(_run())
if args.output:
Path(args.output).write_text(json.dumps(result, indent=2, ensure_ascii=False))
print(f"✅ 评审结果已保存: {args.output}")
else:
print("\n📋 评审结果:")
print(json.dumps(result, indent=2, ensure_ascii=False))
def run_verify(args):
"""运行科学声明验证 (VerificationAgent)"""
import json
from paperbot.agents.verification.agent import VerificationAgent
print("🔍 科学声明验证...")
print(f" 标题: {args.title}")
async def _run():
agent = VerificationAgent({})
result = await agent.process(
title=args.title,
abstract=args.abstract,
num_claims=args.num_claims
)
return result
result = asyncio.run(_run())
if args.output:
Path(args.output).write_text(json.dumps(result, indent=2, ensure_ascii=False))
print(f"✅ 验证结果已保存: {args.output}")
else:
print("\n📋 验证结果:")
print(json.dumps(result, indent=2, ensure_ascii=False))
def run_gencode(args):
"""运行 Paper2Code 代码生成 (ReproAgent)"""
from paperbot.repro import ReproAgent, PaperContext
print("🔧 Paper2Code 代码生成...")
print(f" 标题: {args.title}")
# 显示模式信息
if args.use_orchestrator:
print(" 模式: 多 Agent 协调模式 (Blueprint + CodeMemory + RAG)")
else:
print(" 模式: Legacy 节点流水线模式")
if args.no_rag:
print(" RAG: 已禁用")
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
ctx = PaperContext(
title=args.title,
abstract=args.abstract,
method_section=args.method or ""
)
async def _run():
config = {
"use_orchestrator": args.use_orchestrator,
"use_rag": not args.no_rag,
}
agent = ReproAgent(config)
result = await agent.reproduce_from_paper(ctx, output_dir=output_dir)
return result
result = asyncio.run(_run())
print(f"\n📦 生成结果:")
print(f" 状态: {result.status}")
print(f" 生成文件: {list(result.generated_files.keys())}")
print(f" 重试次数: {result.retry_count}")
print(f" 输出目录: {output_dir}")
if __name__ == "__main__":
main()