papersearch 0.6.3 → 0.6.5
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 +16 -20
- package/README.md +16 -20
- package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.js +1 -1
- package/package.json +1 -1
- package/school/paper_search_school/adapters/base.py +3 -2
- package/school/paper_search_school/adapters/elsevier/__init__.py +46 -0
- package/school/paper_search_school/adapters/sage/__init__.py +9 -1
- package/school/paper_search_school/cli.py +1 -1
- package/school/paper_search_school/config.py +2 -0
- package/school/paper_search_school/engine/batch_institution.py +153 -17
- package/school/paper_search_school/engine/batch_login.py +42 -11
- package/school/paper_search_school/federations/builtin/aaieduhr.json +11 -0
- package/school/paper_search_school/federations/builtin/aaiedumk.json +11 -0
- package/school/paper_search_school/federations/builtin/aconet.json +11 -0
- package/school/paper_search_school/federations/builtin/arnesaai.json +11 -0
- package/school/paper_search_school/federations/builtin/azsciencenet.json +11 -0
- package/school/paper_search_school/federations/builtin/belnet.json +11 -0
- package/school/paper_search_school/federations/builtin/bif.json +11 -0
- package/school/paper_search_school/federations/builtin/cstcloud.json +11 -0
- package/school/paper_search_school/federations/builtin/cynet.json +11 -0
- package/school/paper_search_school/federations/builtin/dfnaai.json +11 -0
- package/school/paper_search_school/federations/builtin/edugate.json +11 -0
- package/school/paper_search_school/federations/builtin/eduidcz.json +11 -0
- package/school/paper_search_school/federations/builtin/eduidhu.json +11 -0
- package/school/paper_search_school/federations/builtin/eduidlu.json +11 -0
- package/school/paper_search_school/federations/builtin/febas.json +11 -0
- package/school/paper_search_school/federations/builtin/feide.json +11 -0
- package/school/paper_search_school/federations/builtin/grnet.json +11 -0
- package/school/paper_search_school/federations/builtin/haka.json +11 -0
- package/school/paper_search_school/federations/builtin/iamres.json +11 -0
- package/school/paper_search_school/federations/builtin/idedume.json +11 -0
- package/school/paper_search_school/federations/builtin/idem.json +11 -0
- package/school/paper_search_school/federations/builtin/irfed.json +11 -0
- package/school/paper_search_school/federations/builtin/iucc.json +11 -0
- package/school/paper_search_school/federations/builtin/laife.json +11 -0
- package/school/paper_search_school/federations/builtin/leaf.json +11 -0
- package/school/paper_search_school/federations/builtin/litnet.json +11 -0
- package/school/paper_search_school/federations/builtin/maeen.json +11 -0
- package/school/paper_search_school/federations/builtin/peano.json +11 -0
- package/school/paper_search_school/federations/builtin/pionierid.json +11 -0
- package/school/paper_search_school/federations/builtin/rash.json +11 -0
- package/school/paper_search_school/federations/builtin/rctsaai.json +11 -0
- package/school/paper_search_school/federations/builtin/renater.json +11 -0
- package/school/paper_search_school/federations/builtin/ricerkanet.json +11 -0
- package/school/paper_search_school/federations/builtin/roedunetid.json +11 -0
- package/school/paper_search_school/federations/builtin/safeid.json +11 -0
- package/school/paper_search_school/federations/builtin/sir.json +11 -0
- package/school/paper_search_school/federations/builtin/surfconext.json +11 -0
- package/school/paper_search_school/federations/builtin/swamid.json +11 -0
- package/school/paper_search_school/federations/builtin/switchaai.json +11 -0
- package/school/paper_search_school/federations/builtin/taat.json +11 -0
- package/school/paper_search_school/federations/builtin/ukfederation.json +11 -0
- package/school/paper_search_school/federations/builtin/wayf.json +11 -0
- package/school/paper_search_school/federations/schools.py +96 -20
- package/school/paper_search_school/login_routes.py +6 -6
- package/school/paper_search_school/report_sanitizer.py +1 -1
- package/skills/paper-search/SKILL.md +1 -1
- package/skills/paper-search/references/federation-support.md +149 -11
- package/skills/paper-search/references/school-setup.md +3 -2
package/README.en.md
CHANGED
|
@@ -133,27 +133,23 @@ Papers the open channels cannot get can come through your school's subscriptions
|
|
|
133
133
|
1. Through the federations interconnected via [eduGAIN](https://edugain.org/), such as CARSI in China, HKAF in Hong Kong and SGAF in Singapore;
|
|
134
134
|
2. Schools in no national federation that have [OpenAthens](https://www.openathens.net/) access can sign in through it as well.
|
|
135
135
|
|
|
136
|
-
**Supported academic identity federations** (
|
|
136
|
+
**Supported academic identity federations** (by continent and region)
|
|
137
137
|
|
|
138
|
-
|
|
|
138
|
+
| Continent | Region | Supported (place: federation) |
|
|
139
139
|
|---|---|---|
|
|
140
|
-
| Chinese mainland, Macau
|
|
141
|
-
|
|
|
142
|
-
|
|
|
143
|
-
|
|
|
144
|
-
|
|
|
145
|
-
|
|
|
146
|
-
|
|
|
147
|
-
|
|
|
148
|
-
|
|
|
149
|
-
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
| Schools in no national federation (most universities in Southeast Asia and others) | OpenAthens | OpenAthens institutional sign-in |
|
|
154
|
-
|
|
155
|
-
- What each federation supports: [federation support table](skills/paper-search/references/federation-support.md) (Chinese).
|
|
156
|
-
- Planned: the UK (UK federation), Australia (AAF) and the federations of European countries, then the other countries in eduGAIN; see the [roadmap](docs/ROADMAP.zh.md) (Chinese).
|
|
140
|
+
| Asia | East Asia | Chinese mainland, Macau: CARSI; research institutions in the Chinese mainland: CSTCloud; Hong Kong: HKAF; Japan: GakuNin; South Korea: KAFE; Taiwan: through OpenAthens |
|
|
141
|
+
| Asia | Southeast Asia | Singapore: SGAF; Malaysia: SIFULAN; Thailand, the Philippines and others: through OpenAthens |
|
|
142
|
+
| Asia | South Asia | India: INFED; Sri Lanka: LIAF; Bangladesh: TIGERfed; Pakistan: PKIFED |
|
|
143
|
+
| Asia | West Asia | Turkey: YETKİM; Saudi Arabia: Maeen; Cyprus: CyNet; Israel: IUCC; Iran: IRFED; Azerbaijan: AzScienceNet; Oman: OMREN |
|
|
144
|
+
| Europe | Western Europe | United Kingdom: UK federation; Ireland: Edugate; France: RENATER; Netherlands: SURFconext; Belgium: Belnet; Luxembourg: eduID Luxembourg |
|
|
145
|
+
| Europe | Northern Europe | Denmark (with Iceland and Greenland): WAYF; Sweden: SWAMID; Finland: Haka; Norway: Feide |
|
|
146
|
+
| Europe | Central Europe | Germany: DFN-AAI; Switzerland: Switch edu-ID; Austria: ACOnet; Poland: PIONIER.Id; Czechia: eduID.cz; Slovakia: safeID; Hungary: eduId.hu |
|
|
147
|
+
| Europe | Southern Europe | Spain: SIR; Portugal: RCTSaai; Italy: IDEM; Greece: GRNET; Malta: RiċerkaNET; Slovenia: ArnesAAI; Croatia: AAI@EduHr; Serbia: iAMRES; Montenegro: IDeduME; North Macedonia: AAIEduMk; Albania: RASH; Bulgaria: BIF; Romania: RoEduNetID |
|
|
148
|
+
| Europe | Eastern Europe | Estonia: TAAT; Latvia: LAIFE; Lithuania: LITNET FEDI; Belarus: FEBAS; Ukraine: PEANO; Moldova: LEAF |
|
|
149
|
+
| Americas | North America | United States: InCommon |
|
|
150
|
+
|
|
151
|
+
- Full names, school counts and tested schools of each federation: [federation support table](skills/paper-search/references/federation-support.md) (Chinese).
|
|
152
|
+
- Planned, in this order: the Americas (Canada, then Latin America and the Caribbean), Oceania, and Africa last; see the [roadmap](docs/ROADMAP.zh.md) (Chinese).
|
|
157
153
|
|
|
158
154
|
- **Your school account is enough**: no keys to apply for; publisher API keys only cover Elsevier and Springer.
|
|
159
155
|
- **Deep publisher adaptation**: the general download flow is deeply optimized, and more than 30 publishers have dedicated rules, one by one: where the institutional login is and how to fetch the PDF and supplementary files follow each publisher as it really is, so downloads are more accurate and fewer papers are missed. The main publishers:
|
|
@@ -245,7 +241,7 @@ Next on the list:
|
|
|
245
241
|
1. **A better progress capsule**: better-timed reminders, with no early prompt when the school login page lets you through by itself; less of the browser briefly jumping to the front on Windows when it starts or changes pages; a cleaner look.
|
|
246
242
|
2. **Parallel downloads**: papers from different publishers download at the same time, cutting the total time for dozens or hundreds of papers; each publisher's download limits still apply.
|
|
247
243
|
3. **A Markdown full-text package**: besides the PDF, the original XML/HTML, a Markdown reading copy and the figures, with figure numbers, captions and in-text references matched, ready to hand to an AI for reading and citing.
|
|
248
|
-
4. **School sign-in worldwide**: the academic identity federations of Asia are supported; next come
|
|
244
|
+
4. **School sign-in worldwide**: the academic identity federations of Asia, Europe and the US are supported; next come Canada, Latin America and the Caribbean, Oceania, and Africa last, covering every country in eduGAIN; WebVPN, EZProxy and similar where possible.
|
|
249
245
|
5. **Better paper search and full-text snippets**: learn from similar tools and improve how papers and passages are found.
|
|
250
246
|
|
|
251
247
|
The full plan is in the [roadmap](docs/ROADMAP.zh.md) (Chinese); how it works inside is in the [architecture](docs/ARCHITECTURE.zh.md) (Chinese). Feature ideas are welcome as [issues](https://github.com/dr-dumpling/PaperSearch/issues/new/choose) and pull requests; for failed downloads or publisher requests use the matching issue template, and to add publisher rules yourself see [school/CONTRIBUTING.md](school/CONTRIBUTING.md).
|
package/README.md
CHANGED
|
@@ -133,27 +133,23 @@ AI 会先问你要不要装 PaperSearch 的命令行程序,你同意后装好
|
|
|
133
133
|
1.通过 [eduGAIN](https://edugain.org/) 互联,如中国CARSI、香港HKAF,新加坡SGAF等;
|
|
134
134
|
2.没有加入本国联盟的学校,有 [OpenAthens](https://www.openathens.net/) 权限的,也能经它登录。
|
|
135
135
|
|
|
136
|
-
|
|
136
|
+
**支持的学术身份联盟**(按大洲和区域)
|
|
137
137
|
|
|
138
|
-
|
|
|
138
|
+
| 大洲 | 区域 | 已支持(地区:联盟) |
|
|
139
139
|
|---|---|---|
|
|
140
|
-
|
|
|
141
|
-
|
|
|
142
|
-
|
|
|
143
|
-
|
|
|
144
|
-
|
|
|
145
|
-
|
|
|
146
|
-
|
|
|
147
|
-
|
|
|
148
|
-
|
|
|
149
|
-
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
| 未加入本国联盟的学校(东南亚多数大学等) | OpenAthens | OpenAthens 机构登录服务 |
|
|
154
|
-
|
|
155
|
-
- 每个联盟的支持情况,见 [学术联盟支持表](skills/paper-search/references/federation-support.md)。
|
|
156
|
-
- 计划中:英国(UK federation)、澳大利亚(AAF)、欧洲各国联盟,之后是 eduGAIN 里的其他国家,见 [路线图](docs/ROADMAP.zh.md)。
|
|
140
|
+
| 亚洲 | 东亚 | 中国内地、澳门:CARSI;中国内地科研机构:CSTCloud(中国科技云联盟);香港:HKAF;日本:GakuNin(学認);韩国:KAFE;台湾:经 OpenAthens |
|
|
141
|
+
| 亚洲 | 东南亚 | 新加坡:SGAF;马来西亚:SIFULAN;泰国、菲律宾等:经 OpenAthens |
|
|
142
|
+
| 亚洲 | 南亚 | 印度:INFED;斯里兰卡:LIAF;孟加拉:TIGERfed;巴基斯坦:PKIFED |
|
|
143
|
+
| 亚洲 | 西亚 | 土耳其:YETKİM;沙特阿拉伯:Maeen;塞浦路斯:CyNet;以色列:IUCC;伊朗:IRFED;阿塞拜疆:AzScienceNet;阿曼:OMREN |
|
|
144
|
+
| 欧洲 | 西欧 | 英国:UK federation;爱尔兰:Edugate;法国:RENATER;荷兰:SURFconext;比利时:Belnet;卢森堡:eduID Luxembourg |
|
|
145
|
+
| 欧洲 | 北欧 | 丹麦(含冰岛、格陵兰):WAYF;瑞典:SWAMID;芬兰:Haka;挪威:Feide |
|
|
146
|
+
| 欧洲 | 中欧 | 德国:DFN-AAI;瑞士:Switch edu-ID;奥地利:ACOnet;波兰:PIONIER.Id;捷克:eduID.cz;斯洛伐克:safeID;匈牙利:eduId.hu |
|
|
147
|
+
| 欧洲 | 南欧 | 西班牙:SIR;葡萄牙:RCTSaai;意大利:IDEM;希腊:GRNET;马耳他:RiċerkaNET;斯洛文尼亚:ArnesAAI;克罗地亚:AAI@EduHr;塞尔维亚:iAMRES;黑山:IDeduME;北马其顿:AAIEduMk;阿尔巴尼亚:RASH;保加利亚:BIF;罗马尼亚:RoEduNetID |
|
|
148
|
+
| 欧洲 | 东欧 | 爱沙尼亚:TAAT;拉脱维亚:LAIFE;立陶宛:LITNET FEDI;白俄罗斯:FEBAS;乌克兰:PEANO;摩尔多瓦:LEAF |
|
|
149
|
+
| 美洲 | 北美洲 | 美国:InCommon |
|
|
150
|
+
|
|
151
|
+
- 各联盟的全称、学校数和实测过的学校,见 [学术联盟支持表](skills/paper-search/references/federation-support.md)。
|
|
152
|
+
- 计划中,按这个顺序推进:美洲(加拿大,再拉丁美洲和加勒比)、大洋洲,最后非洲,见 [路线图](docs/ROADMAP.zh.md)。
|
|
157
153
|
|
|
158
154
|
- **学校账号就能用**:不用另外申请 key;出版社 API key 只覆盖 Elsevier、Springer 两家。
|
|
159
155
|
- **深度适配出版社**:深度优化了下载的通用流程,并且针对 30 多家出版社逐家写了专门规则,机构登录入口在哪、PDF 和补充材料怎么取,都按各自出版社的实际情况来,下载更准、更少漏篇。优化的出版社主要有:
|
|
@@ -245,7 +241,7 @@ paper-search school status --format text # 查看是否装好
|
|
|
245
241
|
1. **进度胶囊优化**:提醒时机更准,学校登录页能自动放行时不提前打扰;减少 Windows 上浏览器启动、换页时短暂跳到前台的情况,优化显示效果。
|
|
246
242
|
2. **并行下载**:不同出版社之间并行下载,同时处理多篇,缩短几十上百篇的总耗时;每家出版社仍遵守下载上限。
|
|
247
243
|
3. **Markdown 全文包**:除了 PDF,再交付原始 XML/HTML、Markdown 阅读副本和正文图片,图号、图注和正文引用一一对应,方便直接交给 AI 阅读和引用。
|
|
248
|
-
4.
|
|
244
|
+
4. **全球学校登录**:亚洲、欧洲和美国的学术身份联盟已支持;接下来是加拿大、拉丁美洲和加勒比、大洋洲,最后非洲,覆盖 eduGAIN 里的所有国家;有条件的话再接入 WebVPN、EZProxy 等访问方式。
|
|
249
245
|
5. **检索论文、搜正文片段再优化**:参考同类工具的做法,进一步提升检索论文和搜正文片段的效果。
|
|
250
246
|
|
|
251
247
|
完整计划见 [路线图](docs/ROADMAP.zh.md),原理和代码结构见 [架构说明](docs/ARCHITECTURE.zh.md)。还想要什么功能,欢迎提 [Issue](https://github.com/dr-dumpling/PaperSearch/issues/new/choose) 和 PR;下载失败或想支持某家出版社,请用对应的 Issue 模板,想自己加出版社规则见 [school/CONTRIBUTING.md](school/CONTRIBUTING.md)。
|
|
@@ -20,7 +20,7 @@ export const SCHOOL_DOWNLOAD_TIMEOUT_MS = 1_200_000;
|
|
|
20
20
|
export const SCHOOL_CLEANUP_TIMEOUT_MS = 5_000;
|
|
21
21
|
const SCHOOL_BACKEND_SOURCE = "school";
|
|
22
22
|
// MCP clientInfo is informational only; keep in step with package.json on release.
|
|
23
|
-
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.6.
|
|
23
|
+
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.6.5";
|
|
24
24
|
const NO_BATCH_SUPPORT = {
|
|
25
25
|
downloadFields: false,
|
|
26
26
|
supplementsField: false,
|
package/package.json
CHANGED
|
@@ -242,8 +242,9 @@ class PublisherAdapter:
|
|
|
242
242
|
return None
|
|
243
243
|
|
|
244
244
|
def leave_email_step(self, page: Any, result: Any) -> bool:
|
|
245
|
-
"""The publisher's sign-in asks for the user's work email, not the school
|
|
246
|
-
|
|
245
|
+
"""The publisher's sign-in asks for the user's work email, not the school, or
|
|
246
|
+
offers only another school chosen before in this browser: go back to its
|
|
247
|
+
school search before anything is typed; True when clicked."""
|
|
247
248
|
return False
|
|
248
249
|
|
|
249
250
|
def prepare_institution_choice(self, page: Any, result: Any) -> bool | None:
|
|
@@ -86,6 +86,27 @@ _EMAIL_STEP_JS = """() => {
|
|
|
86
86
|
return true;
|
|
87
87
|
}"""
|
|
88
88
|
|
|
89
|
+
# Elsevier ID's "Access through your organization – You will be sent to <school>"
|
|
90
|
+
# for a school chosen before in this browser, with "Try Another way" to its search:
|
|
91
|
+
# the school shown, when the page is that one (2026-11-13: it named the previous
|
|
92
|
+
# school and no other could be chosen there).
|
|
93
|
+
_REMEMBERED_JS = """() => {
|
|
94
|
+
const shown = (el) => !!el && el.getClientRects().length > 0;
|
|
95
|
+
const another = [...document.querySelectorAll("#bdd-elsSecondaryBtn-tryAnotherWay, #bdd-elsSecondaryBtn")]
|
|
96
|
+
.find((el) => shown(el) && /try another way/i.test(el.textContent || ""));
|
|
97
|
+
const body = (document.body && document.body.innerText) || "";
|
|
98
|
+
if (!another || !/you will be sent to/i.test(body)) return null;
|
|
99
|
+
const school = [...document.querySelectorAll("#bdd-elsPrimaryBtn .els-institution-group, #bdd-elsPrimaryBtn")].find(shown);
|
|
100
|
+
return {school: ((school && (school.innerText || school.textContent)) || "").replace(/\\s+/g, " ").trim()};
|
|
101
|
+
}"""
|
|
102
|
+
_TRY_ANOTHER_JS = """() => {
|
|
103
|
+
const el = [...document.querySelectorAll("#bdd-elsSecondaryBtn-tryAnotherWay, #bdd-elsSecondaryBtn")]
|
|
104
|
+
.find((el) => el.getClientRects().length > 0 && /try another way/i.test(el.textContent || ""));
|
|
105
|
+
if (!el) return false;
|
|
106
|
+
el.click();
|
|
107
|
+
return true;
|
|
108
|
+
}"""
|
|
109
|
+
|
|
89
110
|
_ENTRY_JS = """
|
|
90
111
|
({manualSelection, institutionQuery}) => {
|
|
91
112
|
const visible = (el) => {
|
|
@@ -281,6 +302,31 @@ class ElsevierAdapter(PublisherAdapter):
|
|
|
281
302
|
return False # the page moved on while it was read
|
|
282
303
|
if clicked:
|
|
283
304
|
self.d._event(result, "elsevier_email_step_left", "Access via another organization")
|
|
305
|
+
return True
|
|
306
|
+
return self._leave_remembered_other_school(page, result)
|
|
307
|
+
|
|
308
|
+
def _leave_remembered_other_school(self, page: Any, result: Any) -> bool:
|
|
309
|
+
"""Elsevier ID offers only a school chosen before in this browser (``_REMEMBERED_JS``):
|
|
310
|
+
when it is not the configured school, "Try Another way" goes to the search.
|
|
311
|
+
The configured school's own page, and any page with no school configured,
|
|
312
|
+
stay as they are."""
|
|
313
|
+
names = [n for n in self.d._institution_names() if n]
|
|
314
|
+
if not names:
|
|
315
|
+
return False
|
|
316
|
+
try:
|
|
317
|
+
shown = page.evaluate(_REMEMBERED_JS)
|
|
318
|
+
if not isinstance(shown, dict) or not shown.get("school"):
|
|
319
|
+
return False
|
|
320
|
+
key = lambda text: re.sub(r"[\W_]+", "", str(text or "").casefold())
|
|
321
|
+
if any(key(name) and key(name) in key(shown["school"]) for name in names):
|
|
322
|
+
return False
|
|
323
|
+
clicked = page.evaluate(_TRY_ANOTHER_JS) is True
|
|
324
|
+
except Exception as exc:
|
|
325
|
+
if not is_driver_error(exc):
|
|
326
|
+
raise
|
|
327
|
+
return False # the page moved on while it was read
|
|
328
|
+
if clicked:
|
|
329
|
+
self.d._event(result, "elsevier_remembered_school_left", f"{shown['school'][:120]}: not the configured school")
|
|
284
330
|
return clicked
|
|
285
331
|
|
|
286
332
|
def is_redirect_page(self, url: str) -> bool:
|
|
@@ -97,8 +97,16 @@ class SageAdapter(PublisherAdapter):
|
|
|
97
97
|
and not page.locator('a[href*="/action/ssostart"]').count()):
|
|
98
98
|
institution = page.get_by_role("button", name="Institution", exact=True)
|
|
99
99
|
if not institution_opened and institution.count() and institution.first.is_visible():
|
|
100
|
-
institution.first.click(timeout=5_000, no_wait_after=True)
|
|
101
100
|
institution_opened = True
|
|
101
|
+
# Open already: a click would close it, and under an overlay it
|
|
102
|
+
# timed out and ended the article (2026-11-14).
|
|
103
|
+
if institution.first.get_attribute("aria-expanded") != "true":
|
|
104
|
+
try:
|
|
105
|
+
institution.first.click(timeout=5_000, no_wait_after=True)
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
if not _is_browser_error(exc, "TimeoutError"):
|
|
108
|
+
raise
|
|
109
|
+
institution.first.evaluate("el => el.click()") # covered, as above
|
|
102
110
|
page.wait_for_timeout(500)
|
|
103
111
|
if not page.locator('a[href*="/action/ssostart"]').count():
|
|
104
112
|
d._event(result, "sage_institution_link_missing", self._panel_text(page))
|
|
@@ -136,7 +136,7 @@ def _set_carsi_school(cfg: dict[str, Any], query: str) -> dict[str, Any] | None:
|
|
|
136
136
|
return {"error": "carsi_school_ambiguous", "query": query, "count": len(candidates),
|
|
137
137
|
"candidates": [s.summary() for s in candidates[:10]],
|
|
138
138
|
"hint": "run again with the full name, the domain or the entityID of one candidate"}
|
|
139
|
-
cfg.update(school_name=school.name, school_name_en=school.name_en, idp_entity_id=school.entity_id,
|
|
139
|
+
cfg.update(school_name=school.name, school_name_en=school.name_en, school_entry_name="", idp_entity_id=school.entity_id,
|
|
140
140
|
idp_login_hosts=[], idp_login_pages=[], idp_domains=[school.domain] if school.domain else [])
|
|
141
141
|
return None
|
|
142
142
|
|
|
@@ -28,6 +28,8 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
28
28
|
# Empty: the user picks in the window.
|
|
29
29
|
"school_name": "",
|
|
30
30
|
"school_name_en": "",
|
|
31
|
+
# A shared login entry's own name (a national one), when the school is saved by the user's name.
|
|
32
|
+
"school_entry_name": "",
|
|
31
33
|
"idp_entity_id": "",
|
|
32
34
|
"idp_login_hosts": [],
|
|
33
35
|
# The school's own login pages on a service shared by many schools (OpenAthens).
|
|
@@ -6,6 +6,7 @@ from __future__ import annotations
|
|
|
6
6
|
|
|
7
7
|
import re
|
|
8
8
|
import time
|
|
9
|
+
import unicodedata
|
|
9
10
|
from typing import Any
|
|
10
11
|
from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
|
|
11
12
|
|
|
@@ -526,6 +527,22 @@ class InstitutionMixin:
|
|
|
526
527
|
|
|
527
528
|
# CARSI writes some English names with a curly apostrophe ("Xi’an"), publisher lists a straight one.
|
|
528
529
|
_QUOTES = str.maketrans({"\u2019": "'", "\u2018": "'"})
|
|
530
|
+
_FULL_WIDTH_BRACKETS = str.maketrans({"\uff08": "(", "\uff09": ")"})
|
|
531
|
+
|
|
532
|
+
@classmethod
|
|
533
|
+
def _comparable(cls, text: str) -> str:
|
|
534
|
+
"""A name as entries and the school's names are compared: lower case, with
|
|
535
|
+
no accent (Latin, Greek) or punctuation, brackets kept (they hold a school's
|
|
536
|
+
other names). Publishers write names their own way: "Kita University St
|
|
537
|
+
Hanako" for a school listed as 'Kita University "St. Hanako"' (2026-11-13)."""
|
|
538
|
+
text = str(text or "").translate(cls._FULL_WIDTH_BRACKETS).replace("&", " and ")
|
|
539
|
+
text = re.sub(r"[\u0300-\u036f]", "", unicodedata.normalize("NFD", text))
|
|
540
|
+
text = re.sub(r"[^\w\s()]+|_", " ", unicodedata.normalize("NFC", text))
|
|
541
|
+
return " ".join(text.split()).lower()
|
|
542
|
+
|
|
543
|
+
# A login server's words after the school's name ("<entry> Single Sign-On Service",
|
|
544
|
+
# a national entry on Springer Nature's list, 2026-11-14), as ``_comparable`` writes them.
|
|
545
|
+
_LOGIN_SERVER_WORDS = r"(?: (?:idp|sso|identity provider|single sign on(?: service)?|login service))?"
|
|
529
546
|
|
|
530
547
|
def _institution_match_score(self, text: str) -> int:
|
|
531
548
|
"""3 = exactly the configured school, 2 = "<school> University" or "<school>,
|
|
@@ -535,7 +552,7 @@ class InstitutionMixin:
|
|
|
535
552
|
Parentheses that only repeat the school's other names keep the score of
|
|
536
553
|
the name before them: Elsevier lists a school as "<Chinese name>(<English
|
|
537
554
|
name>) (<English name>)", next to other schools whose names contain its own."""
|
|
538
|
-
text =
|
|
555
|
+
text = self._comparable(text)
|
|
539
556
|
# Long English names fit: "华中科技大学(Huazhong University of Science and Technology) (...)".
|
|
540
557
|
aliased = re.fullmatch(r"([^()]+?)((?:\s*\([^()]{1,120}\))+)", text)
|
|
541
558
|
if aliased:
|
|
@@ -548,12 +565,13 @@ class InstitutionMixin:
|
|
|
548
565
|
if self._name_residue(text) == "":
|
|
549
566
|
return 3 # only the school's own names ("<Chinese name> <English name>")
|
|
550
567
|
for name in self._institution_names():
|
|
551
|
-
name = re.sub(r"^the ", "",
|
|
568
|
+
name = re.sub(r"^the ", "", self._comparable(name))
|
|
552
569
|
if not name:
|
|
553
570
|
continue
|
|
554
571
|
if text == name:
|
|
555
572
|
best = max(best, 3)
|
|
556
|
-
elif re.fullmatch(re.escape(name) + r"(?: university)?(?:,? (?:the )?librar(?:y|ies))?(?: \([^)]{1,40}\))?"
|
|
573
|
+
elif re.fullmatch(re.escape(name) + r"(?: university)?(?:,? (?:the )?librar(?:y|ies))?(?: \([^)]{1,40}\))?"
|
|
574
|
+
+ self._LOGIN_SERVER_WORDS, text):
|
|
557
575
|
best = max(best, 2)
|
|
558
576
|
elif name in text:
|
|
559
577
|
best = max(best, 1)
|
|
@@ -593,9 +611,9 @@ class InstitutionMixin:
|
|
|
593
611
|
def _name_residue(self, text: str) -> str | None:
|
|
594
612
|
"""What is left of ``text`` (lower case) once the school's names are taken
|
|
595
613
|
out, as words; None when it holds none of them."""
|
|
596
|
-
names = sorted({re.sub(r"^the ", "",
|
|
597
|
-
|
|
598
|
-
rest, found = f" {text} ", False
|
|
614
|
+
names = sorted({re.sub(r"^the ", "", self._comparable(n)) for n in self._institution_names()} - {""},
|
|
615
|
+
key=len, reverse=True)
|
|
616
|
+
rest, found = f" {self._comparable(text)} ", False
|
|
599
617
|
for name in names:
|
|
600
618
|
if name in rest:
|
|
601
619
|
rest, found = rest.replace(name, " "), True
|
|
@@ -603,7 +621,8 @@ class InstitutionMixin:
|
|
|
603
621
|
|
|
604
622
|
# Words a unit of the school itself may add to its name (its library, campus,
|
|
605
623
|
# hospital): such an entry may be the school's, so the search settles nothing.
|
|
606
|
-
|
|
624
|
+
# A campus by its own name too ("<school> - Campus <name>", 2026-11-13).
|
|
625
|
+
_OWN_UNIT = re.compile(r"^(?:graduate school|school of|faculty of|department of|institute of|cent(?:er|re) for|campus)\b"
|
|
607
626
|
r"|^(?:(?:the|main|central|university|univ|library|libraries|campus|branch|hospital|"
|
|
608
627
|
r"medical|medicine|dentistry|nursing|pharmacy|law|business|graduate|department|"
|
|
609
628
|
r"health|engineering|center|centre|faculty|school|college|of|and)\b\s*)+$")
|
|
@@ -615,6 +634,8 @@ class InstitutionMixin:
|
|
|
615
634
|
r"没有找到|无结果|未找到|找不到(?:相关|匹配)", re.I)
|
|
616
635
|
# How long the results must stay the same before they settle the school's absence.
|
|
617
636
|
SEARCH_SETTLED_SEC = 4
|
|
637
|
+
# Entries enough to be a search's results, not a page's own links.
|
|
638
|
+
UNRELATED_RESULTS = 3
|
|
618
639
|
|
|
619
640
|
def _search_lists_no_school(self, page: Any, result: DownloadResult, url: str, scored: list) -> bool:
|
|
620
641
|
"""The school's name was searched on this page, the results are shown and
|
|
@@ -625,7 +646,7 @@ class InstitutionMixin:
|
|
|
625
646
|
def searched_here(event: dict) -> bool:
|
|
626
647
|
# A record keeps 500 characters: a long address (Elsevier ID's) is cut short in it.
|
|
627
648
|
where = str(event.get("detail", "")).split(" @ ", 1)[-1]
|
|
628
|
-
return event["state"] == "auto_institution_search" and
|
|
649
|
+
return event["state"] == "auto_institution_search" and self._same_address(where, url)
|
|
629
650
|
|
|
630
651
|
if not any(searched_here(e) for e in result.events):
|
|
631
652
|
return False # nothing searched here: a page's other lists say nothing
|
|
@@ -634,9 +655,10 @@ class InstitutionMixin:
|
|
|
634
655
|
# unless its publisher marks it as signing in no one (IP, VPN, email).
|
|
635
656
|
may_sign_in = [str(it.get("t") or "") for score, it in scored if score == 1
|
|
636
657
|
and self.adapter.institution_entry_signs_in(unquote(str(it.get("ids") or ""))) is not False]
|
|
637
|
-
residues = [self._name_residue(
|
|
658
|
+
residues = [self._name_residue(o) for o in may_sign_in]
|
|
638
659
|
if any(r is not None and self._OWN_UNIT.match(r) for r in residues):
|
|
639
660
|
return False # perhaps the school's own library or campus: left to the user
|
|
661
|
+
settled = self.SEARCH_SETTLED_SEC
|
|
640
662
|
if others:
|
|
641
663
|
evidence = f"{len(others)} other entries: " + "; ".join(others[:3])
|
|
642
664
|
else:
|
|
@@ -646,21 +668,128 @@ class InstitutionMixin:
|
|
|
646
668
|
if not _is_browser_error(exc):
|
|
647
669
|
raise
|
|
648
670
|
return False
|
|
649
|
-
|
|
671
|
+
baseline = getattr(result, "_search_baseline", None)
|
|
672
|
+
before = baseline[1] if isinstance(baseline, tuple) and self._same_address(baseline[0], url) else set()
|
|
673
|
+
# Only what the search added: the page's own links listed before it are no results
|
|
674
|
+
# (2026-11-13: "About Elsevier", "Cookie settings" ended four searches still loading).
|
|
675
|
+
unrelated = sorted({str(it.get("t") or "")[:60] for score, it in scored if score == 0
|
|
676
|
+
and str(it.get("t") or "").strip() and str(it.get("t") or "")[:60] not in before})
|
|
677
|
+
if said:
|
|
678
|
+
evidence = f'"{said.group(0)}"'
|
|
679
|
+
elif len(unrelated) >= self.UNRELATED_RESULTS and not self._search_list_closed(page, result, url):
|
|
680
|
+
# A fuzzy search listing only schools of other names, none carrying
|
|
681
|
+
# the school's entityID (2026-11-13: "University of <town>" for one
|
|
682
|
+
# school, 20 of them): longer, a slow search may still be replacing them.
|
|
683
|
+
evidence, settled = f"{len(unrelated)} unrelated entries: " + "; ".join(unrelated[:3]), 2 * settled
|
|
684
|
+
else:
|
|
650
685
|
return False # results not shown yet: looked at again next pass
|
|
651
|
-
evidence = f'"{said.group(0)}"'
|
|
652
686
|
now = time.time()
|
|
653
687
|
seen = getattr(result, "_search_miss", None)
|
|
654
|
-
if not seen or seen[0]
|
|
688
|
+
if not seen or not self._same_address(seen[0], url) or seen[1] != evidence:
|
|
655
689
|
result._search_miss = (url, evidence, now)
|
|
656
690
|
return False
|
|
657
|
-
if now - seen[2] <
|
|
691
|
+
if now - seen[2] < settled:
|
|
692
|
+
return False
|
|
693
|
+
# The publisher may list the school by another of its names (2026-11-13: a
|
|
694
|
+
# Swedish name found twenty other schools; the school is listed in English).
|
|
695
|
+
if self._search_again_by_another_name(page, result, url, list(self._institution_names()), settled=True):
|
|
658
696
|
return False
|
|
659
697
|
self._event(result, "auto_institution_not_found",
|
|
660
698
|
f"{self.institution_query} (search: {evidence[:160]}) @ {url}")
|
|
661
699
|
result._institution_not_listed = True
|
|
662
700
|
return True
|
|
663
701
|
|
|
702
|
+
# How long a search by one of the school's names may show nothing before the next is typed.
|
|
703
|
+
SEARCH_RETRY_SEC = 6
|
|
704
|
+
|
|
705
|
+
@staticmethod
|
|
706
|
+
def _same_address(recorded: str, url: str) -> bool:
|
|
707
|
+
"""``url`` is the page at ``recorded`` (a record may cut a long address
|
|
708
|
+
short), percent-encoding aside: a chooser rewrote its own address without
|
|
709
|
+
it once the school was typed (2026-11-14)."""
|
|
710
|
+
recorded, url = unquote(str(recorded or "")), unquote(str(url or ""))
|
|
711
|
+
return len(recorded) > 10 and url.startswith(recorded)
|
|
712
|
+
|
|
713
|
+
def _search_queries(self, names: list[str]) -> list[str]:
|
|
714
|
+
"""The school's names to search by (straight apostrophes): its English name
|
|
715
|
+
first, then the others in Latin letters, then the rest, its shared login
|
|
716
|
+
entry's own name last. A school's own language may be written in Latin
|
|
717
|
+
letters with no accent ("Kitan yliopisto", 2026-11-13), and publishers
|
|
718
|
+
list schools in English more often."""
|
|
719
|
+
typed = [n.translate(self._QUOTES) for n in names]
|
|
720
|
+
english, entry = (str(self.config.get(key) or "").strip().translate(self._QUOTES)
|
|
721
|
+
for key in ("school_name_en", "school_entry_name"))
|
|
722
|
+
schools_own = [q for q in typed if q != entry]
|
|
723
|
+
return list(dict.fromkeys([q for q in schools_own if q == english] + [q for q in schools_own if q.isascii()]
|
|
724
|
+
+ [q for q in schools_own if not q.isascii()] + [q for q in typed if q == entry]))
|
|
725
|
+
|
|
726
|
+
def _search_again_by_another_name(self, page: Any, result: DownloadResult, url: str, names: list[str],
|
|
727
|
+
settled: bool = False) -> bool:
|
|
728
|
+
"""The search by one of the school's names has shown nothing for
|
|
729
|
+
``SEARCH_RETRY_SEC`` (its list closed, or no entry beyond the page's own),
|
|
730
|
+
or ``settled`` results without the school (``_search_lists_no_school``):
|
|
731
|
+
the box is cleared and the next name typed, once each (2026-11-13: a school
|
|
732
|
+
listed by its French name, searched by its English one, found nothing).
|
|
733
|
+
A box holding anything but our own query is the user's and stays."""
|
|
734
|
+
box_at = getattr(result, "_search_box", None)
|
|
735
|
+
if (not isinstance(box_at, tuple) or not self._same_address(box_at[0], url)
|
|
736
|
+
or (not settled and time.time() - float(getattr(result, "_search_typed_at", 0) or 0)
|
|
737
|
+
< self.SEARCH_RETRY_SEC)):
|
|
738
|
+
return False
|
|
739
|
+
tried = []
|
|
740
|
+
for event in result.events:
|
|
741
|
+
query, _, where = str(event.get("detail", "")).partition(" @ ")
|
|
742
|
+
if event["state"] == "auto_institution_search" and self._same_address(where, url):
|
|
743
|
+
tried.append(query)
|
|
744
|
+
left = [q for q in self._search_queries(names) if q not in tried]
|
|
745
|
+
if not left:
|
|
746
|
+
return False
|
|
747
|
+
baseline = getattr(result, "_search_baseline", None)
|
|
748
|
+
before = baseline[1] if isinstance(baseline, tuple) and self._same_address(baseline[0], url) else set()
|
|
749
|
+
if not settled and not self._search_list_closed(page, result, url) and self._entry_texts(page) - before:
|
|
750
|
+
return False # results shown: they decide
|
|
751
|
+
box = page.locator(box_at[1]).first
|
|
752
|
+
try:
|
|
753
|
+
if str(box.input_value(timeout=2_000) or "").strip() not in tried:
|
|
754
|
+
return False
|
|
755
|
+
box.fill("")
|
|
756
|
+
box.press_sequentially(left[0], delay=40)
|
|
757
|
+
except Exception as exc:
|
|
758
|
+
if not _is_browser_error(exc):
|
|
759
|
+
raise
|
|
760
|
+
return False
|
|
761
|
+
result._search_typed_at = time.time()
|
|
762
|
+
result._search_miss = None
|
|
763
|
+
self._event(result, "auto_institution_search", f"{left[0]} @ {url}")
|
|
764
|
+
return True
|
|
765
|
+
|
|
766
|
+
def _search_list_closed(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
767
|
+
"""The search box typed in says its list is closed (``aria-expanded="false"``):
|
|
768
|
+
no results are shown, whatever else the page lists (2026-11-13: a search
|
|
769
|
+
showing nothing, its page's links taken for results)."""
|
|
770
|
+
box = getattr(result, "_search_box", None)
|
|
771
|
+
if not isinstance(box, tuple) or not self._same_address(box[0], url):
|
|
772
|
+
return False
|
|
773
|
+
try:
|
|
774
|
+
return page.evaluate("""(selector) => {
|
|
775
|
+
const el = document.querySelector(selector);
|
|
776
|
+
return !!el && el.getAttribute('aria-expanded') === 'false';
|
|
777
|
+
}""", box[1]) is True
|
|
778
|
+
except Exception as exc:
|
|
779
|
+
if not _is_browser_error(exc):
|
|
780
|
+
raise
|
|
781
|
+
return True # not readable now: nothing concluded from it
|
|
782
|
+
|
|
783
|
+
def _entry_texts(self, page: Any) -> set[str]:
|
|
784
|
+
"""The entries a page lists now, by their text (``_ENTRIES_JS``)."""
|
|
785
|
+
try:
|
|
786
|
+
items = page.evaluate(self._ENTRIES_JS, self._ENTRY_SELECTOR)
|
|
787
|
+
except Exception as exc:
|
|
788
|
+
if not _is_browser_error(exc):
|
|
789
|
+
raise
|
|
790
|
+
return set()
|
|
791
|
+
return {str(it.get("t") or "")[:60] for it in items if isinstance(it, dict)} if isinstance(items, list) else set()
|
|
792
|
+
|
|
664
793
|
def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
|
|
665
794
|
"""Click the single best visible entry for the configured school.
|
|
666
795
|
|
|
@@ -690,9 +819,10 @@ class InstitutionMixin:
|
|
|
690
819
|
if without:
|
|
691
820
|
scored = [(score, it) for score, it in scored if not any(it is w for w in without)]
|
|
692
821
|
if not any(score >= 2 for score, _ in scored):
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
822
|
+
if getattr(result, "_institution_not_listed", False) is not True: # once, not every pass
|
|
823
|
+
self._event(result, "auto_institution_not_found",
|
|
824
|
+
f"{self.institution_query} (listed only without a school sign-in: "
|
|
825
|
+
f"{len(without)} entr{'y' if len(without) == 1 else 'ies'}) @ {url}")
|
|
696
826
|
result._institution_not_listed = True
|
|
697
827
|
return False
|
|
698
828
|
top = max([score for score, _ in scored] or [0])
|
|
@@ -939,6 +1069,8 @@ class InstitutionMixin:
|
|
|
939
1069
|
# never on a verification page, which the challenge wait takes first: a
|
|
940
1070
|
# search there found no school and ended the login (fixture, 2026-11-01).
|
|
941
1071
|
if not once("institution_search"):
|
|
1072
|
+
if self._search_again_by_another_name(page, result, url, names):
|
|
1073
|
+
return True
|
|
942
1074
|
return self._handle_institution_search_miss(page, result, url)
|
|
943
1075
|
if not self._is_challenge_page(page):
|
|
944
1076
|
if self._assist_federation_discovery(page, result):
|
|
@@ -952,7 +1084,11 @@ class InstitutionMixin:
|
|
|
952
1084
|
if str(box.input_value(timeout=2_000) or "").strip():
|
|
953
1085
|
return False # the user is typing; never replace it
|
|
954
1086
|
# The English name, with a straight apostrophe (CARSI writes "Xi’an", 2026-11-01).
|
|
955
|
-
query =
|
|
1087
|
+
query = self._search_queries(names)[0]
|
|
1088
|
+
# What the page lists before the search (its own links): no result of it.
|
|
1089
|
+
result._search_baseline = (url, self._entry_texts(page))
|
|
1090
|
+
result._search_box = (url, selector)
|
|
1091
|
+
result._search_typed_at = time.time()
|
|
956
1092
|
# Key by key: search-as-you-type lists (SAMS Sigma, OpenAthens)
|
|
957
1093
|
# do not search on a filled value (2026-11-01).
|
|
958
1094
|
box.press_sequentially(query, delay=40)
|