papersearch 0.4.9 → 0.4.11
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/LICENSE +1 -1
- package/NOTICE +23 -0
- package/README.en.md +136 -247
- package/README.md +136 -247
- package/assets/carsi-flow.en.png +0 -0
- package/assets/carsi-flow.png +0 -0
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/README.md +6 -7
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/iop/__init__.py +8 -2
- package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
- package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
- package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
- package/carsi/paper_search_carsi/assets/capsule.html +134 -18
- package/carsi/paper_search_carsi/browser/backend.py +269 -233
- package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
- package/carsi/paper_search_carsi/browser/cookies.py +8 -8
- package/carsi/paper_search_carsi/browser/driver.py +29 -0
- package/carsi/paper_search_carsi/browser/engine.py +17 -23
- package/carsi/paper_search_carsi/browser/foreground.py +21 -15
- package/carsi/paper_search_carsi/browser/login.py +12 -18
- package/carsi/paper_search_carsi/browser/preview.py +31 -12
- package/carsi/paper_search_carsi/browser/profiles.py +16 -23
- package/carsi/paper_search_carsi/browser/watchdog.py +113 -58
- package/carsi/paper_search_carsi/cli.py +22 -7
- package/carsi/paper_search_carsi/cold_start.py +65 -51
- package/carsi/paper_search_carsi/config.py +6 -4
- package/carsi/paper_search_carsi/download_diagnostics.py +2 -1
- package/carsi/paper_search_carsi/engine/batch.py +17 -7
- package/carsi/paper_search_carsi/engine/batch_capture.py +97 -31
- package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
- package/carsi/paper_search_carsi/engine/batch_institution.py +132 -13
- package/carsi/paper_search_carsi/engine/batch_login.py +151 -18
- package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
- package/carsi/paper_search_carsi/engine/bridge.py +23 -13
- package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
- package/carsi/paper_search_carsi/engine/supplements.py +36 -2
- package/carsi/paper_search_carsi/mcp_progress.py +13 -5
- package/carsi/paper_search_carsi/network.py +1 -1
- package/carsi/paper_search_carsi/progress_capsule.py +6 -2
- package/carsi/paper_search_carsi/progress_reporter.py +107 -9
- package/carsi/paper_search_carsi/progress_view.py +78 -1
- package/carsi/paper_search_carsi/server.py +53 -10
- package/carsi/paper_search_carsi/session_broker.py +1 -1
- package/carsi/pyproject.toml +7 -7
- package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
- package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
- package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +59 -14
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts +28 -0
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js +155 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +56 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +11 -4
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +114 -30
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +6 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +12 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts +48 -0
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.js +11 -6
- package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
- package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
- package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
- package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
- package/dist/cli.js +30 -15
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +28 -2
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/config/apiKeySignup.d.ts +13 -0
- package/dist/config/apiKeySignup.d.ts.map +1 -0
- package/dist/config/apiKeySignup.js +32 -0
- package/dist/config/apiKeySignup.js.map +1 -0
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +4 -0
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/management/capability-profile/index.d.ts +7 -0
- package/dist/management/capability-profile/index.d.ts.map +1 -1
- package/dist/management/capability-profile/index.js +7 -0
- package/dist/management/capability-profile/index.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +26 -14
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +118 -74
- package/dist/management/carsi/installer.js.map +1 -1
- package/dist/management/carsi/runtime.d.ts +12 -1
- package/dist/management/carsi/runtime.d.ts.map +1 -1
- package/dist/management/carsi/runtime.js +30 -1
- package/dist/management/carsi/runtime.js.map +1 -1
- package/dist/management/diagnostics/index.d.ts.map +1 -1
- package/dist/management/diagnostics/index.js +4 -1
- package/dist/management/diagnostics/index.js.map +1 -1
- package/dist/management/failures/exportReport.js +3 -3
- package/dist/management/reports/index.d.ts.map +1 -1
- package/dist/management/reports/index.js +6 -1
- package/dist/management/reports/index.js.map +1 -1
- package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
- package/dist/platforms/SemanticScholarSearcher.js +2 -1
- package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
- package/package.json +3 -2
- package/skills/paper-search/SKILL.md +9 -9
- package/skills/paper-search/references/browser-download.md +7 -6
- package/skills/paper-search/references/capability-routing.md +3 -3
- package/skills/paper-search/references/carsi-setup.md +8 -7
- package/skills/paper-search/references/cli-contract.md +6 -6
- package/skills/paper-search/references/management-layer.md +3 -3
- package/skills/paper-search/references/publisher-support.md +2 -0
- package/skills/paper-search/references/troubleshooting.md +1 -2
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
- package/carsi/paper_search_carsi/browser/background.py +0 -68
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""End an item whose browser call never returns.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
|
|
3
|
+
A driver call can wait forever for an answer (2026-10-31, on the earlier
|
|
4
|
+
Firefox-based browser, after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
|
|
5
5
|
waits for its 20-minute item timeout. Every sync Playwright call is timed
|
|
6
6
|
here; one still running after ``LIMIT_SEC`` is logged with its caller and
|
|
7
7
|
cancelled, and it and every later browser call of this process raise
|
|
@@ -33,8 +33,10 @@ log = logging.getLogger(__name__)
|
|
|
33
33
|
# timeout); waits for the user are made of short calls.
|
|
34
34
|
LIMIT_SEC = 90
|
|
35
35
|
|
|
36
|
-
_inflight: dict[int, tuple[float, str, list[str], Any, Any]] = {}
|
|
36
|
+
_inflight: dict[int, tuple[float, str, list[str], Any, Any, Any]] = {}
|
|
37
37
|
_call_deadlines: dict[int, tuple[float, str]] = {}
|
|
38
|
+
# Calls dropped by :func:`abandon`: they end in :class:`CallAbandoned`.
|
|
39
|
+
_abandoned: set[int] = set()
|
|
38
40
|
_local = threading.local()
|
|
39
41
|
_installed = False
|
|
40
42
|
# A browser call longer than this is reported to ``on_slow_call(name, seconds,
|
|
@@ -66,6 +68,54 @@ class BrowserOperationTimeout(BrowserUnresponsive):
|
|
|
66
68
|
"""The whole page operation exhausted its budget across browser calls."""
|
|
67
69
|
|
|
68
70
|
|
|
71
|
+
class BrowserBudgetExhausted(BrowserOperationTimeout):
|
|
72
|
+
"""No time remained to send another call; the driver did not stall."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CallAbandoned(Exception):
|
|
76
|
+
"""A call whose answer is no longer wanted (:func:`abandon`)."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _greenlet() -> Any:
|
|
80
|
+
"""The greenlet making a call: the driver runs each event handler in its own."""
|
|
81
|
+
try:
|
|
82
|
+
from greenlet import getcurrent
|
|
83
|
+
except ImportError:
|
|
84
|
+
return None
|
|
85
|
+
return getcurrent()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@contextmanager
|
|
89
|
+
def owned_by(owners: set):
|
|
90
|
+
"""Mark the calls this greenlet makes meanwhile as ``owners``' (see :func:`abandon`)."""
|
|
91
|
+
me = _greenlet()
|
|
92
|
+
owners.add(me)
|
|
93
|
+
try:
|
|
94
|
+
yield
|
|
95
|
+
finally:
|
|
96
|
+
owners.discard(me)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def abandon(owners: set) -> int:
|
|
100
|
+
"""Cancel the running calls of these greenlets without ending the browser: their
|
|
101
|
+
answer is no longer wanted. A response read in an event handler that never
|
|
102
|
+
returned was otherwise timed out 90 s later, and the article running then
|
|
103
|
+
(JAMA after AIAA's blocked PDF, 2026-11-08) ended as browser_unresponsive.
|
|
104
|
+
Returns how many were cancelled."""
|
|
105
|
+
count = 0
|
|
106
|
+
for key, entry in list(_inflight.items()):
|
|
107
|
+
if entry[5] is None or entry[5] not in owners:
|
|
108
|
+
continue
|
|
109
|
+
_abandoned.add(key)
|
|
110
|
+
_inflight.pop(key, None)
|
|
111
|
+
_call_deadlines.pop(key, None)
|
|
112
|
+
loop, coro = entry[3], entry[4]
|
|
113
|
+
if loop is not None and not loop.is_closed():
|
|
114
|
+
loop.call_soon_threadsafe(_cancel, coro)
|
|
115
|
+
count += 1
|
|
116
|
+
return count
|
|
117
|
+
|
|
118
|
+
|
|
69
119
|
@contextmanager
|
|
70
120
|
def operation(seconds: float, label: str):
|
|
71
121
|
"""One monotonic deadline shared by all calls and retries in this scope."""
|
|
@@ -111,65 +161,70 @@ def _timeout_error() -> BrowserUnresponsive:
|
|
|
111
161
|
|
|
112
162
|
|
|
113
163
|
def install(limit_sec: float = LIMIT_SEC) -> None:
|
|
114
|
-
"""Time every sync
|
|
164
|
+
"""Time every sync driver call of this process (once)."""
|
|
115
165
|
global _installed
|
|
116
166
|
if _installed:
|
|
117
167
|
return
|
|
118
|
-
from
|
|
119
|
-
|
|
120
|
-
original
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if fired is not None:
|
|
125
|
-
coro.close()
|
|
126
|
-
raise _timeout_error()
|
|
127
|
-
if interrupted is not None:
|
|
128
|
-
coro.close()
|
|
129
|
-
raise interrupted
|
|
130
|
-
if _soon and not _running_soon:
|
|
131
|
-
try:
|
|
132
|
-
_run_soon_calls()
|
|
133
|
-
except BaseException:
|
|
134
|
-
coro.close()
|
|
135
|
-
raise
|
|
136
|
-
key = id(coro)
|
|
137
|
-
started = time.monotonic()
|
|
138
|
-
_inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
|
|
139
|
-
getattr(self, "_loop", None), coro)
|
|
140
|
-
budgets = getattr(_local, "budgets", [])
|
|
141
|
-
if budgets:
|
|
142
|
-
_call_deadlines[key] = tuple(min(budgets, key=lambda budget: budget[0]))
|
|
143
|
-
ended = "returned"
|
|
144
|
-
try:
|
|
145
|
-
# Refuse to start another candidate after the shared budget expired.
|
|
146
|
-
if key in _call_deadlines and started >= _call_deadlines[key][0]:
|
|
147
|
-
check(limit_sec)
|
|
168
|
+
from .driver import sync_bases
|
|
169
|
+
|
|
170
|
+
def timing(original: Any) -> Any:
|
|
171
|
+
def timed_sync(self: Any, coro: Any) -> Any:
|
|
172
|
+
name = getattr(coro, "__qualname__", "") or type(coro).__name__
|
|
173
|
+
if fired is not None:
|
|
148
174
|
coro.close()
|
|
149
175
|
raise _timeout_error()
|
|
150
|
-
return original(self, coro)
|
|
151
|
-
except asyncio.CancelledError:
|
|
152
|
-
ended = "cancelled"
|
|
153
|
-
if fired is not None:
|
|
154
|
-
raise _timeout_error() from None
|
|
155
176
|
if interrupted is not None:
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
if
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
177
|
+
coro.close()
|
|
178
|
+
raise interrupted
|
|
179
|
+
if _soon and not _running_soon:
|
|
180
|
+
try:
|
|
181
|
+
_run_soon_calls()
|
|
182
|
+
except BaseException:
|
|
183
|
+
coro.close()
|
|
184
|
+
raise
|
|
185
|
+
key = id(coro)
|
|
186
|
+
started = time.monotonic()
|
|
187
|
+
budgets = getattr(_local, "budgets", [])
|
|
188
|
+
if budgets:
|
|
189
|
+
deadline, label = min(budgets, key=lambda budget: budget[0])
|
|
190
|
+
# An unsent call cannot indicate a stalled driver. Keep the browser
|
|
191
|
+
# usable outside this operation, including cleanup and the next item.
|
|
192
|
+
if started >= deadline:
|
|
193
|
+
coro.close()
|
|
194
|
+
raise BrowserBudgetExhausted(f"{label} exhausted its page budget before {name}")
|
|
195
|
+
_call_deadlines[key] = (deadline, label)
|
|
196
|
+
_inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
|
|
197
|
+
getattr(self, "_loop", None), coro, _greenlet())
|
|
198
|
+
ended = "returned"
|
|
199
|
+
try:
|
|
200
|
+
return original(self, coro)
|
|
201
|
+
except asyncio.CancelledError:
|
|
202
|
+
ended = "cancelled"
|
|
203
|
+
if key in _abandoned:
|
|
204
|
+
raise CallAbandoned(name) from None
|
|
205
|
+
if fired is not None:
|
|
206
|
+
raise _timeout_error() from None
|
|
207
|
+
if interrupted is not None:
|
|
208
|
+
raise interrupted from None
|
|
209
|
+
raise
|
|
210
|
+
except BaseException as exc:
|
|
211
|
+
ended = type(exc).__name__
|
|
212
|
+
raise
|
|
213
|
+
finally:
|
|
214
|
+
_inflight.pop(key, None)
|
|
215
|
+
_call_deadlines.pop(key, None)
|
|
216
|
+
_abandoned.discard(key)
|
|
217
|
+
elapsed = time.monotonic() - started
|
|
218
|
+
_period["calls"] += 1
|
|
219
|
+
_period["seconds"] += elapsed
|
|
220
|
+
if elapsed > _period["slowest_sec"]:
|
|
221
|
+
_period["slowest"], _period["slowest_sec"] = name, elapsed
|
|
222
|
+
if elapsed > SLOW_CALL_SEC and on_slow_call is not None:
|
|
223
|
+
_report_slow(name, elapsed, ended)
|
|
224
|
+
return timed_sync
|
|
225
|
+
|
|
226
|
+
for base in sync_bases():
|
|
227
|
+
base._sync = timing(base._sync)
|
|
173
228
|
_installed = True
|
|
174
229
|
threading.Thread(target=_watch, args=(limit_sec,), name="browser-watchdog", daemon=True).start()
|
|
175
230
|
|
|
@@ -203,7 +258,7 @@ def check(limit_sec: float) -> bool:
|
|
|
203
258
|
if not overdue:
|
|
204
259
|
return False
|
|
205
260
|
key, entry = min(overdue, key=lambda pair: pair[1][0])
|
|
206
|
-
started, name, stack, loop, coro = entry
|
|
261
|
+
started, name, stack, loop, coro, _ = entry
|
|
207
262
|
fired = {"call": name, "seconds": int(now - started)}
|
|
208
263
|
deadline = deadlines.get(key)
|
|
209
264
|
if deadline and deadline[0] <= now and deadline[0] <= started + limit_sec:
|
|
@@ -224,7 +279,7 @@ def interrupt(exc: BaseException) -> None:
|
|
|
224
279
|
call raise ``exc`` until :func:`clear_interrupt`."""
|
|
225
280
|
global interrupted
|
|
226
281
|
interrupted = exc
|
|
227
|
-
for _, _, _, loop, coro in list(_inflight.values()):
|
|
282
|
+
for _, _, _, loop, coro, _ in list(_inflight.values()):
|
|
228
283
|
if loop is not None and not loop.is_closed():
|
|
229
284
|
loop.call_soon_threadsafe(_cancel, coro)
|
|
230
285
|
|
|
@@ -53,8 +53,11 @@ def _institutional_summary(cfg: dict[str, Any]) -> dict[str, Any]:
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
|
|
56
|
-
def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]:
|
|
56
|
+
def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]], dict[str, Any]]:
|
|
57
|
+
"""(ready, checks, browser): ``browser`` is the chrome backend's browser
|
|
58
|
+
(backend.browser_check) when that backend is configured, else {}."""
|
|
57
59
|
checks: list[dict[str, str]] = []
|
|
60
|
+
browser: dict[str, Any] = {}
|
|
58
61
|
|
|
59
62
|
def add(item: str, ok: bool, detail: str) -> None:
|
|
60
63
|
checks.append({"item": item, "status": "ok" if ok else "missing", "detail": detail})
|
|
@@ -64,10 +67,16 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
|
|
|
64
67
|
add("config_file", (data_dir / "config.json").exists(), str(data_dir / "config.json"))
|
|
65
68
|
|
|
66
69
|
try:
|
|
67
|
-
from .browser.backend import is_available, resolve_backend
|
|
70
|
+
from .browser.backend import BACKEND_CHROME, CHROME_MISSING, browser_check, is_available, resolve_backend
|
|
68
71
|
|
|
69
72
|
backend = resolve_backend(cfg)
|
|
70
|
-
|
|
73
|
+
if backend == BACKEND_CHROME:
|
|
74
|
+
browser = browser_check(cfg)
|
|
75
|
+
found = f"{browser['browser']} {browser['version']} ({browser['path']}), {browser['driver']}"
|
|
76
|
+
add("browser_backend", bool(is_available(backend, cfg)),
|
|
77
|
+
f"chrome: {found}" if browser["browser"] else f"chrome: {CHROME_MISSING}")
|
|
78
|
+
else:
|
|
79
|
+
add("browser_backend", bool(is_available(backend, cfg)), backend)
|
|
71
80
|
except Exception as exc: # pragma: no cover - import problems are themselves a finding
|
|
72
81
|
add("browser_backend", False, f"{type(exc).__name__}")
|
|
73
82
|
|
|
@@ -82,7 +91,7 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
|
|
|
82
91
|
for item in ("output_dir", "cache_dir"):
|
|
83
92
|
value = cfg.get(item) or ""
|
|
84
93
|
add(item, bool(value), value)
|
|
85
|
-
return all(c["status"] == "ok" for c in checks), checks
|
|
94
|
+
return all(c["status"] == "ok" for c in checks), checks, browser
|
|
86
95
|
|
|
87
96
|
|
|
88
97
|
def _carsi_school_list(cfg: dict[str, Any]) -> tuple[list[Any], dict[str, Any] | None]:
|
|
@@ -168,8 +177,14 @@ def _cmd_setup(args: argparse.Namespace) -> int:
|
|
|
168
177
|
save_config(cfg)
|
|
169
178
|
|
|
170
179
|
if args.check:
|
|
171
|
-
ready, checks = _environment_check(cfg)
|
|
172
|
-
|
|
180
|
+
ready, checks, browser = _environment_check(cfg)
|
|
181
|
+
report: dict[str, Any] = {"ready": ready, "checks": checks, "settings": _institutional_summary(cfg)}
|
|
182
|
+
if browser:
|
|
183
|
+
report["browser"] = browser
|
|
184
|
+
if browser.get("outdated"):
|
|
185
|
+
report["warnings"] = [f"Google Chrome {browser['version']} 低于测试过的 {browser['tested']}:"
|
|
186
|
+
"请先更新 Chrome(菜单 → 帮助 → 关于 Google Chrome)"]
|
|
187
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
173
188
|
return 0 if ready else 2
|
|
174
189
|
|
|
175
190
|
print(json.dumps({"updated": changed, "settings": _institutional_summary(cfg)}, ensure_ascii=False, indent=2))
|
|
@@ -478,7 +493,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
478
493
|
|
|
479
494
|
cs = sub.add_parser("cold-start", help="forget school sessions in the download browser (lists first)")
|
|
480
495
|
cs.add_argument("--yes", action="store_true", help="delete without asking")
|
|
481
|
-
cs.add_argument("--profile", help="another
|
|
496
|
+
cs.add_argument("--profile", help="another Chrome profile directory (default: the download profile)")
|
|
482
497
|
cs.add_argument("--cache-dir", help="the cache whose saved cookie files to filter "
|
|
483
498
|
"(default: the configured one; none with --profile)")
|
|
484
499
|
cs.set_defaults(func=_cmd_cold_start)
|
|
@@ -7,16 +7,18 @@ start forgets:
|
|
|
7
7
|
federation services that remember a school (CARSI, OpenAthens,
|
|
8
8
|
SeamlessAccess, SAMS Sigma, Atypon's SSO hub);
|
|
9
9
|
- the publishers' sessions and remembered schools;
|
|
10
|
-
- every other site's cookies and site data: the
|
|
10
|
+
- every other site's cookies and site data: the Chrome profile belongs to
|
|
11
11
|
the download engine alone, so the rest are journal sites (cell.com,
|
|
12
12
|
thelancet.com, ...) and their trackers.
|
|
13
13
|
|
|
14
14
|
It keeps bot-verification records (Cloudflare), personal publisher accounts
|
|
15
15
|
and cookie-consent choices. Besides the profile's own cookie store it filters
|
|
16
16
|
the files that put cookies back: the session cookies saved for the next
|
|
17
|
-
launch and the saved publisher cookies.
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
launch and the saved publisher cookies. IndexedDB goes per site. Chrome keeps
|
|
18
|
+
every site's local storage in one database, which goes whole when it holds a
|
|
19
|
+
site to forget (the kept categories live in cookies). Chrome's session-restore
|
|
20
|
+
files and session storage are removed whole. The plan lists hosts and cookie
|
|
21
|
+
names only, never values; nothing is changed until it is confirmed.
|
|
20
22
|
"""
|
|
21
23
|
from __future__ import annotations
|
|
22
24
|
|
|
@@ -27,7 +29,7 @@ import sqlite3
|
|
|
27
29
|
from pathlib import Path
|
|
28
30
|
from typing import Any, Iterable
|
|
29
31
|
|
|
30
|
-
from .browser.backend import SESSION_COOKIES_FILE,
|
|
32
|
+
from .browser.backend import SESSION_COOKIES_FILE, chrome_profile_dir, profile_holder
|
|
31
33
|
from .browser.cookies import _CLOUDFLARE_COOKIE_NAMES, PUBLISHER_DOMAINS
|
|
32
34
|
from .engine.batch_institution import InstitutionMixin, _school_auth_patterns
|
|
33
35
|
|
|
@@ -82,17 +84,15 @@ class Classifier:
|
|
|
82
84
|
return "other_site"
|
|
83
85
|
|
|
84
86
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if not origin.startswith(("https+++", "http+++")):
|
|
89
|
-
return ""
|
|
90
|
-
return origin.split("+++", 1)[1].split("+", 1)[0]
|
|
87
|
+
_INDEXEDDB_DIR = re.compile(r"^https?_(.+)_\d+\.indexeddb\.(?:leveldb|blob)$")
|
|
88
|
+
# A site's entry in Chrome's local storage database: "META:<origin>".
|
|
89
|
+
_LOCAL_STORAGE_ORIGIN = re.compile(rb"META:https?://([a-z0-9.-]+)")
|
|
91
90
|
|
|
92
91
|
|
|
93
|
-
def
|
|
94
|
-
"""``
|
|
95
|
-
|
|
92
|
+
def _storage_host(dirname: str) -> str:
|
|
93
|
+
"""``https_www.sciencedirect.com_0.indexeddb.leveldb`` -> host; '' for anything else."""
|
|
94
|
+
found = _INDEXEDDB_DIR.match(dirname)
|
|
95
|
+
return found.group(1) if found else ""
|
|
96
96
|
|
|
97
97
|
|
|
98
98
|
def _netscape_rows(path: Path) -> list[list[str]]:
|
|
@@ -107,19 +107,33 @@ class ColdStart:
|
|
|
107
107
|
|
|
108
108
|
# -- reading ------------------------------------------------------------
|
|
109
109
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
110
|
+
@property
|
|
111
|
+
def _default(self) -> Path:
|
|
112
|
+
return self.profile / "Default"
|
|
113
|
+
|
|
114
|
+
def _cookies_db(self) -> Path:
|
|
115
|
+
"""Chrome's cookie store: ``Default/Network/Cookies`` (Windows), else ``Default/Cookies``."""
|
|
116
|
+
network = self._default / "Network" / "Cookies"
|
|
117
|
+
return network if network.exists() else self._default / "Cookies"
|
|
116
118
|
|
|
117
|
-
def
|
|
118
|
-
path = self.
|
|
119
|
+
def _cookie_rows(self) -> list[tuple[int, str, str]]:
|
|
120
|
+
path = self._cookies_db()
|
|
119
121
|
if not path.exists():
|
|
120
122
|
return []
|
|
121
123
|
with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db:
|
|
122
|
-
return
|
|
124
|
+
return list(db.execute("SELECT rowid, host_key, name FROM cookies"))
|
|
125
|
+
|
|
126
|
+
def _local_storage_hosts(self) -> list[str]:
|
|
127
|
+
"""The sites with an entry in Chrome's local storage database."""
|
|
128
|
+
hosts: set[str] = set()
|
|
129
|
+
store = self._default / "Local Storage" / "leveldb"
|
|
130
|
+
for path in sorted(store.iterdir()) if store.is_dir() else []:
|
|
131
|
+
if path.suffix in (".log", ".ldb"):
|
|
132
|
+
try:
|
|
133
|
+
hosts.update(h.decode() for h in _LOCAL_STORAGE_ORIGIN.findall(path.read_bytes()))
|
|
134
|
+
except OSError:
|
|
135
|
+
continue
|
|
136
|
+
return sorted(hosts)
|
|
123
137
|
|
|
124
138
|
def _cookie_files(self) -> list[Path]:
|
|
125
139
|
files = [self.profile / SESSION_COOKIES_FILE]
|
|
@@ -135,25 +149,25 @@ class ColdStart:
|
|
|
135
149
|
return data, [c for c in cookies if isinstance(c, dict)]
|
|
136
150
|
|
|
137
151
|
def _session_files(self) -> list[Path]:
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
152
|
+
"""Chrome's session restore (tabs, and their session cookies) and session storage."""
|
|
153
|
+
sessions = self._default / "Sessions"
|
|
154
|
+
files = sorted(p for p in sessions.iterdir() if p.is_file()) if sessions.is_dir() else []
|
|
155
|
+
storage = self._default / "Session Storage"
|
|
156
|
+
return files + ([storage] if storage.is_dir() else [])
|
|
141
157
|
|
|
142
158
|
# -- the plan -----------------------------------------------------------
|
|
143
159
|
|
|
144
160
|
def plan(self) -> dict[str, Any]:
|
|
145
|
-
owner = _profile_owner_pid(str(self.profile))
|
|
146
161
|
cookies: dict[str, dict[str, set[str]]] = {c: {} for c in DELETE + KEEP}
|
|
147
162
|
for _id, host, name in self._cookie_rows():
|
|
148
163
|
cookies[self.classify(host, name)].setdefault(host.lstrip("."), set()).add(name)
|
|
149
164
|
site_data: dict[str, list[str]] = {"delete": [], "keep": []}
|
|
150
|
-
storage = self.
|
|
165
|
+
storage = self._default / "IndexedDB"
|
|
151
166
|
for entry in sorted(storage.iterdir()) if storage.is_dir() else []:
|
|
152
167
|
host = _storage_host(entry.name)
|
|
153
168
|
if host:
|
|
154
169
|
site_data["delete" if self.classify(host) in DELETE else "keep"].append(entry.name)
|
|
155
|
-
local =
|
|
156
|
-
if self.classify(_webappsstore_host(k)) in DELETE})
|
|
170
|
+
local = [h for h in self._local_storage_hosts() if self.classify(h) in DELETE]
|
|
157
171
|
files = []
|
|
158
172
|
for path in self._cookie_files():
|
|
159
173
|
try:
|
|
@@ -168,11 +182,14 @@ class ColdStart:
|
|
|
168
182
|
lines = [r for r in _netscape_rows(twin) if len(r) >= 7 and not r[0].startswith("#")]
|
|
169
183
|
gone = sum(self.classify(r[0], r[5]) in DELETE for r in lines)
|
|
170
184
|
files.append({"path": str(twin), "action": "filter", "remove": gone, "keep": len(lines) - gone})
|
|
171
|
-
|
|
185
|
+
if local:
|
|
186
|
+
files.append({"path": str(self._default / "Local Storage"), "action": "delete",
|
|
187
|
+
"why": "Chrome local storage, one database for all sites"})
|
|
188
|
+
files += [{"path": str(p), "action": "delete", "why": "Chrome session restore and session storage"}
|
|
172
189
|
for p in self._session_files()]
|
|
173
190
|
return {
|
|
174
191
|
"profile": str(self.profile),
|
|
175
|
-
"browser_running": bool(
|
|
192
|
+
"browser_running": bool(profile_holder(str(self.profile))),
|
|
176
193
|
"delete": {c: {"hosts": len(cookies[c]), "cookies": sum(len(v) for v in cookies[c].values()),
|
|
177
194
|
"items": [{"host": h, "names": sorted(n)} for h, n in sorted(cookies[c].items())]}
|
|
178
195
|
for c in DELETE},
|
|
@@ -184,32 +201,26 @@ class ColdStart:
|
|
|
184
201
|
# -- applying -----------------------------------------------------------
|
|
185
202
|
|
|
186
203
|
def apply(self) -> dict[str, Any]:
|
|
187
|
-
|
|
188
|
-
if
|
|
189
|
-
raise RuntimeError(f"the download browser (
|
|
204
|
+
holder = profile_holder(str(self.profile))
|
|
205
|
+
if holder:
|
|
206
|
+
raise RuntimeError(f"the download browser ({holder}) is using this profile; close it first")
|
|
190
207
|
done: dict[str, Any] = {"cookies": 0, "site_data": 0, "local_storage": 0, "files": []}
|
|
191
|
-
path = self.
|
|
208
|
+
path = self._cookies_db()
|
|
192
209
|
if path.exists():
|
|
193
210
|
gone = [i for i, host, name in self._cookie_rows() if self.classify(host, name) in DELETE]
|
|
194
211
|
with sqlite3.connect(path) as db:
|
|
195
|
-
db.executemany("DELETE FROM
|
|
196
|
-
with sqlite3.connect(path) as db:
|
|
197
|
-
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
212
|
+
db.executemany("DELETE FROM cookies WHERE rowid = ?", [(i,) for i in gone])
|
|
198
213
|
done["cookies"] = len(gone)
|
|
199
|
-
storage = self.
|
|
214
|
+
storage = self._default / "IndexedDB"
|
|
200
215
|
for entry in sorted(storage.iterdir()) if storage.is_dir() else []:
|
|
201
216
|
host = _storage_host(entry.name)
|
|
202
217
|
if host and self.classify(host) in DELETE:
|
|
203
218
|
shutil.rmtree(entry)
|
|
204
219
|
done["site_data"] += 1
|
|
205
|
-
local = self.
|
|
206
|
-
if local
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
db.executemany("DELETE FROM webappsstore2 WHERE originKey = ?", [(k,) for k in keys])
|
|
210
|
-
with sqlite3.connect(local) as db:
|
|
211
|
-
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
212
|
-
done["local_storage"] = len(keys)
|
|
220
|
+
local = [h for h in self._local_storage_hosts() if self.classify(h) in DELETE]
|
|
221
|
+
if local:
|
|
222
|
+
shutil.rmtree(self._default / "Local Storage")
|
|
223
|
+
done["local_storage"] = len(local)
|
|
213
224
|
for file in self._cookie_files():
|
|
214
225
|
try:
|
|
215
226
|
data, rows = self._file_cookies(file)
|
|
@@ -226,7 +237,10 @@ class ColdStart:
|
|
|
226
237
|
twin.write_text("".join("\t".join(r) + "\n" for r in keep_txt), encoding="utf-8")
|
|
227
238
|
done["files"].append({"path": str(twin), "removed": len(rows_txt) - len(keep_txt)})
|
|
228
239
|
for file in self._session_files():
|
|
229
|
-
file.
|
|
240
|
+
if file.is_dir():
|
|
241
|
+
shutil.rmtree(file)
|
|
242
|
+
else:
|
|
243
|
+
file.unlink()
|
|
230
244
|
done["files"].append({"path": str(file), "removed": "file"})
|
|
231
245
|
return done
|
|
232
246
|
|
|
@@ -239,7 +253,7 @@ def _write_json(path: Path, data: Any) -> None:
|
|
|
239
253
|
|
|
240
254
|
|
|
241
255
|
def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: str | None = None) -> ColdStart:
|
|
242
|
-
"""The cold start for the configured download profile (
|
|
256
|
+
"""The cold start for the configured download profile (Chrome's own directory)
|
|
243
257
|
and the configured cache. Another profile comes with only the cache named for
|
|
244
258
|
it: the configured cache belongs to the configured profile."""
|
|
245
259
|
from .config import DATA_DIR
|
|
@@ -248,4 +262,4 @@ def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: st
|
|
|
248
262
|
if profile:
|
|
249
263
|
return ColdStart(Path(profile), Path(cache_dir) if cache_dir else None, config)
|
|
250
264
|
cache = cache_dir or config.get("cache_dir", str(DATA_DIR / "cache"))
|
|
251
|
-
return ColdStart(
|
|
265
|
+
return ColdStart(chrome_profile_dir(_resolve_profile_dir(config)), Path(cache), config)
|
|
@@ -23,7 +23,7 @@ DEFAULT_SCIHUB_DOMAINS = [
|
|
|
23
23
|
# ALTCHA-protected (stable; used as manual-download hint)
|
|
24
24
|
"https://sci-hub.ru",
|
|
25
25
|
"https://sci-hub.ee",
|
|
26
|
-
# Cloudflare-protected (requires
|
|
26
|
+
# Cloudflare-protected (requires a browser to pass the JS challenge)
|
|
27
27
|
"https://sci-hub.st",
|
|
28
28
|
# Reported intermittent (2026-06); kept but deprioritized
|
|
29
29
|
"https://sci-hub.mksa.top",
|
|
@@ -87,9 +87,11 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
87
87
|
"min_pdf_size_bytes": 10000,
|
|
88
88
|
"browser_headless": False,
|
|
89
89
|
"browser_humanize": True,
|
|
90
|
-
# 浏览器后端,二选一:
|
|
91
|
-
# 或 ego
|
|
92
|
-
"browser_backend": "
|
|
90
|
+
# 浏览器后端,二选一:chrome(默认,本机安装的 Google Chrome,经 Patchright 驱动)
|
|
91
|
+
# 或 ego(正在运行的 ego-lite 浏览器,经远程调试连接)。旧值 camoufox/patchright/cloakbrowser 自动按 chrome 处理。
|
|
92
|
+
"browser_backend": "chrome",
|
|
93
|
+
# 装在别处的 Google Chrome 的程序路径;留空时在默认安装位置找。
|
|
94
|
+
"chrome_executable": "",
|
|
93
95
|
# 批量下载时每 N 篇回收一次浏览器上下文(cookie 内存交接,登录态不丢)。
|
|
94
96
|
# 0 = 关闭。长批次(上千篇)建议 100-200,避免 Chrome 长会话内存漂移。
|
|
95
97
|
"browser_restart_every": 0,
|
|
@@ -43,7 +43,7 @@ challenge_or_viewer_timeout challenge_resolved challenge_wait cookie_banner_dism
|
|
|
43
43
|
advertisement_closed pdf_step_article_page institution_choice_returned_article institution_choice_stopped
|
|
44
44
|
cookie_inject_failed download_capture_error elsevier_institution_entry_error
|
|
45
45
|
institution_continue institution_continue_error institution_entry_unresolved institution_federation_selected
|
|
46
|
-
institution_search_error institution_search_retyped institution_session_other idp_confirmation_required
|
|
46
|
+
institution_search_error institution_search_retyped institution_session_other idp_confirmation_accepted idp_confirmation_required
|
|
47
47
|
institution_required institution_search institution_search_submitted
|
|
48
48
|
institution_select_error institution_selected institution_selection_required
|
|
49
49
|
institution_session_return_article institution_session_return_error
|
|
@@ -56,6 +56,7 @@ pdf_capture_started pdf_navigation_error pdf_saved pdf_state_candidate post_logi
|
|
|
56
56
|
post_login_hold_article_access post_login_hold_auth_wall post_login_hold_login_page
|
|
57
57
|
post_run_hold publisher_access_blocked publisher_content_error publisher_unreachable publisher_login_menu_opened
|
|
58
58
|
publisher_pdf_link_unverified publisher_session_save_failed publisher_session_saved
|
|
59
|
+
publisher_terms_accepted
|
|
59
60
|
record_article_return record_article_return_error seamlessaccess_chooser_opened
|
|
60
61
|
shared_cookies_exported shared_cookies_loaded sso_entry_clicked sso_entry_error sso_start
|
|
61
62
|
access_unknown_pdf_first access_unknown_pdf_failed pdf_step_login_required login_round_trip_returned
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Profile-driven
|
|
1
|
+
"""Profile-driven browser batch downloader with retryable machine states.
|
|
2
2
|
|
|
3
3
|
``PublisherBatchDownloader`` keeps the article flow (``fetch_one``) here and combines
|
|
4
4
|
one mixin per responsibility from the ``batch_*.py`` modules: login, institution
|
|
@@ -48,6 +48,7 @@ from ..adapters import PublisherAdapter, adapter_class # noqa: E402
|
|
|
48
48
|
from .batch_common import (
|
|
49
49
|
page_operation, # re-exported: other modules import these from batch
|
|
50
50
|
open_page,
|
|
51
|
+
goto_retrying,
|
|
51
52
|
settle,
|
|
52
53
|
_is_network_failure,
|
|
53
54
|
DownloadResult,
|
|
@@ -146,8 +147,8 @@ class PublisherBatchDownloader(
|
|
|
146
147
|
deadline = time.monotonic() + 60
|
|
147
148
|
try:
|
|
148
149
|
referer = str(page.url)
|
|
149
|
-
tab
|
|
150
|
-
|
|
150
|
+
goto_retrying(tab, url, timeout_ms=60_000, wait_until="load",
|
|
151
|
+
**({"referer": referer} if referer.startswith(("http://", "https://")) else {}))
|
|
151
152
|
except Exception as exc:
|
|
152
153
|
if not _is_browser_error(exc):
|
|
153
154
|
raise
|
|
@@ -288,7 +289,10 @@ class PublisherBatchDownloader(
|
|
|
288
289
|
if not _is_browser_error(exc):
|
|
289
290
|
raise
|
|
290
291
|
self._event(result, "supplements_failed", f"{type(exc).__name__}: {str(exc)[:160]}")
|
|
291
|
-
|
|
292
|
+
# The site did not answer, not the error's class name ("Error": pubs.acs.org
|
|
293
|
+
# closed the connection on every try, Windows 2026-11-07).
|
|
294
|
+
reason = "publisher_unreachable" if _is_network_failure(exc) else type(exc).__name__
|
|
295
|
+
return [{"status": "failed", "reason": reason, "url": "", "label": ""}]
|
|
292
296
|
finally:
|
|
293
297
|
user_watch.set()
|
|
294
298
|
watchdog.clear_interrupt()
|
|
@@ -310,7 +314,10 @@ class PublisherBatchDownloader(
|
|
|
310
314
|
own = self.adapter.supplement_links(page, doi)
|
|
311
315
|
external = external_links(page, doi)
|
|
312
316
|
if own is None and external is None:
|
|
313
|
-
|
|
317
|
+
from ..adapters.platforms.silverchair import declares_no_supplements
|
|
318
|
+
|
|
319
|
+
# No rule found files, but the page itself may say there are none.
|
|
320
|
+
return [] if declares_no_supplements(page, doi) else None
|
|
314
321
|
return list(dict.fromkeys([*(own or []), *(external or [])]))
|
|
315
322
|
except Exception as exc:
|
|
316
323
|
if (attempt == 2 or not _is_browser_error(exc)
|
|
@@ -623,8 +630,11 @@ class PublisherBatchDownloader(
|
|
|
623
630
|
self._write_diagnostic(page, result, run_dir)
|
|
624
631
|
return result
|
|
625
632
|
except watchdog.BrowserUnresponsive as exc:
|
|
626
|
-
|
|
627
|
-
|
|
633
|
+
if isinstance(exc, watchdog.BrowserBudgetExhausted) and result.state == "challenge_or_viewer_timeout":
|
|
634
|
+
result.reason = result.state
|
|
635
|
+
else:
|
|
636
|
+
result.reason = result.state = ("browser_operation_timeout" if isinstance(exc, watchdog.BrowserOperationTimeout)
|
|
637
|
+
else "browser_unresponsive")
|
|
628
638
|
self._event(result, result.state, str(exc))
|
|
629
639
|
self._write_diagnostic(page, result, run_dir)
|
|
630
640
|
return result
|