papersearch 0.5.13 → 0.5.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/carsi/paper_search_carsi/adapters/base.py +3 -0
- package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +8 -2
- package/carsi/paper_search_carsi/assets/capsule.html +0 -1
- package/carsi/paper_search_carsi/assets/capsule_en.json +1 -1
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +85 -3
- package/carsi/paper_search_carsi/download_diagnostics.py +1 -1
- package/carsi/paper_search_carsi/engine/batch.py +13 -3
- package/carsi/paper_search_carsi/engine/batch_user.py +57 -0
- package/carsi/paper_search_carsi/engine/batch_waits.py +13 -1
- package/carsi/paper_search_carsi/engine/bridge.py +15 -12
- package/carsi/paper_search_carsi/engine/page_activity.py +30 -1
- package/carsi/paper_search_carsi/engine/page_supplements.py +67 -0
- package/carsi/paper_search_carsi/progress_view.py +0 -2
- package/carsi/paper_search_carsi/user_settings.py +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +1 -1
- package/skills/paper-search/references/browser-download.md +3 -3
- package/skills/paper-search/references/cli-contract.md +1 -1
- package/skills/paper-search/references/publisher-support.md +2 -2
|
@@ -16,6 +16,9 @@ class SupplementLink:
|
|
|
16
16
|
label: str = ""
|
|
17
17
|
# Discovery failures are recorded alongside downloaded files.
|
|
18
18
|
error: str = ""
|
|
19
|
+
# Found on the page but not shown to be this article's (a dataset the page
|
|
20
|
+
# only names): recorded with this reason, neither fetched nor counted.
|
|
21
|
+
set_aside: str = ""
|
|
19
22
|
|
|
20
23
|
|
|
21
24
|
class PublisherAdapter:
|
|
@@ -85,7 +85,8 @@ def _belongs(data: dict, doi: str, *, labelled: bool = False) -> bool:
|
|
|
85
85
|
|
|
86
86
|
|
|
87
87
|
def supplement_links(page: Any, doi: str, *, clock=time.monotonic, pause=time.sleep) -> list[SupplementLink] | None:
|
|
88
|
-
"""None means no Figshare route on this article; failures stay in the manifest.
|
|
88
|
+
"""None means no Figshare route on this article; failures stay in the manifest.
|
|
89
|
+
A resource not shown to be this article's is set aside (``set_aside``)."""
|
|
89
90
|
data = page.evaluate(_PAGE_LINKS)
|
|
90
91
|
if not isinstance(data, dict) or _doi(data.get("doi")) != _doi(doi):
|
|
91
92
|
return None
|
|
@@ -190,5 +191,10 @@ def supplement_links(page: Any, doi: str, *, clock=time.monotonic, pause=time.sl
|
|
|
190
191
|
raise
|
|
191
192
|
except Exception as exc:
|
|
192
193
|
reason = str(exc) if isinstance(exc, ValueError) and str(exc).startswith("figshare_") else "figshare_request_failed"
|
|
193
|
-
|
|
194
|
+
if reason == "figshare_article_mismatch":
|
|
195
|
+
# A dataset the article names (its data availability statement) is
|
|
196
|
+
# not its supplement unless one of them says so (JEM, 2026-11-11).
|
|
197
|
+
links.append(SupplementLink(root, "Figshare resource", set_aside=reason))
|
|
198
|
+
else:
|
|
199
|
+
links.append(SupplementLink(root, "Figshare supplementary material", error=reason))
|
|
194
200
|
return list(dict.fromkeys(links))
|
|
@@ -190,7 +190,7 @@
|
|
|
190
190
|
"机构下载": "School download",
|
|
191
191
|
"学校登录页最多等": "Wait for school login",
|
|
192
192
|
"其他页面最多等": "Wait for other pages",
|
|
193
|
-
"
|
|
193
|
+
"提醒你操作前最多等": "Wait before asking you",
|
|
194
194
|
"每家出版社每小时最多": "Per publisher per hour",
|
|
195
195
|
"秒": "s",
|
|
196
196
|
"篇": "papers",
|
|
@@ -5,6 +5,7 @@ engine owns waiting and decides whether verification has actually ended.
|
|
|
5
5
|
"""
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
|
+
import re
|
|
8
9
|
import time
|
|
9
10
|
from collections.abc import Callable
|
|
10
11
|
from typing import Any, Literal
|
|
@@ -100,12 +101,93 @@ def is_image_verification(page: Any) -> bool:
|
|
|
100
101
|
|
|
101
102
|
|
|
102
103
|
def needs_manual_verification(page: Any) -> bool:
|
|
103
|
-
"""A puzzle or
|
|
104
|
+
"""A puzzle, reCAPTCHA or another provider's widget on an already recognised
|
|
105
|
+
verification page.
|
|
104
106
|
|
|
105
107
|
Reading a checked box or a response token cannot prove that the enclosing
|
|
106
|
-
page's confirmation was submitted. Leave
|
|
108
|
+
page's confirmation was submitted. Leave these actions to the user.
|
|
107
109
|
"""
|
|
108
|
-
return is_image_verification(page) or has_visible_recaptcha(page)
|
|
110
|
+
return (is_image_verification(page) or has_visible_recaptcha(page)
|
|
111
|
+
or bool(verification_widget(page, manual_only=True)))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# Verification widgets the program never operates (the user, 2026-11-11): a page
|
|
115
|
+
# showing one is a verification for the user. Frames by their address, read without
|
|
116
|
+
# a browser call; elements by the providers' fixed names; AWS WAF, whose puzzle has
|
|
117
|
+
# no fixed element, by its script. Turnstile is Cloudflare's own check, whose box the
|
|
118
|
+
# program clicks (``click_checkbox``). Not a verification page: an article (citation
|
|
119
|
+
# metadata), whose comment or newsletter form may carry a widget, and a long page,
|
|
120
|
+
# where a widget is one form among others (a publisher's personal sign-in).
|
|
121
|
+
_WIDGET_FRAMES: tuple[tuple[str, Callable[[str], bool]], ...] = (
|
|
122
|
+
("reCAPTCHA", re.compile(r"^https://(?:www\.)?(?:google\.com|recaptcha\.net)/recaptcha/"
|
|
123
|
+
r"(?:api2|enterprise)/(?:anchor|bframe)").search),
|
|
124
|
+
("hCaptcha", re.compile(r"^https://(?:[a-z0-9-]+\.)*hcaptcha\.com/captcha/").search),
|
|
125
|
+
("DataDome", re.compile(r"^https://(?:[a-z0-9-]+\.)*captcha-delivery\.com/").search),
|
|
126
|
+
("Arkose", re.compile(r"^https://(?:[a-z0-9-]+\.)*(?:arkoselabs\.com|funcaptcha\.com)/").search),
|
|
127
|
+
("Tencent", re.compile(r"^https://(?:turing\.captcha\.qcloud\.com|t\.captcha\.qq\.com|"
|
|
128
|
+
r"ssl\.captcha\.qq\.com)/").search),
|
|
129
|
+
("Turnstile", lambda url: is_turnstile_frame(url)),
|
|
130
|
+
)
|
|
131
|
+
_WIDGET_ELEMENTS = (
|
|
132
|
+
("GeeTest", ".geetest_holder, .geetest_panel, .geetest_box, .geetest_captcha"),
|
|
133
|
+
("Aliyun", "[id^='aliyunCaptcha-'], #nc_1_wrapper"),
|
|
134
|
+
("Tencent", "#tcaptcha_iframe, #tcaptcha_transform"),
|
|
135
|
+
("PerimeterX", "#px-captcha"),
|
|
136
|
+
)
|
|
137
|
+
# Longer than this, the page is more than a verification interstitial.
|
|
138
|
+
_WIDGET_PAGE_TEXT = 2500
|
|
139
|
+
_WIDGET_PAGE_JS = r"""([groups, longest]) => {
|
|
140
|
+
if (document.querySelector('meta[name="citation_doi"], meta[name="citation_title"]')) return '#page';
|
|
141
|
+
if ((document.body?.innerText || '').trim().length > longest) return '#page';
|
|
142
|
+
const shown = el => { const r = el.getBoundingClientRect(), s = getComputedStyle(el);
|
|
143
|
+
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
|
|
144
|
+
for (const [name, selector] of groups)
|
|
145
|
+
if ([...document.querySelectorAll(selector)].some(shown)) return name;
|
|
146
|
+
if ([...document.scripts].some(s => /^https:\/\/[^/]*\.captcha\.awswaf\.com\//.test(s.src || ''))) return 'AWS WAF';
|
|
147
|
+
return '';
|
|
148
|
+
}"""
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def verification_widget(page: Any, *, manual_only: bool = False) -> str:
|
|
152
|
+
"""The provider of a visible verification widget making up ``page``, or "".
|
|
153
|
+
``manual_only``: leave out Turnstile, which the program may click itself."""
|
|
154
|
+
from .driver import Error
|
|
155
|
+
from .watchdog import CallAbandoned, call_limit
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
with call_limit(READ_LIMIT_SEC):
|
|
159
|
+
found = page.evaluate(_WIDGET_PAGE_JS, [[list(group) for group in _WIDGET_ELEMENTS], _WIDGET_PAGE_TEXT])
|
|
160
|
+
except CallAbandoned:
|
|
161
|
+
return ""
|
|
162
|
+
except Error as exc:
|
|
163
|
+
if any(text in str(exc).lower() for text in _NAVIGATED):
|
|
164
|
+
return "" # the page went on: the next check reads the new one
|
|
165
|
+
raise
|
|
166
|
+
found = found if isinstance(found, str) else ""
|
|
167
|
+
if found == "#page":
|
|
168
|
+
return ""
|
|
169
|
+
if found:
|
|
170
|
+
return found
|
|
171
|
+
frames = getattr(page, "frames", ())
|
|
172
|
+
frames = frames if isinstance(frames, (list, tuple)) else ()
|
|
173
|
+
for name, matches in _WIDGET_FRAMES:
|
|
174
|
+
if manual_only and name == "Turnstile":
|
|
175
|
+
continue
|
|
176
|
+
for frame in frames:
|
|
177
|
+
url = str(getattr(frame, "url", "") or "")
|
|
178
|
+
# reCAPTCHA v3's badge is a frame too, on ordinary pages.
|
|
179
|
+
if not matches(url) or "size=invisible" in url:
|
|
180
|
+
continue
|
|
181
|
+
try:
|
|
182
|
+
with call_limit(READ_LIMIT_SEC):
|
|
183
|
+
if frame.frame_element().is_visible() is True:
|
|
184
|
+
return name
|
|
185
|
+
except CallAbandoned:
|
|
186
|
+
continue
|
|
187
|
+
except Error as exc:
|
|
188
|
+
if not any(text in str(exc).lower() for text in _NAVIGATED):
|
|
189
|
+
raise
|
|
190
|
+
return ""
|
|
109
191
|
|
|
110
192
|
|
|
111
193
|
def has_visible_recaptcha(page: Any) -> bool:
|
|
@@ -37,7 +37,7 @@ pdf_captured saved_pending_verification route_failed access_ready
|
|
|
37
37
|
""".split())
|
|
38
38
|
_EVENTS = frozenset("""
|
|
39
39
|
aps_institution_entry_missing article_access_ready article_open browser_closed login_only_done
|
|
40
|
-
carsi_school_list_unconfirmed
|
|
40
|
+
carsi_school_list_unconfirmed unknown_page_attention unknown_page_check_error
|
|
41
41
|
auth_wall_after_article_load auth_wall_after_pdf_attempt browser_capture_detach_error
|
|
42
42
|
browser_capture_disable_error browser_pdf_response_captured browser_pdf_response_error
|
|
43
43
|
browser_response_continue_error browser_response_discard_error challenge_manual_wait
|
|
@@ -238,7 +238,7 @@ class PublisherBatchDownloader(
|
|
|
238
238
|
self._wait_for_page_text(page, result)
|
|
239
239
|
if self._challenge_shell(page) or self._is_challenge_page(page):
|
|
240
240
|
continue
|
|
241
|
-
links = self._settled_supplement_links(page, doi)
|
|
241
|
+
links = self._settled_supplement_links(page, doi, result)
|
|
242
242
|
if not (self._challenge_shell(page) or self._is_challenge_page(page)):
|
|
243
243
|
break
|
|
244
244
|
self._snapshot(page, result, "supplements page")
|
|
@@ -311,15 +311,25 @@ class PublisherBatchDownloader(
|
|
|
311
311
|
except Exception:
|
|
312
312
|
pass
|
|
313
313
|
|
|
314
|
-
def _settled_supplement_links(self, page: Any, doi: str) -> Any:
|
|
314
|
+
def _settled_supplement_links(self, page: Any, doi: str, result: Any = None) -> Any:
|
|
315
315
|
"""The adapter's links once the page has stopped navigating (ScienceDirect
|
|
316
|
-
moves /pii/ to /abs/pii/ by script after the document has loaded).
|
|
316
|
+
moves /pii/ to /abs/pii/ by script after the document has loaded). A site
|
|
317
|
+
without a rule of its own gets the shared one (``page_supplements``); a
|
|
318
|
+
Figshare resource set aside is recorded on ``result``, not returned."""
|
|
317
319
|
for attempt in range(3):
|
|
318
320
|
try:
|
|
319
321
|
from ..adapters.platforms.figshare import supplement_links as external_links
|
|
322
|
+
from .page_supplements import listed_files
|
|
320
323
|
|
|
321
324
|
own = self.adapter.supplement_links(page, doi)
|
|
325
|
+
if own is None:
|
|
326
|
+
own = listed_files(page, doi) or None
|
|
322
327
|
external = external_links(page, doi)
|
|
328
|
+
if result is not None:
|
|
329
|
+
for link in external or ():
|
|
330
|
+
if link.set_aside:
|
|
331
|
+
self._event(result, "supplements_set_aside", f"{link.set_aside} {link.url}")
|
|
332
|
+
external = [link for link in external or () if not link.set_aside] or None
|
|
323
333
|
if own is None and external is None:
|
|
324
334
|
from ..adapters.platforms.silverchair import declares_no_supplements
|
|
325
335
|
|
|
@@ -106,11 +106,68 @@ class UserRequestsMixin:
|
|
|
106
106
|
activity = getattr(result, "_page_activity", None)
|
|
107
107
|
owned = activity is None or activity.closed
|
|
108
108
|
if owned:
|
|
109
|
+
from ..browser import watchdog
|
|
110
|
+
|
|
109
111
|
result._page_activity = activity = PageActivity(result.doi, self.config)
|
|
112
|
+
watched = activity
|
|
113
|
+
watched.on_idle = lambda: watchdog.run_soon(lambda: self._remind_on_unknown_page(watched, result))
|
|
110
114
|
if page is not None:
|
|
111
115
|
activity.observe(page)
|
|
112
116
|
return activity, owned
|
|
113
117
|
|
|
118
|
+
UNKNOWN_PAGE_NOTICE = "页面可能需要你处理,请查看浏览器窗口"
|
|
119
|
+
# Something to click on a short page that is not an article or a PDF: a prompt the
|
|
120
|
+
# program does not know (an unrecognised verification). The longest such page.
|
|
121
|
+
_UNKNOWN_PAGE_TEXT = 2000
|
|
122
|
+
_UNKNOWN_PAGE_CONTROL_JS = r"""(longest) => {
|
|
123
|
+
if (document.contentType === 'application/pdf'
|
|
124
|
+
|| document.querySelector('meta[name="citation_doi"], meta[name="citation_title"]')) return '';
|
|
125
|
+
if ((document.body?.innerText || '').trim().length > longest) return '';
|
|
126
|
+
const shown = el => { const r = el.getBoundingClientRect(), s = getComputedStyle(el);
|
|
127
|
+
return r.width >= 12 && r.height >= 12 && s.visibility !== 'hidden' && s.display !== 'none'; };
|
|
128
|
+
const control = [...document.querySelectorAll(
|
|
129
|
+
'input[type=checkbox], [role=checkbox], iframe, canvas, button, [role=button], input[type=submit]')]
|
|
130
|
+
.find(el => shown(el) && (el.tagName !== 'IFRAME' || el.getBoundingClientRect().height >= 30));
|
|
131
|
+
if (!control) return '';
|
|
132
|
+
const kind = control.getAttribute('role') || control.tagName.toLowerCase();
|
|
133
|
+
const label = (control.innerText || control.value || control.getAttribute('aria-label') || control.title || '').trim();
|
|
134
|
+
return (kind + (label ? ' "' + label.slice(0, 40) + '"' : '')).slice(0, 80);
|
|
135
|
+
}"""
|
|
136
|
+
|
|
137
|
+
def _remind_on_unknown_page(self, activity: PageActivity, result: DownloadResult) -> None:
|
|
138
|
+
"""On the browser thread, after ``browser_stall_notify_after`` seconds without
|
|
139
|
+
progress: a page the program does not know, short and with something to click,
|
|
140
|
+
asks the user to look (an unrecognised verification; the user, 2026-11-11).
|
|
141
|
+
Recognised verification and the school's login remind the user themselves; an
|
|
142
|
+
article, a PDF or a long page asks nothing, and the program's own steps count as
|
|
143
|
+
progress (2026-11-06). A reminder is optional: a failed look never ends the article."""
|
|
144
|
+
from ..browser import watchdog
|
|
145
|
+
|
|
146
|
+
if activity.closed or not activity.stalled():
|
|
147
|
+
return
|
|
148
|
+
page = activity.page
|
|
149
|
+
if page is None or progress_reporter.has_attention(current=result.doi, excluding=activity.key):
|
|
150
|
+
return
|
|
151
|
+
try:
|
|
152
|
+
if page.is_closed() or self._is_challenge_page(page) or self._users_login_step(page):
|
|
153
|
+
return
|
|
154
|
+
url = str(getattr(page, "url", "") or "")
|
|
155
|
+
with watchdog.call_limit(5):
|
|
156
|
+
control = page.evaluate(self._UNKNOWN_PAGE_CONTROL_JS, self._UNKNOWN_PAGE_TEXT)
|
|
157
|
+
except watchdog.CallAbandoned:
|
|
158
|
+
return
|
|
159
|
+
except (watchdog.BrowserUnresponsive, UserMarkedNoEntitlement):
|
|
160
|
+
raise
|
|
161
|
+
except Exception as exc:
|
|
162
|
+
if exc is watchdog.interrupted:
|
|
163
|
+
raise # the window's skip or stop: it ends the article, not this look
|
|
164
|
+
first = str(exc).splitlines()[0][:160] if str(exc) else ""
|
|
165
|
+
self._event(result, "unknown_page_check_error", f"{type(exc).__name__}: {first}")
|
|
166
|
+
return
|
|
167
|
+
if isinstance(control, str) and control:
|
|
168
|
+
self._event(result, "unknown_page_attention", f"{control} @ {url[:160]}")
|
|
169
|
+
activity.remind(self.UNKNOWN_PAGE_NOTICE)
|
|
170
|
+
|
|
114
171
|
def _show_download_browser(self, page: Any, result: DownloadResult) -> None:
|
|
115
172
|
"""Focus the existing task page only after the user requests it."""
|
|
116
173
|
from ..browser import watchdog
|
|
@@ -425,6 +425,10 @@ class UserWaitMixin:
|
|
|
425
425
|
if activity is not None:
|
|
426
426
|
activity.automatic_for(automatic_end - now)
|
|
427
427
|
if challenge_interaction.needs_manual_verification(page):
|
|
428
|
+
widget = challenge_interaction.verification_widget(page, manual_only=True)
|
|
429
|
+
if widget and not attempt.get("widget"):
|
|
430
|
+
attempt["widget"] = widget # whose widget the user is asked to complete
|
|
431
|
+
self._event(result, "challenge_observation", f"manual widget: {widget}")
|
|
428
432
|
return False
|
|
429
433
|
if ((attempt["attempts"] >= 3 and now >= attempt["retry_at"])
|
|
430
434
|
or (attempt.get("unavailable") and now >= attempt["handoff_at"])):
|
|
@@ -607,4 +611,12 @@ class UserWaitMixin:
|
|
|
607
611
|
title = self._title(page)
|
|
608
612
|
return (challenges.has_challenge_text(title, self._body_text(page, 1_200))
|
|
609
613
|
or (challenges.continues_manual_challenge(title)
|
|
610
|
-
and challenge_interaction.is_image_verification(page))
|
|
614
|
+
and challenge_interaction.is_image_verification(page))
|
|
615
|
+
or self._verification_widget_page(page))
|
|
616
|
+
|
|
617
|
+
def _verification_widget_page(self, page: Any) -> bool:
|
|
618
|
+
"""Another provider's verification widget makes up the page (reCAPTCHA, hCaptcha,
|
|
619
|
+
sliders; ``challenge_interaction.verification_widget``). Not on the school's own
|
|
620
|
+
sign-in, where a captcha is part of the login the user does."""
|
|
621
|
+
host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
|
|
622
|
+
return not self._is_idp_host(host) and bool(challenge_interaction.verification_widget(page))
|
|
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|
|
15
15
|
import html
|
|
16
16
|
import json
|
|
17
17
|
import re
|
|
18
|
+
import shutil
|
|
18
19
|
import time
|
|
19
20
|
from pathlib import Path
|
|
20
21
|
from typing import Any
|
|
@@ -60,6 +61,17 @@ _FAILURE_KINDS = {
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
|
|
64
|
+
def _move_into_place(src: Path, output_path: Path) -> None:
|
|
65
|
+
"""Put a captured PDF at ``output_path``. The backend saves it in its run folder
|
|
66
|
+
first, which is in PaperSearch's own data (since 0.5.13) and can sit on another
|
|
67
|
+
drive than the download folder: a rename cannot cross drives (WinError 17, Windows
|
|
68
|
+
with D:\\Downloads, 2026-11-11), so the file is moved, copied when it must."""
|
|
69
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
if output_path.exists():
|
|
71
|
+
output_path.unlink()
|
|
72
|
+
shutil.move(str(src), str(output_path))
|
|
73
|
+
|
|
74
|
+
|
|
63
75
|
def _remember_blocked_journal(doi: str, identity: dict[str, Any]) -> None:
|
|
64
76
|
"""The journal whose site blocked the current network (``blocked_journals``)."""
|
|
65
77
|
from .. import blocked_journals
|
|
@@ -216,10 +228,7 @@ def _instsci_result_to_dict(result, doi: str, output_path: Path) -> dict[str, An
|
|
|
216
228
|
src = Path(paper.pdf_path)
|
|
217
229
|
if src.exists():
|
|
218
230
|
if src != output_path:
|
|
219
|
-
|
|
220
|
-
if output_path.exists():
|
|
221
|
-
output_path.unlink()
|
|
222
|
-
src.rename(output_path)
|
|
231
|
+
_move_into_place(src, output_path)
|
|
223
232
|
return {
|
|
224
233
|
"success": True, "identifier": doi, "doi": doi,
|
|
225
234
|
"file": str(output_path),
|
|
@@ -457,10 +466,7 @@ def _try_session_broker(
|
|
|
457
466
|
if pdf_path and Path(pdf_path).exists():
|
|
458
467
|
src = Path(pdf_path)
|
|
459
468
|
if src != output_path:
|
|
460
|
-
|
|
461
|
-
if output_path.exists():
|
|
462
|
-
output_path.unlink()
|
|
463
|
-
src.rename(output_path)
|
|
469
|
+
_move_into_place(src, output_path)
|
|
464
470
|
log.info(f" [Institutional] Session broker download succeeded")
|
|
465
471
|
return {
|
|
466
472
|
"success": True, "identifier": doi, "doi": doi,
|
|
@@ -630,10 +636,7 @@ def _try_browser_batch_download(
|
|
|
630
636
|
src = Path(result.pdf_path)
|
|
631
637
|
if src.exists():
|
|
632
638
|
if src != output_path:
|
|
633
|
-
|
|
634
|
-
if output_path.exists():
|
|
635
|
-
output_path.unlink()
|
|
636
|
-
src.rename(output_path)
|
|
639
|
+
_move_into_place(src, output_path)
|
|
637
640
|
result.pdf_path = str(output_path)
|
|
638
641
|
_note_supplements(result, len(getattr(result, "events", [])))
|
|
639
642
|
log.info(f" [Institutional] Browser download succeeded: {result.size_bytes:,} bytes")
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
"""Track idle owned pages without treating missing progress as a user action.
|
|
2
2
|
|
|
3
|
+
A quiet interval is handed to the downloader (``on_idle``): it looks at the page on
|
|
4
|
+
the browser thread and reminds the user (``remind``) only for a page it does not know
|
|
5
|
+
with something to click on it (the user, 2026-11-11). Silence alone asks nothing.
|
|
6
|
+
|
|
3
7
|
Main-document requests, navigation, a loaded document, a workflow step or
|
|
4
8
|
received file bytes refresh the timer. An in-flight navigation gets only the
|
|
5
9
|
existing page wait budget; polling and unrelated background traffic do not.
|
|
@@ -28,6 +32,11 @@ class PageActivity:
|
|
|
28
32
|
self._lock = threading.RLock()
|
|
29
33
|
self._doi = doi
|
|
30
34
|
self._reported = False
|
|
35
|
+
self.key = f"page-unknown:{id(self)}:{doi}"
|
|
36
|
+
self._shown = False
|
|
37
|
+
# Called with the lock held once a quiet interval has passed, from any thread
|
|
38
|
+
# and without a browser call: it may only schedule work (``watchdog.run_soon``).
|
|
39
|
+
self.on_idle: Any = None
|
|
31
40
|
self._transfers = 0
|
|
32
41
|
self._automatic_until = 0.0
|
|
33
42
|
self.closed = False
|
|
@@ -46,6 +55,9 @@ class PageActivity:
|
|
|
46
55
|
|
|
47
56
|
def _clear(self) -> None:
|
|
48
57
|
self._reported = False
|
|
58
|
+
if self._shown:
|
|
59
|
+
progress_reporter.clear_attention(self.key)
|
|
60
|
+
self._shown = False
|
|
49
61
|
|
|
50
62
|
def automatic_for(self, seconds: float) -> None:
|
|
51
63
|
"""Defer idle diagnostics until the caller's existing automatic deadline.
|
|
@@ -64,7 +76,7 @@ class PageActivity:
|
|
|
64
76
|
with self._lock:
|
|
65
77
|
if self.closed:
|
|
66
78
|
return
|
|
67
|
-
if progress_reporter.has_attention(current=self._doi):
|
|
79
|
+
if progress_reporter.has_attention(current=self._doi, excluding=self.key):
|
|
68
80
|
# School login and other explicit requests have priority. Start
|
|
69
81
|
# a fresh quiet interval when they finish rather than duplicating them.
|
|
70
82
|
self._last_progress = self._clock()
|
|
@@ -79,6 +91,23 @@ class PageActivity:
|
|
|
79
91
|
logging.getLogger(__name__).info("page_idle: no observed progress for %.0f seconds",
|
|
80
92
|
self._clock() - self._last_progress)
|
|
81
93
|
self._reported = True
|
|
94
|
+
if self.on_idle is not None:
|
|
95
|
+
self.on_idle()
|
|
96
|
+
|
|
97
|
+
def stalled(self) -> bool:
|
|
98
|
+
"""Still quiet for the whole interval: the downloader checks again before reminding."""
|
|
99
|
+
with self._lock:
|
|
100
|
+
return (not self.closed and not self._transfers and self._clock() >= self._automatic_until
|
|
101
|
+
and not self._navigation_loading() and self._clock() - self._last_progress >= self.after)
|
|
102
|
+
|
|
103
|
+
def remind(self, message: str) -> None:
|
|
104
|
+
"""Ask the user to look at the page; the downloader calls it after inspecting the
|
|
105
|
+
page. Progress, another reminder for this paper or the article's end clears it."""
|
|
106
|
+
with self._lock:
|
|
107
|
+
if self.closed or self._shown:
|
|
108
|
+
return
|
|
109
|
+
progress_reporter.set_attention(self.key, message, current=self._doi, phase="需要你操作")
|
|
110
|
+
self._shown = True
|
|
82
111
|
|
|
83
112
|
def _navigation_loading(self) -> bool:
|
|
84
113
|
pending = self._navigations.get(id(self.page))
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""The shared rule for a site without a supplementary-file rule of its own: the
|
|
2
|
+
files the article page itself lists as its supplementary material.
|
|
3
|
+
|
|
4
|
+
A link counts only inside the page's supplementary part (an element whose class
|
|
5
|
+
or id says so, or the part under a "Supplementary data", "Supplemental
|
|
6
|
+
material" or "Supporting information" heading), only when its address names this
|
|
7
|
+
article's DOI ("/" kept, or as "_") between two "/", and only when it ends in a
|
|
8
|
+
file name. The DOI in the address binds the file to this article; a page's links
|
|
9
|
+
to other articles, datasets or web pages are no files of it (the Journal of
|
|
10
|
+
Experimental Medicine's tables on its own CDN, 2026-11-11).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import unquote, urlparse
|
|
17
|
+
|
|
18
|
+
from ..adapters.base import SupplementLink
|
|
19
|
+
|
|
20
|
+
_SECTION_LINKS_JS = r"""() => {
|
|
21
|
+
const part = '[class*="suppl" i], [id*="suppl" i], [class*="datasupp" i], [class*="supporting" i], [id*="supporting" i]';
|
|
22
|
+
const heading = /^(?:online )?(?:supplementa(?:ry|l) (?:data|materials?|information|files?)|supporting information)$/i;
|
|
23
|
+
const headed = [...document.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')]
|
|
24
|
+
.filter(h => heading.test((h.textContent || '').replace(/\s+/g, ' ').trim()) && h.parentElement)
|
|
25
|
+
.map(h => h.parentElement);
|
|
26
|
+
return {
|
|
27
|
+
doi: document.querySelector('meta[name="citation_doi"]')?.content || '',
|
|
28
|
+
rows: [...document.querySelectorAll('a[href]')]
|
|
29
|
+
.filter(a => a.closest(part) || headed.some(p => p.contains(a)))
|
|
30
|
+
.map(a => ({href: a.href, label: (a.innerText || a.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 200)}))
|
|
31
|
+
};
|
|
32
|
+
}"""
|
|
33
|
+
# Addresses that end in a web page, not a file (figure slides are .aspx).
|
|
34
|
+
_WEB_PAGES = frozenset({"html", "htm", "xhtml", "shtml", "asp", "aspx", "php", "jsp", "cfm"})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def listed_files(page: Any, doi: str) -> list[SupplementLink]:
|
|
38
|
+
"""This article's files in its page's supplementary part (see the module); a
|
|
39
|
+
page that names another article in ``citation_doi`` lists none. A file linked
|
|
40
|
+
several times (signed addresses differ in their query) is taken once."""
|
|
41
|
+
doi = (doi or "").strip().lower()
|
|
42
|
+
data = page.evaluate(_SECTION_LINKS_JS)
|
|
43
|
+
if not doi or not isinstance(data, dict):
|
|
44
|
+
return []
|
|
45
|
+
page_doi = str(data.get("doi") or "").strip().lower()
|
|
46
|
+
if page_doi and page_doi != doi:
|
|
47
|
+
return []
|
|
48
|
+
forms = (f"/{doi}/", f"/{doi.replace('/', '_')}/")
|
|
49
|
+
links: list[SupplementLink] = []
|
|
50
|
+
seen: set[tuple[str, str]] = set()
|
|
51
|
+
rows = data.get("rows")
|
|
52
|
+
for row in rows if isinstance(rows, list) else ():
|
|
53
|
+
if not isinstance(row, dict):
|
|
54
|
+
continue
|
|
55
|
+
target = urlparse(str(row.get("href") or ""))
|
|
56
|
+
path = unquote(target.path)
|
|
57
|
+
name = path.rsplit("/", 1)[-1]
|
|
58
|
+
extension = name.rpartition(".")[2].lower() if "." in name else ""
|
|
59
|
+
if (target.scheme != "https" or not target.hostname or target.username or target.password
|
|
60
|
+
or not any(form in path.lower() for form in forms)
|
|
61
|
+
or not re.fullmatch(r"[a-z0-9]{1,5}", extension) or extension in _WEB_PAGES):
|
|
62
|
+
continue
|
|
63
|
+
key = (target.hostname.lower(), path)
|
|
64
|
+
if key not in seen:
|
|
65
|
+
seen.add(key)
|
|
66
|
+
links.append(SupplementLink(target._replace(fragment="").geturl(), str(row.get("label") or "")))
|
|
67
|
+
return links
|
|
@@ -376,8 +376,6 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
|
|
|
376
376
|
"title": str(state.get("title") or ""), "current": current,
|
|
377
377
|
"run_id": str(state.get("run_id") or ""),
|
|
378
378
|
"step": step, "steps": list(STEPS), "line": status_text(state, running) if running else "",
|
|
379
|
-
# What each lane got in a batch checking open access beside its downloads, on one line.
|
|
380
|
-
"lanes": str(state.get("lanes") or "") if running else "",
|
|
381
379
|
"elapsed": elapsed, "attention": prompt, "notice": notice,
|
|
382
380
|
"completion_detail": str(state.get("phase") or "")
|
|
383
381
|
if not running and state.get("stage") == "supplements_checked" else "",
|
|
@@ -23,7 +23,7 @@ class Field:
|
|
|
23
23
|
FIELDS = (
|
|
24
24
|
Field("login", "学校登录页最多等", "browser_login_timeout", 180, 30, 1800, "秒", "wait"),
|
|
25
25
|
Field("page", "其他页面最多等", "browser_page_wait_timeout", 60, 10, 600, "秒", "wait"),
|
|
26
|
-
Field("stalled", "
|
|
26
|
+
Field("stalled", "提醒你操作前最多等", "browser_stall_notify_after", 30, 1, 600, "秒", "wait"),
|
|
27
27
|
Field("hourly", "每家出版社每小时最多", "publisher_hourly_limit", 100, 0, 1000, "篇", "download"),
|
|
28
28
|
)
|
|
29
29
|
|
|
@@ -18,7 +18,7 @@ export const CARSI_DOWNLOAD_TIMEOUT_MS = 1_200_000;
|
|
|
18
18
|
export const CARSI_CLEANUP_TIMEOUT_MS = 5_000;
|
|
19
19
|
const CARSI_BACKEND_SOURCE = "carsi";
|
|
20
20
|
// MCP clientInfo is informational only; keep in step with package.json on release.
|
|
21
|
-
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.5.
|
|
21
|
+
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.5.15";
|
|
22
22
|
const NO_BATCH_SUPPORT = {
|
|
23
23
|
downloadFields: false,
|
|
24
24
|
supplementsField: false,
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@ description: |
|
|
|
4
4
|
用本机 paper-search 命令做文献工作:检索论文、核对 DOI/PMID、搜正文片段(找方法和结果的原文)、查期刊影响因子与分区、查施引和参考文献、下载全文和补充材料。
|
|
5
5
|
用户要找文献、查期刊、下载论文,或说“请开始配置”时使用;英文请求(literature search、journal metrics、paper download、start setup)同样适用。
|
|
6
6
|
metadata:
|
|
7
|
-
version: "0.5.
|
|
7
|
+
version: "0.5.15"
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
# 文献检索与下载(paper-search)
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
- 机构下载一次一篇,开放渠道同时查后面的篇目。遇到学校登录或验证时停在这一篇;出现人工处理提示后,提醒用户到下载浏览器操作。等待时限:停在学校登录页(以及没配置学校、要用户自己选学校的页面)最多 3 分钟(后端配置 `browser_login_timeout`,秒);停在其他页面(人机验证、出版社页面、选机构页、取 PDF 时等待处理)连续超过 1 分钟就结束这一篇(`browser_page_wait_timeout`)。两项都能在进度窗口右上角的设置(齿轮)里改,从下一篇起生效。学校统一认证登录一次后,其余篇目通常自动通过。一篇等满时限后(日志写“这一篇等你登录或验证已到时限”),后面每篇只等 60 秒;用户在登录框输入时照常等。
|
|
21
21
|
- 每个出版社每小时最多打开 100 篇(后端配置 `publisher_hourly_limit`,0 为不限)。到上限时批量等到可以继续再下这一篇(日志写明时间);单篇返回 `rate_limited`,稍后再试。
|
|
22
22
|
- 出版社网站拦截了当前网络(`access_blocked`,如 Cloudflare 拦截页)时这一篇结束;同一期刊 30 分钟内的其他文章直接跳过(`journal_blocked_earlier`),其他期刊照常继续。告诉用户可能是当前网络被网站防护拦截,也可能是下载过多被暂停:可换网络或稍后再试,后者请联系学校图书馆。
|
|
23
|
-
- 后端会先短暂等待自动验证,每次验证等待对可识别的 Turnstile 复选框最多尝试点击 3 次,两次至少间隔 3 秒;程序提示人工处理时,再提醒用户到下载浏览器接管,不因 `checking_access`
|
|
23
|
+
- 后端会先短暂等待自动验证,每次验证等待对可识别的 Turnstile 复选框最多尝试点击 3 次,两次至少间隔 3 秒;程序提示人工处理时,再提醒用户到下载浏览器接管,不因 `checking_access` 就要求用户操作。学校登录、二次验证和复杂验证码由用户完成(reCAPTCHA、hCaptcha、滑块等验证页,程序认出后直接交给用户);学校认证页的信息发送同意和使用条款、出版社登录途中的条款确认页由后端代点同意(每篇各最多两次,仍停在那一页时才提醒用户)。不索取账号、密码或验证码,agent 不另开浏览器代操作。
|
|
24
24
|
- 在专用人工登录页输入、选择或点击控件,或点击胶囊接管登录后,暂停剩余学校登录预算;输入间停顿不算离开,离开该人工步骤后恢复计时。无人操作仍按原限时结束。不要询问用户的账号密码。用户在登录页中途停下(比如去拿手机验证码)时继续等,按原来的时限算,不重新发起登录。
|
|
25
|
-
-
|
|
25
|
+
- 学校登录提醒依赖当前可见的账号、密码、二次验证码、二维码,或后端没能代点的同意步骤;学校域名和空闲时间不作为人工操作证据。胶囊“提醒你操作前最多等”仍保存到 `browser_stall_notify_after`(默认 30 秒,1–600);可见验证控件无法自动操作时,按该值与剩余预算一半的较早者交接。控件仍在加载、已勾选处理中或尚未出现时继续自动观察。未派发点击不消耗最多 3 次输入额度;失败原因见 `challenge_observation`。明确网站封禁和预算耗尽仍结束当前路径,不保证所有验证码自动通过。程序认不出的页面停住达到这个时长、页面上又有可点的控件时,也会提醒“页面可能需要你处理”,同样请用户到下载浏览器看一眼。
|
|
26
26
|
- 通用 Human Verification 图片验证页会等待 Begin 之后的后续步骤。用户在专用验证页操作或通过胶囊接管后,人工阶段暂停剩余验证及文章等待预算;成功离开验证后继续自动流程。未操作时仍按原时限结束,外层任务资源限制不变。
|
|
27
27
|
- 阶段以本次调用的结构化通知为准(命令写在 stderr,stdout 只有最终 JSON);不凭等待时间猜阶段。
|
|
28
28
|
- PDF 在新标签页打开不等于已保存;以命令的最终结果为准,网页地址不是本地文件。
|
|
@@ -113,7 +113,7 @@ paper-search failures --run <运行ID> --doi <DOI> --export ./failure-report.zip
|
|
|
113
113
|
|
|
114
114
|
- `download_with_fallback` / `download_batch` 的 `content`:`main`(默认,只要正文)、`supplements`(只要补充材料,不走正文的各层)、`both`(正文和补充材料)。
|
|
115
115
|
- 补充材料只经学校订阅下载的浏览器取得:正文由开放渠道拿到时,`both` 会再请它单独取补充材料;它没装或没启用时,这一步记为 `skipped`,写明没有可用的后端。
|
|
116
|
-
- 哪些出版社有补充材料规则见 `publisher-support.md`。完成检查但页面未列出附件时返回空 `supplements`,attempt 为 `skipped/no_supplements`;只取补充材料时整体 `status=ok
|
|
116
|
+
- 哪些出版社有补充材料规则见 `publisher-support.md`。完成检查但页面未列出附件时返回空 `supplements`,attempt 为 `skipped/no_supplements`;只取补充材料时整体 `status=ok`,表示检查完成,不表示保存了文件。这家网站没有补充材料专门规则时先按通用规则取文章页补充材料区块里地址带本文 DOI 的文件,仍没有找到时 attempt 为 `skipped/supplements_not_supported`,整体仍为 `ok`:不知道有没有附件,告诉用户“网站暂不支持自动下载附录”,需要的话打开文章页手动下载,不要说成没有附录。登录未完成(`login_required`)、验证未完成(`challenge_timeout`)、网站的人机验证页挡住了附件下载(`verification_page`,如 Figshare)、拿到网页而不是文件(`html_page`)与其他下载失败分别报告,只取补充材料时为 `error`,不影响已保存正文。
|
|
117
117
|
- 文件存在 `<savePath>/<期刊_年份_标题_短标识>/supplements/`,正文也移进这个文件夹;没取到附件的论文,正文平铺在 `<savePath>` 里;`…_supplements-manifest.json` 记录每个文件的状态(`saved`、`failed`、`skipped`)和原因,在结果 `runLog` 所指的运行记录目录里:有文件没下到时在 `diagnostics/`,都下到时在 `records/`;结果里的 `supplements` 给出实际文件路径。
|
|
118
118
|
- 上限:每篇最多 50 个文件,每个不超过 200 MB,一篇总共 3 分钟;超出的记 `skipped`(原因 `file_limit`、`too_large`、`time_budget`)。`html_page` 表示链接打开的是网页而不是文件,`http_403` 一类是网站拒绝。
|
|
119
119
|
- 只收本文的文件:别的文章的文件、本文的插图、参考文献里的链接都不收。Figshare 公开 article/collection 链接按原文 DOI 关联后解析文件;其他外部附件平台仍需适配。
|
|
@@ -163,7 +163,7 @@ paper-search run download_with_fallback --json-args '{"source":"crossref","paper
|
|
|
163
163
|
|
|
164
164
|
一组论文(几十到几百篇)用一次按顺序执行的 `download_batch`,不要循环调用单篇下载:
|
|
165
165
|
|
|
166
|
-
- `"mode"`:默认 `"two_phase"`,每篇先试开放渠道,没拿到的随即走机构下载(一次一篇),两路同时进行,浏览器和学校登录在开始后几秒就出现;进度窗口按整批计数(k / N),装了学校订阅下载时,5
|
|
166
|
+
- `"mode"`:默认 `"two_phase"`,每篇先试开放渠道,没拿到的随即走机构下载(一次一篇),两路同时进行,浏览器和学校登录在开始后几秒就出现;进度窗口按整批计数(k / N),装了学校订阅下载时,5 篇以上的批量从开头就显示;`"per_item"` 每篇走完整个漏斗;`"entitled_only"` 跳过开放渠道,每篇直接走机构下载(用于测试学校这条路)。
|
|
167
167
|
- 不传 `savePath` 时存到 `DEFAULT_DOWNLOAD_PATH`;整批或每篇都可以带自己的 `savePath`,用户指定了别的文件夹时才传。
|
|
168
168
|
- `"content"`:`"main"`(默认,只要正文)、`"supplements"`(只要本文的补充材料,不走正文的各层)、`"both"`。补充材料存在 `<savePath>/<期刊_年份_标题_短标识>/supplements/`(只下正文时正文直接放在 `<savePath>` 里),清单与浏览器诊断在结果 `runLog` 所指运行记录目录的 `diagnostics/`(都下到时在 `records/`),结果的 `supplements` 列出每个文件的状态;只经机构下载后端获取,哪些出版社有规则见 `publisher-support.md`。
|
|
169
169
|
- 每次下载都会写一份本地运行记录,结果里的 `runLog` 是它的目录(`run.json`;`items.jsonl`,含每一层的耗时、代码,以及后端的页面事件和截图;`timeline.log`)。排查失败时读它,不要猜。结果列出每一篇和它的各次尝试。
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
- 程序按 DOI 实际跳转到的网站判断属于哪一行。DOI 前缀只是线索,期刊换了出版社时前缀不变(例如 ARD 的 `10.1136` 文章现在在 Elsevier)。
|
|
7
7
|
- 用户问“某本期刊能不能下”:先按这张表说明程序能不能走通,再说明学校订阅要以实际下载为准;不要凭这张表断定学校有或没有权限。
|
|
8
8
|
|
|
9
|
-
符号:✓ 实测取得;✓OA 只实测过开放获取文章;○ 已有规则,尚无文件下载成功记录;—
|
|
9
|
+
符号:✓ 实测取得;✓OA 只实测过开放获取文章;○ 已有规则,尚无文件下载成功记录;— 没有补充材料专门规则:按通用规则取文章页补充材料区块里地址带本文 DOI 的文件,取不到时返回 `supplements_not_supported`,正文不受影响。
|
|
10
10
|
|
|
11
11
|
## 有专门规则的出版社
|
|
12
12
|
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
| Frontiers | frontiersin.org | `10.3389` | ✓OA | ✓ |
|
|
49
49
|
| PLOS、Copernicus | 各自网站 | `10.1371`、`10.5194` | ✓ | ✓ |
|
|
50
50
|
|
|
51
|
-
AIP、Optica、Royal Society 的补充材料在 Figshare 上,程序按文章页上的 Figshare 链接取文件。页面没有 Figshare 链接时:AIP 页面标明没有补充材料的,返回空清单;Optica 返回 `supplements_not_supported`,不说明这篇有没有附件。
|
|
51
|
+
AIP、Optica、Royal Society 的补充材料在 Figshare 上,程序按文章页上的 Figshare 链接取文件。页面没有 Figshare 链接时:AIP 页面标明没有补充材料的,返回空清单;Optica 返回 `supplements_not_supported`,不说明这篇有没有附件。Figshare 上的资源既没有标明属于这篇、文章页上的链接也不是“补充材料”字样时(只在数据可用性声明里提到的数据集),不下载,也不算补充材料失败。
|
|
52
52
|
|
|
53
53
|
## 没有专门规则的网站
|
|
54
54
|
|