返回 last30days-skill
arxiv.py
根目录 / skills / last30days / scripts / lib / arxiv.py
1 """arXiv research-paper source for last30days.
2
3 Shells out to ``arxiv-pp-cli`` (open Atom API, no auth) to surface recent
4 research papers relevant to a topic. arXiv carries no engagement signal, so
5 ranking leans on relevance (the CLI's own relevance sort plus token overlap)
6 and recency.
7
8 Activation gate: this source is only available when ``arxiv-pp-cli`` is on
9 PATH. ``pipeline.available_sources`` checks ``shutil.which`` before including
10 ``arxiv``. The functions below also detect the missing-binary case defensively.
11
12 Default-on safety (two gates, both required):
13 1. Query construction. arXiv is queried with a *quoted* phrase and
14 ``--sort-by relevance``. Sorting by submitted-date instead returns the
15 newest cs.* papers regardless of topic -- topic-blind noise.
16 2. Recency cutoff. Entries older than ``RECENCY_DAYS`` are dropped. Research
17 does not trend on a 30-day clock, so this window is wider than the social
18 sources' 30 days; it keeps arXiv current while dropping stale keyword
19 matches (e.g. a 2017 sports-statistics paper that an off-topic query like
20 "Golden State Warriors" would otherwise surface).
21 """
22
23 from __future__ import annotations
24
25 import json
26 import shutil
27 from datetime import date, datetime, time, timedelta, timezone
28 from typing import Any, Dict, List, Optional
29
30 from . import log, subproc
31 from .relevance import token_overlap_relevance
32
33
34 CLI_BIN = "arxiv-pp-cli"
35
36 # Per-depth result counts.
37 DEPTH_CONFIG = {
38 "quick": 5,
39 "default": 10,
40 "deep": 20,
41 }
42
43 # Recency window for arXiv specifically. Papers do not trend daily; a year keeps
44 # the source current (the off-topic 2017 paper still drops) without discarding
45 # the genuinely-relevant work from the last few months.
46 RECENCY_DAYS = 365
47
48 SEARCH_TIMEOUT = 30
49
50
51 def _log(msg: str) -> None:
52 log.source_log("arXiv", msg, tty_only=False)
53
54
55 def _is_available() -> bool:
56 """True when the arxiv-pp-cli binary is on PATH."""
57 return shutil.which(CLI_BIN) is not None
58
59
60 def _today() -> datetime:
61 return datetime.now(timezone.utc)
62
63
64 def _build_search_query(topic: str, *, quoted: bool = True) -> str:
65 """Build the arXiv search-query string for ``topic``.
66
67 Quoted (default): phrase-scoped exact match across all fields. Precise
68 for topics that genuinely appear as a phrase in a title/abstract, but a
69 natural-language multi-word topic ("AI video generation advances") almost
70 never appears verbatim, so it returns zero results (#908). Unquoted uses
71 an AND-conjoined clause for every individual term as a fallback retry.
72
73 Inner double-quotes are stripped (arXiv has no phrase-escaping) either way.
74 """
75 phrase = _clean_phrase(topic)
76 if quoted:
77 return f'all:"{phrase}"'
78 return " AND ".join(f'all:"{term}"' for term in phrase.split())
79
80
81 def _clean_phrase(topic: str) -> str:
82 """Strip quotes and collapse whitespace into a phrase for the query."""
83 return " ".join(topic.replace('"', " ").split())
84
85
86 def _end_of_day(day: date) -> datetime:
87 return datetime.combine(day, time.max, tzinfo=timezone.utc)
88
89
90 def _submitted_date_clause(to_date: str) -> str:
91 end_date = date.fromisoformat(to_date)
92 end = _end_of_day(end_date)
93 anchor = min(_today(), end)
94 # The parser floors age to whole days, so an age just under 366 days still
95 # qualifies. Round down to the start of the first eligible minute.
96 lookback = timedelta(days=RECENCY_DAYS + 1) - datetime.resolution
97 earliest = datetime.min.replace(tzinfo=timezone.utc)
98 start = anchor - min(lookback, anchor - earliest)
99 # arXiv interprets an upper minute as HH:MM:00. Query through midnight
100 # so the full final minute reaches the parser, which checks the end date.
101 query_end = end + datetime.resolution if end_date < date.max else end
102 return (
103 f"submittedDate:[{start.year:04d}{start:%m%d%H%M} "
104 f"TO {query_end.year:04d}{query_end:%m%d%H%M}]"
105 )
106
107
108 def _build_search_args(
109 topic: str, limit: int, date_clause: str, *, quoted: bool = True,
110 ) -> List[str]:
111 return [
112 CLI_BIN,
113 "query",
114 "--search-query",
115 f"{_build_search_query(topic, quoted=quoted)} AND {date_clause}",
116 "--sort-by",
117 "relevance",
118 "--max-results",
119 str(limit),
120 "--agent",
121 ]
122
123
124 def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
125 """Invoke arxiv-pp-cli and parse the JSON envelope.
126
127 arXiv returns ``{"meta": ..., "results": {"entries": [...]}}``. This
128 normalizes to ``{"results": [...entries...]}`` so the parse step sees a
129 flat list, matching the other sources' shape. Never raises.
130 """
131 if not _is_available():
132 return {"results": [], "error": f"{CLI_BIN} not on PATH"}
133 try:
134 result = subproc.run_with_timeout(cmd, timeout=timeout)
135 except subproc.SubprocTimeout as exc:
136 _log(f"Timeout: {exc}")
137 return {"results": [], "error": str(exc)}
138 except FileNotFoundError as exc:
139 _log(f"Binary missing: {exc}")
140 return {"results": [], "error": str(exc)}
141 except OSError as exc:
142 _log(f"Spawn failed: {exc}")
143 return {"results": [], "error": str(exc)}
144
145 if result.returncode != 0:
146 snippet = (result.stderr or "").strip().splitlines()[:1]
147 first = snippet[0] if snippet else f"exit {result.returncode}"
148 _log(f"CLI exit {result.returncode}: {first}")
149 return {"results": [], "error": first}
150
151 stdout = result.stdout or ""
152 if not stdout.strip():
153 _log("CLI returned empty stdout")
154 return {"results": [], "error": "empty stdout"}
155 try:
156 data = json.loads(stdout)
157 except json.JSONDecodeError as exc:
158 _log(f"JSON decode failed: {exc}")
159 return {"results": [], "error": f"json decode: {exc}"}
160
161 if not _is_entry_envelope(data):
162 _log("CLI returned an unrecognized JSON response")
163 return {"results": [], "error": "unrecognized JSON response"}
164
165 return {"results": _extract_entries(data)}
166
167
168 def _extract_entries(data: Any) -> List[Dict[str, Any]]:
169 """Pull the entries list out of arXiv's nested envelope.
170
171 Tolerates ``{"results": {"entries": [...]}}`` (current shape),
172 ``{"entries": [...]}``, and a bare list.
173 """
174 if isinstance(data, list):
175 return [e for e in data if isinstance(e, dict)]
176 if isinstance(data, dict):
177 results = data.get("results")
178 if isinstance(results, dict):
179 entries = results.get("entries")
180 if isinstance(entries, list):
181 return [e for e in entries if isinstance(e, dict)]
182 if isinstance(results, list):
183 return [e for e in results if isinstance(e, dict)]
184 entries = data.get("entries")
185 if isinstance(entries, list):
186 return [e for e in entries if isinstance(e, dict)]
187 return []
188
189
190 def _is_entry_envelope(data: Any) -> bool:
191 """Return whether ``data`` has one of the supported entry-list shapes."""
192 if isinstance(data, list):
193 return True
194 if not isinstance(data, dict):
195 return False
196 results = data.get("results")
197 return (
198 isinstance(results, list)
199 or (isinstance(results, dict) and isinstance(results.get("entries"), list))
200 or isinstance(data.get("entries"), list)
201 )
202
203
204 def search_arxiv(
205 topic: str,
206 from_date: str,
207 to_date: str,
208 depth: str = "default",
209 ) -> Dict[str, Any]:
210 """Search arXiv by relevance within its recency window ending at to_date.
211
212 Returns a dict with a flat ``results`` list of entry dicts. On failure,
213 ``results`` is empty and an ``error`` key carries a one-line description.
214 """
215 if not topic or not topic.strip():
216 return {"results": []}
217 # A topic of only quote characters cleans to an empty phrase (all:""),
218 # which is a topic-blind query; bail rather than search for nothing.
219 if not _clean_phrase(topic):
220 return {"results": []}
221 limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
222 date_clause = _submitted_date_clause(to_date)
223 cmd = _build_search_args(topic, limit, date_clause)
224 _log(f"query '{topic}' (relevance, max={limit})")
225 response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)
226 _log(f"found {len(response.get('results') or [])} entries")
227 # Retry a clean zero-result phrase match with individually quoted AND terms.
228 # CLI failures, malformed responses, and missing binaries skip the retry.
229 if not response.get("error") and not response.get("results"):
230 retry_cmd = _build_search_args(topic, limit, date_clause, quoted=False)
231 _log(f"quoted phrase matched nothing; retrying unquoted for '{topic}'")
232 response = _run_cli(retry_cmd, timeout=SEARCH_TIMEOUT)
233 _log(f"unquoted retry found {len(response.get('results') or [])} entries")
234 return response
235
236
237 def _parse_published(published: Optional[str]) -> Optional[datetime]:
238 """Parse an arXiv ``published`` timestamp (ISO 8601, e.g.
239 '2026-06-25T17:59:48Z') into an aware datetime. Returns None on failure."""
240 if not published or not isinstance(published, str):
241 return None
242 text = published.strip().replace("Z", "+00:00")
243 try:
244 dt = datetime.fromisoformat(text)
245 except ValueError:
246 return None
247 if dt.tzinfo is None:
248 dt = dt.replace(tzinfo=timezone.utc)
249 return dt
250
251
252 def _alternate_url(entry: Dict[str, Any]) -> str:
253 """Return the human-facing abstract URL (rel=alternate), not the PDF."""
254 links = entry.get("links")
255 if isinstance(links, list):
256 for link in links:
257 if isinstance(link, dict) and link.get("rel") == "alternate":
258 href = str(link.get("href") or "").strip()
259 if href:
260 return href
261 # Fall back to the abstract URL derived from the entry id.
262 entry_id = str(entry.get("id") or "").strip()
263 if entry_id.startswith("http"):
264 return entry_id
265 return ""
266
267
268 def _author_names(entry: Dict[str, Any]) -> List[str]:
269 authors = entry.get("authors")
270 out: List[str] = []
271 if isinstance(authors, list):
272 for a in authors:
273 if isinstance(a, dict):
274 name = str(a.get("name") or "").strip()
275 if name:
276 out.append(name)
277 return out
278
279
280 def parse_arxiv_response(
281 response: Dict[str, Any],
282 query: str = "",
283 today: Optional[datetime] = None,
284 to_date: Optional[str] = None,
285 ) -> List[Dict[str, Any]]:
286 """Parse an arXiv envelope into normalized item dicts.
287
288 Applies the recency cutoff (drops entries older than ``RECENCY_DAYS`` and
289 entries with an unparseable date) and computes a token-overlap relevance
290 hint. Returns dicts ready for ``normalize._normalize_arxiv``.
291
292 ``to_date`` (the report window's inclusive end, e.g. from ``--as-of``)
293 anchors the cutoff at that day and drops papers published after it.
294 """
295 raw = response.get("results") if isinstance(response, dict) else None
296 if not isinstance(raw, list):
297 return []
298
299 now = today or _today()
300 end_date = date.fromisoformat(to_date) if to_date else None
301 if end_date is not None:
302 now = min(now, _end_of_day(end_date))
303 items: List[Dict[str, Any]] = []
304 for i, entry in enumerate(raw):
305 if not isinstance(entry, dict):
306 continue
307 title = " ".join(str(entry.get("title") or "").split()).strip()
308 if not title:
309 continue
310 published = _parse_published(entry.get("published") or entry.get("updated"))
311 if published is None:
312 # No usable date -> cannot honor the recency contract; drop.
313 continue
314 if end_date is not None and published.date() > end_date:
315 continue
316 age_days = (now - published).days
317 # Allow a one-day grace on the future side: a paper announced later in
318 # the same UTC day yields age_days == -1 (timedelta.days floors toward
319 # negative); dropping it as "future" would discard the freshest work.
320 if age_days > RECENCY_DAYS or age_days < -1:
321 continue
322
323 summary = " ".join(str(entry.get("summary") or "").split()).strip()
324 authors = _author_names(entry)
325 url = _alternate_url(entry)
326
327 rank_decay = max(0.3, 1.0 - (i * 0.03))
328 if query:
329 content_score = token_overlap_relevance(query, f"{title} {summary}".strip())
330 else:
331 content_score = 0.5
332 relevance = min(1.0, 0.6 * rank_decay + 0.4 * content_score)
333
334 primary_author = authors[0] if authors else ""
335 author_label = primary_author
336 if len(authors) > 1:
337 author_label = f"{primary_author} et al."
338
339 items.append(
340 {
341 "id": str(entry.get("id") or url or f"AX{i + 1}"),
342 "title": title,
343 "url": url,
344 "summary": summary,
345 "author": author_label,
346 "authors": authors,
347 "date": published.date().isoformat(),
348 "engagement": {},
349 "relevance": round(relevance, 2),
350 "why_relevant": (
351 f"arXiv paper ({primary_author}, {published.date().isoformat()})"
352 if primary_author
353 else f"arXiv paper ({published.date().isoformat()})"
354 ),
355 }
356 )
357
358 return items
359
359 lines PYTHON