papersearch 0.4.4 → 0.4.6
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/README.en.md +7 -4
- package/README.md +7 -4
- package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
- package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
- package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
- package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
- package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
- package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
- package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
- package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
- package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
- package/carsi/paper_search_carsi/assets/capsule.html +112 -32
- package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
- package/carsi/paper_search_carsi/browser/backend.py +36 -0
- package/carsi/paper_search_carsi/browser/background.py +68 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
- package/carsi/paper_search_carsi/browser/challenges.py +10 -0
- package/carsi/paper_search_carsi/browser/foreground.py +201 -0
- package/carsi/paper_search_carsi/browser/login.py +3 -1
- package/carsi/paper_search_carsi/browser/preview.py +3 -1
- package/carsi/paper_search_carsi/config.py +4 -1
- package/carsi/paper_search_carsi/engine/batch.py +73 -21
- package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
- package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +10 -0
- package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
- package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
- package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
- package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
- package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
- package/carsi/paper_search_carsi/engine/supplement_transfer.py +55 -0
- package/carsi/paper_search_carsi/engine/supplements.py +96 -24
- package/carsi/paper_search_carsi/entitlements.py +23 -3
- package/carsi/paper_search_carsi/progress_capsule.py +246 -30
- package/carsi/paper_search_carsi/progress_macos.py +166 -0
- package/carsi/paper_search_carsi/progress_reporter.py +22 -1
- package/carsi/paper_search_carsi/progress_view.py +1 -0
- package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
- package/carsi/paper_search_carsi/server.py +17 -1
- package/carsi/paper_search_carsi/user_settings.py +4 -4
- package/carsi/pyproject.toml +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +28 -4
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +3 -2
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +2 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +24 -1
- package/dist/management/carsi/installer.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/references/browser-download.md +11 -7
- package/skills/paper-search/references/carsi-setup.md +1 -0
- package/skills/paper-search/references/publisher-support.md +42 -41
|
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|
|
15
15
|
import json
|
|
16
16
|
import mimetypes
|
|
17
17
|
import re
|
|
18
|
+
import tempfile
|
|
18
19
|
import time
|
|
19
20
|
from pathlib import Path
|
|
20
21
|
from typing import Any, Callable, Iterable
|
|
@@ -22,16 +23,26 @@ from urllib.parse import unquote, urlparse
|
|
|
22
23
|
|
|
23
24
|
from ..adapters.base import SupplementLink
|
|
24
25
|
from ..browser.watchdog import BrowserUnresponsive, BrowserOperationTimeout
|
|
26
|
+
from ..browser import watchdog
|
|
25
27
|
from ..entitlements import UserMarkedNoEntitlement, UserSkippedArticle, UserStoppedBatch
|
|
26
28
|
|
|
27
29
|
MAX_FILES = 50
|
|
28
30
|
MAX_FILE_BYTES = 200 * 1024 * 1024
|
|
31
|
+
# No progress for this long ends the collection; active transfers refresh it.
|
|
29
32
|
TIME_BUDGET_SEC = 180
|
|
33
|
+
# Still bounded even when a server trickles bytes forever; below the MCP cap.
|
|
34
|
+
MAX_COLLECTION_SEC = 900
|
|
30
35
|
REQUEST_TIMEOUT_MS = 60_000
|
|
31
36
|
# The connection dropped before any answer: worth one more request.
|
|
32
37
|
_DROPPED_CONNECTION = ("socket disconnected", "socket hang up", "ECONNRESET", "EPIPE")
|
|
33
38
|
|
|
34
39
|
|
|
40
|
+
class SupplementTooLarge(ValueError):
|
|
41
|
+
def __init__(self, size: int):
|
|
42
|
+
self.size = size
|
|
43
|
+
super().__init__("attachment exceeds file size limit")
|
|
44
|
+
|
|
45
|
+
|
|
35
46
|
def supplements_dir(output_dir: Path, doi: str) -> Path:
|
|
36
47
|
return Path(output_dir) / (re.sub(r"[^A-Za-z0-9._-]+", "_", doi) + "_supplements")
|
|
37
48
|
|
|
@@ -62,28 +73,47 @@ def _file_name(url: str, disposition: str, taken: set[str], label: str = "", con
|
|
|
62
73
|
class _Downloaded:
|
|
63
74
|
"""A file the browser downloaded itself, shaped like Playwright's APIResponse."""
|
|
64
75
|
|
|
65
|
-
def __init__(self, body: bytes, name: str):
|
|
76
|
+
def __init__(self, body: bytes | Path, name: str):
|
|
66
77
|
self._body = body
|
|
67
78
|
self.status = 200
|
|
68
79
|
self.ok = True
|
|
69
80
|
self.headers = {"content-type": mimetypes.guess_type(name)[0] or "application/octet-stream",
|
|
70
81
|
"content-disposition": f'attachment; filename="{name}"',
|
|
71
|
-
"content-length": str(len(body))}
|
|
82
|
+
"content-length": str(body.stat().st_size if isinstance(body, Path) else len(body))}
|
|
83
|
+
|
|
84
|
+
def chunks(self):
|
|
85
|
+
if isinstance(self._body, Path):
|
|
86
|
+
with self._body.open("rb") as fh:
|
|
87
|
+
while chunk := fh.read(64 * 1024):
|
|
88
|
+
yield chunk
|
|
89
|
+
else:
|
|
90
|
+
yield self._body
|
|
91
|
+
|
|
92
|
+
def dispose(self):
|
|
93
|
+
if isinstance(self._body, Path):
|
|
94
|
+
self._body.unlink(missing_ok=True)
|
|
95
|
+
|
|
72
96
|
|
|
73
|
-
|
|
74
|
-
|
|
97
|
+
def _check_interrupted() -> None:
|
|
98
|
+
if watchdog.interrupted is not None:
|
|
99
|
+
raise watchdog.interrupted
|
|
75
100
|
|
|
76
101
|
|
|
77
102
|
def _get(request: Any, url: str, entry: dict[str, Any], sleep) -> Any:
|
|
78
103
|
"""GET the file; once more after the connection dropped before any answer
|
|
79
104
|
(a CDN's TLS handshake cut off midway, Oxford Academic 2026-11-01)."""
|
|
105
|
+
_check_interrupted()
|
|
80
106
|
try:
|
|
81
107
|
return request.get(url, timeout=REQUEST_TIMEOUT_MS)
|
|
108
|
+
except (BrowserUnresponsive, UserMarkedNoEntitlement):
|
|
109
|
+
raise
|
|
82
110
|
except Exception as exc:
|
|
83
111
|
if not any(marker in str(exc) for marker in _DROPPED_CONNECTION):
|
|
84
112
|
raise
|
|
85
|
-
entry["retried"] =
|
|
113
|
+
entry["retried"] = "socket disconnected before response"
|
|
114
|
+
_check_interrupted()
|
|
86
115
|
sleep(2)
|
|
116
|
+
_check_interrupted()
|
|
87
117
|
return request.get(url, timeout=REQUEST_TIMEOUT_MS)
|
|
88
118
|
|
|
89
119
|
|
|
@@ -91,8 +121,9 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
91
121
|
clock=time.monotonic, sleep=time.sleep,
|
|
92
122
|
manifest_dir: Path | None = None,
|
|
93
123
|
target_dir: Path | None = None,
|
|
94
|
-
download: Callable[[str], tuple[bytes, str]] | None = None,
|
|
95
|
-
progress: Callable[[int], None] | None = None
|
|
124
|
+
download: Callable[[str], tuple[bytes | Path, str]] | None = None,
|
|
125
|
+
progress: Callable[[int], None] | None = None,
|
|
126
|
+
activity: Callable[[], None] | None = None) -> list[dict[str, Any]]:
|
|
96
127
|
"""Fetch ``links`` with ``request`` (a Playwright APIRequestContext). A file
|
|
97
128
|
refused with 403 is taken through ``download`` when given: the browser
|
|
98
129
|
opens it and downloads it itself (Taylor & Francis behind Cloudflare
|
|
@@ -107,7 +138,7 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
107
138
|
return []
|
|
108
139
|
target = target_dir or supplements_dir(output_dir, doi)
|
|
109
140
|
target.mkdir(parents=True, exist_ok=True)
|
|
110
|
-
started = clock()
|
|
141
|
+
started = last_progress = clock()
|
|
111
142
|
taken: set[str] = set()
|
|
112
143
|
files: list[dict[str, Any]] = []
|
|
113
144
|
stopped_reason = ""
|
|
@@ -119,14 +150,20 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
119
150
|
entry.update(status="failed", reason=link.error)
|
|
120
151
|
elif index >= MAX_FILES:
|
|
121
152
|
entry.update(status="skipped", reason="file_limit")
|
|
122
|
-
elif clock() - started > TIME_BUDGET_SEC:
|
|
153
|
+
elif clock() - started > MAX_COLLECTION_SEC or clock() - last_progress > TIME_BUDGET_SEC:
|
|
123
154
|
entry.update(status="skipped", reason="time_budget")
|
|
124
155
|
else:
|
|
125
156
|
try:
|
|
157
|
+
response = None
|
|
126
158
|
response = _get(request, link.url, entry, sleep)
|
|
159
|
+
_check_interrupted()
|
|
127
160
|
if response.status == 403 and download is not None:
|
|
161
|
+
if callable(getattr(response, "dispose", None)):
|
|
162
|
+
response.dispose()
|
|
163
|
+
response = None
|
|
128
164
|
response = _Downloaded(*download(link.url))
|
|
129
165
|
entry["via"] = "browser_download"
|
|
166
|
+
_check_interrupted()
|
|
130
167
|
content_type = str(response.headers.get("content-type", "") or "")
|
|
131
168
|
length = int(response.headers.get("content-length") or 0)
|
|
132
169
|
if not response.ok:
|
|
@@ -137,16 +174,43 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
137
174
|
# A login wall or landing page instead of the file.
|
|
138
175
|
entry.update(status="failed", reason="html_page")
|
|
139
176
|
else:
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
177
|
+
name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
|
|
178
|
+
link.label, content_type)
|
|
179
|
+
path = target / name
|
|
180
|
+
temporary = None
|
|
181
|
+
size = 0
|
|
182
|
+
try:
|
|
183
|
+
chunks = response.chunks() if callable(getattr(response, "chunks", None)) else [response.body()]
|
|
184
|
+
with tempfile.NamedTemporaryFile(dir=target, prefix=".supplement-", suffix=".part", delete=False) as fh:
|
|
185
|
+
temporary = Path(fh.name)
|
|
186
|
+
for chunk in chunks:
|
|
187
|
+
_check_interrupted()
|
|
188
|
+
now = clock()
|
|
189
|
+
if now - started > MAX_COLLECTION_SEC:
|
|
190
|
+
raise TimeoutError("attachment collection time budget exhausted")
|
|
191
|
+
if not chunk:
|
|
192
|
+
continue
|
|
193
|
+
size += len(chunk)
|
|
194
|
+
if size > MAX_FILE_BYTES:
|
|
195
|
+
break
|
|
196
|
+
fh.write(chunk)
|
|
197
|
+
last_progress = now
|
|
198
|
+
if activity is not None:
|
|
199
|
+
activity()
|
|
200
|
+
_check_interrupted()
|
|
201
|
+
if size > MAX_FILE_BYTES:
|
|
202
|
+
entry.update(status="skipped", reason="too_large", size=size)
|
|
203
|
+
elif not size or (length and not response.headers.get("content-encoding") and size != length):
|
|
204
|
+
entry.update(status="failed", reason="incomplete_body", size=size)
|
|
205
|
+
else:
|
|
206
|
+
temporary.replace(path)
|
|
207
|
+
entry.update(status="saved", file=str(path), size=size,
|
|
208
|
+
content_type=content_type.split(";")[0].strip())
|
|
209
|
+
finally:
|
|
210
|
+
if temporary is not None:
|
|
211
|
+
temporary.unlink(missing_ok=True)
|
|
212
|
+
except SupplementTooLarge as exc:
|
|
213
|
+
entry.update(status="skipped", reason="too_large", size=exc.size)
|
|
150
214
|
except (BrowserUnresponsive, UserMarkedNoEntitlement) as exc:
|
|
151
215
|
stopped_reason = ("batch_stopped" if isinstance(exc, UserStoppedBatch) else
|
|
152
216
|
"user_skipped" if isinstance(exc, UserSkippedArticle) else
|
|
@@ -156,12 +220,20 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
156
220
|
entry.update(status="skipped" if isinstance(exc, UserMarkedNoEntitlement) else "failed",
|
|
157
221
|
reason=stopped_reason)
|
|
158
222
|
except Exception as exc:
|
|
159
|
-
|
|
223
|
+
# Network exception messages may carry signed URLs or credentials.
|
|
224
|
+
entry.update(status="failed", reason=f"{type(exc).__name__}: attachment transfer failed")
|
|
225
|
+
finally:
|
|
226
|
+
if response is not None and callable(getattr(response, "dispose", None)):
|
|
227
|
+
response.dispose()
|
|
160
228
|
files.append(entry)
|
|
229
|
+
if entry.get("status") == "saved":
|
|
230
|
+
last_progress = clock()
|
|
231
|
+
manifest_target = manifest_dir or target
|
|
232
|
+
manifest_target.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
manifest = manifest_target / "manifest.json"
|
|
234
|
+
temporary_manifest = manifest.with_suffix(".json.tmp")
|
|
235
|
+
temporary_manifest.write_text(json.dumps({"doi": doi, "files": files}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
236
|
+
temporary_manifest.replace(manifest)
|
|
161
237
|
if progress is not None:
|
|
162
238
|
progress(sum(1 for f in files if f.get("status") == "saved"))
|
|
163
|
-
manifest_target = manifest_dir or target
|
|
164
|
-
manifest_target.mkdir(parents=True, exist_ok=True)
|
|
165
|
-
(manifest_target / "manifest.json").write_text(
|
|
166
|
-
json.dumps({"doi": doi, "files": files}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
167
239
|
return files
|
|
@@ -40,6 +40,7 @@ class UserStoppedBatch(UserMarkedNoEntitlement):
|
|
|
40
40
|
|
|
41
41
|
# Not an entitlement decision: nothing is recorded, the batch ends.
|
|
42
42
|
STOP_BATCH = "stop_batch"
|
|
43
|
+
SHOW_BROWSER = "show_browser"
|
|
43
44
|
|
|
44
45
|
|
|
45
46
|
SKIP = "skip"
|
|
@@ -191,13 +192,30 @@ def clear(key: str) -> bool:
|
|
|
191
192
|
|
|
192
193
|
def request_action(current: str, action: str, run_id: str = "") -> None:
|
|
193
194
|
"""Written by the progress window when the user presses a button."""
|
|
194
|
-
if action not in _ACTIONS and action
|
|
195
|
+
if action not in _ACTIONS and action not in (STOP_BATCH, SHOW_BROWSER):
|
|
195
196
|
raise ValueError("unknown action")
|
|
196
|
-
|
|
197
|
+
data = {"current": current, "action": action, "run_id": run_id, "at": time.time()}
|
|
198
|
+
if action == STOP_BATCH and run_id:
|
|
199
|
+
# A batch stop survives both item handoff and later focus requests.
|
|
200
|
+
# A new run has a new identity, so an old stop cannot cancel it.
|
|
201
|
+
_write_json(control_path().with_name("stop.json"), data)
|
|
202
|
+
else:
|
|
203
|
+
_write_json(control_path(), data)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def batch_stop_requested() -> bool:
|
|
207
|
+
"""A durable stop for the current run, including the gap between papers."""
|
|
208
|
+
stop = _read_json(control_path().with_name("stop.json"))
|
|
209
|
+
if stop.get("action") != STOP_BATCH or not stop.get("run_id"):
|
|
210
|
+
return False
|
|
211
|
+
state = _read_json(control_path().with_name("current.json"))
|
|
212
|
+
return state.get("status") == "running" and stop["run_id"] == state.get("run_id")
|
|
197
213
|
|
|
198
214
|
|
|
199
215
|
def take_action(doi: str, since: float) -> str | None:
|
|
200
216
|
"""The user's pending action for this paper (requested after ``since``), consumed once."""
|
|
217
|
+
if batch_stop_requested():
|
|
218
|
+
return STOP_BATCH
|
|
201
219
|
path = control_path()
|
|
202
220
|
data = _read_json(path)
|
|
203
221
|
if not data or str(data.get("current", "")).lower() != (doi or "").lower():
|
|
@@ -212,7 +230,7 @@ def take_action(doi: str, since: float) -> str | None:
|
|
|
212
230
|
except OSError:
|
|
213
231
|
pass
|
|
214
232
|
action = data.get("action")
|
|
215
|
-
return action if action in _ACTIONS or action
|
|
233
|
+
return action if action in _ACTIONS or action in (STOP_BATCH, SHOW_BROWSER) else None
|
|
216
234
|
|
|
217
235
|
|
|
218
236
|
def apply_user_decision(doi: str, publisher: str, since: float) -> str | None:
|
|
@@ -220,6 +238,8 @@ def apply_user_decision(doi: str, publisher: str, since: float) -> str | None:
|
|
|
220
238
|
action = take_action(doi, since)
|
|
221
239
|
if not action:
|
|
222
240
|
return None
|
|
241
|
+
if action == SHOW_BROWSER:
|
|
242
|
+
return action # an explicit focus request, never an entitlement decision
|
|
223
243
|
if action == STOP_BATCH:
|
|
224
244
|
raise UserStoppedBatch(action)
|
|
225
245
|
if action == "skip_item":
|