litloop 1.18.3__py3-none-any.whl

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.
Files changed (176) hide show
  1. litloop/__init__.py +89 -0
  2. litloop/__main__.py +6 -0
  3. litloop/_source_hygiene.py +158 -0
  4. litloop/agents/__init__.py +13 -0
  5. litloop/agents/client.py +164 -0
  6. litloop/agents/runner.py +123 -0
  7. litloop/agents/system.py +54 -0
  8. litloop/agents/tools.py +142 -0
  9. litloop/app_server.py +8 -0
  10. litloop/browser/__init__.py +1 -0
  11. litloop/browser/backend.py +1009 -0
  12. litloop/browser/camofox_api.py +368 -0
  13. litloop/browser/chrome_copy.py +136 -0
  14. litloop/browser/cloakbrowser_compat.py +72 -0
  15. litloop/browser/cookies.py +347 -0
  16. litloop/browser/engine.py +965 -0
  17. litloop/browser/login.py +636 -0
  18. litloop/browser/pdf.py +263 -0
  19. litloop/browser/profile_health.py +167 -0
  20. litloop/browser/runtime.py +210 -0
  21. litloop/cache.py +104 -0
  22. litloop/citations/__init__.py +1 -0
  23. litloop/citations/bib_import.py +102 -0
  24. litloop/citations/bibtex_crossref.py +143 -0
  25. litloop/citations/formats.py +225 -0
  26. litloop/citations/paper_list.py +200 -0
  27. litloop/citations/session_export.py +94 -0
  28. litloop/cli/__init__.py +12 -0
  29. litloop/cli/_utils.py +267 -0
  30. litloop/cli/commands.py +1098 -0
  31. litloop/cli/doctor.py +141 -0
  32. litloop/cli/main.py +1173 -0
  33. litloop/cli/web.py +190 -0
  34. litloop/config.py +413 -0
  35. litloop/data/VARCON-LICENSE.txt +62 -0
  36. litloop/data/elements.tsv +119 -0
  37. litloop/data/institutional_identity_policy.json +165 -0
  38. litloop/data/publisher_access_catalog.json +969 -0
  39. litloop/data/publisher_carsi.json +105 -0
  40. litloop/data/spelling_search.tsv.gz +0 -0
  41. litloop/data/spelling_us.tsv.gz +0 -0
  42. litloop/data/webvpn.dat +0 -0
  43. litloop/data/webvpn.json +603 -0
  44. litloop/db.py +1922 -0
  45. litloop/deps.py +128 -0
  46. litloop/desktop/__init__.py +1 -0
  47. litloop/desktop/agent_runner.py +537 -0
  48. litloop/desktop/download_jobs.py +571 -0
  49. litloop/desktop/error_text.py +192 -0
  50. litloop/desktop/server.py +999 -0
  51. litloop/desktop/settings.py +552 -0
  52. litloop/desktop/translate.py +103 -0
  53. litloop/diagnostics.py +126 -0
  54. litloop/download/__init__.py +1 -0
  55. litloop/download/doi_check.py +44 -0
  56. litloop/download/fetcher.py +975 -0
  57. litloop/download/markdown.py +130 -0
  58. litloop/download/pdf.py +454 -0
  59. litloop/download/pipeline.py +1166 -0
  60. litloop/download/progress.py +312 -0
  61. litloop/download/rename.py +211 -0
  62. litloop/extractors/__init__.py +0 -0
  63. litloop/extractors/html_extractor.py +31 -0
  64. litloop/extractors/pdf_extractor.py +151 -0
  65. litloop/extractors/publisher_adapters/__init__.py +0 -0
  66. litloop/extractors/publisher_adapters/acs.py +167 -0
  67. litloop/extractors/publisher_adapters/elsevier.py +178 -0
  68. litloop/extractors/publisher_adapters/generic.py +191 -0
  69. litloop/extractors/publisher_adapters/nature.py +204 -0
  70. litloop/extractors/publisher_adapters/rsc.py +154 -0
  71. litloop/extractors/publisher_adapters/tandfonline.py +154 -0
  72. litloop/extractors/publisher_adapters/wiley.py +160 -0
  73. litloop/http_utils.py +57 -0
  74. litloop/identifiers.py +134 -0
  75. litloop/institutional/__init__.py +1 -0
  76. litloop/institutional/auth.py +576 -0
  77. litloop/institutional/carsi_login.py +569 -0
  78. litloop/institutional/config_adapter.py +63 -0
  79. litloop/institutional/proxy_check.py +98 -0
  80. litloop/institutional/remote_assist.py +274 -0
  81. litloop/institutional/schools.py +102 -0
  82. litloop/institutional/session_heal.py +73 -0
  83. litloop/institutional/session_store.py +105 -0
  84. litloop/log.py +47 -0
  85. litloop/models.py +269 -0
  86. litloop/network.py +417 -0
  87. litloop/optional.py +310 -0
  88. litloop/publishers/__init__.py +1 -0
  89. litloop/publishers/access.py +232 -0
  90. litloop/publishers/pdf_router.py +451 -0
  91. litloop/publishers/profiles.py +899 -0
  92. litloop/publishers/strategies/__init__.py +122 -0
  93. litloop/publishers/strategies/_core.py +2340 -0
  94. litloop/publishers/strategies/_elsevier_api.py +578 -0
  95. litloop/publishers/strategies/acm.py +27 -0
  96. litloop/publishers/strategies/acs.py +42 -0
  97. litloop/publishers/strategies/aip.py +27 -0
  98. litloop/publishers/strategies/aps.py +29 -0
  99. litloop/publishers/strategies/asce.py +28 -0
  100. litloop/publishers/strategies/base.py +108 -0
  101. litloop/publishers/strategies/copernicus.py +24 -0
  102. litloop/publishers/strategies/elsevier.py +66 -0
  103. litloop/publishers/strategies/generic.py +39 -0
  104. litloop/publishers/strategies/ieee.py +28 -0
  105. litloop/publishers/strategies/iop.py +27 -0
  106. litloop/publishers/strategies/nature.py +27 -0
  107. litloop/publishers/strategies/oxford.py +27 -0
  108. litloop/publishers/strategies/registry.py +83 -0
  109. litloop/publishers/strategies/royalsociety.py +28 -0
  110. litloop/publishers/strategies/rsc.py +27 -0
  111. litloop/publishers/strategies/sage.py +30 -0
  112. litloop/publishers/strategies/science.py +27 -0
  113. litloop/publishers/strategies/springer.py +34 -0
  114. litloop/publishers/strategies/tandfonline.py +32 -0
  115. litloop/publishers/strategies/wiley.py +32 -0
  116. litloop/publishers/supplementary.py +219 -0
  117. litloop/quota.py +202 -0
  118. litloop/search/__init__.py +1 -0
  119. litloop/search/abstracts.py +291 -0
  120. litloop/search/deep.py +1216 -0
  121. litloop/search/quick.py +1102 -0
  122. litloop/search/scansci_find.py +410 -0
  123. litloop/search/screening.py +225 -0
  124. litloop/search/title_to_doi.py +163 -0
  125. litloop/search/watches.py +124 -0
  126. litloop/server.py +1731 -0
  127. litloop/sources/__init__.py +1339 -0
  128. litloop/sources/_batch.py +529 -0
  129. litloop/sources/_index.py +221 -0
  130. litloop/sources/_routes.py +290 -0
  131. litloop/sources/altcha.py +90 -0
  132. litloop/sources/arxiv.py +45 -0
  133. litloop/sources/attempt.py +91 -0
  134. litloop/sources/carsi.py +74 -0
  135. litloop/sources/core_api.py +46 -0
  136. litloop/sources/crossref.py +162 -0
  137. litloop/sources/elsevier_api.py +620 -0
  138. litloop/sources/elsevier_check.py +274 -0
  139. litloop/sources/europepmc.py +81 -0
  140. litloop/sources/ezproxy.py +317 -0
  141. litloop/sources/instsci.py +1295 -0
  142. litloop/sources/libgen.py +116 -0
  143. litloop/sources/nature.py +39 -0
  144. litloop/sources/oa_discovery.py +135 -0
  145. litloop/sources/openaire.py +122 -0
  146. litloop/sources/openalex.py +100 -0
  147. litloop/sources/publishers.py +684 -0
  148. litloop/sources/sage_cn.py +139 -0
  149. litloop/sources/scibban.py +10 -0
  150. litloop/sources/scihub.py +1379 -0
  151. litloop/sources/scihub_domains.py +203 -0
  152. litloop/sources/scihub_speed.py +187 -0
  153. litloop/sources/scoring.py +250 -0
  154. litloop/sources/semantic_scholar.py +146 -0
  155. litloop/sources/springer_tdm.py +172 -0
  156. litloop/sources/unpaywall.py +116 -0
  157. litloop/sources/vpnsci.py +38 -0
  158. litloop/store.py +264 -0
  159. litloop/templates/index.html +347 -0
  160. litloop/terms/__init__.py +1 -0
  161. litloop/terms/glossary.py +422 -0
  162. litloop/terms/spelling.py +89 -0
  163. litloop/terms/text.py +106 -0
  164. litloop/tor/__init__.py +1 -0
  165. litloop/tor/embedded.py +371 -0
  166. litloop/tor/proxy.py +110 -0
  167. litloop/updates.py +148 -0
  168. litloop/zotero/__init__.py +1 -0
  169. litloop/zotero/bridge.py +309 -0
  170. litloop/zotero/client.py +317 -0
  171. litloop-1.18.3.dist-info/METADATA +347 -0
  172. litloop-1.18.3.dist-info/RECORD +176 -0
  173. litloop-1.18.3.dist-info/WHEEL +5 -0
  174. litloop-1.18.3.dist-info/entry_points.txt +2 -0
  175. litloop-1.18.3.dist-info/licenses/LICENSE +197 -0
  176. litloop-1.18.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,552 @@
1
+ """What the settings page shows, and the "test" button behind each group.
2
+
3
+ One list of settings, in the groups of CHARTER's first-run setup, so the
4
+ desktop app's settings page, its first-run guide and (later) the built-in
5
+ agent all describe the same things the same way. Values are read with
6
+ ``config.load_config`` and written with ``config.update_config``; secrets are
7
+ shown as their first and last characters only.
8
+
9
+ Each test makes the smallest real request it can. Those that spend a unit of
10
+ a provider's quota say so in ``cost`` (limits: docs/API_LIMITS.md).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from .. import config as _config
22
+ from ..download.rename import FORMATS as _RENAME_FORMATS
23
+ from ..download.rename import rename_format as _rename_format
24
+
25
+ # type: secret | text | email | path | bool | select; a path may say pick: dir | file (the app offers a chooser)
26
+ GROUPS: list[dict[str, Any]] = [
27
+ {
28
+ "id": "sources", "title": "检索接口", "test": "sources",
29
+ "fields": [
30
+ {"key": "openalex_api_key", "label": "OpenAlex Key", "type": "secret",
31
+ "link": "https://help.openalex.org/how-to-use-the-api/rate-limits-and-authentication"},
32
+ {"key": "elsevier_api_key", "label": "Elsevier Key", "type": "secret", "link": "https://dev.elsevier.com"},
33
+ {"key": "elsevier_api_fulltext", "label": "用 Elsevier Key 下载全文", "type": "bool",
34
+ "help": "Key 没有全文权限时关闭;补摘要和 Scopus 检索不受影响"},
35
+ {"key": "springer_meta_api_key", "label": "Springer Nature Key", "type": "secret",
36
+ "help": "Meta API 的 Key", "link": "https://dev.springernature.com"},
37
+ {"key": "email", "label": "联系邮箱", "type": "email"},
38
+ {"key": "core_api_key", "label": "CORE Key", "type": "secret", "link": "https://core.ac.uk/services/api"},
39
+ ],
40
+ },
41
+ {
42
+ "id": "downloads", "title": "下载", "test": "downloads",
43
+ "fields": [
44
+ {"key": "output_dir", "label": "保存位置", "type": "path", "pick": "dir"},
45
+ {"key": "rename_format", "label": "文件名", "type": "select",
46
+ "options": [[k, v] for k, v in _RENAME_FORMATS.items()]},
47
+ {"key": "download_strategy", "label": "来源顺序", "type": "select",
48
+ "options": [["fastest", "速度优先"], ["oa_first", "开放获取优先"], ["legal_only", "只用合法来源"],
49
+ ["scihub_first", "Sci-Hub 优先"], ["scihub_only", "只用 Sci-Hub"], ["grey_only", "只用 Sci-Hub、LibGen 等"]]},
50
+ {"key": "scihub_enabled", "label": "允许 Sci-Hub、LibGen 等来源", "type": "bool",
51
+ "help": "可能违反出版商条款或学校规定,自行判断是否开启", "warn": True},
52
+ {"key": "scihub_skip_from_year", "label": "较新的文献不查 Sci-Hub", "type": "select",
53
+ "options": [["0", "不限"], ["2022", "2022 年起"], ["2023", "2023 年起"], ["2024", "2024 年起"], ["2025", "2025 年起"]],
54
+ "help": "Sci-Hub 很少收录新文献;不知道年份的文献仍会查"},
55
+ {"key": "scihub_route", "label": "Sci-Hub、LibGen 线路", "type": "select",
56
+ "options": [["direct", "直连"], ["proxy", "经代理"], ["auto", "下载前测速选择"]],
57
+ "help": "代理是「网络」中的代理软件地址;选「经代理」时不从校园网直连"},
58
+ ],
59
+ },
60
+ {
61
+ "id": "network", "title": "网络", "test": "network",
62
+ "fields": [
63
+ # network_proxy is the campus egress (auth.py skips the school login when it is set),
64
+ # not a personal VPN: filling in Clash's port breaks institutional downloads.
65
+ {"key": "network_proxy", "label": "校园出口代理", "type": "text",
66
+ "help": "只填学校提供的代理地址,个人代理软件的端口会导致学校认证失败"},
67
+ {"key": "host_proxy_url", "label": "代理软件地址", "type": "text", "placeholder": "http://127.0.0.1:10808",
68
+ "help": "只有指定的网站(如 Sci-Hub)经它访问,其余直连"},
69
+ {"key": "is_campus_network", "label": "已连接校园网", "type": "bool",
70
+ "help": "打开后直接按学校 IP 下载,不再登录 WebVPN 或 CARSI"},
71
+ ],
72
+ },
73
+ {
74
+ "id": "school", "title": "学校认证",
75
+ "fields": [
76
+ {"key": "vpnsci_school", "label": "学校代号", "type": "text", "placeholder": "buaa"},
77
+ {"key": "vpnsci_enabled", "label": "WebVPN", "type": "bool"},
78
+ {"key": "carsi_enabled", "label": "CARSI", "type": "bool"},
79
+ {"key": "ezproxy_enabled", "label": "EZProxy", "type": "bool"},
80
+ ],
81
+ },
82
+ {
83
+ "id": "screening", "title": "筛选", "test": "screening",
84
+ "fields": [
85
+ {"key": "abstract_translation", "label": "自动翻译摘要", "type": "select",
86
+ "options": [["高", "评为高的文献"], ["高中", "评为高、中的文献"], ["all", "全部文献"], ["off", "不自动翻译"]],
87
+ "help": "打开范围内的文献时自动翻译并保存,其他文献可在详情页翻译"},
88
+ {"key": "translation_provider", "label": "翻译服务", "type": "select",
89
+ "options": [["deepseek", "DeepSeek"], ["deepl", "DeepL"], ["agent", "Agent(评分时翻译)"]],
90
+ "help": "DeepSeek 翻译专业术语较好;Agent 不需要 Key,但消耗对话额度"},
91
+ {"key": "deepseek_api_key", "label": "DeepSeek Key", "type": "secret",
92
+ "link": "https://platform.deepseek.com/api_keys"},
93
+ {"key": "deepl_api_key", "label": "DeepL Key", "type": "secret",
94
+ "link": "https://www.deepl.com/your-account/keys", "help": "免费版 Key 以 :fx 结尾"},
95
+ ],
96
+ },
97
+ {
98
+ "id": "agent", "title": "Agent",
99
+ "fields": [
100
+ {"key": "agent_backend", "label": "用哪个后端", "type": "select",
101
+ "options": [["command", "Agent 命令(在后端 A 里跑,用你自己的账号)"],
102
+ ["builtin", "内置 Agent(app 直接调模型接口)"]],
103
+ "help": "内置 Agent 的接口和模型在下面一组里设置"},
104
+ {"key": "agent_command", "label": "Agent 命令", "type": "text", "placeholder": "claude",
105
+ "help": "在 app 里发起检索时,把检索要求发给这个 Agent"},
106
+ {"key": "agent_args", "label": "命令参数", "type": "text",
107
+ "help": "检索要求从标准输入传入;默认只允许 Agent 调用 LitLoop 的工具"},
108
+ ],
109
+ },
110
+ {
111
+ # Backend B: no agent command, the app talks to a model API itself.
112
+ "id": "builtin_agent", "title": "内置 Agent", "test": "builtin_agent",
113
+ "intro": "不装 Agent 命令,让 app 自己调模型接口。模型必须支持工具调用,点「测试」会当场验证。",
114
+ "fields": [
115
+ {"key": "builtin_agent_provider", "label": "接口", "type": "select",
116
+ "options": [["openai", "OpenAI 兼容(DeepSeek、通义千问、Kimi、智谱 GLM、OpenRouter、Ollama、vLLM)"],
117
+ ["anthropic", "Anthropic (Claude)"]],
118
+ "help": "OpenAI 兼容接口只要填对地址,本地模型也走这一项"},
119
+ {"key": "builtin_agent_base_url", "label": "地址", "type": "text",
120
+ "placeholder": "留空用官方地址,例如 http://127.0.0.1:11434/v1"},
121
+ {"key": "builtin_agent_api_key", "label": "Key", "type": "secret",
122
+ "help": "本机 Ollama、vLLM 不用填"},
123
+ {"key": "builtin_agent_model", "label": "模型名", "type": "text",
124
+ "placeholder": "例如 deepseek-chat、claude-sonnet-4-5"},
125
+ ],
126
+ },
127
+ {
128
+ # What is installed, checked on opening (TESTS["components"]); the mirror
129
+ # only matters when installing a component from there.
130
+ "id": "components", "title": "可选组件", "test": "components", "auto": True, "fields": [
131
+ {"key": "package_index_url", "label": "组件下载镜像", "type": "text", "placeholder": "留空用 PyPI,例如 https://pypi.tuna.tsinghua.edu.cn/simple",
132
+ "help": "安装版面分析时从这里下载;默认的 PyPI 在国内可能很慢"},
133
+ ],
134
+ },
135
+ {
136
+ "id": "zotero", "title": "Zotero", "test": "zotero",
137
+ "fields": [
138
+ {"key": "zotero_mcp_python", "label": "zotero-mcp 的 Python", "type": "path", "pick": "file", "placeholder": "留空自动查找"},
139
+ {"key": "zotero_auto_push", "label": "下载完自动推送", "type": "bool"},
140
+ {"key": "zotero_collection_root", "label": "默认分类", "type": "text", "placeholder": "LitLoop",
141
+ "help": "推送到「默认分类/检索问题」"},
142
+ ],
143
+ },
144
+ ]
145
+
146
+ _FIELDS = {f["key"]: f for g in GROUPS for f in g["fields"]}
147
+
148
+ # The first-run guide: settings groups in the order a new user needs them, each
149
+ # with why it matters. Every step can be checked on the spot or skipped.
150
+ STEPS = [
151
+ {"group": "sources", "intro": "检索和补摘要靠这些接口。什么都不填也能先试一次快速检索(退回 Crossref);"
152
+ "要长期用,OpenAlex Key 免费,在 help.openalex.org 申请;不填时用的是同一个网络出口共享的匿名额度,"
153
+ "别人用完了就会被限流。"
154
+ "Elsevier Key 用于 ScienceDirect 全文和 Scopus 摘要,对深度检索影响很大。"
155
+ "联系邮箱只发给 Crossref、OpenAlex、Unpaywall,它们要求填写。"},
156
+ {"group": "screening", "intro": "筛选时可把摘要翻译成中文。填 DeepSeek 或 DeepL 的 Key 后由 app 翻译,不占用对话额度;也可以以后再设置。"},
157
+ {"group": "downloads", "intro": "设置 PDF 的保存位置和文件名。Sci-Hub、LibGen 等来源可能违反出版商条款或学校规定,默认不使用,是否开启由你决定。"},
158
+ {"group": "network", "intro": "开启代理软件时,学校认证的流量需要直连,否则学校无法识别你的身份。选择「检测」查看当前网络和需要的设置。"},
159
+ {"group": "school", "intro": "下载学校订阅的期刊需要学校认证。填写学校代号并选择认证方式;不在校园网时会弹出浏览器让你登录一次。"},
160
+ {"group": "components", "intro": "下面这些组件不装也能检索和下载开放获取文献,缺了只影响列出的功能。"
161
+ "装好后选择「检测」再看一次。"},
162
+ {"group": "zotero", "intro": "下载的文献可推送到 Zotero。需要 Zotero 7 以上和 zotero-mcp;推荐授权本地写入,速度最快。"},
163
+ ]
164
+ _CONFIGURED = ("openalex_api_key", "elsevier_api_key", "springer_meta_api_key")
165
+
166
+
167
+ def onboarding() -> dict[str, Any]:
168
+ """Whether the first-run guide still has to show, and its steps.
169
+
170
+ Someone who already set a key or their e-mail (by hand or through an agent)
171
+ has set LitLoop up: the guide stays away for them too.
172
+ """
173
+ cfg = _config.load_config()
174
+ done = bool(cfg.get("onboarding_done")) or any(str(cfg.get(k) or "").strip() for k in _CONFIGURED) \
175
+ or str(cfg.get("email") or "") not in ("", _config.DEFAULT_CONFIG["email"])
176
+ return {"done": done, "steps": STEPS}
177
+
178
+
179
+ def finish_onboarding(done: bool = True) -> dict[str, Any]:
180
+ _config.update_config("onboarding_done", "true" if done else "false")
181
+ return {"done": done}
182
+
183
+
184
+ def mask(value: str) -> str:
185
+ """First and last four characters of a secret, the rest hidden."""
186
+ value = str(value or "")
187
+ if not value:
188
+ return ""
189
+ return value[:4] + "…" + value[-4:] if len(value) > 12 else "•" * 8
190
+
191
+
192
+ def _source(key: str, cfg: dict[str, Any]) -> str:
193
+ """Where the value comes from: the config file, an environment variable, or the default."""
194
+ env = _config.ENV_KEYS.get(key)
195
+ on_file = {}
196
+ try:
197
+ import json
198
+ on_file = json.loads(_config.CONFIG_FILE.read_text(encoding="utf-8")) if _config.CONFIG_FILE.exists() else {}
199
+ except (OSError, ValueError):
200
+ pass
201
+ if key in on_file and on_file[key] not in ("", None):
202
+ return "file"
203
+ if env and os.environ.get(env) and cfg.get(key) == os.environ.get(env):
204
+ return "env"
205
+ return "default"
206
+
207
+
208
+ def settings() -> list[dict[str, Any]]:
209
+ cfg = _config.load_config()
210
+ out = []
211
+ for g in GROUPS:
212
+ fields = []
213
+ for f in g["fields"]:
214
+ value = _rename_format(cfg) if f["key"] == "rename_format" else cfg.get(f["key"])
215
+ if f["key"] == "email" and str(value).endswith(".invalid"):
216
+ value = "" # the shipped placeholder is not an address
217
+ shown = {**f, "set": bool(value), "source": _source(f["key"], cfg)}
218
+ shown["value"] = mask(value) if f["type"] == "secret" else value
219
+ if f["key"] in _config.ENV_KEYS:
220
+ shown["env"] = _config.ENV_KEYS[f["key"]]
221
+ fields.append(shown)
222
+ out.append({**g, "fields": fields})
223
+ return out
224
+
225
+
226
+ def _check_path(value: str, pick: str) -> None:
227
+ r"""A path setting must be a full path on a drive that exists (2026-10-19: the
228
+ user typed ":\Users\Echo\.litloop\papers" and the app said it was saved).
229
+ A folder that does not exist yet is fine: downloads create it."""
230
+ p = Path(value).expanduser()
231
+ if not p.is_absolute():
232
+ raise ValueError(r"填写从盘符开始的完整路径,例如 D:\文献\papers")
233
+ if not Path(p.anchor).exists():
234
+ raise ValueError(f"找不到 {p.drive or p.anchor},换成本机存在的盘符")
235
+ if pick == "dir" and p.exists() and not p.is_dir():
236
+ raise ValueError("这里是一个文件,填写文件夹的路径")
237
+ if pick == "file" and not p.is_file():
238
+ raise ValueError("找不到这个文件,检查路径后重新填写")
239
+
240
+
241
+ def update(key: str, value: Any) -> dict[str, Any]:
242
+ """Save one setting from the app. Only keys on the settings page can be changed."""
243
+ field = _FIELDS.get(key)
244
+ if field is None:
245
+ raise KeyError(f"{key} is not a setting the app may change")
246
+ if field["type"] == "bool":
247
+ value = "true" if value in (True, "true", "1", 1) else "false"
248
+ elif field["type"] == "select" and value not in [o[0] for o in field["options"]]:
249
+ raise ValueError(f"从列表中选择一项({key} 不接受 {value!r})")
250
+ elif field["type"] == "email" and value and "@" not in str(value):
251
+ raise ValueError("填写完整邮箱,例如 name@example.edu")
252
+ elif field["type"] == "path" and str(value or "").strip():
253
+ _check_path(str(value).strip(), field.get("pick", ""))
254
+ _config.update_config(key, str(value if value is not None else "").strip())
255
+ if key == "rename_format":
256
+ _config.update_config("auto_rename", "true") # the older switch must not override the choice
257
+ return next(f for g in settings() for f in g["fields"] if f["key"] == key)
258
+
259
+
260
+ # --------------------------------------------------------------------------- tests
261
+
262
+ def _result(name: str, ok: bool | None, detail: str, cost: str = "", **extra: Any) -> dict[str, Any]:
263
+ """ok: True passed, False failed, None not configured (nothing to test).
264
+
265
+ extra: ``guides``, each with a ``title``, numbered ``steps``, ``copy`` blocks
266
+ ({label, lines}) to paste, and an optional ``note``.
267
+ """
268
+ return {"name": name, "ok": ok, "detail": detail, **({"cost": cost} if cost else {}), **extra}
269
+
270
+
271
+ def _get(url: str, **kw: Any):
272
+ import requests
273
+ return requests.get(url, timeout=15, **kw)
274
+
275
+
276
+ def _cannot_reach(name: str, raw: Any) -> str:
277
+ """'无法连接 <name>:<reason>' with the raw error translated (docs/UI_COPY.md 7.2)."""
278
+ from . import error_text
279
+ why = error_text.reason(str(raw)) if raw else "没有响应"
280
+ return f"无法连接 {name}" if why == "出现意外错误" else f"无法连接 {name}:{why}"
281
+
282
+
283
+ def _openalex_failure(raw: Any, has_key: bool) -> str:
284
+ """OpenAlex's anonymous budget is shared per IP, so a refusal rarely means "no network"."""
285
+ from . import error_text
286
+ why = error_text.reason(str(raw)) if raw else "没有响应"
287
+ if "限流" in why or "拒绝访问" in why:
288
+ if not has_key:
289
+ return "无法连接 OpenAlex:这个网络出口的匿名额度已经用完。填一个免费 Key 就能用,或换个网络再试"
290
+ return "无法连接 OpenAlex:这个出口被限流,稍后再试"
291
+ return f"无法连接 OpenAlex:{why}"
292
+
293
+
294
+ def test_sources() -> list[dict[str, Any]]:
295
+ from .. import quota
296
+ cfg = _config.load_config()
297
+ out = []
298
+
299
+ live = quota.openalex_live()
300
+ key = str(cfg.get("openalex_api_key") or "").strip()
301
+ if not live or live.get("error"):
302
+ out.append(_result("OpenAlex", False if key else None,
303
+ _openalex_failure((live or {}).get("error"), bool(key))))
304
+ else:
305
+ left, limit = live.get("credits_remaining"), live.get("credits_limit")
306
+ if live.get("has_key"):
307
+ out.append(_result("OpenAlex", True, f"可用,今日剩余 {left} / {limit} 积分"))
308
+ else:
309
+ out.append(_result("OpenAlex", None, f"未填写 Key,今日剩余 {left} / {limit} 积分"))
310
+
311
+ key = str(cfg.get("elsevier_api_key") or "").strip()
312
+ if not key:
313
+ out.append(_result("Elsevier", None, "未填写"))
314
+ else:
315
+ try:
316
+ r = _get("https://api.elsevier.com/content/abstract/doi/10.1016/j.jeurceramsoc.2008.06.007",
317
+ headers={"X-ELS-APIKey": key, "Accept": "application/json"})
318
+ quota.record("scopus", r)
319
+ left = r.headers.get("X-RateLimit-Remaining")
320
+ if r.status_code == 200:
321
+ out.append(_result("Elsevier", True, "可用" + (f",本周剩余 {left} 次" if left else ""),
322
+ cost="Scopus 1 次"))
323
+ elif r.status_code in (401, 403):
324
+ out.append(_result("Elsevier", False, f"Key 无效(HTTP {r.status_code})"))
325
+ else:
326
+ out.append(_result("Elsevier", False, f"无法使用(HTTP {r.status_code})"))
327
+ except Exception as exc:
328
+ out.append(_result("Elsevier", False, _cannot_reach("Elsevier", exc)))
329
+
330
+ key = str(cfg.get("springer_meta_api_key") or "").strip()
331
+ if not key:
332
+ out.append(_result("Springer Nature", None, "未填写"))
333
+ else:
334
+ try:
335
+ r = _get("https://api.springernature.com/meta/v2/json",
336
+ params={"q": "doi:10.1007/bf00723813", "api_key": key, "p": 1})
337
+ quota.record("springer", r)
338
+ if r.status_code == 200:
339
+ out.append(_result("Springer Nature", True, "可用", cost="Meta API 1 次"))
340
+ elif r.status_code in (401, 403):
341
+ out.append(_result("Springer Nature", False, f"Key 无效或不是 Meta API 的 Key(HTTP {r.status_code})"))
342
+ else:
343
+ out.append(_result("Springer Nature", False, f"无法使用(HTTP {r.status_code})"))
344
+ except Exception as exc:
345
+ out.append(_result("Springer Nature", False, _cannot_reach("Springer Nature", exc)))
346
+
347
+ email = str(cfg.get("email") or "").strip()
348
+ if not email or email.endswith(".invalid"):
349
+ out.append(_result("Crossref", None, "未填写联系邮箱"))
350
+ else:
351
+ try:
352
+ r = _get("https://api.crossref.org/works", params={"rows": 0, "mailto": email})
353
+ out.append(_result("Crossref", r.status_code == 200,
354
+ "可用" if r.status_code == 200 else f"无法使用(HTTP {r.status_code})"))
355
+ except Exception as exc:
356
+ out.append(_result("Crossref", False, _cannot_reach("Crossref", exc)))
357
+ return out
358
+
359
+
360
+ def test_downloads() -> list[dict[str, Any]]:
361
+ folder = Path(str(_config.load_config().get("output_dir") or "")).expanduser()
362
+ try:
363
+ folder.mkdir(parents=True, exist_ok=True)
364
+ with tempfile.NamedTemporaryFile(dir=folder, prefix=".litloop-test-", delete=True):
365
+ pass
366
+ free = None
367
+ try:
368
+ import shutil
369
+ free = shutil.disk_usage(folder).free / 1024 ** 3
370
+ except OSError:
371
+ pass
372
+ return [_result("保存位置", True, "可写入" + (f",剩余 {free:.0f} GB" if free is not None else ""))]
373
+ except OSError as exc:
374
+ why = "没有此文件夹的写入权限" if isinstance(exc, PermissionError) else "检查保存位置是否正确"
375
+ return [_result("保存位置", False, f"无法写入:{why}")]
376
+
377
+
378
+ def test_zotero() -> list[dict[str, Any]]:
379
+ try:
380
+ r = _get("http://127.0.0.1:23119/connector/ping", proxies={"http": None, "https": None})
381
+ if r.status_code == 200:
382
+ return [_result("Zotero", True, "Zotero 运行中")]
383
+ return [_result("Zotero", False, f"Zotero 没有响应(HTTP {r.status_code})")]
384
+ except Exception:
385
+ return [_result("Zotero", False, "Zotero 未运行")]
386
+
387
+
388
+ def test_network() -> list[dict[str, Any]]:
389
+ """Proxy programs: system-proxy mode is bypassed by itself; TUN mode needs direct rules.
390
+
391
+ The steps follow the programs' own docs (checked 2026-10-16):
392
+ v2rayN https://github.com/2dust/v2rayN/wiki/Description-of-some-ui ,
393
+ Clash Verge Rev https://www.clashverge.dev/guide/rules.html ,
394
+ mihomo find-process-mode https://wiki.metacubex.one/config/general/ .
395
+ """
396
+ from ..institutional import proxy_check
397
+ out = []
398
+ cfg = _config.load_config()
399
+ if str(cfg.get("network_proxy") or "").strip():
400
+ out.append(_result("校园出口代理", None, "已填写:LitLoop 会跳过学校登录。只填学校提供的代理地址。"))
401
+ found = proxy_check.detect()
402
+ names, paths = found["direct_processes"], proxy_check.litloop_paths()
403
+ programs = "、".join(found["programs"]) or "代理软件"
404
+ if found["mode"] == "unknown":
405
+ out.append(_result("代理软件", None, "暂不支持在此系统上检测"))
406
+ elif found["mode"] == "none":
407
+ out.append(_result("代理软件", True, "未检测到代理软件"))
408
+ elif found["mode"] == "system":
409
+ out.append(_result("代理软件", True, f"{programs} 以系统代理模式运行,LitLoop 会自动直连,无需设置"))
410
+ else:
411
+ guides = []
412
+ if any(p in ("v2rayN", "sing-box", "Xray") for p in found["programs"]) or not found["programs"]:
413
+ # v2rayN's wiki names the 进程名 field and the direct outbound but not the
414
+ # value's format; full paths are offered for when the name does not match.
415
+ guides.append({
416
+ "title": "在 v2rayN 中设置直连",
417
+ "steps": ["打开「路由设置」,新建一条规则。",
418
+ "在「进程名」中填写下方的一个程序名,出站选择「direct」。每个程序单独建一条规则。",
419
+ "将这些规则移到列表最上方并保存。规则按顺序生效。"],
420
+ "copy": [{"label": "程序名", "lines": names},
421
+ {"label": "完整路径(填程序名不生效时使用)", "lines": paths}],
422
+ })
423
+ if any("Clash" in p or p == "mihomo" for p in found["programs"]):
424
+ guides.append({
425
+ "title": "在 Clash Verge 中设置直连",
426
+ "steps": ["右键当前订阅,选择「编辑规则」。",
427
+ "在「前置规则」中添加下方的规则并保存。"],
428
+ "copy": [{"label": "规则", "lines": [f"PROCESS-NAME,{n},DIRECT" for n in names]}],
429
+ "note": "如果规则未生效,在「扩展配置」中加入 find-process-mode: always。",
430
+ })
431
+ out.append(_result("代理软件", False,
432
+ f"{programs} 正以 TUN 模式运行,学校认证的流量会经代理出口,学校无法识别你的身份。"
433
+ "按下方步骤设置直连后,查看下面两项的结果。",
434
+ guides=guides))
435
+ out += _egress_checks(cfg)
436
+ return out
437
+
438
+
439
+ # A subscription paper whose full-text right says whether publishers accept this
440
+ # network's exit (Ceramics International: subscribed by most universities).
441
+ EGRESS_SAMPLE_DOI = "10.1016/j.ceramint.2024.08.002"
442
+
443
+
444
+ def _egress_checks(cfg: dict[str, Any]) -> list[dict[str, Any]]:
445
+ """Where LitLoop's own traffic leaves this computer, and whether the Elsevier
446
+ API serves full text to this key from here.
447
+
448
+ The API's 403 "Requestor configuration settings insufficient" is about the
449
+ key's full-text configuration, not proof that publishers refuse this exit:
450
+ on 2026-10-17 ScienceDirect recognized the same exit as the school's and the
451
+ browser route downloaded the paper. So a refusal is a notice, not a failure.
452
+ """
453
+ import requests
454
+ out = []
455
+ try:
456
+ s = requests.Session()
457
+ s.trust_env = False # LitLoop's own route (proxy programs in TUN mode still apply)
458
+ info = s.get("https://ipinfo.io/json", timeout=10).json()
459
+ where = " ".join(x for x in (info.get("city"), info.get("country")) if x)
460
+ out.append(_result("出口 IP", None, f"{info.get('ip')}({where},{info.get('org') or '运营商未知'})"))
461
+ except Exception:
462
+ out.append(_result("出口 IP", None, "无法查询出口 IP"))
463
+ key = str(cfg.get("elsevier_api_key") or "").strip()
464
+ if not key:
465
+ out.append(_result("Elsevier 全文接口", None, "未填写 Elsevier Key"))
466
+ return out
467
+ from ..sources.elsevier_check import ENTITLED, NOT_ENTITLED, _head_probe
468
+ proxy = str(cfg.get("network_proxy") or "").strip()
469
+ code, verdict = _head_probe(EGRESS_SAMPLE_DOI, key, {"http": proxy, "https": proxy} if proxy else None)
470
+ if verdict.startswith(ENTITLED):
471
+ out.append(_result("Elsevier 全文接口", True, "可用:ScienceDirect 的订阅全文可直接通过接口下载"))
472
+ elif verdict.startswith(NOT_ENTITLED):
473
+ out.append(_result("Elsevier 全文接口", None,
474
+ "此 Key 没有全文权限,ScienceDirect 的文献改由浏览器从官网下载。"
475
+ "要判断出口是否被学校认可,关闭代理后用浏览器打开一篇 ScienceDirect "
476
+ "订阅文献,看页面上是否显示学校名称。"))
477
+ else:
478
+ out.append(_result("Elsevier 全文接口", None, f"无法判断(HTTP {code})" if code else "无法判断:Elsevier 没有响应"))
479
+ return out
480
+
481
+
482
+ def test_screening() -> list[dict[str, Any]]:
483
+ """Translate one sentence with the chosen service."""
484
+ from . import translate
485
+ config = load_config()
486
+ name = translate.provider(config)
487
+ label = {"deepseek": "DeepSeek", "deepl": "DeepL", "agent": "Agent"}[name]
488
+ if name == "agent":
489
+ return [_result("翻译服务", None, "由 Agent 在评分时翻译,无需检测")]
490
+ if not str(config.get(f"{name}_api_key") or "").strip():
491
+ return [_result(label, None, "未填写 Key")]
492
+ try:
493
+ out = translate.translate_text("Amorphous calcium phosphate nanoparticles release doxorubicin at pH 5.5.", config)
494
+ except translate.TranslationError as exc:
495
+ return [_result(label, False, str(exc))]
496
+ return [_result(label, True, f"可用,示例译文:{out}")]
497
+
498
+
499
+ def test_components() -> list[dict[str, Any]]:
500
+ """What is installed, and what a missing piece costs (deps, embedded_tor)."""
501
+ import shutil
502
+
503
+ from ..browser import backend as browser_backend; from .. import deps
504
+ from ..tor import embedded as embedded_tor
505
+ cfg = _config.load_config()
506
+ out = []
507
+ if not browser_backend.is_available():
508
+ out.append(_result("浏览器组件", False, "未安装 patchright:出版商官网和学校登录不可用。运行 pip install patchright"))
509
+ else:
510
+ info = browser_backend.browser_info(cfg)
511
+ if info.get("binary") == "channel=chrome":
512
+ out.append(_result("浏览器组件", False, "找不到 Chrome:出版商官网和学校登录不可用。安装 Chrome 后重新检测"))
513
+ else:
514
+ out.append(_result("浏览器组件", True, f"Chrome {info.get('version') or ''}".strip()))
515
+ out.append(_result("WebVPN 加密", True, "已安装") if deps.check_dependency("Crypto")
516
+ else _result("WebVPN 加密", False, "未安装 pycryptodome:WebVPN 不可用。运行 pip install pycryptodome"))
517
+ out.append(_result("SOCKS 代理", True, "已安装") if deps.check_dependency("socks")
518
+ else _result("SOCKS 代理", None, "未安装:暂无法使用 SOCKS 代理和 Tor。运行 pip install \"requests[socks]\""))
519
+ out.append(_result("Tor", True, "已安装") if embedded_tor.is_tor_installed(cfg)
520
+ else _result("Tor", None, "未安装:只在经 Tor 访问 Sci-Hub、LibGen 时需要"))
521
+ from .. import optional
522
+ if optional.installed("layout"):
523
+ out.append(_result("版面分析", True, "已安装:PDF 转 Markdown 会按版面整理表格和分栏"))
524
+ else:
525
+ out.append(_result("版面分析", None, "未安装:PDF 转 Markdown 按纯文本顺序,表格和分栏可能不规整",
526
+ action={"key": "layout", "label": "安装(约 65 MB)"}))
527
+ cmd = str(cfg.get("agent_command") or "claude").strip()
528
+ out.append(_result("Agent 命令", True, f"找到 {cmd}") if shutil.which(cmd)
529
+ else _result("Agent 命令", None, f"找不到 {cmd}:在 app 里发起检索需要它,可在「设置 → Agent」中修改"))
530
+ return out
531
+
532
+
533
+ def test_builtin_agent() -> list[dict[str, Any]]:
534
+ """Whether the configured model is there and can call a tool."""
535
+ from ..agents import test_model
536
+
537
+ cfg = _config.load_config()
538
+ reply = test_model(cfg)
539
+ detail = str(reply.get("detail") or "")
540
+ ok: bool | None = True if reply.get("ok") else (None if detail.startswith("还没有") else False)
541
+ return [_result("模型", ok, detail)]
542
+
543
+
544
+ TESTS = {"sources": test_sources, "downloads": test_downloads, "network": test_network, "zotero": test_zotero,
545
+ "screening": test_screening, "components": test_components, "builtin_agent": test_builtin_agent}
546
+
547
+
548
+ def run_test(group: str) -> dict[str, Any]:
549
+ if group not in TESTS:
550
+ raise KeyError(f"no test for {group}")
551
+ t0 = time.time()
552
+ return {"group": group, "results": TESTS[group](), "seconds": round(time.time() - t0, 1)}
@@ -0,0 +1,103 @@
1
+ """Abstract translation for the app: DeepSeek or DeepL, or left to the agent.
2
+
3
+ Config:
4
+ - ``abstract_translation``: which ratings are translated without asking —
5
+ "高", "高中", "all" or "off" (``screening.translate_wanted``).
6
+ - ``translation_provider``: "deepseek", "deepl" or "agent". With an API
7
+ provider the app backend translates a paper when the user opens it, once,
8
+ and stores the result in the record (``abstract_zh``); the agent is not
9
+ asked. With "agent" the agent adds ``abstract_zh`` when it rates.
10
+ - ``deepseek_api_key`` / ``deepl_api_key``. A DeepL key ending in ":fx" is a
11
+ free-plan key and goes to the free endpoint.
12
+
13
+ Errors raise ``TranslationError`` with text the app shows as is.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ import requests
21
+
22
+ from ..config import load_config
23
+
24
+ PROVIDERS = ("deepseek", "deepl", "agent")
25
+
26
+ # DeepSeek is a chat model: say what to keep, so formulas, units and names survive.
27
+ PROMPT = ("把下面的英文论文摘要翻译成简体中文学术语言。化学式、元素符号、缩写、数值和单位、"
28
+ "基因与蛋白名称保持原样;专业术语用通行的中文译名,没有通行译名的保留英文。"
29
+ "不要增删内容,不要解释,只输出译文。")
30
+
31
+
32
+ class TranslationError(Exception):
33
+ pass
34
+
35
+
36
+ def provider(config: dict[str, Any] | None = None) -> str:
37
+ value = str((config or load_config()).get("translation_provider") or "agent")
38
+ return value if value in PROVIDERS else "agent"
39
+
40
+
41
+ def by_api(config: dict[str, Any] | None = None) -> bool:
42
+ """True when the app translates (DeepSeek / DeepL), not the agent."""
43
+ return provider(config) != "agent"
44
+
45
+
46
+ def _key(name: str, config: dict[str, Any]) -> str:
47
+ key = str(config.get(f"{name}_api_key") or "").strip()
48
+ if not key:
49
+ label = "DeepSeek" if name == "deepseek" else "DeepL"
50
+ raise TranslationError(f"未填写 {label} Key。在「设置 → 筛选」中填写")
51
+ return key
52
+
53
+
54
+ def _fail(service: str, r: requests.Response) -> TranslationError:
55
+ if r.status_code in (401, 403):
56
+ return TranslationError(f"{service} Key 无效")
57
+ if r.status_code == 402:
58
+ return TranslationError(f"{service} 账户余额不足")
59
+ if r.status_code == 456:
60
+ return TranslationError("DeepL 本月额度已用完")
61
+ if r.status_code == 429:
62
+ return TranslationError(f"{service} 请求过于频繁,已被限流")
63
+ return TranslationError(f"{service} 返回错误(HTTP {r.status_code})")
64
+
65
+
66
+ def _deepseek(text: str, config: dict[str, Any]) -> str:
67
+ r = requests.post("https://api.deepseek.com/chat/completions", timeout=60,
68
+ headers={"Authorization": f"Bearer {_key('deepseek', config)}"},
69
+ json={"model": config.get("deepseek_model") or "deepseek-chat", "temperature": 1.3,
70
+ "messages": [{"role": "system", "content": PROMPT}, {"role": "user", "content": text}]})
71
+ if r.status_code != 200:
72
+ raise _fail("DeepSeek", r)
73
+ return r.json()["choices"][0]["message"]["content"].strip()
74
+
75
+
76
+ def _deepl(text: str, config: dict[str, Any]) -> str:
77
+ key = _key("deepl", config)
78
+ host = "api-free.deepl.com" if key.endswith(":fx") else "api.deepl.com"
79
+ r = requests.post(f"https://{host}/v2/translate", timeout=60,
80
+ headers={"Authorization": f"DeepL-Auth-Key {key}"},
81
+ json={"text": [text], "source_lang": "EN", "target_lang": "ZH-HANS"})
82
+ if r.status_code != 200:
83
+ raise _fail("DeepL", r)
84
+ return r.json()["translations"][0]["text"].strip()
85
+
86
+
87
+ def translate_text(text: str, config: dict[str, Any] | None = None) -> str:
88
+ """English abstract -> Chinese with the configured API provider."""
89
+ config = config or load_config()
90
+ name = provider(config)
91
+ if name == "agent":
92
+ raise TranslationError("翻译服务设为 Agent,由 Agent 在评分时翻译")
93
+ try:
94
+ out = (_deepseek if name == "deepseek" else _deepl)(text, config)
95
+ except requests.Timeout as exc:
96
+ raise TranslationError("连接翻译服务超时。检查网络后重试") from exc
97
+ except requests.RequestException as exc:
98
+ raise TranslationError("翻译服务没有响应。检查网络或代理设置") from exc
99
+ except (KeyError, IndexError, ValueError) as exc:
100
+ raise TranslationError("翻译服务返回了无法识别的结果") from exc
101
+ if not out:
102
+ raise TranslationError("翻译服务返回了空结果")
103
+ return out