papersearch 0.7.1 → 0.7.2
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/dist/capabilities/download/batch/batch.d.ts.map +1 -1
- package/dist/capabilities/download/batch/batch.js +12 -1
- package/dist/capabilities/download/batch/batch.js.map +1 -1
- package/dist/capabilities/download/batch/batchSummary.d.ts.map +1 -1
- package/dist/capabilities/download/batch/batchSummary.js +16 -7
- package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
- package/dist/capabilities/download/batch/journalKey.d.ts +12 -0
- package/dist/capabilities/download/batch/journalKey.d.ts.map +1 -0
- package/dist/capabilities/download/batch/journalKey.js +30 -0
- package/dist/capabilities/download/batch/journalKey.js.map +1 -0
- package/dist/capabilities/download/content/pdf/DownloadTier.d.ts +4 -0
- package/dist/capabilities/download/content/pdf/DownloadTier.d.ts.map +1 -1
- package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.d.ts.map +1 -1
- package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js +2 -0
- package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/download/content/pdf/school.js +2 -0
- package/dist/capabilities/download/content/pdf/school.js.map +1 -1
- package/dist/capabilities/download/types.d.ts +4 -0
- package/dist/capabilities/download/types.d.ts.map +1 -1
- package/dist/cli.js +32 -9
- package/dist/cli.js.map +1 -1
- package/dist/infrastructure/school/SchoolMcpClient.d.ts +4 -0
- package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolMcpClient.js +20 -1
- package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
- package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
- package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolReadiness.js +3 -0
- package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
- package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
- package/dist/infrastructure/school/SchoolResultNormalizer.js +5 -0
- package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
- package/dist/infrastructure/school/types.d.ts +12 -0
- package/dist/infrastructure/school/types.d.ts.map +1 -1
- package/dist/management/pro/activate.d.ts +36 -0
- package/dist/management/pro/activate.d.ts.map +1 -0
- package/dist/management/pro/activate.js +122 -0
- package/dist/management/pro/activate.js.map +1 -0
- package/dist/management/pro/install.d.ts +15 -0
- package/dist/management/pro/install.d.ts.map +1 -1
- package/dist/management/pro/install.js +39 -12
- package/dist/management/pro/install.js.map +1 -1
- package/dist/management/reports/index.d.ts +6 -0
- package/dist/management/reports/index.d.ts.map +1 -1
- package/dist/management/reports/index.js +6 -0
- package/dist/management/reports/index.js.map +1 -1
- package/dist/management/school/autoUpdate.d.ts.map +1 -1
- package/dist/management/school/autoUpdate.js +1 -0
- package/dist/management/school/autoUpdate.js.map +1 -1
- package/dist/management/school/cliProgress.d.ts.map +1 -1
- package/dist/management/school/cliProgress.js +1 -0
- package/dist/management/school/cliProgress.js.map +1 -1
- package/dist/management/school/settingsWindow.d.ts +1 -0
- package/dist/management/school/settingsWindow.d.ts.map +1 -1
- package/dist/management/school/settingsWindow.js +2 -0
- package/dist/management/school/settingsWindow.js.map +1 -1
- package/dist/management/updates/selfUpdate.d.ts +86 -0
- package/dist/management/updates/selfUpdate.d.ts.map +1 -0
- package/dist/management/updates/selfUpdate.js +194 -0
- package/dist/management/updates/selfUpdate.js.map +1 -0
- package/package.json +1 -1
- package/school/paper_search_school/adapters/annual_reviews/__init__.py +1 -0
- package/school/paper_search_school/adapters/ieee/__init__.py +1 -0
- package/school/paper_search_school/assets/capsule.html +927 -202
- package/school/paper_search_school/assets/capsule_en.json +290 -22
- package/school/paper_search_school/assets/capsule_fr.json +1331 -0
- package/school/paper_search_school/assets/capsule_ja.json +1331 -0
- package/school/paper_search_school/assets/capsule_ko.json +1331 -0
- package/school/paper_search_school/assets/capsule_zh-Hant.json +2462 -0
- package/school/paper_search_school/cli.py +15 -1
- package/school/paper_search_school/cold_start.py +70 -8
- package/school/paper_search_school/config.py +2 -0
- package/school/paper_search_school/download_diagnostics.py +4 -4
- package/school/paper_search_school/engine/batch_capture.py +35 -1
- package/school/paper_search_school/engine/batch_diagnostics.py +1 -1
- package/school/paper_search_school/engine/batch_institution.py +41 -0
- package/school/paper_search_school/engine/batch_login.py +65 -1
- package/school/paper_search_school/engine/batch_waits.py +22 -8
- package/school/paper_search_school/engine/bridge.py +11 -0
- package/school/paper_search_school/i18n.py +46 -22
- package/school/paper_search_school/orchestrator.py +60 -8
- package/school/paper_search_school/pro_status.py +54 -63
- package/school/paper_search_school/progress_capsule.py +180 -24
- package/school/paper_search_school/progress_reporter.py +51 -5
- package/school/paper_search_school/progress_view.py +3 -2
- package/school/paper_search_school/school_login.py +18 -4
- package/school/paper_search_school/school_switch.py +102 -0
- package/school/paper_search_school/school_test.py +335 -0
- package/school/paper_search_school/server.py +16 -0
- package/school/paper_search_school/updates.py +222 -0
- package/school/paper_search_school/user_settings.py +8 -3
- package/skills/paper-search/SKILL.md +1 -1
- package/skills/paper-search/references/cli-contract.md +1 -1
- package/skills/paper-search/references/school-setup.md +1 -1
|
@@ -4,6 +4,8 @@ Commands:
|
|
|
4
4
|
run start the MCP stdio server (what PaperSearch spawns)
|
|
5
5
|
setup [...] show or change institutional access settings; --check for an environment check
|
|
6
6
|
login --doi DOI sign in to the school as a download does (no PDF); success only once confirmed
|
|
7
|
+
school-test --school ENTITY --doi DOI the settings' 测试登录: one download with a saved school, its PDF deleted,
|
|
8
|
+
the verdict in progress/school-test.json (school_test.py)
|
|
7
9
|
config get|set|list read or write the backend config in SCHOOL_DATA_DIR
|
|
8
10
|
list-publishers print publisher profiles and their platform labels
|
|
9
11
|
publisher-check --doi DOI run one institutional download and print a sanitized report
|
|
@@ -392,6 +394,12 @@ def _cmd_login(args: argparse.Namespace) -> int:
|
|
|
392
394
|
return 0 if reply["success"] else 1
|
|
393
395
|
|
|
394
396
|
|
|
397
|
+
def _cmd_school_test(args: argparse.Namespace) -> int:
|
|
398
|
+
from .school_test import run
|
|
399
|
+
|
|
400
|
+
return run(args.school, args.doi)
|
|
401
|
+
|
|
402
|
+
|
|
395
403
|
# ---------------------------------------------------------------------------
|
|
396
404
|
# other commands
|
|
397
405
|
# ---------------------------------------------------------------------------
|
|
@@ -619,7 +627,8 @@ def _cmd_issues(args: argparse.Namespace) -> int:
|
|
|
619
627
|
return 0
|
|
620
628
|
|
|
621
629
|
|
|
622
|
-
|
|
630
|
+
# about: PaperSearch's version and its update, Pro's with it (user, 2026-11-21); pro opens it too, by its old name.
|
|
631
|
+
SETTINGS_PAGES = ("home", "about", "download", "wait", "keys", "pro", "markdown", "login")
|
|
623
632
|
# PaperSearch Pro's pages (edition.py): Pro itself, its Markdown, the school's sign-in (school_login.py).
|
|
624
633
|
PRO_PAGES = ("pro", "markdown", "login")
|
|
625
634
|
|
|
@@ -729,6 +738,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
729
738
|
help="seconds to wait on the school's login page (default: the setting browser_login_timeout)")
|
|
730
739
|
lg.set_defaults(func=_cmd_login)
|
|
731
740
|
|
|
741
|
+
stt = sub.add_parser("school-test", help="the settings' 测试登录: one download with a saved school, its PDF deleted")
|
|
742
|
+
stt.add_argument("--school", required=True, help="the saved school's entityID")
|
|
743
|
+
stt.add_argument("--doi", required=True)
|
|
744
|
+
stt.set_defaults(func=_cmd_school_test)
|
|
745
|
+
|
|
732
746
|
cfg = sub.add_parser("config", help="read or write backend config")
|
|
733
747
|
cfg.add_argument("action", choices=["get", "set", "list"])
|
|
734
748
|
cfg.add_argument("key", nargs="?")
|
|
@@ -12,7 +12,8 @@ start forgets:
|
|
|
12
12
|
thelancet.com, ...) and their trackers.
|
|
13
13
|
|
|
14
14
|
It keeps bot-verification records (Cloudflare), personal publisher accounts
|
|
15
|
-
and cookie-consent choices
|
|
15
|
+
and cookie-consent choices; before a sign-in with another school (``before_sign_in``)
|
|
16
|
+
the personal accounts go too: Elsevier's keeps the school's access with it. Besides the profile's own cookie store it filters
|
|
16
17
|
the files that put cookies back: the session cookies saved for the next
|
|
17
18
|
launch and the saved publisher cookies. IndexedDB goes per site. Chrome keeps
|
|
18
19
|
every site's local storage in one database, which goes whole when it holds a
|
|
@@ -65,17 +66,23 @@ def _publisher_domains() -> tuple[str, ...]:
|
|
|
65
66
|
|
|
66
67
|
|
|
67
68
|
class Classifier:
|
|
68
|
-
"""Sorts a cookie (host, name) or a site's data (host) into the categories above.
|
|
69
|
+
"""Sorts a cookie (host, name) or a site's data (host) into the categories above. ``accounts``: the personal
|
|
70
|
+
publisher accounts are forgotten as a school's login (another school to sign in with)."""
|
|
69
71
|
|
|
70
|
-
def __init__(self, config: dict[str, Any]):
|
|
72
|
+
def __init__(self, config: dict[str, Any], accounts: bool = False):
|
|
71
73
|
self.school_tokens = tuple(t.lower() for t in _school_auth_patterns(config) if t)
|
|
72
74
|
self.publishers = _publisher_domains()
|
|
75
|
+
self.accounts = accounts
|
|
73
76
|
|
|
74
77
|
def __call__(self, host: str, name: str = "") -> str:
|
|
75
78
|
host = (host or "").lower().lstrip(".").split(":")[0]
|
|
76
79
|
if name and (name in _CLOUDFLARE_COOKIE_NAMES or name.startswith(("cf_chl", "__cf"))):
|
|
77
80
|
return "verification"
|
|
78
81
|
if _under(host, PERSONAL_ACCOUNT_HOSTS):
|
|
82
|
+
# Elsevier's account keeps the school it was signed in through (remember.me signs the next visit in with
|
|
83
|
+
# it, the school's access and all: a test of another school passed with the last one's, user 2026-11-21).
|
|
84
|
+
if self.accounts:
|
|
85
|
+
return "consent" if name and _CONSENT_NAME.search(name) else "school_login"
|
|
79
86
|
return "school_login" if name and _REMEMBERED_SCHOOL_NAME.search(name) else "personal_account"
|
|
80
87
|
if name and _CONSENT_NAME.search(name):
|
|
81
88
|
return "consent"
|
|
@@ -103,10 +110,10 @@ def _netscape_rows(path: Path) -> list[list[str]]:
|
|
|
103
110
|
|
|
104
111
|
|
|
105
112
|
class ColdStart:
|
|
106
|
-
def __init__(self, profile: Path, cache_dir: Path | None, config: dict[str, Any]):
|
|
113
|
+
def __init__(self, profile: Path, cache_dir: Path | None, config: dict[str, Any], accounts: bool = False):
|
|
107
114
|
self.profile = profile
|
|
108
115
|
self.cache_dir = cache_dir # None: the profile only, no saved cookie files
|
|
109
|
-
self.classify = Classifier(config)
|
|
116
|
+
self.classify = Classifier(config, accounts)
|
|
110
117
|
|
|
111
118
|
# -- reading ------------------------------------------------------------
|
|
112
119
|
|
|
@@ -257,7 +264,8 @@ def _write_json(path: Path, data: Any) -> None:
|
|
|
257
264
|
tmp.replace(path)
|
|
258
265
|
|
|
259
266
|
|
|
260
|
-
def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: str | None = None
|
|
267
|
+
def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: str | None = None,
|
|
268
|
+
accounts: bool = False) -> ColdStart:
|
|
261
269
|
"""The cold start for the configured download profile (Chrome's own directory)
|
|
262
270
|
and the configured cache. Another profile comes with only the cache named for
|
|
263
271
|
it: the configured cache belongs to the configured profile."""
|
|
@@ -265,6 +273,60 @@ def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: st
|
|
|
265
273
|
from .engine.batch_common import _resolve_profile_dir
|
|
266
274
|
|
|
267
275
|
if profile:
|
|
268
|
-
return ColdStart(Path(profile), Path(cache_dir) if cache_dir else None, config)
|
|
276
|
+
return ColdStart(Path(profile), Path(cache_dir) if cache_dir else None, config, accounts)
|
|
269
277
|
cache = cache_dir or config.get("cache_dir", str(DATA_DIR / "cache"))
|
|
270
|
-
return ColdStart(chrome_profile_dir(_resolve_profile_dir(config)), Path(cache), config)
|
|
278
|
+
return ColdStart(chrome_profile_dir(_resolve_profile_dir(config)), Path(cache), config, accounts)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# -- another school's sign-in --------------------------------------------------------------------
|
|
282
|
+
# Switched to another school, the download browser stayed signed in with the last one: the publisher's page opened
|
|
283
|
+
# through it, and the new school's account was never used (user, 2026-11-21). The school the browser last signed in
|
|
284
|
+
# with is kept; a download with another forgets that sign-in first, as a cold start does (the publishers' sessions and
|
|
285
|
+
# remembered schools with it; verification records, personal accounts and consent choices kept).
|
|
286
|
+
|
|
287
|
+
def _signed_in_path() -> Path:
|
|
288
|
+
from .data_home import default_data_dir
|
|
289
|
+
|
|
290
|
+
return default_data_dir() / "browser_school.json"
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def signed_in_school() -> str:
|
|
294
|
+
"""The school the download browser last signed in with ("" not known)."""
|
|
295
|
+
try:
|
|
296
|
+
data = json.loads(_signed_in_path().read_text(encoding="utf-8"))
|
|
297
|
+
except (OSError, ValueError):
|
|
298
|
+
return ""
|
|
299
|
+
return str(data.get("school") or "") if isinstance(data, dict) else ""
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def before_sign_in(config: dict[str, Any], *, always: bool = False) -> str:
|
|
303
|
+
"""Before a download signs in with ``config``'s school: the browser last signed in with another forgets that
|
|
304
|
+
sign-in (``always``, the settings' 测试登录: whatever it was, so that the account is what the test tries).
|
|
305
|
+
"cleared"; "" when there was nothing to forget (the same school, or none known yet: kept from now on); "busy"
|
|
306
|
+
when the download browser is open (nothing changed)."""
|
|
307
|
+
entity = str(config.get("idp_entity_id") or "").strip()
|
|
308
|
+
if not entity:
|
|
309
|
+
return ""
|
|
310
|
+
last = signed_in_school()
|
|
311
|
+
if not always and (not last or last == entity):
|
|
312
|
+
if not last:
|
|
313
|
+
_signed_in_path().parent.mkdir(parents=True, exist_ok=True)
|
|
314
|
+
_write_json(_signed_in_path(), {"school": entity})
|
|
315
|
+
return ""
|
|
316
|
+
# The personal publisher accounts too: Elsevier's signs the next visit in with the last school's access.
|
|
317
|
+
run = for_config(config, accounts=True)
|
|
318
|
+
try:
|
|
319
|
+
run.apply()
|
|
320
|
+
except RuntimeError:
|
|
321
|
+
# A browser just closed (a batch's, for the next school) takes a few seconds to let go of the profile.
|
|
322
|
+
from .browser.profiles import wait_for_profile_release
|
|
323
|
+
|
|
324
|
+
if not wait_for_profile_release(str(run.profile), timeout=10):
|
|
325
|
+
return "busy"
|
|
326
|
+
try:
|
|
327
|
+
run.apply()
|
|
328
|
+
except RuntimeError:
|
|
329
|
+
return "busy"
|
|
330
|
+
_signed_in_path().parent.mkdir(parents=True, exist_ok=True)
|
|
331
|
+
_write_json(_signed_in_path(), {"school": entity})
|
|
332
|
+
return "cleared"
|
|
@@ -84,6 +84,8 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
84
84
|
"publisher_hourly_limit": 100,
|
|
85
85
|
# 改了上面的上限时,正在等上限的篇目是否立即按新上限接着下;false = 这一小时过后再按新上限。
|
|
86
86
|
"publisher_hourly_limit_now": False,
|
|
87
|
+
# 没权限时换下一所学校 (school_switch.py; user, 2026-11-21): on unless turned off.
|
|
88
|
+
"school_switch": True,
|
|
87
89
|
# 灰色源竞速浏览器的独立无头开关(只影响 sci-hub 竞速,机构登录仍有可见窗口)。
|
|
88
90
|
# true = 竞速全程零窗口、零任务栏闪烁;指纹安全性由 UA 清洗保证。
|
|
89
91
|
"scihub_browser_headless": False,
|
|
@@ -19,7 +19,7 @@ login_timeout login_page_closed login_credentials_rejected login_retries_exhaust
|
|
|
19
19
|
login_required verification_required institution_not_registered idp_login_error sso_required
|
|
20
20
|
idp_account_locked idp_password_expired
|
|
21
21
|
sso_redirect_stalled institution_pdf_entitlement_missing publisher_content_error publisher_unreachable
|
|
22
|
-
publisher_access_blocked
|
|
22
|
+
publisher_access_blocked publisher_download_limit
|
|
23
23
|
publisher_institution_entry_missing institution_entry_unresolved
|
|
24
24
|
publisher_temporarily_unavailable
|
|
25
25
|
challenge_or_viewer_timeout ip_blocked access_blocked pdf_not_captured
|
|
@@ -46,7 +46,7 @@ advertisement_closed pdf_step_article_page institution_choice_returned_article i
|
|
|
46
46
|
cookie_inject_failed download_capture_error elsevier_institution_entry_error
|
|
47
47
|
institution_continue institution_continue_error institution_entry_unresolved institution_federation_selected
|
|
48
48
|
institution_search_error institution_search_retyped institution_session_other idp_confirmation_accepted idp_confirmation_required
|
|
49
|
-
institution_required institution_search institution_search_submitted
|
|
49
|
+
institution_required institution_search institution_search_submitted institution_search_lost
|
|
50
50
|
institution_select_error institution_selected institution_selection_required
|
|
51
51
|
institution_session_return_article institution_session_return_error
|
|
52
52
|
ip_blocked_body ip_blocked_response karger_institution_chooser_opened
|
|
@@ -58,14 +58,14 @@ pdf_capture_started pdf_navigation_error pdf_saved pdf_state_candidate post_logi
|
|
|
58
58
|
post_login_hold_article_access post_login_hold_auth_wall post_login_hold_login_page
|
|
59
59
|
post_run_hold publisher_access_blocked publisher_content_error publisher_unreachable publisher_login_menu_opened
|
|
60
60
|
publisher_pdf_link_unverified publisher_session_save_failed publisher_session_saved
|
|
61
|
-
publisher_terms_accepted
|
|
61
|
+
publisher_terms_accepted personal_account_offer_skipped personal_account_offer_left
|
|
62
62
|
record_article_return record_article_return_error seamlessaccess_chooser_opened
|
|
63
63
|
shared_cookies_exported shared_cookies_loaded sso_entry_clicked sso_entry_error sso_start
|
|
64
64
|
access_unknown_pdf_first access_unknown_pdf_failed pdf_step_login_required login_round_trip_returned
|
|
65
65
|
pdf_probe pdf_probe_captured pdf_probe_refused no_access_after_login pdf_found_while_waiting
|
|
66
66
|
login_entry_missing login_entry_controls access_menu_opened access_menu_entry_refused access_menu_error
|
|
67
67
|
open_access_signal open_access_no_login no_institution_entry_remembered
|
|
68
|
-
article_reopen_error supplements_skipped browser_start
|
|
68
|
+
article_reopen_error supplements_skipped browser_start challenge_wait_ended
|
|
69
69
|
""".split()) | _FAILURES
|
|
70
70
|
_DETAIL_CATEGORIES = {
|
|
71
71
|
"login_observed": frozenset("""
|
|
@@ -1268,11 +1268,43 @@ class CaptureMixin:
|
|
|
1268
1268
|
self._event(result, "pdf_attempt",
|
|
1269
1269
|
f"{entry['how']} {entry['url'][:160]} -> {outcome}; {entry['status'] or '-'} "
|
|
1270
1270
|
f"{entry['type'] or '-'} {entry['size'] or '-'} bytes; ended at {final[:160]}; {entry['seconds']} s")
|
|
1271
|
+
if outcome != "pdf ok":
|
|
1272
|
+
self._note_download_limit(page, result)
|
|
1271
1273
|
if outcome != "pdf ok" and not any(s["why"] == "pdf attempt failed" for s in result.snapshots):
|
|
1272
1274
|
self._snapshot(page, result, "pdf attempt failed")
|
|
1273
1275
|
except Exception as exc: # the record never ends the capture
|
|
1274
1276
|
self._event(result, "pdf_attempt_record_error", f"{type(exc).__name__}: {str(exc)[:160]}")
|
|
1275
1277
|
|
|
1278
|
+
# The text of the dialogs over the page (a react-modal's content is role="dialog").
|
|
1279
|
+
_DIALOG_TEXT_JS = """() => [...document.querySelectorAll(
|
|
1280
|
+
'[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], .ReactModal__Content')]
|
|
1281
|
+
.filter(el => el.getClientRects().length > 0)
|
|
1282
|
+
.map(el => el.innerText || '').join(' ').slice(0, 2000)"""
|
|
1283
|
+
# A site's notice that the reader has used up its downloads for now.
|
|
1284
|
+
_DOWNLOAD_LIMIT = re.compile(
|
|
1285
|
+
r"download limit|(?:exceeded|reached)\b.{0,60}\bdownloads?\b|too many (?:pdf )?downloads"
|
|
1286
|
+
r"|下载.{0,8}(?:达到|超过|超出).{0,4}(?:上限|限额|限制)", re.I | re.S)
|
|
1287
|
+
|
|
1288
|
+
def _note_download_limit(self, page: Any, result: DownloadResult) -> None:
|
|
1289
|
+
"""A PDF attempt that got no PDF, with a dialog over the page saying the downloads
|
|
1290
|
+
are used up (ScienceDirect's "You have reached the daily bulk download limit" after
|
|
1291
|
+
its View PDF, 2026-11-21: 381 articles of one journal that day). Kept on the result:
|
|
1292
|
+
if the article ends without its PDF, that is why (bridge ``_failure_reason_code``).
|
|
1293
|
+
Read only from dialogs, not the article's own text."""
|
|
1294
|
+
if getattr(result, "_download_limit", ""):
|
|
1295
|
+
return
|
|
1296
|
+
try:
|
|
1297
|
+
said = " ".join(str(page.evaluate(self._DIALOG_TEXT_JS) or "").split())
|
|
1298
|
+
except Exception:
|
|
1299
|
+
return
|
|
1300
|
+
found = self._DOWNLOAD_LIMIT.search(said)
|
|
1301
|
+
if not found:
|
|
1302
|
+
return
|
|
1303
|
+
quoted = said[max(0, found.start() - 80):found.end() + 40]
|
|
1304
|
+
result._download_limit = quoted
|
|
1305
|
+
host = urlparse(str(getattr(page, "url", "") or "")).hostname or ""
|
|
1306
|
+
self._event(result, "publisher_download_limit", f'{host}: "{quoted[:200]}"')
|
|
1307
|
+
|
|
1276
1308
|
# Every link's address, label and visibility in one round trip: asking per
|
|
1277
1309
|
# link took ~25 s on a Nature page with hundreds of links.
|
|
1278
1310
|
_LINKS_JS = """() => [...document.querySelectorAll('a[href]')].map(a => ({
|
|
@@ -1750,7 +1782,9 @@ class CaptureMixin:
|
|
|
1750
1782
|
# not use up the PDF step, and once the check clears the PDF
|
|
1751
1783
|
# gets its full time again.
|
|
1752
1784
|
challenge_deadline = time.time() + max(self.page_wait_sec, timeout_sec)
|
|
1753
|
-
|
|
1785
|
+
# The PDF's answer can arrive while the tab still shows the check.
|
|
1786
|
+
arrived = (lambda: bool(captured.get("bytes"))) if captured is not None else None
|
|
1787
|
+
if not self._wait_for_challenge_with_deadline(page, result, challenge_deadline, until=arrived):
|
|
1754
1788
|
return None, str(getattr(page, "url", "") or "")
|
|
1755
1789
|
deadline = time.time() + timeout_sec
|
|
1756
1790
|
attempted.clear()
|
|
@@ -89,7 +89,7 @@ class DiagnosticsMixin:
|
|
|
89
89
|
"institution_search_submitted", "institution_search_retyped",
|
|
90
90
|
"institution_list_submitted", "institution_continue",
|
|
91
91
|
"login_round_trip_returned", "redirect_page_passed",
|
|
92
|
-
"publisher_terms_accepted", "idp_confirmation_accepted",
|
|
92
|
+
"publisher_terms_accepted", "idp_confirmation_accepted", "personal_account_offer_skipped",
|
|
93
93
|
}:
|
|
94
94
|
activity.progress()
|
|
95
95
|
# Only publish fixed phase text; event details can contain signed URLs.
|
|
@@ -154,6 +154,7 @@ class InstitutionMixin:
|
|
|
154
154
|
try:
|
|
155
155
|
inp = page.locator(selector).first
|
|
156
156
|
if inp.is_visible(timeout=5_000):
|
|
157
|
+
self._clear_before_typing(page, result)
|
|
157
158
|
inp.fill(self._typed_school_name())
|
|
158
159
|
self._event(result, "institution_search", selector)
|
|
159
160
|
settle(page, 2_000)
|
|
@@ -835,6 +836,8 @@ class InstitutionMixin:
|
|
|
835
836
|
if (not settled and not chosen and not getattr(result, "_institution_not_listed", False)
|
|
836
837
|
and time.time() - float(getattr(result, "_search_typed_at", 0) or 0) >= self.SEARCH_NOTHING_SEC
|
|
837
838
|
and (self._search_list_closed(page, result, url) or not self._entry_texts(page) - before)):
|
|
839
|
+
if self._retype_lost_search(page, result, url, tried[-1]):
|
|
840
|
+
return True
|
|
838
841
|
result._institution_not_listed = True
|
|
839
842
|
self._event(result, "institution_search_found_nothing", f"{', '.join(tried)[:120]} @ {url[:200]}")
|
|
840
843
|
return False
|
|
@@ -852,6 +855,7 @@ class InstitutionMixin:
|
|
|
852
855
|
if settled:
|
|
853
856
|
self._event(result, "institution_search_retry_skipped", f"box holds {value[:60]!r} @ {url[:200]}")
|
|
854
857
|
return False
|
|
858
|
+
self._clear_before_typing(page, result)
|
|
855
859
|
box.fill("")
|
|
856
860
|
box.press_sequentially(left[0], delay=40)
|
|
857
861
|
except Exception as exc:
|
|
@@ -867,6 +871,41 @@ class InstitutionMixin:
|
|
|
867
871
|
self._event(result, "auto_institution_search", f"{left[0]} @ {url}")
|
|
868
872
|
return True
|
|
869
873
|
|
|
874
|
+
def _clear_before_typing(self, page: Any, result: DownloadResult | None) -> None:
|
|
875
|
+
"""Before the school's name is typed into a page, wherever: a cookie banner over it answered first
|
|
876
|
+
(``_dismiss_cookie_banners``). One keeping the focus takes the keys typed behind it (Springer Nature's
|
|
877
|
+
chooser, 2026-11-22: the box stayed empty and the school was said not listed); the school's and the
|
|
878
|
+
federations' own pages stay as they are."""
|
|
879
|
+
if self._dismiss_cookie_banners(page, result):
|
|
880
|
+
settle(page, 1_000)
|
|
881
|
+
|
|
882
|
+
def _retype_lost_search(self, page: Any, result: DownloadResult, url: str, query: str) -> bool:
|
|
883
|
+
"""Before the school is said not listed: the box typed in is empty, nothing chosen or
|
|
884
|
+
answered there, so the keys went elsewhere (a cookie banner over Springer Nature's chooser
|
|
885
|
+
took them, 2026-11-22). Any banner answered, the name is typed again, once per page. True
|
|
886
|
+
when typed; a box holding anything is left as it is."""
|
|
887
|
+
box_at = getattr(result, "_search_box", None)
|
|
888
|
+
if (not query or not isinstance(box_at, tuple)
|
|
889
|
+
or any(e["state"] == "institution_search_lost"
|
|
890
|
+
and self._same_address(str(e.get("detail", "")).partition(" @ ")[2], url) for e in result.events)):
|
|
891
|
+
return False
|
|
892
|
+
try:
|
|
893
|
+
box = page.locator(f"[{self._SEARCH_BOX_MARK}]").first
|
|
894
|
+
if box.is_visible(timeout=500) is not True:
|
|
895
|
+
box = page.locator(box_at[1]).first
|
|
896
|
+
if box.is_visible(timeout=500) is not True or str(box.input_value(timeout=2_000) or "").strip():
|
|
897
|
+
return False
|
|
898
|
+
self._clear_before_typing(page, result)
|
|
899
|
+
box.fill("")
|
|
900
|
+
box.press_sequentially(query, delay=40)
|
|
901
|
+
except Exception as exc:
|
|
902
|
+
if not _is_browser_error(exc):
|
|
903
|
+
raise
|
|
904
|
+
return False
|
|
905
|
+
result._search_typed_at = time.time()
|
|
906
|
+
self._event(result, "institution_search_lost", f"{query} @ {url}")
|
|
907
|
+
return True
|
|
908
|
+
|
|
870
909
|
def _search_list_closed(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
871
910
|
"""The search box typed in says its list is closed (``aria-expanded="false"``):
|
|
872
911
|
no results are shown, whatever else the page lists (2026-11-13: a search
|
|
@@ -1229,6 +1268,7 @@ class InstitutionMixin:
|
|
|
1229
1268
|
continue
|
|
1230
1269
|
if str(box.input_value(timeout=2_000) or "").strip():
|
|
1231
1270
|
return False # the user is typing; never replace it
|
|
1271
|
+
self._clear_before_typing(page, result)
|
|
1232
1272
|
# Marked before typing: a box found by its placeholder loses it once it holds a
|
|
1233
1273
|
# name, and the next name is typed into it again (Science, 2026-11-17).
|
|
1234
1274
|
box.evaluate(f"el => el.setAttribute('{self._SEARCH_BOX_MARK}', '')")
|
|
@@ -1351,6 +1391,7 @@ class InstitutionMixin:
|
|
|
1351
1391
|
continue
|
|
1352
1392
|
if (box.input_value(timeout=2_000) or "").strip():
|
|
1353
1393
|
return False # the user already typed; never overwrite
|
|
1394
|
+
self._clear_before_typing(page, result)
|
|
1354
1395
|
box.fill(self._typed_school_name())
|
|
1355
1396
|
self._event(result, "institution_search", f"{federation.code}:{selector}")
|
|
1356
1397
|
pump_until(page, lambda: self._any_visible(page, self._institution_result_selectors()), 2_000)
|
|
@@ -729,7 +729,8 @@ class LoginMixin:
|
|
|
729
729
|
continue
|
|
730
730
|
if self._return_from_login_site(page, result):
|
|
731
731
|
continue
|
|
732
|
-
if self._accept_publisher_terms(page, result) or self._accept_idp_confirmation(page, result)
|
|
732
|
+
if (self._accept_publisher_terms(page, result) or self._accept_idp_confirmation(page, result)
|
|
733
|
+
or self._skip_personal_account_offer(page, result)):
|
|
733
734
|
continue
|
|
734
735
|
if manual_selection:
|
|
735
736
|
if self._is_challenge_page(page):
|
|
@@ -905,6 +906,69 @@ class LoginMixin:
|
|
|
905
906
|
settle(page, 2_000)
|
|
906
907
|
return True
|
|
907
908
|
|
|
909
|
+
# After the school's sign-in, the publisher's offer of an account of the user's own (Elsevier ID's
|
|
910
|
+
# "Personalize your experience. We now know you're from <school>. … enter your email to sign in or
|
|
911
|
+
# create an Elsevier account", 2026-11-22, once the browser kept no Elsevier account's sign-in): the
|
|
912
|
+
# school's access needs none, so it is skipped (user, 2026-11-22). Its empty email field, and a
|
|
913
|
+
# "Skip", "Not now" or "No thanks", else its close (×), marked for the click.
|
|
914
|
+
_ACCOUNT_OFFER_JS = r"""() => {
|
|
915
|
+
const shown = el => !!el && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
|
|
916
|
+
const words = el => [el.innerText || el.value || '', el.getAttribute('aria-label') || '', el.getAttribute('title') || '']
|
|
917
|
+
.join(' ').replace(/\s+/g, ' ').trim();
|
|
918
|
+
const body = ((document.body && document.body.innerText) || '').replace(/\s+/g, ' ').slice(0, 4000);
|
|
919
|
+
const OFFER = /personali[sz]e your experience|\b(?:sign|log) in or (?:create|register)\b|\bcreate (?:an?|your)(?: free)?(?: [\w-]+)? account\b|\bregister for (?:an?|your)(?: free)? account\b|创建(?:个人)?账[号户]|注册(?:个人)?账[号户]/i;
|
|
920
|
+
if (!OFFER.test(body)) return null;
|
|
921
|
+
const email = [...document.querySelectorAll('input')].filter(el => shown(el) && !el.disabled && !el.readOnly
|
|
922
|
+
&& (el.type === 'email' || /e-?mail|邮箱/i.test([el.name, el.id, el.autocomplete, el.placeholder,
|
|
923
|
+
el.getAttribute('aria-label'), el.labels && [...el.labels].map(l => l.innerText).join(' ')].join(' '))));
|
|
924
|
+
if (!email.length || email.some(el => String(el.value || '').length > 0)) return null; // someone typing: theirs
|
|
925
|
+
const controls = [...document.querySelectorAll('button, a, [role="button"], input[type="button"], input[type="submit"]')]
|
|
926
|
+
.filter(el => shown(el) && !el.disabled);
|
|
927
|
+
const SKIP = /^(?:skip(?: for now| this step)?|not now|no,? thanks?|maybe later|remind me later|later|continue without(?: an?)?(?: account| signing in| sign-?in| registering)|continue as (?:a )?guest|跳过|暂不|以后再说|稍后再说)$/i;
|
|
928
|
+
const named = el => `${el.getAttribute('aria-label') || ''} ${el.getAttribute('title') || ''}`;
|
|
929
|
+
let kind = 'skip', pick = controls.find(el => SKIP.test(words(el)));
|
|
930
|
+
if (!pick) {
|
|
931
|
+
kind = 'close';
|
|
932
|
+
pick = controls.find(el => /^(?:close|dismiss|关闭|[×✕✖xX])$/i.test((el.innerText || el.value || '').trim())
|
|
933
|
+
|| /\bclose\b|\bdismiss\b|关闭/i.test(named(el))
|
|
934
|
+
|| (!(el.innerText || '').trim() && /(?:^|[-_ ])close(?:$|[-_ ])/i.test(`${el.id} ${el.getAttribute('class') || ''}`)));
|
|
935
|
+
}
|
|
936
|
+
if (pick) pick.setAttribute('data-papersearch-offer', '1');
|
|
937
|
+
const heading = ((document.querySelector('h1, h2') || {}).innerText || '').replace(/\s+/g, ' ').trim();
|
|
938
|
+
return {kind: pick ? kind : '', label: pick ? words(pick).slice(0, 60) : '', heading: heading.slice(0, 80)};
|
|
939
|
+
}"""
|
|
940
|
+
ACCOUNT_OFFER_SKIPS = 2
|
|
941
|
+
|
|
942
|
+
def _skip_personal_account_offer(self, page: Any, result: DownloadResult) -> bool:
|
|
943
|
+
"""After the school's sign-in, on the publisher's site or its sign-in service: skip its offer
|
|
944
|
+
of a personal account (``_ACCOUNT_OFFER_JS``). Still offered after ``ACCOUNT_OFFER_SKIPS``
|
|
945
|
+
clicks, or with nothing to skip it by, the article is opened again, once. True when done."""
|
|
946
|
+
url = str(getattr(page, "url", "") or "")
|
|
947
|
+
if (not self._school_login_done() or not (self._on_publisher_host(url) or self._is_auth_page(url))
|
|
948
|
+
or self._is_idp_host(urlparse(url).netloc) or self._on_school_login_page(url)):
|
|
949
|
+
return False
|
|
950
|
+
try:
|
|
951
|
+
offer = page.evaluate(self._ACCOUNT_OFFER_JS)
|
|
952
|
+
except Exception as exc:
|
|
953
|
+
if not _is_browser_error(exc):
|
|
954
|
+
raise
|
|
955
|
+
return False
|
|
956
|
+
if not isinstance(offer, dict):
|
|
957
|
+
return False
|
|
958
|
+
where = f"{offer.get('heading') or ''} @ {url[:160]}"
|
|
959
|
+
skips = sum(e["state"] == "personal_account_offer_skipped" for e in result.events)
|
|
960
|
+
if offer.get("kind") and skips < self.ACCOUNT_OFFER_SKIPS and self._click_control(
|
|
961
|
+
page, page.locator('[data-papersearch-offer="1"]').first, result, "skip the publisher's account offer"):
|
|
962
|
+
self._event(result, "personal_account_offer_skipped", f"{offer['kind']} \"{offer.get('label') or ''}\" | {where}")
|
|
963
|
+
settle(page, 3_000)
|
|
964
|
+
return True
|
|
965
|
+
if not result.article_url or any(e["state"] == "personal_account_offer_left" for e in result.events):
|
|
966
|
+
return False
|
|
967
|
+
open_page(page, result.article_url, timeout_ms=60_000)
|
|
968
|
+
self._event(result, "personal_account_offer_left", where)
|
|
969
|
+
settle(page, 3_000)
|
|
970
|
+
return True
|
|
971
|
+
|
|
908
972
|
# The school's IdP asking to agree before it goes on (Shibboleth's attribute
|
|
909
973
|
# release and terms of use): accepted for the user too, as they asked
|
|
910
974
|
# (2026-11-08). The release keeps the choices the school preselected; the
|
|
@@ -7,6 +7,7 @@ from __future__ import annotations
|
|
|
7
7
|
import inspect
|
|
8
8
|
import re
|
|
9
9
|
import time
|
|
10
|
+
from collections.abc import Callable
|
|
10
11
|
from contextlib import ExitStack
|
|
11
12
|
from typing import Any
|
|
12
13
|
from urllib.parse import urlparse
|
|
@@ -24,17 +25,21 @@ class UserWaitMixin:
|
|
|
24
25
|
page: Any,
|
|
25
26
|
result: DownloadResult,
|
|
26
27
|
deadline: float,
|
|
28
|
+
until: Callable[[], bool] | None = None,
|
|
27
29
|
) -> bool:
|
|
30
|
+
"""``until``: what the wait is for has arrived behind the verification page
|
|
31
|
+
(``_wait_for_challenge``)."""
|
|
28
32
|
try:
|
|
29
33
|
signature = inspect.signature(self._wait_for_challenge)
|
|
30
34
|
except (TypeError, ValueError):
|
|
31
35
|
return self._wait_for_challenge(page, result)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
any_keyword = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in signature.parameters.values())
|
|
37
|
+
options: dict[str, Any] = {}
|
|
38
|
+
if "deadline" in signature.parameters or any_keyword:
|
|
39
|
+
options["deadline"] = deadline
|
|
40
|
+
if until is not None and ("until" in signature.parameters or any_keyword):
|
|
41
|
+
options["until"] = until
|
|
42
|
+
return self._wait_for_challenge(page, result, **options)
|
|
38
43
|
|
|
39
44
|
# A wait off the school's login page (verification, the publisher's pages and
|
|
40
45
|
# choosers, the PDF step): config ``browser_page_wait_timeout``, else this.
|
|
@@ -571,8 +576,12 @@ class UserWaitMixin:
|
|
|
571
576
|
else:
|
|
572
577
|
progress_reporter.update_attention_deadline(key, deadline)
|
|
573
578
|
|
|
574
|
-
def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None
|
|
575
|
-
|
|
579
|
+
def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None,
|
|
580
|
+
until: Callable[[], bool] | None = None) -> bool:
|
|
581
|
+
"""Wait while a verification page is up, until ``_wait_deadline``. ``until``: the
|
|
582
|
+
wait ends, as passed, once it says what it waits for has arrived though the page
|
|
583
|
+
is still up (the PDF's answer, captured while ScienceDirect's tab stayed on "Just
|
|
584
|
+
a moment...": two articles failed with the PDF in hand, 2026-11-21)."""
|
|
576
585
|
interaction = ExitStack()
|
|
577
586
|
activity, activity_owned = self._observe_page_activity(page, result)
|
|
578
587
|
automatic: dict[str, Any] = {}
|
|
@@ -587,6 +596,11 @@ class UserWaitMixin:
|
|
|
587
596
|
checks = 0
|
|
588
597
|
while True:
|
|
589
598
|
self._check_user_decision(result, page)
|
|
599
|
+
if until is not None and until():
|
|
600
|
+
if waited:
|
|
601
|
+
result.state = state_before
|
|
602
|
+
self._event(result, "challenge_wait_ended", "what it waited for arrived")
|
|
603
|
+
return True
|
|
590
604
|
# While the interstitial is up, look only at title and URL.
|
|
591
605
|
shell = self._challenge_shell(page)
|
|
592
606
|
if not shell:
|
|
@@ -42,6 +42,9 @@ _FAILURE_KINDS = {
|
|
|
42
42
|
"browser_unresponsive": ("browser_unresponsive", "review_browser"),
|
|
43
43
|
"browser_operation_timeout": ("browser_operation_timeout", "review_browser"),
|
|
44
44
|
"publisher_access_blocked": ("access_blocked", "review_access"),
|
|
45
|
+
# The site said its downloads are used up for now (batch_capture ``_note_download_limit``):
|
|
46
|
+
# like a block, the journal's later articles wait and one re-checks now and then.
|
|
47
|
+
"publisher_download_limit": ("access_blocked", "review_access"),
|
|
45
48
|
"publisher_unreachable": ("publisher_unreachable", "review_publisher_error"),
|
|
46
49
|
"sso_required": ("paywall", "login_required"),
|
|
47
50
|
"institution_pdf_entitlement_missing": ("paywall", "review_entitlement"),
|
|
@@ -124,9 +127,17 @@ def _failure_reason_code(result: Any) -> str:
|
|
|
124
127
|
reason_code = "login_timeout" if wait_page in ("school_login", "school_choice") else "login_not_reached"
|
|
125
128
|
elif reason_code == "sso_required" and getattr(result, "_user_wait_expired", False):
|
|
126
129
|
reason_code = "login_timeout" # the login waited on the user until its time was up
|
|
130
|
+
if getattr(result, "_download_limit", "") and reason_code in _PDF_NOT_ARRIVED:
|
|
131
|
+
# The site had said its downloads were used up: that, not the wait, is why.
|
|
132
|
+
reason_code = "publisher_download_limit"
|
|
127
133
|
return reason_code
|
|
128
134
|
|
|
129
135
|
|
|
136
|
+
# Failures that only say the PDF did not come (a site's download-limit notice says why).
|
|
137
|
+
_PDF_NOT_ARRIVED = frozenset({"challenge_or_viewer_timeout", "pdf_not_captured", "download_failed",
|
|
138
|
+
"request_failed", "download_timeout", "browser_operation_timeout", ""})
|
|
139
|
+
|
|
140
|
+
|
|
130
141
|
def try_institutional(
|
|
131
142
|
doi: str,
|
|
132
143
|
output_path: Path,
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
"""The progress window in
|
|
2
|
-
text it can show (its own, the download's prompts and phases, PaperSearch's
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
"""The progress window in other languages than its own simplified Chinese: ``assets/capsule_en.json`` maps each
|
|
2
|
+
Chinese text it can show (its own, the download's prompts and phases, PaperSearch's failure reasons) to a short
|
|
3
|
+
English one; ``assets/capsule_zh-Hant.json`` (made from it by ``school/tools/zh_hant_table.py``, user 2026-11-21)
|
|
4
|
+
says each in Traditional Chinese, and turns any other text character by character; ``capsule_ja.json``,
|
|
5
|
+
``capsule_ko.json`` and ``capsule_fr.json`` say them in Japanese, Korean and French (user, 2026-11-21), a text they
|
|
6
|
+
do not know in English. The page translates what it shows with them; the system notifications use them here. In
|
|
7
|
+
English a text the table does not know stays as it is."""
|
|
6
8
|
from __future__ import annotations
|
|
7
9
|
|
|
8
10
|
import json
|
|
@@ -10,42 +12,64 @@ import re
|
|
|
10
12
|
from functools import lru_cache
|
|
11
13
|
from pathlib import Path
|
|
12
14
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
+
ASSETS = Path(__file__).resolve().parent / "assets"
|
|
16
|
+
#: Each language's table; Chinese (zh, simplified) is the windows' own.
|
|
17
|
+
TABLES = {"en": ASSETS / "capsule_en.json", "zh-Hant": ASSETS / "capsule_zh-Hant.json",
|
|
18
|
+
"ja": ASSETS / "capsule_ja.json", "ko": ASSETS / "capsule_ko.json", "fr": ASSETS / "capsule_fr.json"}
|
|
19
|
+
TABLE = TABLES["en"]
|
|
20
|
+
LANGUAGES = ("zh", "zh-Hant", "en", "ja", "ko", "fr")
|
|
15
21
|
_HAN = re.compile(r"[\u4e00-\u9fff]")
|
|
16
22
|
_BRACKETS = re.compile(r"^(.+?)((.+))$")
|
|
23
|
+
_LISTED = re.compile(r"^([^:]+):(.+)$")
|
|
17
24
|
|
|
18
25
|
|
|
19
|
-
@lru_cache(maxsize=
|
|
20
|
-
def table() -> dict:
|
|
21
|
-
return json.loads(
|
|
26
|
+
@lru_cache(maxsize=None)
|
|
27
|
+
def table(lang: str = "en") -> dict:
|
|
28
|
+
return json.loads(TABLES[lang].read_text(encoding="utf-8"))
|
|
22
29
|
|
|
23
30
|
|
|
24
|
-
@lru_cache(maxsize=
|
|
25
|
-
def _patterns() -> list[tuple[re.Pattern, str]]:
|
|
26
|
-
|
|
27
|
-
return [(re.compile(source), re.sub(r"\$(\d)", r"\\g<\1>", target)) for source, target in table()["patterns"]]
|
|
31
|
+
@lru_cache(maxsize=None)
|
|
32
|
+
def _patterns(lang: str = "en") -> list[tuple[re.Pattern, str]]:
|
|
33
|
+
return [(re.compile(source), target) for source, target in table(lang)["patterns"]]
|
|
28
34
|
|
|
29
35
|
|
|
30
|
-
def
|
|
36
|
+
def _part(text: str, lang: str) -> str:
|
|
37
|
+
return _one(text, lang) if _HAN.search(text) else text
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _one(text: str, lang: str = "en") -> str:
|
|
31
41
|
core = text.strip()
|
|
32
42
|
if not core or not _HAN.search(core):
|
|
33
43
|
return text
|
|
34
|
-
exact = table()["exact"].get(core)
|
|
44
|
+
exact = table(lang)["exact"].get(core)
|
|
35
45
|
if exact is None:
|
|
36
|
-
for pattern, target in _patterns():
|
|
37
|
-
|
|
38
|
-
|
|
46
|
+
for pattern, target in _patterns(lang):
|
|
47
|
+
found = pattern.search(core)
|
|
48
|
+
if found:
|
|
49
|
+
# What it names is said too where it is a text of the table; a name keeps its words (as the page does).
|
|
50
|
+
said = re.sub(r"\$(\d)", lambda m: _part(found.group(int(m.group(1))) or "", lang), target)
|
|
51
|
+
exact = core[:found.start()] + said + core[found.end():]
|
|
39
52
|
break
|
|
53
|
+
if exact is None and lang == "zh-Hant":
|
|
54
|
+
# Not a text of the table: its characters (a name keeps its words).
|
|
55
|
+
chars = table(lang)["chars"]
|
|
56
|
+
exact = "".join(chars.get(c, c) for c in core)
|
|
40
57
|
parts = _BRACKETS.match(core) if exact is None else None
|
|
41
58
|
if parts:
|
|
42
59
|
# "开放下载 18(出版社 API 3、预印本 1)": the text and what its brackets list, each on its own.
|
|
43
|
-
exact = f"{_one(parts[1])} ({', '.join(_one(item) for item in parts[2].split('、'))})"
|
|
60
|
+
exact = f"{_one(parts[1], lang)} ({', '.join(_one(item, lang) for item in parts[2].split('、'))})"
|
|
61
|
+
listed = _LISTED.match(core) if exact is None else None
|
|
62
|
+
if listed and _one(listed[1], lang) != listed[1]:
|
|
63
|
+
# "读取失败:TimeoutError": a known word, then what it says, each on its own (as the page does).
|
|
64
|
+
exact = f"{_one(listed[1], lang)}: {', '.join(_one(item, lang) for item in listed[2].split(','))}"
|
|
65
|
+
if exact is None and lang not in ("en", "zh-Hant"):
|
|
66
|
+
# Japanese, Korean, French: what their table does not know, in English rather than in Chinese.
|
|
67
|
+
return _one(text, "en")
|
|
44
68
|
return text if exact is None else text.replace(core, exact)
|
|
45
69
|
|
|
46
70
|
|
|
47
71
|
def translate(text: str, lang: str) -> str:
|
|
48
72
|
"""``text`` in ``lang``; its " · " parts one by one, as the page does."""
|
|
49
|
-
if lang
|
|
73
|
+
if lang not in TABLES or not text:
|
|
50
74
|
return text
|
|
51
|
-
return " · ".join(_one(part) for part in text.split(" · "))
|
|
75
|
+
return " · ".join(_one(part, lang) for part in text.split(" · "))
|