Skip to content
Back to search

dailypaper-skills

用Agent skills打造我的论文流水线

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/huangkiki--dailypaper-skills/badge.svg)](/listings/huangkiki--dailypaper-skills)

HTML

<a href="/listings/huangkiki--dailypaper-skills"><img src="/api/listings/huangkiki--dailypaper-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 168 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # dailypaper-skills 🗞️
  2. **简体中文** | [English](README.en.md)
  3. **每天一句话,筛论文、看锐评,把值得读的研究变成自己的笔记。**
  4. 这是我自己平时追论文、读论文用的一套 Agent skills。从 HuggingFace 和 arXiv 找新论文,按研究兴趣挑重点,再把重点论文读完,整理成带公式、图表和概念链接的 Markdown 笔记。
  5. ```text
  6. 今日论文推荐
  7. ```
  8. 一次跑完 **抓取 → 筛选 → 点评 → 重点论文笔记**。也可以直接丢一个 arXiv 链接,自动精读并保存到已配置的 Obsidian / Markdown 笔记库。
  9. [🎬 看演示](#-先看效果) · [🧭 常用指令](#-平时怎么用) · [🚀 开始使用](#-开始使用) · [📖 详细指南](docs/usage.md)
  10. ## 🎬 先看效果
  11. > ### [▶ 用 Claude Code 打造我的论文流水线|小红书视频](http://xhslink.com/o/1dhQCn40EWY)
  12. >
  13. > 我录的一段实际使用演示。想先看看这套东西怎么用,可以从这里开始。
  14. >
  15. > 视频展示的是早期 Claude Code 工作流;当前版本也提供 Codex、Cursor 等 Agent 的安装入口,安装方法以下文为准。
  16. 跑完后,你会拿到三类相互链接的内容:
  17. | 产物 | 你可以用它做什么 |
  18. | --- | --- |
  19. | 🗞️ **每日推荐页** | 先看“必读 / 值得看 / 可跳过”,决定今天读哪几篇;默认每天最多推荐 10 篇 |
  20. | 📝 **重点论文笔记** | 跟着研究问题、方法、公式、图表、实验和局限读懂一篇论文 |
  21. | 🔗 **概念笔记与目录** | 遇到术语顺着链接查,读到相关方法时找到以前的积累 |
  22. **点评是这套 skills 的一个重点。** 每篇都要说清楚:做了什么、和你的研究有什么关系、哪个设计值得借鉴、哪些结论还需要追问。可以尖锐,但要给出依据;摘要里没说的内容,会标明需要全文确认。
  23. 推荐页链接到重点论文,论文再链接到 `[[概念]]`。以下是默认目录下的产物结构示意,文件名和分类会随实际内容变化:
  24. ```text
  25. 你的笔记目录/
  26. ├── DailyPapers/
  27. │ └── YYYY-MM-DD-论文推荐.md ← 今日锐评、阅读优先级、逐篇点评
  28. └── 论文笔记/
  29. ├── 具体分类/MethodName.md ← 方法、公式、图表、实验与局限
  30. └── _概念/主题/Concept.md ← 定义、相关方法、关联论文
  31. ```
  32. [查看完整论文笔记模板](obsidian-templates/论文笔记模板.md)。用 Obsidian 浏览双向链接很方便,也可以用普通 Markdown 编辑器或项目自带的 [Web Viewer](docs/usage.md#可选在浏览器里看笔记)。
  33. ## 🧭 平时怎么用
  34. 装好后,在 Agent 对话里说你想做什么:
  35. | 场景 | 直接这样说 |
  36. | --- | --- |
  37. | 今天有哪些论文值得看 | `今日论文推荐` |
  38. | 几天没跟进,补一下 | `过去3天论文推荐` / `过去一周论文推荐` |
  39. | 发链接就精读并保存 | `https://arxiv.org/abs/2509.24527` |
  40. | 精读指定论文 | `读一下这篇论文 <arXiv 链接或 PDF 路径>` |
  41. | 按标题或上下文读论文 | `读一下 Diffusion Policy` / `帮我读这篇` |
  42. | 先抓住核心贡献 | `快速看一下这篇论文 <PDF 路径>` |
  43. | 带着问题看方法 | `批判性分析这篇论文 <PDF 路径>` |
  44. | 读已有收藏 | `读一下 Zotero 里的 Diffusion Policy` |
  45. | 看开源项目进展 | `GitHub 周榜` |
  46. | 移动笔记后刷新导航 | `更新索引` |
  47. **读论文默认就保存笔记。** 单独发送 arXiv 的 `/abs/`、`/pdf/` 或 `/html/` 链接,或说“读一下 XXX”“读一下这篇”“帮我读”,都会获取全文、完整解析并写入已配置的笔记库;保存成功后返回实际笔记路径,不再询问是否保存。快速摘要、批判分析和公式提取保留你要求的阅读深度,也默认保存相应笔记。明确说“只在聊天里回答”“不要保存”或指定其他输出位置时,以你的要求为准。论文身份不明确或保存路径配置缺失时,只补问具体缺项;作为其他任务引用的链接不会自动触发阅读。
  48. **单篇精读,锐评放最前。** 笔记标题后先给完整锐评,再展开元信息、摘要、方法和实验;聊天答复也先给判断。锐评覆盖真正的新意、最强证据、关键缺口或适用边界,以及值不值得读和复现。评价有来源,不为尖锐编造缺陷;快速摘要、公式提取或明确“只总结、不评价”仍按你的要求执行。
  49. **研究方向由你设置。** 默认关注大模型 RL、RL infra、世界模型 / JEPA、灵巧手与物理仿真;可以改成你自己的方向。推荐会结合历史去重,相关论文不足时不凑数。“必读”继续生成完整笔记,已有笔记会匹配并链接。
  50. **中英文跟随你的提问。** `Recommend papers from the past week` 会生成英文推荐和笔记;也可以明确说“用英文输出”或 “write in Chinese”。切换语言不会重命名已有目录和笔记。[语言说明](docs/usage.md#中英文自动切换)
  51. ## 🚀 开始使用
  52. 需要一个能读写文件、执行命令和联网的 Agent,以及 **Python 3.10+、Git、curl**。精读 PDF 需要 **Poppler**;Obsidian、Zotero 按需使用。[环境准备](docs/usage.md#1-准备运行环境)
  53. ### 1. 安装完整技能包
  54. ```bash
  55. git clone https://github.com/huangkiki/dailypaper-skills.git
  56. cd dailypaper-skills
  57. python3 install.py --agent codex
  58. ```
  59. 把 `codex` 换成你使用的 Agent:`claude`、`cursor`、`copilot`、`gemini`、`opencode` 或 `openclaw`。Windows 可将 `python3` 换成 `py -3`。安装器会一起复制七个技能及共享依赖。
  60. ### 2. 告诉它你的研究方向和保存位置
  61. 先创建个人配置,已有配置不会被覆盖:
  62. ```bash
  63. python3 skills/_shared/user_config.py --init
  64. ```
  65. 刷新或重启 Agent 会话,然后在对话中输入,替换成自己的目录和方向:
  66. ```text
  67. 帮我配置 dailypaper-skills,使用跨 Agent 的共享配置。
  68. 把 Markdown 保存到 /path/to/my-research-notes。
  69. 我关注 robot learning、VLA、世界模型和物理仿真。
  70. 每天最多推荐 10 篇。
  71. ```
  72. **默认无需额外 API key。** 筛选、点评和精读使用当前 Agent 的模型额度。输出目录可以是普通文件夹,也可以是你指定的 Obsidian 库。
  73. ### 3. 开始第一次推荐
  74. ```text
  75. 今日论文推荐
  76. ```
  77. Agent 会完成筛选、点评和重点论文笔记,并告诉你产物位置。想从一篇论文试起,直接发送 arXiv 链接或 `读一下这篇论文 <链接或 PDF 路径>`,读完会自动保存笔记。
  78. 升级、多 Agent 安装、自定义目录和排错见 [使用指南](docs/usage.md)。
  79. ## 🧩 里面有哪些 Skills
  80. 日常用 `daily-papers` 追新论文,用 `paper-reader` 读指定论文。抓取、点评和笔记三个阶段会自动衔接,需要补跑时也能单独调用。
  81. | Skill | 负责什么 |
  82. | --- | --- |
  83. | [`daily-papers`](skills/daily-papers/SKILL.md) | 一句话启动完整每日论文流程 |
  84. | [`paper-reader`](skills/paper-reader/SKILL.md) | arXiv 链接或阅读请求直接读并保存;支持精读、快速摘要、批判分析、本地 PDF、Zotero |
  85. | [`daily-papers-fetch`](skills/daily-papers-fetch/SKILL.md) | 从 HuggingFace Daily / Trending 与 arXiv 抓取、筛选、富化 |
  86. | [`daily-papers-review`](skills/daily-papers-review/SKILL.md) | 生成锐评、阅读优先级和推荐页 |
  87. | [`daily-papers-notes`](skills/daily-papers-notes/SKILL.md) | 重点笔记、概念补充、链接回填 |
  88. | [`generate-mocs`](skills/generate-mocs/SKILL.md) | 更新论文和概念的目录页 |
  89. | [`github-trending`](skills/github-trending/SKILL.md) | 开源项目日榜 / 周榜 / 月榜,以及仿真主题检索 |
  90. 我也会搭配 [Zotero AI Sidebar](https://github.com/huangkiki/zotero-ai-sidebar):用这套 skills 筛选和积累笔记,在 Zotero 里打开 PDF 时,用 Sidebar 即时问答、点译和追问。
  91. ## 💬 使用前你可能想知道
  92. **必须用 Obsidian 吗?** 不需要,指定一个本地 Markdown 输出目录即可。Zotero 也只在读取自己的文献库时需要。
  93. **会每天自动运行、自动上传笔记吗?** 默认由你发起,安装不会创建定时任务;阅读请求默认保存到本地笔记库,Git 自动提交、推送的配置默认关闭。Git 同步遵循有效配置和你已有的长期或当次授权,已有授权不重复询问。定时运行用宿主或系统调度。
  94. **这些 Agent 都能完整跑通吗?** 安装器提供多个目标,但完整流程需要文件、命令和网络能力。安装与脚本测试通过,不代表所有客户端都完成了端到端实测。[兼容与验证范围](docs/agents.md)
  95. **能换论文筛选方式吗?** 默认 `agent` 使用当前 Agent 评分,也可选 `keyword` 关键词筛选或 `jev` 专用 API;只有 Jev 需要额外的 `TYPESAFE_API_KEY`。[配置与旧版本迁移](docs/usage.md#3-配置并开始使用)
  96. <details>
  97. <summary>⚡ 可选 Jev:历史评分费用与耗时对照</summary>
  98. <!-- JEV_BENCHMARK_START -->
  99. 2026-10-05 的一次对照中,同一批 30 篇候选、两组均选 10 篇:GPT-6 Astra 评分约 **$0.109264 / 10.35 秒**,Jev 1.13.0 约 **$0.000576408 / 0.52 秒**,入选重合 **9/10**。按当时标准 API 标价折算,评分费用降低 **99.47%**,调用约快 **20 倍**。
  100. 这是计入主模型缓存的**单次评分环节测量**,不代表整个阅读流程的费用或账户实际账单;重合率也不等于人工质量评价。[原始证据与复现方法](docs/jev-benchmark.md)
  101. <!-- JEV_BENCHMARK_END -->
  102. </details>
  103. ## 🛠️ 开发与贡献
  104. [架构说明](ARCHITECTURE.md) · [Agent 接入](docs/agents.md) · [使用指南](docs/usage.md)
  105. ```bash
  106. python3 -m pip install -r web-viewer/requirements.txt
  107. python3 -m unittest discover -s tests -v
  108. ```
  109. 欢迎分享用法、适配反馈,或提交 Issue / PR。反馈问题时请附 Agent 与系统版本、失败阶段,以及去除敏感信息的日志。
  110. [![Star History Chart](https://star-history.dera.page/svg?repos=huangkiki/dailypaper-skills&type=Date)](https://star-history.dera.page/#huangkiki/dailypaper-skills&Date)
  111. ## 📄 License
  112. Apache-2.0. See [LICENSE](LICENSE).
skills/paper-reader/paper_daemon.py · Bundled script · 788 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Paper Reading Daemon - 后台论文阅读守护进程
  4. 功能:
  5. 1. 从 Zotero 获取指定分类的论文列表(递归子分类)
  6. 2. 调用 Claude Code 逐篇处理
  7. 3. 遇到 rate limit 时自动等待并重试
  8. 4. 支持断点续传
  9. 用法:
  10. # 启动守护进程处理 VLA 分类
  11. screen -S paper-daemon
  12. python3 paper_daemon.py -c "VLA"
  13. # 查看进度
  14. python3 paper_daemon.py --status
  15. """
  16. import os
  17. import sys
  18. import json
  19. import sqlite3
  20. import subprocess
  21. import shutil
  22. import time
  23. import argparse
  24. import logging
  25. import re
  26. from pathlib import Path
  27. from datetime import datetime, timedelta
  28. from typing import Optional
  29. from zoneinfo import ZoneInfo
  30. _SHARED_DIR = Path(__file__).resolve().parents[1] / "_shared"
  31. if str(_SHARED_DIR) not in sys.path:
  32. sys.path.insert(0, str(_SHARED_DIR))
  33. from user_config import concepts_dir, obsidian_vault_path, paper_notes_dir, zotero_db_path, zotero_storage_dir, temp_file_path
  34. # 配置
  35. ZOTERO_DB = str(zotero_db_path())
  36. ZOTERO_STORAGE = str(zotero_storage_dir())
  37. OBSIDIAN_VAULT = str(obsidian_vault_path())
  38. PAPER_NOTES_ROOT = str(paper_notes_dir())
  39. CONCEPTS_ROOT = str(concepts_dir())
  40. _DAEMON_STATE_DIR = os.path.expanduser(os.environ.get("PAPER_DAEMON_STATE_DIR", "~/.claude"))
  41. PROGRESS_FILE = os.path.join(_DAEMON_STATE_DIR, "paper_daemon_progress.json")
  42. LOG_FILE = os.path.join(_DAEMON_STATE_DIR, "paper_daemon.log")
  43. PID_FILE = os.path.join(_DAEMON_STATE_DIR, "paper_daemon.pid")
  44. # Rate limit 配置
  45. INITIAL_WAIT = 60 # 初始等待时间(秒)
  46. MAX_WAIT = 21600 # 最大等待时间(6小时)
  47. WAIT_MULTIPLIER = 2 # 等待时间倍数
  48. BETWEEN_PAPERS_WAIT = 5 # 论文之间的等待时间(秒)
  49. QUOTA_WAIT_TIME = 1800 # 命中配额上限时的默认等待时间(30分钟)
  50. # 设置日志
  51. os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
  52. logging.basicConfig(
  53. level=logging.INFO,
  54. format='%(asctime)s [%(levelname)s] %(message)s',
  55. handlers=[
  56. logging.FileHandler(LOG_FILE),
  57. logging.StreamHandler()
  58. ]
  59. )
  60. logger = logging.getLogger(__name__)
  61. _SUBSCRIPT_TRANSLATION = str.maketrans("₀₁₂₃₄₅₆₇₈₉₊₋", "0123456789+-")
  62. _GREEK_REPLACEMENTS = {
  63. "π": "pi",
  64. "ϕ": "phi",
  65. "φ": "phi",
  66. "α": "alpha",
  67. "β": "beta",
  68. "γ": "gamma",
  69. }
  70. def acquire_lock() -> bool:
  71. """获取进程锁,防止重复运行"""
  72. if os.path.exists(PID_FILE):
  73. with open(PID_FILE, 'r') as f:
  74. old_pid = f.read().strip()
  75. # 检查进程是否还在运行
  76. try:
  77. os.kill(int(old_pid), 0)
  78. return False # 进程还在运行
  79. except (OSError, ValueError):
  80. pass # 进程已结束,可以继续
  81. # 写入当前 PID
  82. with open(PID_FILE, 'w') as f:
  83. f.write(str(os.getpid()))
  84. return True
  85. def release_lock():
  86. """释放进程锁"""
  87. if os.path.exists(PID_FILE):
  88. os.remove(PID_FILE)
  89. def wait_for_quota_reset(wait_seconds: Optional[int] = None):
  90. """等待配额重置或人工恢复后再继续。"""
  91. if wait_seconds is None:
  92. wait_seconds = QUOTA_WAIT_TIME
  93. wait_minutes = max(1, wait_seconds // 60)
  94. logger.info(f"⏳ 配额受限,等待 {wait_minutes} 分钟...")
  95. time.sleep(wait_seconds)
  96. def detect_limit_error(output: str) -> Optional[str]:
  97. """识别限额/限速错误类型"""
  98. text = output.lower()
  99. if 'rate limit' in text or 'too many requests' in text:
  100. return 'RATE_LIMIT'
  101. if 'hit your limit' in text or 'usage limit' in text or 'resets' in text:
  102. return 'QUOTA_LIMIT'
  103. return None
  104. def parse_reset_wait_seconds(message: str) -> Optional[int]:
  105. """
  106. 解析 "resets 9pm (Asia/Shanghai)" 等提示,计算等待秒数
  107. """
  108. match = re.search(
  109. r'resets\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?',
  110. message,
  111. re.IGNORECASE
  112. )
  113. if not match:
  114. return None
  115. hour = int(match.group(1))
  116. minute = int(match.group(2) or 0)
  117. ampm = (match.group(3) or '').lower()
  118. tz_name = match.group(4) or 'Asia/Shanghai'
  119. if ampm == 'pm' and hour < 12:
  120. hour += 12
  121. if ampm == 'am' and hour == 12:
  122. hour = 0
  123. try:
  124. tz = ZoneInfo(tz_name)
  125. except Exception:
  126. return None
  127. now = datetime.now(tz)
  128. target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
  129. if target <= now:
  130. target = target + timedelta(days=1)
  131. wait_seconds = int((target - now).total_seconds())
  132. return max(60, wait_seconds)
  133. def copy_zotero_db() -> str:
  134. """复制 Zotero 数据库以避免锁定"""
  135. tmp_db = str(temp_file_path("zotero_readonly.sqlite"))
  136. shutil.copy(ZOTERO_DB, tmp_db)
  137. return tmp_db
  138. def get_collection_id_and_path(db_path: str, collection_name: str) -> tuple[Optional[int], Optional[str]]:
  139. """根据分类名称获取 ID 和完整路径"""
  140. conn = sqlite3.connect(db_path)
  141. cursor = conn.cursor()
  142. cursor.execute("SELECT collectionID, collectionName, parentCollectionID FROM collections")
  143. collections = {row[0]: {'name': row[1], 'parent': row[2]} for row in cursor.fetchall()}
  144. def get_path(cid):
  145. path_parts = []
  146. current = cid
  147. while current:
  148. if current in collections:
  149. path_parts.insert(0, collections[current]['name'])
  150. current = collections[current]['parent']
  151. else:
  152. break
  153. return '/'.join(path_parts)
  154. for cid, info in collections.items():
  155. if info['name'].lower() == collection_name.lower():
  156. conn.close()
  157. return cid, get_path(cid)
  158. if collection_name.lower() in info['name'].lower():
  159. conn.close()
  160. return cid, get_path(cid)
  161. conn.close()
  162. return None, None
  163. def get_all_child_collections(db_path: str, collection_id: int) -> list[int]:
  164. """递归获取所有子分类ID(包含自身)"""
  165. conn = sqlite3.connect(db_path)
  166. cursor = conn.cursor()
  167. cursor.execute("SELECT collectionID, parentCollectionID FROM collections")
  168. all_collections = cursor.fetchall()
  169. conn.close()
  170. children_map = {}
  171. for cid, parent_id in all_collections:
  172. if parent_id not in children_map:
  173. children_map[parent_id] = []
  174. children_map[parent_id].append(cid)
  175. result = [collection_id]
  176. def collect_children(cid):
  177. if cid in children_map:
  178. for child_id in children_map[cid]:
  179. result.append(child_id)
  180. collect_children(child_id)
  181. collect_children(collection_id)
  182. return result
  183. def get_papers_in_collection(db_path: str, collection_id: int) -> list[dict]:
  184. """获取分类下的所有论文(递归包含子分类)"""
  185. conn = sqlite3.connect(db_path)
  186. cursor = conn.cursor()
  187. collection_ids = get_all_child_collections(db_path, collection_id)
  188. placeholders = ','.join('?' * len(collection_ids))
  189. query = f"""
  190. SELECT DISTINCT i.itemID, idv.value as title
  191. FROM items i
  192. JOIN collectionItems ci ON i.itemID = ci.itemID
  193. JOIN itemData id ON i.itemID = id.itemID
  194. JOIN itemDataValues idv ON id.valueID = idv.valueID
  195. JOIN fields f ON id.fieldID = f.fieldID
  196. WHERE ci.collectionID IN ({placeholders}) AND f.fieldName = 'title' AND i.itemTypeID != 14
  197. """
  198. cursor.execute(query, collection_ids)
  199. logger.info(f"递归查询,包含 {len(collection_ids)} 个分类")
  200. papers = [{'item_id': row[0], 'title': row[1]} for row in cursor.fetchall()]
  201. conn.close()
  202. return papers
  203. def get_pdf_path(db_path: str, item_id: int) -> Optional[str]:
  204. """获取论文的 PDF 路径"""
  205. conn = sqlite3.connect(db_path)
  206. cursor = conn.cursor()
  207. cursor.execute("""
  208. SELECT ia.path, items.key
  209. FROM itemAttachments ia
  210. JOIN items ON ia.itemID = items.itemID
  211. WHERE ia.parentItemID = ? AND ia.contentType = 'application/pdf'
  212. """, (item_id,))
  213. row = cursor.fetchone()
  214. conn.close()
  215. if row:
  216. path, key = row
  217. if path and path.startswith('storage:'):
  218. filename = path.replace('storage:', '')
  219. return os.path.join(ZOTERO_STORAGE, key, filename)
  220. return None
  221. def get_paper_online_source(db_path: str, item_id: int) -> Optional[dict]:
  222. """
  223. 获取论文的在线来源信息(arXiv ID、DOI、URL)
  224. 用于处理没有 PDF 的论文
  225. """
  226. conn = sqlite3.connect(db_path)
  227. cursor = conn.cursor()
  228. # 获取论文的各种字段
  229. cursor.execute("""
  230. SELECT f.fieldName, idv.value
  231. FROM itemData id
  232. JOIN fields f ON id.fieldID = f.fieldID
  233. JOIN itemDataValues idv ON id.valueID = idv.valueID
  234. WHERE id.itemID = ?
  235. """, (item_id,))
  236. fields = {row[0]: row[1] for row in cursor.fetchall()}
  237. conn.close()
  238. result = {}
  239. # 检查 arXiv ID (可能在 extra 字段或 archiveID)
  240. extra = fields.get('extra', '')
  241. if 'arXiv:' in extra:
  242. # 格式: arXiv:2401.12345
  243. match = re.search(r'arXiv[:\s]+(\d{4}\.\d{4,5})', extra, re.IGNORECASE)
  244. if match:
  245. result['arxiv_id'] = match.group(1)
  246. # 检查 DOI
  247. doi = fields.get('DOI', '')
  248. if doi:
  249. result['doi'] = doi
  250. # 检查 URL
  251. url = fields.get('url', '')
  252. if url:
  253. result['url'] = url
  254. # 尝试从 URL 提取 arXiv ID
  255. if 'arxiv.org' in url and 'arxiv_id' not in result:
  256. match = re.search(r'arxiv\.org/(?:abs|pdf)/(\d{4}\.\d{4,5})', url)
  257. if match:
  258. result['arxiv_id'] = match.group(1)
  259. return result if result else None
  260. def get_existing_notes() -> dict[str, str]:
  261. """获取 Obsidian 中已有的笔记(返回 {方法名: 文件路径})"""
  262. existing = {}
  263. notes_dir = Path(PAPER_NOTES_ROOT)
  264. if notes_dir.exists():
  265. for md_file in notes_dir.rglob("*.md"):
  266. name = md_file.stem
  267. relative_parts = md_file.relative_to(notes_dir).parts
  268. # 跳过 _待整理, _概念 等特殊目录和目录页
  269. if any(part.startswith("_") for part in relative_parts):
  270. continue
  271. if md_file.parent.name == name:
  272. continue
  273. for method_name in _extract_note_method_names(name):
  274. existing[method_name] = str(md_file)
  275. return existing
  276. def title_matches_note(title: str, existing_notes: dict[str, str]) -> bool:
  277. """
  278. 检查论文标题是否与已有笔记匹配
  279. 只有精确匹配方法名时才返回 True
  280. """
  281. if not title:
  282. return False
  283. normalized_candidates = {
  284. _normalize_method_name(title.strip()),
  285. _normalize_method_name(title.split(':', 1)[0].strip()),
  286. }
  287. for method_normalized in normalized_candidates:
  288. if not method_normalized:
  289. continue
  290. for note_method in existing_notes.keys():
  291. # 完全相等
  292. if note_method == method_normalized:
  293. return True
  294. # 笔记方法名完全包含在标题方法名中(且长度相近)
  295. if note_method in method_normalized and len(note_method) > 3:
  296. # 确保不是太短的匹配(避免 "gs" 匹配 "3dgs")
  297. if len(note_method) >= len(method_normalized) * 0.5:
  298. return True
  299. return False
  300. def _normalize_method_name(value: str) -> str:
  301. normalized = value.strip().lower().translate(_SUBSCRIPT_TRANSLATION)
  302. for source, target in _GREEK_REPLACEMENTS.items():
  303. normalized = normalized.replace(source, target)
  304. normalized = normalized.replace("&", "and")
  305. return re.sub(r"[^a-z0-9]+", "", normalized)
  306. def _extract_note_method_names(stem: str) -> set[str]:
  307. candidates = {stem}
  308. match = re.match(r"^(?:19|20)\d{2}_(.+)$", stem)
  309. if match:
  310. candidates.add(match.group(1))
  311. return {
  312. normalized
  313. for candidate in candidates
  314. if (normalized := _normalize_method_name(candidate))
  315. }
  316. def load_progress() -> dict:
  317. """加载进度"""
  318. if os.path.exists(PROGRESS_FILE):
  319. with open(PROGRESS_FILE, 'r') as f:
  320. return json.load(f)
  321. return {'completed': [], 'failed': [], 'current': None, 'started_at': None}
  322. def save_progress(progress: dict):
  323. """保存进度"""
  324. os.makedirs(os.path.dirname(PROGRESS_FILE), exist_ok=True)
  325. with open(PROGRESS_FILE, 'w') as f:
  326. json.dump(progress, f, indent=2, ensure_ascii=False)
  327. def call_claude_code(paper_source: dict, collection_path: str, item_id: int) -> tuple[bool, str]:
  328. """
  329. 调用 Claude Code 处理论文
  330. paper_source 可以包含:
  331. - pdf_path: 本地 PDF 路径
  332. - arxiv_id: arXiv ID (如 2401.12345)
  333. - doi: DOI
  334. - url: 论文 URL
  335. - title: 论文标题 (用于搜索)
  336. """
  337. arxiv_id = paper_source.get('arxiv_id', '')
  338. notes_root = PAPER_NOTES_ROOT
  339. concepts_root = CONCEPTS_ROOT
  340. # 构建来源信息
  341. source_lines = []
  342. if paper_source.get('pdf_path'):
  343. source_lines.append(f"PDF 路径: {paper_source['pdf_path']}")
  344. if arxiv_id:
  345. source_lines.append(f"arXiv ID: {arxiv_id}")
  346. source_lines.append(f"arXiv 页面: https://arxiv.org/abs/{arxiv_id}")
  347. source_lines.append(f"arXiv PDF: https://arxiv.org/pdf/{arxiv_id}.pdf")
  348. source_lines.append(f"arXiv HTML (图片): https://arxiv.org/html/{arxiv_id}")
  349. if paper_source.get('doi'):
  350. source_lines.append(f"DOI: {paper_source['doi']}")
  351. source_lines.append(f"DOI 链接: https://doi.org/{paper_source['doi']}")
  352. if paper_source.get('url'):
  353. source_lines.append(f"URL: {paper_source['url']}")
  354. if paper_source.get('title'):
  355. source_lines.append(f"论文标题: {paper_source['title']}")
  356. source_info = '\n'.join(source_lines)
  357. # 如果没有 PDF,添加特殊说明
  358. no_pdf_instruction = ""
  359. if not paper_source.get('pdf_path'):
  360. fallback_steps = []
  361. if arxiv_id:
  362. fallback_steps.extend(
  363. [
  364. f"1. **arXiv HTML 版本**(推荐): 用 WebFetch 读取 https://arxiv.org/html/{arxiv_id},可直接获取图片 URL",
  365. f"2. **arXiv 摘要页**: 用 WebFetch 读取 https://arxiv.org/abs/{arxiv_id}",
  366. f"3. **arXiv PDF**: 下载 https://arxiv.org/pdf/{arxiv_id}.pdf 到本地后用 Read 读取",
  367. ]
  368. )
  369. if paper_source.get('doi'):
  370. fallback_steps.append(f"{len(fallback_steps) + 1}. **DOI 页面**: 跳转到 https://doi.org/{paper_source['doi']} 读取")
  371. if paper_source.get('url'):
  372. fallback_steps.append(f"{len(fallback_steps) + 1}. **原始 URL**: 读取 {paper_source['url']}")
  373. if not fallback_steps:
  374. fallback_steps.append("1. 根据标题搜索在线来源,再优先读取可直接获取图片的 HTML 版本")
  375. no_pdf_instruction = f"""
  376. ## 无本地 PDF - 在线获取(重要)
  377. 这篇论文没有本地 PDF,请按以下优先级获取内容:
  378. {chr(10).join(fallback_steps)}
  379. 优先使用 HTML 版本,因为可以直接获取在线图片链接!
  380. """
  381. prompt = f"""请使用 paper-reader skill 读取并分析这篇论文,生成完整的结构化笔记。
  382. {source_info}
  383. Zotero 分类路径: {collection_path}
  384. Zotero ItemID: {item_id}
  385. {no_pdf_instruction}
  386. ## 质量要求(重要)
  387. 参考高质量笔记风格,必须包含:
  388. 1. **元信息表格**: 机构、日期、项目主页、对比基线
  389. 2. **内联概念链接**: 在正文中使用 `[[Flow Matching]]`、`[[DiT]]` 链接概念,不只是在文末
  390. 3. **公式格式**: 每个公式包含 "含义" + "符号说明" 小节
  391. 4. **图片格式**: `### Figure X: 英文标题 / 中文标题` + 在线URL + `**说明**:`
  392. 5. **独立锐评**: 遵循 paper-reader 的锐评要求,完整锐评放在笔记标题后第一节,最终答复也以简短锐评开头;给出新意、最强证据、关键缺口或边界和明确判决,关键判断附来源,不把未核实当作缺失
  393. 6. **关联笔记分类**: 分为 "基于"、"对比"、"方法相关"、"硬件/数据相关"
  394. 7. **速查卡片**: ASCII 框格式的快速参考
  395. ## 处理规则
  396. 1. **图片优先在线链接**:先检查 arXiv HTML 版本 (arxiv.org/html/xxx),有则用在线图片 URL
  397. ## 概念库更新(必须执行)
  398. **每篇论文处理完后,必须为新遇到的技术概念创建笔记!**
  399. ### 概念库位置
  400. {concepts_root}
  401. ### 需要创建概念笔记的情况
  402. 1. 论文中首次遇到的技术术语(如 Flow Matching、Action Chunking、DiT)
  403. 2. 论文提出的新方法名(如果是通用概念)
  404. 3. 在笔记中使用了 [[概念]] 链接但该概念笔记不存在
  405. ### 概念笔记格式
  406. ```markdown
  407. ---
  408. type: concept
  409. aliases: [别名1, 别名2]
  410. ---
  411. # 概念名称
  412. ## 定义
  413. 一句话定义
  414. ## 数学形式(如有)
  415. $$公式$$
  416. ## 核心要点
  417. 1. 要点1
  418. 2. 要点2
  419. ## 代表工作
  420. - [[论文1]]: 说明
  421. - [[论文2]]: 说明
  422. ## 相关概念
  423. - [[相关概念1]]
  424. ```
  425. ### 概念目录结构(已存在的分类)
  426. - 1-生成模型/: Diffusion Model, DiT, VAE, Flow Matching, EDM, Latent Diffusion 等
  427. - 2-强化学习/: MDP, Policy, Value Function, PPO, GAIL, World Model 等
  428. - 3-机器人策略/: Action Chunking, Inverse Dynamics Model, Sim-to-Real 等
  429. - 4-足式运动/: CPG, Curriculum Learning, Privileged Learning 等
  430. - 5-导航与定位/: VLN 等
  431. - 如果是新领域,创建新的子目录(如 6-3D视觉/)
  432. ### 执行步骤
  433. 1. 分析完论文后,列出笔记中所有 [[概念]] 链接
  434. 2. 检查每个概念是否已存在:查看 `{concepts_root}` 下已有概念笔记
  435. 3. 对于不存在的概念,创建概念笔记文件
  436. 4. 使用 Write 工具写入概念笔记
  437. ## 自动分类与 Zotero 同步(重要)
  438. **不要依赖关键词匹配!** 你需要真正理解论文后自主判断分类。
  439. ### 分类判断原则
  440. 1. 理解论文的**核心贡献**是什么
  441. 2. 问自己:如果我要找这篇论文,我会去哪个分类找?
  442. 3. 按**主要贡献**分类,而不是使用的技术
  443. - 例:用 Diffusion 做机器人控制 → VLA,不是 Diffusion Model
  444. - 例:用 3DGS 做 SLAM → SLAM,不是 3DGS
  445. ### 分类操作
  446. 使用 zotero_helper.py 脚本:
  447. - collections: 列出所有分类
  448. - find-collection "名称": 查找分类ID
  449. - move <item_id> <collection_id>: 移动论文
  450. ### 何时必须移动
  451. - 当前在 "2025"、"杂项"、"feifeili" 等临时分类 → 必须移动
  452. - 分类与论文内容明显不符 → 移动
  453. ## 保存位置
  454. 根据你对论文的理解,保存到对应的 Obsidian 目录:
  455. - 基本结构:{notes_root}/对应分类路径/
  456. - 不确定时:{notes_root}/_待整理/
  457. 请直接开始处理,不需要确认。提取所有公式、图片和表格。"""
  458. try:
  459. result = subprocess.run(
  460. ['claude', '-p', prompt, '--model', 'opus', '--permission-mode', 'acceptEdits', '--dangerously-skip-permissions'],
  461. capture_output=True,
  462. text=True,
  463. timeout=900 # 15分钟超时(因为要提取图片)
  464. )
  465. output = result.stdout + result.stderr
  466. limit_type = detect_limit_error(output)
  467. if limit_type == 'RATE_LIMIT':
  468. return False, 'RATE_LIMIT'
  469. if limit_type == 'QUOTA_LIMIT':
  470. return False, f'QUOTA_LIMIT|{output[:200]}'
  471. if result.returncode == 0:
  472. return True, ''
  473. else:
  474. return False, output[:500]
  475. except subprocess.TimeoutExpired:
  476. return False, 'TIMEOUT'
  477. except Exception as e:
  478. return False, str(e)
  479. def process_collection(collection_name: str, resume: bool = True):
  480. """处理整个分类的论文"""
  481. logger.info(f"=== 开始处理分类: {collection_name} ===")
  482. db_path = copy_zotero_db()
  483. collection_id, collection_path = get_collection_id_and_path(db_path, collection_name)
  484. if not collection_id:
  485. logger.error(f"找不到分类: {collection_name}")
  486. return
  487. logger.info(f"分类路径: {collection_path} (ID: {collection_id})")
  488. papers = get_papers_in_collection(db_path, collection_id)
  489. logger.info(f"分类下共有 {len(papers)} 篇论文")
  490. progress = load_progress() if resume else {'completed': [], 'failed': [], 'current': None, 'started_at': None}
  491. if not progress['started_at']:
  492. progress['started_at'] = datetime.now().isoformat()
  493. # 获取已有笔记
  494. existing_notes = get_existing_notes()
  495. logger.info(f"Obsidian 中已有 {len(existing_notes)} 篇笔记")
  496. # 过滤待处理论文
  497. pending = []
  498. skipped_existing = 0
  499. for paper in papers:
  500. item_id = paper['item_id']
  501. title = paper['title']
  502. if item_id in progress['completed']:
  503. continue
  504. # 检查是否已有笔记
  505. if title_matches_note(title, existing_notes):
  506. logger.info(f"跳过 (已有笔记): {title[:50]}")
  507. skipped_existing += 1
  508. progress['completed'].append(item_id) # 标记为已完成
  509. continue
  510. pdf_path = get_pdf_path(db_path, item_id)
  511. paper_source = {'title': title}
  512. if pdf_path and os.path.exists(pdf_path):
  513. paper_source['pdf_path'] = pdf_path
  514. else:
  515. # 尝试获取在线来源
  516. online_source = get_paper_online_source(db_path, item_id)
  517. if online_source:
  518. paper_source.update(online_source)
  519. logger.info(f"无本地 PDF,使用在线来源: {list(online_source.keys())}")
  520. else:
  521. logger.warning(f"跳过 (无PDF且无在线来源): {title[:50]}")
  522. continue
  523. pending.append({**paper, 'source': paper_source})
  524. if skipped_existing > 0:
  525. logger.info(f"跳过已有笔记: {skipped_existing} 篇")
  526. save_progress(progress)
  527. logger.info(f"待处理: {len(pending)} 篇")
  528. wait_time = INITIAL_WAIT
  529. for i, paper in enumerate(pending):
  530. item_id = paper['item_id']
  531. title = paper['title']
  532. paper_source = paper['source']
  533. source_type = "PDF" if paper_source.get('pdf_path') else "在线"
  534. logger.info(f"\n[{i+1}/{len(pending)}] 处理 ({source_type}): {title[:60]}...")
  535. progress['current'] = {'item_id': item_id, 'title': title}
  536. save_progress(progress)
  537. success, error = call_claude_code(paper_source, collection_path, item_id)
  538. if success:
  539. logger.info(f"✓ 完成: {title[:50]}")
  540. progress['completed'].append(item_id)
  541. progress['current'] = None
  542. save_progress(progress)
  543. wait_time = INITIAL_WAIT
  544. if i < len(pending) - 1:
  545. time.sleep(BETWEEN_PAPERS_WAIT)
  546. elif error == 'RATE_LIMIT':
  547. logger.warning(f"⏳ Rate limit, 等待 {wait_time} 秒...")
  548. time.sleep(wait_time)
  549. wait_time = min(wait_time * WAIT_MULTIPLIER, MAX_WAIT)
  550. pending.insert(i + 1, paper) # 重新加入队列
  551. elif error.startswith('QUOTA_LIMIT'):
  552. reset_wait = parse_reset_wait_seconds(error)
  553. if reset_wait:
  554. logger.warning(f"⏳ 用量上限,等待到重置(约 {reset_wait // 60} 分钟)...")
  555. time.sleep(reset_wait)
  556. else:
  557. wait_for_quota_reset()
  558. pending.insert(i + 1, paper) # 重新加入队列
  559. elif error == 'TIMEOUT':
  560. logger.error(f"✗ 超时: {title[:50]}")
  561. progress['failed'].append({'item_id': item_id, 'title': title, 'error': 'TIMEOUT'})
  562. save_progress(progress)
  563. else:
  564. logger.error(f"✗ 失败: {title[:50]} - {error[:100]}")
  565. progress['failed'].append({'item_id': item_id, 'title': title, 'error': error[:200]})
  566. save_progress(progress)
  567. progress['current'] = None
  568. progress['finished_at'] = datetime.now().isoformat()
  569. save_progress(progress)
  570. logger.info("\n=== 处理完成 ===")
  571. logger.info(f"成功: {len(progress['completed'])} 篇")
  572. logger.info(f"失败: {len(progress['failed'])} 篇")
  573. def show_status():
  574. """显示当前进度"""
  575. progress = load_progress()
  576. print("\n=== Paper Daemon 状态 ===")
  577. print(f"开始时间: {progress.get('started_at', 'N/A')}")
  578. print(f"完成时间: {progress.get('finished_at', '进行中...')}")
  579. print(f"已完成: {len(progress.get('completed', []))} 篇")
  580. print(f"失败: {len(progress.get('failed', []))} 篇")
  581. current = progress.get('current')
  582. if current:
  583. print(f"当前处理: {current.get('title', 'N/A')[:60]}")
  584. if progress.get('failed'):
  585. print("\n失败的论文:")
  586. for item in progress['failed'][:5]:
  587. print(f" - {item['title'][:50]}: {item['error'][:50]}")
  588. def main():
  589. parser = argparse.ArgumentParser(description='Paper Reading Daemon')
  590. parser.add_argument('--collection', '-c', type=str, help='Zotero 分类名称')
  591. parser.add_argument('--status', '-s', action='store_true', help='显示当前状态')
  592. parser.add_argument('--no-resume', action='store_true', help='不恢复之前的进度')
  593. parser.add_argument('--list', '-l', action='store_true', help='列出所有 Zotero 分类')
  594. args = parser.parse_args()
  595. if args.status:
  596. show_status()
  597. return
  598. if args.list:
  599. db_path = copy_zotero_db()
  600. conn = sqlite3.connect(db_path)
  601. cursor = conn.cursor()
  602. cursor.execute("""
  603. SELECT c.collectionName, COUNT(ci.itemID) as count
  604. FROM collections c
  605. LEFT JOIN collectionItems ci ON c.collectionID = ci.collectionID
  606. GROUP BY c.collectionID
  607. HAVING count > 0
  608. ORDER BY c.collectionName
  609. """)
  610. print("\n=== Zotero 分类 ===")
  611. for name, count in cursor.fetchall():
  612. print(f" {name}: {count} 篇")
  613. conn.close()
  614. return
  615. if not args.collection:
  616. parser.print_help()
  617. return
  618. # 检查是否已有进程在运行
  619. if not acquire_lock():
  620. logger.error("另一个 paper_daemon 进程正在运行!请先停止它或删除 ~/.claude/paper_daemon.pid")
  621. return
  622. try:
  623. process_collection(args.collection, resume=not args.no_resume)
  624. finally:
  625. release_lock()
  626. if __name__ == '__main__':
  627. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.