papersearch 0.4.12 → 0.5.1
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/.env.example +8 -0
- package/README.en.md +89 -75
- package/README.md +90 -76
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/carsi/paper_search_carsi/api_keys.py +138 -0
- package/carsi/paper_search_carsi/assets/api_keys.json +146 -0
- package/carsi/paper_search_carsi/assets/capsule.html +316 -29
- package/carsi/paper_search_carsi/assets/capsule_en.json +437 -0
- package/carsi/paper_search_carsi/cli.py +46 -4
- package/carsi/paper_search_carsi/cli_config.py +51 -0
- package/carsi/paper_search_carsi/config.py +2 -0
- package/carsi/paper_search_carsi/download_directory.py +5 -33
- package/carsi/paper_search_carsi/engine/batch_capture.py +19 -10
- package/carsi/paper_search_carsi/engine/bridge.py +2 -1
- package/carsi/paper_search_carsi/engine/pdf_guard.py +3 -6
- package/carsi/paper_search_carsi/extractors/pdf_extractor.py +4 -18
- package/carsi/paper_search_carsi/i18n.py +46 -0
- package/carsi/paper_search_carsi/orchestrator.py +14 -1
- package/carsi/paper_search_carsi/pdf_text.py +84 -0
- package/carsi/paper_search_carsi/pdf_utils.py +3 -12
- package/carsi/paper_search_carsi/progress_capsule.py +94 -10
- package/carsi/paper_search_carsi/progress_reporter.py +64 -4
- package/carsi/paper_search_carsi/server.py +9 -1
- package/carsi/paper_search_carsi/user_settings.py +17 -4
- package/carsi/pyproject.toml +6 -4
- package/dist/capabilities/citation-expansion/CitationService.d.ts +8 -0
- package/dist/capabilities/citation-expansion/CitationService.d.ts.map +1 -1
- package/dist/capabilities/citation-expansion/CitationService.js +14 -4
- package/dist/capabilities/citation-expansion/CitationService.js.map +1 -1
- package/dist/capabilities/citation-expansion/CrossrefReferences.d.ts +18 -0
- package/dist/capabilities/citation-expansion/CrossrefReferences.d.ts.map +1 -0
- package/dist/capabilities/citation-expansion/CrossrefReferences.js +83 -0
- package/dist/capabilities/citation-expansion/CrossrefReferences.js.map +1 -0
- package/dist/capabilities/citation-expansion/OpenAlexGraph.d.ts +36 -0
- package/dist/capabilities/citation-expansion/OpenAlexGraph.d.ts.map +1 -0
- package/dist/capabilities/citation-expansion/OpenAlexGraph.js +120 -0
- package/dist/capabilities/citation-expansion/OpenAlexGraph.js.map +1 -0
- package/dist/capabilities/citation-expansion/handler.d.ts +14 -5
- package/dist/capabilities/citation-expansion/handler.d.ts.map +1 -1
- package/dist/capabilities/citation-expansion/handler.js +64 -14
- package/dist/capabilities/citation-expansion/handler.js.map +1 -1
- package/dist/capabilities/citation-expansion/schemas.d.ts +1 -5
- package/dist/capabilities/citation-expansion/schemas.d.ts.map +1 -1
- package/dist/capabilities/citation-expansion/schemas.js +2 -2
- package/dist/capabilities/citation-expansion/schemas.js.map +1 -1
- package/dist/capabilities/citation-expansion/tools.d.ts +0 -18
- package/dist/capabilities/citation-expansion/tools.d.ts.map +1 -1
- package/dist/capabilities/citation-expansion/tools.js +4 -16
- package/dist/capabilities/citation-expansion/tools.js.map +1 -1
- package/dist/capabilities/citation-expansion/types.d.ts +4 -0
- package/dist/capabilities/citation-expansion/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +36 -24
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +3 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +5 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts +5 -0
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/outputLayout.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/outputLayout.js +2 -1
- package/dist/capabilities/pdf-discovery/outputLayout.js.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
- package/dist/cli.js +86 -11
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +3 -0
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/config/apiKeySignup.d.ts +11 -1
- package/dist/config/apiKeySignup.d.ts.map +1 -1
- package/dist/config/apiKeySignup.js +18 -6
- package/dist/config/apiKeySignup.js.map +1 -1
- package/dist/config/apiKeyTest.d.ts +18 -0
- package/dist/config/apiKeyTest.d.ts.map +1 -0
- package/dist/config/apiKeyTest.js +109 -0
- package/dist/config/apiKeyTest.js.map +1 -0
- package/dist/config/selfCommand.d.ts +8 -0
- package/dist/config/selfCommand.d.ts.map +1 -0
- package/dist/config/selfCommand.js +10 -0
- package/dist/config/selfCommand.js.map +1 -0
- package/dist/management/capability-profile/index.js +4 -4
- package/dist/management/capability-profile/index.js.map +1 -1
- package/dist/management/carsi/autoUpdate.d.ts +21 -0
- package/dist/management/carsi/autoUpdate.d.ts.map +1 -0
- package/dist/management/carsi/autoUpdate.js +88 -0
- package/dist/management/carsi/autoUpdate.js.map +1 -0
- package/dist/management/carsi/installer.d.ts +1 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +38 -7
- package/dist/management/carsi/installer.js.map +1 -1
- package/dist/management/carsi/runtime.d.ts +9 -0
- package/dist/management/carsi/runtime.d.ts.map +1 -1
- package/dist/management/carsi/runtime.js +11 -0
- package/dist/management/carsi/runtime.js.map +1 -1
- package/dist/management/carsi/settingsWindow.d.ts +30 -0
- package/dist/management/carsi/settingsWindow.d.ts.map +1 -0
- package/dist/management/carsi/settingsWindow.js +51 -0
- package/dist/management/carsi/settingsWindow.js.map +1 -0
- package/dist/management/diagnostics/index.d.ts.map +1 -1
- package/dist/management/diagnostics/index.js +16 -0
- package/dist/management/diagnostics/index.js.map +1 -1
- package/dist/management/skills/nextSteps.d.ts +5 -0
- package/dist/management/skills/nextSteps.d.ts.map +1 -0
- package/dist/management/skills/nextSteps.js +21 -0
- package/dist/management/skills/nextSteps.js.map +1 -0
- package/dist/platforms/ACMSearcher.d.ts.map +1 -1
- package/dist/platforms/ACMSearcher.js +3 -2
- package/dist/platforms/ACMSearcher.js.map +1 -1
- package/dist/platforms/CrossrefSearcher.d.ts.map +1 -1
- package/dist/platforms/CrossrefSearcher.js +4 -3
- package/dist/platforms/CrossrefSearcher.js.map +1 -1
- package/dist/platforms/OpenAlexSearcher.d.ts.map +1 -1
- package/dist/platforms/OpenAlexSearcher.js +4 -1
- package/dist/platforms/OpenAlexSearcher.js.map +1 -1
- package/dist/registry/platformMetadata.d.ts.map +1 -1
- package/dist/registry/platformMetadata.js +1 -0
- package/dist/registry/platformMetadata.js.map +1 -1
- package/dist/utils/plainText.d.ts +7 -0
- package/dist/utils/plainText.d.ts.map +1 -0
- package/dist/utils/plainText.js +19 -0
- package/dist/utils/plainText.js.map +1 -0
- package/package.json +3 -1
- package/skills/paper-search/SKILL.md +18 -5
- package/skills/paper-search/references/capability-routing.md +5 -3
- package/skills/paper-search/references/carsi-setup.md +6 -3
- package/skills/paper-search/references/cli-contract.md +9 -4
- package/skills/paper-search/references/management-layer.md +4 -4
- package/skills/paper-search/references/troubleshooting.md +1 -1
|
@@ -494,7 +494,8 @@ def _try_browser_batch_download(
|
|
|
494
494
|
log.info(" [Institutional] no browser backend available, skipping browser download")
|
|
495
495
|
return None
|
|
496
496
|
|
|
497
|
-
|
|
497
|
+
# The caller's title checks the PDF when the article page names none (orchestrator).
|
|
498
|
+
record = PaperRecord(doi=doi, title=str(config.get("record_title") or ""))
|
|
498
499
|
# The institution name is the user's own setting (explicit CARSI); empty means "choose by hand".
|
|
499
500
|
institution_query = (config.get("carsi_idp_name", "") if config.get("publisher_institution_federation") == "carsi"
|
|
500
501
|
else "")
|
|
@@ -276,14 +276,11 @@ def assess(first_pages: str, identifier: str, title: str = "", source: str = "")
|
|
|
276
276
|
|
|
277
277
|
def first_pages_text(body: bytes) -> str | None:
|
|
278
278
|
"""Text of the first pages; None for an unreadable PDF."""
|
|
279
|
-
import
|
|
279
|
+
from .. import pdf_text
|
|
280
280
|
|
|
281
281
|
try:
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
return None
|
|
285
|
-
return "\n".join(document[i].get_text() for i in range(min(PAGES, document.page_count)))
|
|
286
|
-
except (pymupdf.FileDataError, RuntimeError, ValueError) as exc:
|
|
282
|
+
return pdf_text.text(body, PAGES)
|
|
283
|
+
except pdf_text.PdfError as exc:
|
|
287
284
|
log.info("pdf_guard: unreadable PDF (%s)", type(exc).__name__)
|
|
288
285
|
return None
|
|
289
286
|
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"""PDF text extraction
|
|
1
|
+
"""PDF text extraction (through ``pdf_text``)."""
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
4
|
import re
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
|
|
7
|
-
import
|
|
7
|
+
from .. import pdf_text
|
|
8
8
|
|
|
9
9
|
logger = logging.getLogger(__name__)
|
|
10
10
|
|
|
@@ -30,18 +30,11 @@ def extract_text(pdf_path: str | Path) -> str:
|
|
|
30
30
|
return ""
|
|
31
31
|
|
|
32
32
|
try:
|
|
33
|
-
|
|
33
|
+
text_parts = [text for text in pdf_text.page_texts(pdf_path) if text]
|
|
34
34
|
except Exception as e:
|
|
35
35
|
logger.error("Failed to open PDF %s: %s", pdf_path, e)
|
|
36
36
|
return ""
|
|
37
37
|
|
|
38
|
-
text_parts = []
|
|
39
|
-
for page in doc:
|
|
40
|
-
text = page.get_text("text")
|
|
41
|
-
if text:
|
|
42
|
-
text_parts.append(text)
|
|
43
|
-
|
|
44
|
-
doc.close()
|
|
45
38
|
full_text = "\n\n".join(text_parts)
|
|
46
39
|
|
|
47
40
|
# Clean up common PDF artifacts
|
|
@@ -102,18 +95,11 @@ def extract_from_bytes(pdf_bytes: bytes) -> str:
|
|
|
102
95
|
Extracted text content.
|
|
103
96
|
"""
|
|
104
97
|
try:
|
|
105
|
-
|
|
98
|
+
text_parts = [text for text in pdf_text.page_texts(pdf_bytes) if text]
|
|
106
99
|
except Exception as e:
|
|
107
100
|
logger.error("Failed to open PDF from bytes: %s", e)
|
|
108
101
|
return ""
|
|
109
102
|
|
|
110
|
-
text_parts = []
|
|
111
|
-
for page in doc:
|
|
112
|
-
text = page.get_text("text")
|
|
113
|
-
if text:
|
|
114
|
-
text_parts.append(text)
|
|
115
|
-
|
|
116
|
-
doc.close()
|
|
117
103
|
return _clean_text("\n\n".join(text_parts))
|
|
118
104
|
|
|
119
105
|
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""The progress window in English: ``assets/capsule_en.json`` maps each Chinese
|
|
2
|
+
text it can show (its own, the download's prompts and phases, PaperSearch's
|
|
3
|
+
failure reasons) to a short English one. The page translates what it shows with
|
|
4
|
+
it; the system notifications use it here. A text the table does not know stays
|
|
5
|
+
as it is."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
TABLE = Path(__file__).resolve().parent / "assets" / "capsule_en.json"
|
|
14
|
+
LANGUAGES = ("zh", "en")
|
|
15
|
+
_HAN = re.compile(r"[\u4e00-\u9fff]")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@lru_cache(maxsize=1)
|
|
19
|
+
def table() -> dict:
|
|
20
|
+
return json.loads(TABLE.read_text(encoding="utf-8"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@lru_cache(maxsize=1)
|
|
24
|
+
def _patterns() -> list[tuple[re.Pattern, str]]:
|
|
25
|
+
# The table's replacements are written for JavaScript ($1); Python's are \g<1>.
|
|
26
|
+
return [(re.compile(source), re.sub(r"\$(\d)", r"\\g<\1>", target)) for source, target in table()["patterns"]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _one(text: str) -> str:
|
|
30
|
+
core = text.strip()
|
|
31
|
+
if not core or not _HAN.search(core):
|
|
32
|
+
return text
|
|
33
|
+
exact = table()["exact"].get(core)
|
|
34
|
+
if exact is None:
|
|
35
|
+
for pattern, target in _patterns():
|
|
36
|
+
if pattern.search(core):
|
|
37
|
+
exact = pattern.sub(target, core)
|
|
38
|
+
break
|
|
39
|
+
return text if exact is None else text.replace(core, exact)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def translate(text: str, lang: str) -> str:
|
|
43
|
+
"""``text`` in ``lang``; its " · " parts one by one, as the page does."""
|
|
44
|
+
if lang != "en" or not text:
|
|
45
|
+
return text
|
|
46
|
+
return " · ".join(_one(part) for part in text.split(" · "))
|
|
@@ -6,6 +6,8 @@ sources and no renaming; the caller names and verifies the file.
|
|
|
6
6
|
"""
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import html
|
|
10
|
+
import re
|
|
9
11
|
import threading
|
|
10
12
|
from pathlib import Path
|
|
11
13
|
from typing import Any
|
|
@@ -25,6 +27,11 @@ _INFLIGHT: set[str] = set()
|
|
|
25
27
|
_INFLIGHT_LOCK = threading.Lock()
|
|
26
28
|
|
|
27
29
|
|
|
30
|
+
def plain_title(title: str) -> str:
|
|
31
|
+
"""A metadata title as plain text: no markup or entities (Crossref gives <i>…</i> and &)."""
|
|
32
|
+
return " ".join(html.unescape(re.sub(r"<[^>]+>", "", str(title))).split())[:500]
|
|
33
|
+
|
|
34
|
+
|
|
28
35
|
def download_institutional(
|
|
29
36
|
identifier: str,
|
|
30
37
|
output_dir: str | Path | None = None,
|
|
@@ -33,6 +40,7 @@ def download_institutional(
|
|
|
33
40
|
supplements: str | None = None,
|
|
34
41
|
user_wait: str | None = None,
|
|
35
42
|
diagnostics_dir: str | None = None,
|
|
43
|
+
title: str | None = None,
|
|
36
44
|
) -> dict[str, Any]:
|
|
37
45
|
"""Download one DOI through institutional access only.
|
|
38
46
|
|
|
@@ -69,6 +77,8 @@ def download_institutional(
|
|
|
69
77
|
extra["user_wait"] = user_wait
|
|
70
78
|
if diagnostics_dir:
|
|
71
79
|
extra["diagnostics_dir"] = diagnostics_dir
|
|
80
|
+
if title:
|
|
81
|
+
extra["title"] = title
|
|
72
82
|
return _download_impl(doi, output_dir, **extra)
|
|
73
83
|
finally:
|
|
74
84
|
with _INFLIGHT_LOCK:
|
|
@@ -77,8 +87,11 @@ def download_institutional(
|
|
|
77
87
|
|
|
78
88
|
def _download_impl(doi: str, output_dir: str | Path | None, *,
|
|
79
89
|
supplements: str | None = None, user_wait: str | None = None,
|
|
80
|
-
diagnostics_dir: str | None = None) -> dict[str, Any]:
|
|
90
|
+
diagnostics_dir: str | None = None, title: str | None = None) -> dict[str, Any]:
|
|
81
91
|
config = load_config()
|
|
92
|
+
if title:
|
|
93
|
+
# The caller's title for the PDF identity check (bridge's PaperRecord).
|
|
94
|
+
config["record_title"] = plain_title(title)
|
|
82
95
|
if user_wait == "short":
|
|
83
96
|
config["user_wait"] = "short"
|
|
84
97
|
if supplements in ("with", "only"):
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Reading PDFs: page count, page text, and whether a transfer ended whole.
|
|
2
|
+
|
|
3
|
+
Every PDF the backend reads goes through here, so the library can change in one
|
|
4
|
+
place. It is pypdfium2 (PDFium, Chrome's PDF engine; BSD/Apache, about 10 MB),
|
|
5
|
+
which replaced PyMuPDF (AGPL, about 54 MB) in 2026-11. PDFium allows one call at
|
|
6
|
+
a time in a process, even on different documents, so every call takes a lock."""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import threading
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
_LOCK = threading.Lock()
|
|
14
|
+
# The last startxref of a file and the cross-reference it names.
|
|
15
|
+
_STARTXREF = re.compile(rb"startxref\s+(\d+)\s+%%EOF")
|
|
16
|
+
_XREF_OBJECT = re.compile(rb"\d+\s+\d+\s+obj\b")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PdfError(Exception):
|
|
20
|
+
"""Not a PDF the library can read, or one without pages."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _open(source: bytes | str | Path):
|
|
24
|
+
import pypdfium2
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
return pypdfium2.PdfDocument(bytes(source) if isinstance(source, (bytes, bytearray)) else str(source))
|
|
28
|
+
except pypdfium2.PdfiumError as exc:
|
|
29
|
+
raise PdfError(str(exc)) from exc
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def page_count(source: bytes | str | Path) -> int:
|
|
33
|
+
with _LOCK:
|
|
34
|
+
document = _open(source)
|
|
35
|
+
try:
|
|
36
|
+
return len(document)
|
|
37
|
+
finally:
|
|
38
|
+
document.close()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def page_texts(source: bytes | str | Path, pages: int | None = None) -> list[str]:
|
|
42
|
+
"""The text of each of the first ``pages`` pages (all when None)."""
|
|
43
|
+
with _LOCK:
|
|
44
|
+
document = _open(source)
|
|
45
|
+
try:
|
|
46
|
+
count = len(document)
|
|
47
|
+
if not count:
|
|
48
|
+
raise PdfError("no pages")
|
|
49
|
+
texts = []
|
|
50
|
+
for index in range(count if pages is None else min(pages, count)):
|
|
51
|
+
page = document[index]
|
|
52
|
+
textpage = page.get_textpage()
|
|
53
|
+
try:
|
|
54
|
+
texts.append(_clean(textpage.get_text_bounded()))
|
|
55
|
+
finally:
|
|
56
|
+
textpage.close()
|
|
57
|
+
page.close()
|
|
58
|
+
return texts
|
|
59
|
+
finally:
|
|
60
|
+
document.close()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def text(source: bytes | str | Path, pages: int | None = None) -> str:
|
|
64
|
+
"""The first ``pages`` pages' text (all when None), a line break between pages."""
|
|
65
|
+
return "\n".join(page_texts(source, pages))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _clean(text: str) -> str:
|
|
69
|
+
# PDFium ends lines with \r\n and writes a hyphen it found at a line's end as \x02.
|
|
70
|
+
return text.replace("\r\n", "\n").replace("\r", "\n").replace("\x02", "-")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def complete(body: bytes) -> bool:
|
|
74
|
+
"""Whether the bytes end as a whole PDF: %%EOF after a startxref that points
|
|
75
|
+
at a cross-reference table or stream. A cut-off or damaged transfer, which
|
|
76
|
+
a reader would have to repair, does not."""
|
|
77
|
+
found = list(_STARTXREF.finditer(body[-2048:]))
|
|
78
|
+
if not found:
|
|
79
|
+
return False
|
|
80
|
+
offset = int(found[-1].group(1))
|
|
81
|
+
if offset >= len(body):
|
|
82
|
+
return False
|
|
83
|
+
head = body[offset:offset + 64].lstrip()
|
|
84
|
+
return head.startswith(b"xref") or _XREF_OBJECT.match(head) is not None
|
|
@@ -77,19 +77,10 @@ def is_suspicious_pdf(path: Path) -> bool:
|
|
|
77
77
|
# Very small files are suspicious regardless
|
|
78
78
|
if size < 50_000:
|
|
79
79
|
return True
|
|
80
|
+
from . import pdf_text
|
|
81
|
+
|
|
80
82
|
try:
|
|
81
|
-
|
|
82
|
-
except Exception:
|
|
83
|
-
# No pymupdf: fall back to the cheap regex heuristic
|
|
84
|
-
with path.open("rb") as fh:
|
|
85
|
-
content = fh.read(512_000)
|
|
86
|
-
# Count PDF page objects: look for "/Type /Page" not followed by "s"
|
|
87
|
-
import re
|
|
88
|
-
pages = len(re.findall(rb"/Type\s*/Page\b", content))
|
|
89
|
-
return pages <= 1
|
|
90
|
-
try:
|
|
91
|
-
with fitz.open(path) as doc:
|
|
92
|
-
return int(doc.page_count) <= 1
|
|
83
|
+
return pdf_text.page_count(path) <= 1
|
|
93
84
|
except Exception:
|
|
94
85
|
return True # unreadable PDF — treat as suspicious
|
|
95
86
|
except OSError:
|
|
@@ -12,6 +12,8 @@ Windows. Without pywebview or a usable engine the classic window
|
|
|
12
12
|
|
|
13
13
|
Usage: ``paper-search-carsi progress`` (or ``python -m paper_search_carsi.progress_capsule``).
|
|
14
14
|
Spawned automatically by ``progress_reporter.ensure_progress_bar`` when a download starts.
|
|
15
|
+
``paper-search-carsi settings`` opens it at the settings (download folder,
|
|
16
|
+
waits and reminders, API keys), also with no download running.
|
|
15
17
|
"""
|
|
16
18
|
|
|
17
19
|
from __future__ import annotations
|
|
@@ -24,12 +26,17 @@ import time
|
|
|
24
26
|
from pathlib import Path
|
|
25
27
|
from typing import Any
|
|
26
28
|
|
|
27
|
-
from . import download_directory, progress_view, user_settings
|
|
29
|
+
from . import api_keys, download_directory, i18n, progress_view, user_settings
|
|
28
30
|
from .capsule_placement import Placement, Rect, ScreenArea
|
|
29
|
-
from .progress_reporter import progress_path, read_state
|
|
31
|
+
from .progress_reporter import progress_path, read_state, take_settings_request
|
|
30
32
|
|
|
31
33
|
ASSETS = Path(__file__).with_name("assets")
|
|
32
34
|
PAGE = ASSETS / "capsule.html"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def page_html() -> str:
|
|
38
|
+
"""The page with its English table in it (the window loads it as one string)."""
|
|
39
|
+
return PAGE.read_text(encoding="utf-8").replace("/*CAPSULE_EN*/null", i18n.TABLE.read_text(encoding="utf-8"))
|
|
33
40
|
# PaperSearch's icon (assets/icon.svg) for the Dock and the Windows taskbar.
|
|
34
41
|
ICON, TASKBAR_ICON = ASSETS / "icon-512.png", ASSETS / "icon-64.png"
|
|
35
42
|
# The first, collapsed frame; the page then reports the size it needs.
|
|
@@ -103,6 +110,7 @@ class Notifier:
|
|
|
103
110
|
if not new:
|
|
104
111
|
return
|
|
105
112
|
message = str(new[-1].get("message") or "需要你在浏览器里处理")
|
|
113
|
+
message = i18n.translate(message, user_settings.language())
|
|
106
114
|
threading.Thread(target=self._send, args=("PaperSearch", message, state), daemon=True).start()
|
|
107
115
|
|
|
108
116
|
|
|
@@ -124,6 +132,10 @@ class Api:
|
|
|
124
132
|
self._layout: tuple[int, bool, Rect, Rect] | None = None
|
|
125
133
|
self._closed = False
|
|
126
134
|
self._close_requested: float | None = None
|
|
135
|
+
try:
|
|
136
|
+
self._lang = user_settings.language()
|
|
137
|
+
except Exception:
|
|
138
|
+
self._lang = "zh"
|
|
127
139
|
|
|
128
140
|
# --- what to show -----------------------------------------------------
|
|
129
141
|
def platform(self) -> str:
|
|
@@ -133,9 +145,12 @@ class Api:
|
|
|
133
145
|
"""The capsule's view of the progress file; ``hovering`` keeps a finished window open."""
|
|
134
146
|
self._hovering = bool(hovering) or self._dragging
|
|
135
147
|
try:
|
|
136
|
-
|
|
148
|
+
shown = progress_view.view(read_state(), time.time())
|
|
137
149
|
except Exception:
|
|
138
|
-
|
|
150
|
+
shown = {"mode": "idle"}
|
|
151
|
+
shown["lang"] = self._lang
|
|
152
|
+
request = take_settings_request() # `paper-search-carsi settings`: show the settings
|
|
153
|
+
return {**shown, "open_settings": request} if request else shown
|
|
139
154
|
|
|
140
155
|
# --- watching the task, also while the capsule is minimized ------------
|
|
141
156
|
def watch(self) -> None:
|
|
@@ -242,11 +257,23 @@ class Api:
|
|
|
242
257
|
values = user_settings.current()
|
|
243
258
|
return {
|
|
244
259
|
"fields": [{"name": f.name, "label": f.label, "unit": f.unit, "value": values[f.name],
|
|
245
|
-
"default": f.default} for f in user_settings.FIELDS],
|
|
260
|
+
"default": f.default, "page": f.page} for f in user_settings.FIELDS],
|
|
246
261
|
"notify": user_settings.notify_enabled(),
|
|
247
262
|
"download_dir": download_directory.current(),
|
|
263
|
+
"language": self._lang,
|
|
248
264
|
}
|
|
249
265
|
|
|
266
|
+
def set_language(self, lang: str) -> dict[str, Any]:
|
|
267
|
+
"""The language switch saves at once and the page follows it."""
|
|
268
|
+
if lang not in i18n.LANGUAGES:
|
|
269
|
+
return {"ok": False, "error": "语言只能是中文或英文"}
|
|
270
|
+
try:
|
|
271
|
+
user_settings.set_language(lang)
|
|
272
|
+
except (OSError, ValueError) as exc:
|
|
273
|
+
return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
|
|
274
|
+
self._lang = lang
|
|
275
|
+
return {"ok": True, "language": lang}
|
|
276
|
+
|
|
250
277
|
def set_notifications(self, enabled: bool) -> dict[str, Any]:
|
|
251
278
|
"""The notification switch saves immediately, independently of other fields."""
|
|
252
279
|
if not isinstance(enabled, bool):
|
|
@@ -258,11 +285,14 @@ class Api:
|
|
|
258
285
|
return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
|
|
259
286
|
return {"ok": True, "notify": enabled}
|
|
260
287
|
|
|
261
|
-
def save_settings(self, values: dict[str, Any],
|
|
262
|
-
"""Check
|
|
288
|
+
def save_settings(self, values: dict[str, Any], download_dir: str | None = None) -> dict[str, Any]:
|
|
289
|
+
"""Check the fields of one settings page, then save them all; nothing is
|
|
290
|
+
saved when one is wrong. The notification switch saves on its own."""
|
|
263
291
|
checked, errors = {}, {}
|
|
264
292
|
for field in user_settings.FIELDS:
|
|
265
|
-
|
|
293
|
+
if field.name not in (values or {}):
|
|
294
|
+
continue
|
|
295
|
+
value, problem = user_settings.check(field, str(values[field.name]))
|
|
266
296
|
if problem:
|
|
267
297
|
errors[field.name] = problem
|
|
268
298
|
else:
|
|
@@ -278,11 +308,65 @@ class Api:
|
|
|
278
308
|
if download_dir is not None:
|
|
279
309
|
download_directory.save(download_dir)
|
|
280
310
|
user_settings.save(checked)
|
|
281
|
-
user_settings.set_notify(bool(notify_on))
|
|
282
311
|
except Exception as exc:
|
|
283
312
|
return {"ok": False, "errors": {"": f"保存失败:{type(exc).__name__}"}}
|
|
284
313
|
return {"ok": True}
|
|
285
314
|
|
|
315
|
+
# --- API keys: values go to the config, never back to the page ---------
|
|
316
|
+
def api_keys(self) -> dict[str, Any]:
|
|
317
|
+
try:
|
|
318
|
+
return {"ok": True, **api_keys.listing()}
|
|
319
|
+
except Exception as exc:
|
|
320
|
+
return {"ok": False, "error": f"读取配置失败:{type(exc).__name__}"}
|
|
321
|
+
|
|
322
|
+
def api_key_values(self, service: str) -> dict[str, Any]:
|
|
323
|
+
"""The values of the row the user opened, for its hidden fields."""
|
|
324
|
+
try:
|
|
325
|
+
return {"ok": True, "values": api_keys.saved(str(service or ""))}
|
|
326
|
+
except ValueError as exc:
|
|
327
|
+
return {"ok": False, "error": str(exc)}
|
|
328
|
+
except Exception as exc:
|
|
329
|
+
return {"ok": False, "error": f"读取配置失败:{type(exc).__name__}"}
|
|
330
|
+
|
|
331
|
+
def save_api_key(self, service: str, values: dict[str, Any]) -> dict[str, Any]:
|
|
332
|
+
try:
|
|
333
|
+
api_keys.save(str(service or ""), {str(k): str(v) for k, v in (values or {}).items()})
|
|
334
|
+
except ValueError as exc:
|
|
335
|
+
return {"ok": False, "error": str(exc)}
|
|
336
|
+
except Exception as exc:
|
|
337
|
+
return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
|
|
338
|
+
return self.api_keys()
|
|
339
|
+
|
|
340
|
+
def clear_api_key(self, service: str) -> dict[str, Any]:
|
|
341
|
+
try:
|
|
342
|
+
api_keys.clear(str(service or ""))
|
|
343
|
+
except ValueError as exc:
|
|
344
|
+
return {"ok": False, "error": str(exc)}
|
|
345
|
+
except Exception as exc:
|
|
346
|
+
return {"ok": False, "error": f"清除失败:{type(exc).__name__}"}
|
|
347
|
+
return self.api_keys()
|
|
348
|
+
|
|
349
|
+
def test_api_key(self, service: str, values: dict[str, Any]) -> dict[str, Any]:
|
|
350
|
+
"""Whether the service takes what is in the row's fields (saved or not)."""
|
|
351
|
+
try:
|
|
352
|
+
return api_keys.test(str(service or ""), {str(k): str(v) for k, v in (values or {}).items()})
|
|
353
|
+
except ValueError as exc:
|
|
354
|
+
return {"status": "error", "message": str(exc)}
|
|
355
|
+
|
|
356
|
+
def open_signup(self, service: str, guide: bool = False) -> dict[str, Any]:
|
|
357
|
+
"""The service's page for getting a key, or its guide; only the listed pages open."""
|
|
358
|
+
found = api_keys.find(str(service or ""))
|
|
359
|
+
address = found and (found.get("guide") if guide else found["url"])
|
|
360
|
+
if not address:
|
|
361
|
+
return {"ok": False, "message": "打开失败:没有这一项"}
|
|
362
|
+
import webbrowser
|
|
363
|
+
|
|
364
|
+
try:
|
|
365
|
+
opened = webbrowser.open(address)
|
|
366
|
+
except Exception as exc:
|
|
367
|
+
return {"ok": False, "message": f"打开失败:{type(exc).__name__}"}
|
|
368
|
+
return {"ok": True} if opened else {"ok": False, "message": "打开失败:没有找到默认浏览器"}
|
|
369
|
+
|
|
286
370
|
def choose_download_directory(self) -> str | None:
|
|
287
371
|
"""Native directory picker; cancelling leaves the field unchanged."""
|
|
288
372
|
import webview
|
|
@@ -822,7 +906,7 @@ def main() -> None:
|
|
|
822
906
|
_classic()
|
|
823
907
|
return
|
|
824
908
|
try:
|
|
825
|
-
page =
|
|
909
|
+
page = page_html()
|
|
826
910
|
screens = _screen_areas()
|
|
827
911
|
placement = Placement(progress_path().parent / "capsule.json", _corner())
|
|
828
912
|
x, y = placement.start(screens, START_SIZE, _window_scale())
|
|
@@ -134,15 +134,25 @@ def ensure_progress_bar(config: dict[str, Any] | None = None) -> None:
|
|
|
134
134
|
return
|
|
135
135
|
if config is not None and config.get("progress_bar_auto") is False:
|
|
136
136
|
return
|
|
137
|
+
if _window_up() is False:
|
|
138
|
+
_spawn_window()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _window_up() -> bool | None:
|
|
142
|
+
"""Whether a progress window is open; None when its lock cannot be read.
|
|
143
|
+
A stale lock (the window died) counts as none: the next window takes it over."""
|
|
137
144
|
lock = _progress_dir() / "bar.pid"
|
|
138
145
|
try:
|
|
139
146
|
if lock.exists():
|
|
140
147
|
pid = int(lock.read_text(encoding="utf-8").strip() or 0)
|
|
141
148
|
if _pid_alive(pid, created_before=lock.stat().st_mtime + 1):
|
|
142
|
-
return
|
|
143
|
-
|
|
149
|
+
return True
|
|
150
|
+
return False
|
|
144
151
|
except (ValueError, OSError):
|
|
145
|
-
return
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _spawn_window() -> bool:
|
|
146
156
|
try:
|
|
147
157
|
import subprocess
|
|
148
158
|
import sys
|
|
@@ -155,8 +165,58 @@ def ensure_progress_bar(config: dict[str, Any] | None = None) -> None:
|
|
|
155
165
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
|
|
156
166
|
env=env, start_new_session=(os.name != "nt"), **kwargs,
|
|
157
167
|
)
|
|
168
|
+
return True
|
|
158
169
|
except Exception:
|
|
159
|
-
|
|
170
|
+
return False
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
SETTINGS_REQUEST_SECONDS = 60 # a request no window has picked up by then is dropped
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _settings_request_path() -> Path:
|
|
177
|
+
return _progress_dir() / "open-settings.json"
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def open_settings(page: str = "home", service: str = "") -> str:
|
|
181
|
+
"""Show the progress window's settings (``paper-search-carsi settings``).
|
|
182
|
+
|
|
183
|
+
An open window switches to them ("existing"). Otherwise a window starts on
|
|
184
|
+
them ("opened"); it closes when they are closed with no download running,
|
|
185
|
+
and a download that starts meanwhile shows in it. RuntimeError when no
|
|
186
|
+
window could start."""
|
|
187
|
+
up = _window_up()
|
|
188
|
+
request = {"page": page, "service": service, "new_window": up is not True, "at": time.time()}
|
|
189
|
+
path = _settings_request_path()
|
|
190
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
|
|
192
|
+
try:
|
|
193
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
194
|
+
json.dump(request, fh)
|
|
195
|
+
os.replace(tmp, path)
|
|
196
|
+
finally:
|
|
197
|
+
Path(tmp).unlink(missing_ok=True)
|
|
198
|
+
if up is True:
|
|
199
|
+
return "existing"
|
|
200
|
+
if not _spawn_window():
|
|
201
|
+
path.unlink(missing_ok=True)
|
|
202
|
+
raise RuntimeError("进度窗口没能启动")
|
|
203
|
+
return "opened"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def take_settings_request() -> dict[str, Any] | None:
|
|
207
|
+
"""The pending request to show the settings, once; None when there is none
|
|
208
|
+
or it is too old (the window it was meant for never came up)."""
|
|
209
|
+
path = _settings_request_path()
|
|
210
|
+
try:
|
|
211
|
+
request = json.loads(path.read_text(encoding="utf-8"))
|
|
212
|
+
path.unlink()
|
|
213
|
+
fresh = time.time() - float(request["at"]) <= SETTINGS_REQUEST_SECONDS
|
|
214
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
215
|
+
return None
|
|
216
|
+
if not fresh:
|
|
217
|
+
return None
|
|
218
|
+
return {"page": str(request.get("page") or "home"), "service": str(request.get("service") or ""),
|
|
219
|
+
"new_window": request.get("new_window") is True}
|
|
160
220
|
|
|
161
221
|
|
|
162
222
|
@dataclass(frozen=True)
|
|
@@ -81,6 +81,7 @@ def carsi_download(
|
|
|
81
81
|
supplements: str | None = None,
|
|
82
82
|
user_wait: str | None = None,
|
|
83
83
|
diagnostics_dir: str | None = None,
|
|
84
|
+
title: str | None = None,
|
|
84
85
|
) -> str:
|
|
85
86
|
"""Synchronous download entry; ``download`` is module-level so tests can stub it.
|
|
86
87
|
|
|
@@ -98,6 +99,8 @@ def carsi_download(
|
|
|
98
99
|
kwargs["user_wait"] = user_wait
|
|
99
100
|
if diagnostics_dir:
|
|
100
101
|
kwargs["diagnostics_dir"] = diagnostics_dir
|
|
102
|
+
if title:
|
|
103
|
+
kwargs["title"] = title
|
|
101
104
|
from .entitlements import batch_stop_requested
|
|
102
105
|
|
|
103
106
|
if batch_stop_requested():
|
|
@@ -150,6 +153,7 @@ async def _carsi_download_with_progress(
|
|
|
150
153
|
user_wait: Literal["short"] | None = None,
|
|
151
154
|
diagnostics_dir: str | None = None,
|
|
152
155
|
keep_browser: bool = False,
|
|
156
|
+
title: str | None = None,
|
|
153
157
|
ctx: Context = None,
|
|
154
158
|
) -> str:
|
|
155
159
|
"""Download one paper by DOI through institutional access only.
|
|
@@ -169,6 +173,10 @@ async def _carsi_download_with_progress(
|
|
|
169
173
|
diagnostics_dir: optional separate directory for browser records, screenshots and
|
|
170
174
|
attachment manifests. When set, attachments go in output_dir/supplements/.
|
|
171
175
|
|
|
176
|
+
title: the paper's title as the caller knows it (its metadata). The PDF is checked against
|
|
177
|
+
it when the article page gives no title of its own (citation_title): Science on Atypon
|
|
178
|
+
gives none, and its older PDFs print the DOI only on the last page.
|
|
179
|
+
|
|
172
180
|
user_wait: "short" when the user seems away (an earlier article of the batch waited on them
|
|
173
181
|
until its time was up): each wait on the user (school login, human verification) lasts at
|
|
174
182
|
most 60 s, unless someone starts typing on the login page.
|
|
@@ -179,7 +187,7 @@ async def _carsi_download_with_progress(
|
|
|
179
187
|
use_vpnsci, bibtex, strategy, batch_id=batch_id, batch_index=batch_index,
|
|
180
188
|
batch_total=batch_total, batch_done=batch_done, batch_succeeded=batch_succeeded,
|
|
181
189
|
batch_failed=batch_failed, supplements=supplements, user_wait=user_wait,
|
|
182
|
-
diagnostics_dir=diagnostics_dir)
|
|
190
|
+
diagnostics_dir=diagnostics_dir, title=title)
|
|
183
191
|
if keep_browser and batch_id:
|
|
184
192
|
return await run_with_progress(ctx, identifier, partial(_with_batch_browser, batch_id, operation),
|
|
185
193
|
executor=_batch_worker)
|
|
@@ -17,13 +17,14 @@ class Field:
|
|
|
17
17
|
low: int
|
|
18
18
|
high: int
|
|
19
19
|
unit: str
|
|
20
|
+
page: str # the settings page it is on: "download" or "wait"
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
FIELDS = (
|
|
23
|
-
Field("login", "学校登录页最多等", "browser_login_timeout", 180, 30, 1800, "秒"),
|
|
24
|
-
Field("page", "其他页面最多等", "browser_page_wait_timeout", 60, 10, 600, "秒"),
|
|
25
|
-
Field("stalled", "验证提醒前最多等", "browser_stall_notify_after", 30, 1, 600, "秒"),
|
|
26
|
-
Field("hourly", "每家出版社每小时最多", "publisher_hourly_limit", 100, 0, 1000, "篇"),
|
|
24
|
+
Field("login", "学校登录页最多等", "browser_login_timeout", 180, 30, 1800, "秒", "wait"),
|
|
25
|
+
Field("page", "其他页面最多等", "browser_page_wait_timeout", 60, 10, 600, "秒", "wait"),
|
|
26
|
+
Field("stalled", "验证提醒前最多等", "browser_stall_notify_after", 30, 1, 600, "秒", "wait"),
|
|
27
|
+
Field("hourly", "每家出版社每小时最多", "publisher_hourly_limit", 100, 0, 1000, "篇", "download"),
|
|
27
28
|
)
|
|
28
29
|
|
|
29
30
|
|
|
@@ -65,3 +66,15 @@ def notify_enabled() -> bool:
|
|
|
65
66
|
|
|
66
67
|
def set_notify(on: bool) -> None:
|
|
67
68
|
_config.update_config(NOTIFY_KEY, "true" if on else "false")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
LANGUAGE_KEY = "progress_language"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def language() -> str:
|
|
75
|
+
"""The progress window's language: "zh" (the default) or "en"."""
|
|
76
|
+
return "en" if _config.load_config().get(LANGUAGE_KEY) == "en" else "zh"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def set_language(lang: str) -> None:
|
|
80
|
+
_config.update_config(LANGUAGE_KEY, "en" if lang == "en" else "zh")
|
package/carsi/pyproject.toml
CHANGED
|
@@ -11,8 +11,9 @@ dependencies = [
|
|
|
11
11
|
"requests[socks]>=2.31,<3",
|
|
12
12
|
"urllib3>=2.7.0,<3",
|
|
13
13
|
"beautifulsoup4>=4.12,<5",
|
|
14
|
-
"mcp
|
|
15
|
-
|
|
14
|
+
"mcp>=1.12,<3.0",
|
|
15
|
+
# Reading PDFs (pdf_text.py): PDFium, Chrome's PDF engine; BSD/Apache, about 10 MB.
|
|
16
|
+
"pypdfium2>=4.30,<6",
|
|
16
17
|
# The progress capsule (progress_capsule.py): the system web engine through pywebview.
|
|
17
18
|
"pywebview>=6.2,<7",
|
|
18
19
|
# Drives the user's installed Google Chrome, and ego over remote debugging:
|
|
@@ -23,7 +24,8 @@ dependencies = [
|
|
|
23
24
|
[project.optional-dependencies]
|
|
24
25
|
# ego backend: one shared remote-debugging connection (browser/ego_relay.py).
|
|
25
26
|
ego = ["websockets>=13,<18"]
|
|
26
|
-
|
|
27
|
+
# PyMuPDF only builds the tests' sample PDFs; the backend reads PDFs with pypdfium2.
|
|
28
|
+
dev = ["pytest>=8.0", "pymupdf>=1.24,<2"]
|
|
27
29
|
|
|
28
30
|
[project.scripts]
|
|
29
31
|
paper-search-carsi = "paper_search_carsi.cli:main"
|
|
@@ -37,7 +39,7 @@ where = ["."]
|
|
|
37
39
|
include = ["paper_search_carsi*"]
|
|
38
40
|
|
|
39
41
|
[tool.setuptools.package-data]
|
|
40
|
-
paper_search_carsi = ["publishers/builtin/*.json", "publishers/schema.json", "data/*.json", "assets/*.png", "assets/*.html", "assets/papersearch-notifier"]
|
|
42
|
+
paper_search_carsi = ["publishers/builtin/*.json", "publishers/schema.json", "data/*.json", "assets/*.png", "assets/*.html", "assets/*.json", "assets/papersearch-notifier"]
|
|
41
43
|
|
|
42
44
|
[tool.pytest.ini_options]
|
|
43
45
|
testpaths = ["tests"]
|