papersearch 0.4.11 → 0.5.0
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 +97 -75
- package/README.md +98 -76
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/carsi/paper_search_carsi/adapters/ams/__init__.py +12 -0
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +5 -2
- package/carsi/paper_search_carsi/adapters/elsevier/sciencedirect.py +18 -1
- package/carsi/paper_search_carsi/adapters/iop/__init__.py +11 -2
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +24 -14
- 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 +327 -30
- package/carsi/paper_search_carsi/assets/capsule_en.json +437 -0
- package/carsi/paper_search_carsi/browser/preview.py +16 -3
- package/carsi/paper_search_carsi/browser/watchdog.py +15 -0
- package/carsi/paper_search_carsi/capsule_placement.py +51 -31
- 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_diagnostics.py +1 -0
- package/carsi/paper_search_carsi/download_directory.py +5 -33
- package/carsi/paper_search_carsi/engine/access_rules.py +11 -0
- package/carsi/paper_search_carsi/engine/batch.py +13 -1
- package/carsi/paper_search_carsi/engine/batch_access.py +3 -0
- package/carsi/paper_search_carsi/engine/batch_capture.py +39 -10
- package/carsi/paper_search_carsi/engine/batch_common.py +4 -0
- package/carsi/paper_search_carsi/engine/batch_institution.py +27 -18
- package/carsi/paper_search_carsi/engine/bridge.py +7 -3
- package/carsi/paper_search_carsi/engine/pdf_guard.py +3 -6
- package/carsi/paper_search_carsi/engine/supplements.py +34 -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 +181 -19
- package/carsi/paper_search_carsi/progress_macos.py +35 -10
- package/carsi/paper_search_carsi/progress_reporter.py +76 -9
- package/carsi/paper_search_carsi/progress_view.py +7 -1
- 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/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +2 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.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 +85 -12
- 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/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +2 -0
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- 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 +2 -0
- package/dist/management/skills/nextSteps.d.ts.map +1 -0
- package/dist/management/skills/nextSteps.js +16 -0
- package/dist/management/skills/nextSteps.js.map +1 -0
- package/dist/management/updates/index.d.ts +6 -1
- package/dist/management/updates/index.d.ts.map +1 -1
- package/dist/management/updates/index.js +18 -11
- package/dist/management/updates/index.js.map +1 -1
- 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 -3
- package/skills/paper-search/SKILL.md +20 -15
- package/skills/paper-search/references/browser-download.md +1 -1
- 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/publisher-support.md +4 -4
- package/skills/paper-search/references/troubleshooting.md +1 -1
- package/NOTICE +0 -23
- package/carsi/NOTICE +0 -5
|
@@ -9,6 +9,7 @@ Commands:
|
|
|
9
9
|
publisher-check --doi DOI run one institutional download and print a sanitized report
|
|
10
10
|
progress open the floating progress window
|
|
11
11
|
progress --json [--watch] read-only snapshot of the current task progress file
|
|
12
|
+
settings [PAGE|KEY] show the progress window's settings: download, wait, keys, or one API key (e.g. EASYSCHOLAR_KEY)
|
|
12
13
|
preview [--run-id ID --doi DOI] latest screenshots of the download browser (JSON)
|
|
13
14
|
entitlements [list|set|clear] remembered "has access / no access" decisions per journal or publisher
|
|
14
15
|
issues [list|show ID|resolve ID --note TEXT] problem reports filed from the progress window (agent review)
|
|
@@ -315,11 +316,10 @@ def _cmd_publisher_check(args: argparse.Namespace) -> int:
|
|
|
315
316
|
report["file"] = path.name
|
|
316
317
|
report["size_kb"] = result.get("size_kb")
|
|
317
318
|
try:
|
|
318
|
-
import
|
|
319
|
+
from . import pdf_text
|
|
319
320
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
first = doc[0].get_text() if doc.page_count else ""
|
|
321
|
+
report["pages"] = pdf_text.page_count(path)
|
|
322
|
+
first = pdf_text.text(path, 1) if report["pages"] else ""
|
|
323
323
|
report["first_page_has_doi"] = (result.get("doi") or "").lower() in first.lower()
|
|
324
324
|
except Exception:
|
|
325
325
|
report["pages"] = None
|
|
@@ -422,6 +422,44 @@ def _cmd_issues(args: argparse.Namespace) -> int:
|
|
|
422
422
|
return 0
|
|
423
423
|
|
|
424
424
|
|
|
425
|
+
SETTINGS_PAGES = ("home", "download", "wait", "keys")
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _cmd_settings(args: argparse.Namespace) -> int:
|
|
429
|
+
"""Open the settings in the progress window, at a page or at one service's key."""
|
|
430
|
+
from . import api_keys, progress_reporter
|
|
431
|
+
|
|
432
|
+
target = (args.target or "home").strip()
|
|
433
|
+
page = target if target in SETTINGS_PAGES else "keys"
|
|
434
|
+
found = None if target in SETTINGS_PAGES else api_keys.find(target)
|
|
435
|
+
if page == "keys" and target != "keys" and found is None:
|
|
436
|
+
print(json.dumps({"ok": False, "error": f"没有这一项设置:{target}"}, ensure_ascii=False))
|
|
437
|
+
return 2
|
|
438
|
+
service = found["id"] if found else ""
|
|
439
|
+
# Servers and other machines without a screen keep the terminal: `paper-search setup`.
|
|
440
|
+
terminal = "paper-search setup " + (found["keys"][0]["key"] if found else "<KEY>")
|
|
441
|
+
if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
|
|
442
|
+
print(json.dumps({"ok": False, "error": f"这台电脑没有图形界面,打不开设置窗口;请在终端运行 {terminal}"},
|
|
443
|
+
ensure_ascii=False))
|
|
444
|
+
return 1
|
|
445
|
+
try:
|
|
446
|
+
import webview # noqa: F401 (the settings need the capsule's web view, not the classic window)
|
|
447
|
+
except Exception:
|
|
448
|
+
print(json.dumps({"ok": False, "error": f"设置窗口需要 pywebview,当前环境里没有;请运行 paper-search carsi update,或在终端运行 {terminal}"},
|
|
449
|
+
ensure_ascii=False))
|
|
450
|
+
return 1
|
|
451
|
+
try:
|
|
452
|
+
window = progress_reporter.open_settings(page, service)
|
|
453
|
+
except (OSError, RuntimeError) as exc:
|
|
454
|
+
print(json.dumps({"ok": False, "error": f"设置窗口没能打开:{exc};也可以在终端运行 {terminal}"}, ensure_ascii=False))
|
|
455
|
+
return 1
|
|
456
|
+
reply = {"ok": True, "window": window, "page": page, **({"service": service} if service else {})}
|
|
457
|
+
if os.environ.get("SSH_CONNECTION"):
|
|
458
|
+
reply["note"] = f"窗口开在这台电脑自己的屏幕上;远程连接、看不到这块屏幕时,请在终端运行 {terminal}"
|
|
459
|
+
print(json.dumps(reply, ensure_ascii=False))
|
|
460
|
+
return 0
|
|
461
|
+
|
|
462
|
+
|
|
425
463
|
def main(argv: list[str] | None = None) -> int:
|
|
426
464
|
# Fingerprint generation needs no parallel linear algebra. On Windows its
|
|
427
465
|
# default OpenBLAS worker pool reserves hundreds of MiB in each backend.
|
|
@@ -515,6 +553,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
515
553
|
|
|
516
554
|
sub.add_parser("progress", help="open the progress window; `progress --json` for a read-only snapshot", add_help=False)
|
|
517
555
|
|
|
556
|
+
stg = sub.add_parser("settings", help="show the progress window's settings")
|
|
557
|
+
stg.add_argument("target", nargs="?", help="download, wait, keys, or an API key name such as EASYSCHOLAR_KEY")
|
|
558
|
+
stg.set_defaults(func=_cmd_settings)
|
|
559
|
+
|
|
518
560
|
args = parser.parse_args(argv)
|
|
519
561
|
if args.command == "config" and args.action != "list" and not args.key:
|
|
520
562
|
parser.error("config get/set needs KEY")
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""PaperSearch's CLI config file (``config.json``), shared with ``paper-search setup``.
|
|
2
|
+
|
|
3
|
+
The progress window writes the download directory and API keys here, so the
|
|
4
|
+
CLI and the window always show the same values."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def config_path() -> Path:
|
|
14
|
+
override = os.environ.get("PAPER_SEARCH_CONFIG_FILE")
|
|
15
|
+
if override:
|
|
16
|
+
return Path(override).expanduser()
|
|
17
|
+
return Path(os.environ.get("PAPER_SEARCH_CONFIG_DIR", str(Path.home() / ".config" / "paper-search-cli"))) / "config.json"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def read() -> dict:
|
|
21
|
+
path = config_path()
|
|
22
|
+
if not path.exists():
|
|
23
|
+
return {}
|
|
24
|
+
data = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
25
|
+
if not isinstance(data, dict):
|
|
26
|
+
raise ValueError("PaperSearch 配置必须是 JSON 对象")
|
|
27
|
+
return data
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def update(changes: dict[str, str | None]) -> None:
|
|
31
|
+
"""Set (or, for None, remove) these keys and keep every other setting.
|
|
32
|
+
|
|
33
|
+
The file is replaced atomically, never left half written; like the CLI's
|
|
34
|
+
own writes it is readable by the user only."""
|
|
35
|
+
data = read()
|
|
36
|
+
for key, value in changes.items():
|
|
37
|
+
if value is None:
|
|
38
|
+
data.pop(key, None)
|
|
39
|
+
else:
|
|
40
|
+
data[key] = value
|
|
41
|
+
target = config_path()
|
|
42
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False) as fh:
|
|
44
|
+
temporary = Path(fh.name)
|
|
45
|
+
json.dump(data, fh, ensure_ascii=False, indent=2)
|
|
46
|
+
fh.write("\n")
|
|
47
|
+
try:
|
|
48
|
+
os.chmod(temporary, 0o600)
|
|
49
|
+
temporary.replace(target)
|
|
50
|
+
finally:
|
|
51
|
+
temporary.unlink(missing_ok=True)
|
|
@@ -104,6 +104,8 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
104
104
|
"progress_bar_auto": True,
|
|
105
105
|
# 需要登录学校或完成验证时,除了进度胶囊变色,再发一条系统通知;进度窗口的设置里可以关。
|
|
106
106
|
"progress_notify": False,
|
|
107
|
+
# The progress window's language: "zh" or "en" (user_settings.language).
|
|
108
|
+
"progress_language": "zh",
|
|
107
109
|
# 每篇文章在学校登录页等待用户输入的总时长上限,秒;从第一次等待算起。
|
|
108
110
|
"browser_login_timeout": 180,
|
|
109
111
|
# 不在学校登录页时(出版社页面、选机构页、人机验证、取 PDF 时等待处理)最多等多久,秒;
|
|
@@ -26,6 +26,7 @@ challenge_or_viewer_timeout ip_blocked access_blocked pdf_not_captured
|
|
|
26
26
|
pdf_identity_mismatch pdf_identity_unverified invalid_pdf
|
|
27
27
|
profile_busy cancelled interrupted skipped_cached_attempt target_verified_reached navigation_error
|
|
28
28
|
unsupported_platform unsupported_publisher user_skipped user_marked_no_entitlement pdf_wrong_article
|
|
29
|
+
article_not_yet_published
|
|
29
30
|
institution_federation_unavailable browser_unresponsive browser_operation_timeout login_not_reached idp_no_return_to_publisher
|
|
30
31
|
generic_institution_entry_missing
|
|
31
32
|
""".split())
|
|
@@ -1,33 +1,17 @@
|
|
|
1
1
|
"""Shared default download directory, stored in PaperSearch's CLI config."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
-
import json
|
|
5
4
|
import os
|
|
6
|
-
import tempfile
|
|
7
5
|
from pathlib import Path
|
|
8
6
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def config_path() -> Path:
|
|
13
|
-
override = os.environ.get("PAPER_SEARCH_CONFIG_FILE")
|
|
14
|
-
if override:
|
|
15
|
-
return Path(override).expanduser()
|
|
16
|
-
return Path(os.environ.get("PAPER_SEARCH_CONFIG_DIR", str(Path.home() / ".config" / "paper-search-cli"))) / "config.json"
|
|
7
|
+
from . import cli_config
|
|
8
|
+
from .cli_config import config_path # noqa: F401 (kept for callers of this module)
|
|
17
9
|
|
|
18
|
-
|
|
19
|
-
def _read() -> dict:
|
|
20
|
-
path = config_path()
|
|
21
|
-
if not path.exists():
|
|
22
|
-
return {}
|
|
23
|
-
data = json.loads(path.read_text(encoding="utf-8"))
|
|
24
|
-
if not isinstance(data, dict):
|
|
25
|
-
raise ValueError("PaperSearch 配置必须是 JSON 对象")
|
|
26
|
-
return data
|
|
10
|
+
KEY = "DEFAULT_DOWNLOAD_PATH"
|
|
27
11
|
|
|
28
12
|
|
|
29
13
|
def configured() -> str:
|
|
30
|
-
value = os.environ.get(KEY) or
|
|
14
|
+
value = os.environ.get(KEY) or cli_config.read().get(KEY) or ""
|
|
31
15
|
return str(Path(str(value)).expanduser()) if value else ""
|
|
32
16
|
|
|
33
17
|
|
|
@@ -52,17 +36,5 @@ def validate(value: str) -> str:
|
|
|
52
36
|
def save(value: str) -> str:
|
|
53
37
|
value = validate(value)
|
|
54
38
|
Path(value).mkdir(parents=True, exist_ok=True)
|
|
55
|
-
|
|
56
|
-
data[KEY] = value
|
|
57
|
-
target = config_path()
|
|
58
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
-
# Preserve unrelated CLI settings; replace atomically, never write a partial config.
|
|
60
|
-
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False) as fh:
|
|
61
|
-
temporary = Path(fh.name)
|
|
62
|
-
json.dump(data, fh, ensure_ascii=False, indent=2)
|
|
63
|
-
fh.write("\n")
|
|
64
|
-
try:
|
|
65
|
-
temporary.replace(target)
|
|
66
|
-
finally:
|
|
67
|
-
temporary.unlink(missing_ok=True)
|
|
39
|
+
cli_config.update({KEY: value})
|
|
68
40
|
return value
|
|
@@ -80,6 +80,17 @@ def registrable_domain(host: str) -> str:
|
|
|
80
80
|
_ABSTRACT_ONLY = re.compile(r"/article-abstract/|/abs/pii/", re.I)
|
|
81
81
|
|
|
82
82
|
|
|
83
|
+
# The publisher shows the article as accepted, its full text not online yet:
|
|
84
|
+
# Optica's page "This paper has been accepted for publication. The DOI ... has been
|
|
85
|
+
# registered ... will redirect to the published article when available" (2026-11-08).
|
|
86
|
+
_NOT_YET_PUBLISHED = (("accepted for publication", "redirect to the published article when available"),)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def not_yet_published(text: str) -> bool:
|
|
90
|
+
flat = " ".join(text.lower().split())
|
|
91
|
+
return any(all(marker in flat for marker in markers) for markers in _NOT_YET_PUBLISHED)
|
|
92
|
+
|
|
93
|
+
|
|
83
94
|
def abstract_only(url: str) -> bool:
|
|
84
95
|
return bool(_ABSTRACT_ONLY.search(urlparse(url or "").path))
|
|
85
96
|
|
|
@@ -62,6 +62,7 @@ from .batch_common import (
|
|
|
62
62
|
PublisherAccessBlocked,
|
|
63
63
|
PublisherContentError,
|
|
64
64
|
PublisherPlatformUnsupported,
|
|
65
|
+
ArticleNotYetPublished,
|
|
65
66
|
RETRYABLE_REASONS,
|
|
66
67
|
_ACCESS_GATE_JS,
|
|
67
68
|
_IN_REFERENCES_JS,
|
|
@@ -213,7 +214,12 @@ class PublisherBatchDownloader(
|
|
|
213
214
|
own_page = [final_url] if final_url and self.adapter.is_article_page_url(final_url) else []
|
|
214
215
|
candidates = self.adapter.supplements_page_urls(doi) or [self._article_url(doi)]
|
|
215
216
|
incomplete = ""
|
|
216
|
-
|
|
217
|
+
listed = list(getattr(result, "_listed_supplements", None) or [])
|
|
218
|
+
if listed:
|
|
219
|
+
# Read on the article page before its PDF: no second load.
|
|
220
|
+
links = listed
|
|
221
|
+
self._event(result, "supplements_listed_on_article", str(len(links)))
|
|
222
|
+
for url in ([] if listed else dict.fromkeys(own_page + candidates)):
|
|
217
223
|
open_page(page, url, timeout_ms=60_000)
|
|
218
224
|
if self._challenge_shell(page) or self._is_challenge_page(page):
|
|
219
225
|
if not self._wait_for_challenge(page, result):
|
|
@@ -616,6 +622,12 @@ class PublisherBatchDownloader(
|
|
|
616
622
|
self._event(result, "publisher_access_blocked")
|
|
617
623
|
self._write_diagnostic(page, result, run_dir)
|
|
618
624
|
return result
|
|
625
|
+
except ArticleNotYetPublished as page_url:
|
|
626
|
+
result.reason = result.state = "article_not_yet_published"
|
|
627
|
+
self._event(result, "article_not_yet_published", str(page_url))
|
|
628
|
+
progress_reporter.update(phase="出版社尚未发布这篇论文的全文,当前路径已停止")
|
|
629
|
+
self._write_diagnostic(page, result, run_dir)
|
|
630
|
+
return result
|
|
619
631
|
except PublisherPlatformUnsupported as platform:
|
|
620
632
|
result.reason = result.state = "unsupported_platform"
|
|
621
633
|
self._event(result, "unsupported_platform", str(platform))
|
|
@@ -16,6 +16,7 @@ from .batch_common import (
|
|
|
16
16
|
settle,
|
|
17
17
|
DownloadResult,
|
|
18
18
|
PublisherAccessBlocked,
|
|
19
|
+
ArticleNotYetPublished,
|
|
19
20
|
PublisherContentError,
|
|
20
21
|
PublisherPlatformUnsupported,
|
|
21
22
|
_ACCESS_GATE_JS,
|
|
@@ -211,6 +212,8 @@ class AccessMixin:
|
|
|
211
212
|
if self._is_auth_page(url):
|
|
212
213
|
return access_rules.OUT, "login_page", url[:160]
|
|
213
214
|
snap = snapshot or self._access_snapshot(page)
|
|
215
|
+
if access_rules.not_yet_published(str(getattr(snap, "text", "") or "")):
|
|
216
|
+
raise ArticleNotYetPublished(url[:160])
|
|
214
217
|
if self._institution_session(page, snap) == "ours":
|
|
215
218
|
names = access_rules.session_names(snap.lines)
|
|
216
219
|
label = next((str(l) for l in snap.probe.get("labels") or () if not access_rules.is_generic_label(str(l))), "")
|
|
@@ -215,10 +215,19 @@ class CaptureMixin:
|
|
|
215
215
|
from ..browser.preview import pause as pause_preview
|
|
216
216
|
|
|
217
217
|
with pause_preview(getattr(page, "context", None)):
|
|
218
|
-
|
|
219
|
-
if (body is None and not block and len(result.pdf_attempts) == tried_before
|
|
220
|
-
and not result.reason and self._wait_for_pdf_candidates(page, doi, result)):
|
|
218
|
+
try:
|
|
221
219
|
body, url, block = self._capture_pdf_channels(page, doi, result)
|
|
220
|
+
if (body is None and not block and len(result.pdf_attempts) == tried_before
|
|
221
|
+
and not result.reason and self._wait_for_pdf_candidates(page, doi, result)):
|
|
222
|
+
body, url, block = self._capture_pdf_channels(page, doi, result)
|
|
223
|
+
except watchdog.BrowserBudgetExhausted as exc:
|
|
224
|
+
# The step's time ran out between browser calls, so the browser is fine. A PDF
|
|
225
|
+
# the article's own link already gave is saved unconfirmed for PaperSearch to
|
|
226
|
+
# check, not lost with the time (Science, 2026-11-09).
|
|
227
|
+
if self._fallback_pdf is None:
|
|
228
|
+
raise
|
|
229
|
+
self._event(result, "pdf_budget_exhausted", str(exc))
|
|
230
|
+
body, url, block = None, "", None
|
|
222
231
|
if body is None and not block and self._fallback_pdf is not None:
|
|
223
232
|
body, url = self._fallback_pdf
|
|
224
233
|
self._event(result, "pdf_saved_unconfirmed", f"{url} | no DOI or title on the first pages")
|
|
@@ -337,6 +346,25 @@ class CaptureMixin:
|
|
|
337
346
|
except Exception:
|
|
338
347
|
pass
|
|
339
348
|
|
|
349
|
+
# Figshare links: their files are found by its own API in the attachment step.
|
|
350
|
+
_FIGSHARE_LINKED_JS = "() => !!document.querySelector('a[href*=\"figshare.com\"]')"
|
|
351
|
+
|
|
352
|
+
def _remember_listed_supplements(self, page: Any, doi: str, result: DownloadResult) -> None:
|
|
353
|
+
"""The files the article page lists, read before the PDF takes its tab: the
|
|
354
|
+
attachment step then need not load the page again (AHA's page took more
|
|
355
|
+
than that step's 60 s once, 2026-11-08). Only from an adapter that reads
|
|
356
|
+
them without leaving the page, and not beside Figshare links."""
|
|
357
|
+
read = getattr(self.adapter, "listed_supplement_links", None)
|
|
358
|
+
if read is None or getattr(result, "_listed_supplements", None):
|
|
359
|
+
return
|
|
360
|
+
try:
|
|
361
|
+
links = read(page, doi)
|
|
362
|
+
if links and not page.evaluate(self._FIGSHARE_LINKED_JS):
|
|
363
|
+
result._listed_supplements = list(links)
|
|
364
|
+
except Exception as exc:
|
|
365
|
+
if not _is_browser_error(exc):
|
|
366
|
+
raise
|
|
367
|
+
|
|
340
368
|
def _capture_pdf_channels(self, page: Any, doi: str, result: DownloadResult) -> tuple[bytes | None, str, str | None]:
|
|
341
369
|
"""Capture the PDF for ``doi`` from ``page``.
|
|
342
370
|
|
|
@@ -345,6 +373,7 @@ class CaptureMixin:
|
|
|
345
373
|
was observed during capture, else ``None``.
|
|
346
374
|
"""
|
|
347
375
|
self._event(result, "pdf_capture_started")
|
|
376
|
+
self._remember_listed_supplements(page, doi, result)
|
|
348
377
|
captured: dict[str, Any] = {"bytes": None, "url": "", "deferred_url": "", "block_reason": None,
|
|
349
378
|
"suspect_block": None, "closed": False, "readers": set()}
|
|
350
379
|
cdp_session = None
|
|
@@ -1736,15 +1765,15 @@ class CaptureMixin:
|
|
|
1736
1765
|
if self._is_supplementary_url(url):
|
|
1737
1766
|
return False
|
|
1738
1767
|
if self.adapter.requires_complete_pdf:
|
|
1739
|
-
# Never label a truncated or
|
|
1740
|
-
|
|
1768
|
+
# Never label a truncated or damaged transfer as saved.
|
|
1769
|
+
from .. import pdf_text
|
|
1770
|
+
|
|
1771
|
+
if not pdf_text.complete(body):
|
|
1741
1772
|
return False
|
|
1742
1773
|
try:
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
return False
|
|
1747
|
-
except Exception:
|
|
1774
|
+
if not pdf_text.page_count(body):
|
|
1775
|
+
return False
|
|
1776
|
+
except pdf_text.PdfError:
|
|
1748
1777
|
return False
|
|
1749
1778
|
from .pdf_guard import classify_with_evidence
|
|
1750
1779
|
|
|
@@ -503,5 +503,9 @@ class PublisherPlatformUnsupported(PublisherContentError):
|
|
|
503
503
|
"""The article is served only on a platform this engine cannot use (e.g. ClinicalKey)."""
|
|
504
504
|
|
|
505
505
|
|
|
506
|
+
class ArticleNotYetPublished(PublisherContentError):
|
|
507
|
+
"""The publisher lists the article as accepted; its full text is not online yet."""
|
|
508
|
+
|
|
509
|
+
|
|
506
510
|
class PublisherAccessBlocked(RuntimeError):
|
|
507
511
|
"""An explicit site security block, without an interactive verification."""
|
|
@@ -9,7 +9,8 @@ import time
|
|
|
9
9
|
from typing import Any
|
|
10
10
|
from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
|
|
11
11
|
|
|
12
|
-
from .batch_common import DownloadResult, _is_browser_error, logger, open_page,
|
|
12
|
+
from .batch_common import (DownloadResult, _is_browser_error, _is_navigation_cut, logger, open_page,
|
|
13
|
+
pump_until, settle)
|
|
13
14
|
|
|
14
15
|
|
|
15
16
|
def _school_auth_patterns(config: dict[str, Any]) -> tuple[str, ...]:
|
|
@@ -752,24 +753,32 @@ class InstitutionMixin:
|
|
|
752
753
|
# A widget's accessible name can differ from its visible school
|
|
753
754
|
# text, or it can be a clickable div/span without a role. Use
|
|
754
755
|
# the visible control text, still requiring a click affordance.
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
const
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
return items.filter(el => !items.some(other => other !== el && el.contains(other)))
|
|
768
|
-
.slice(0,10).map((el,i) => {
|
|
769
|
-
el.setAttribute('data-paper-search-remembered', String(i));
|
|
770
|
-
return {i, text:(el.textContent || '').trim()};
|
|
756
|
+
try:
|
|
757
|
+
candidates = page.evaluate("""() => {
|
|
758
|
+
document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
|
|
759
|
+
e.removeAttribute('data-paper-search-remembered'));
|
|
760
|
+
const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
|
|
761
|
+
const native = el.matches('a[href],button,[role="button"]');
|
|
762
|
+
if (!native && el.closest('a,button,[role="button"]')) return false;
|
|
763
|
+
const text = (el.textContent || '').trim();
|
|
764
|
+
return text.length <= 160 && /^access through\\s*\\S/i.test(text)
|
|
765
|
+
&& el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
|
|
766
|
+
&& !el.disabled && el.getAttribute('aria-disabled') !== 'true'
|
|
767
|
+
&& (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
|
|
771
768
|
});
|
|
772
|
-
|
|
769
|
+
return items.filter(el => !items.some(other => other !== el && el.contains(other)))
|
|
770
|
+
.slice(0,10).map((el,i) => {
|
|
771
|
+
el.setAttribute('data-paper-search-remembered', String(i));
|
|
772
|
+
return {i, text:(el.textContent || '').trim()};
|
|
773
|
+
});
|
|
774
|
+
}""")
|
|
775
|
+
except Exception as exc:
|
|
776
|
+
if not _is_navigation_cut(exc):
|
|
777
|
+
raise
|
|
778
|
+
# The page navigated while it was read, e.g. the user chose
|
|
779
|
+
# a school (Karger's wayfinder): looked at again next pass.
|
|
780
|
+
self._event(result, "login_navigation_interrupted", "institution-entry")
|
|
781
|
+
return False
|
|
773
782
|
if isinstance(candidates, list):
|
|
774
783
|
for candidate in candidates:
|
|
775
784
|
label = re.sub(r"^\s*access through\s*", "", candidate["text"], flags=re.I)
|
|
@@ -35,6 +35,7 @@ _LOGIN_FAILURE_CODES = (
|
|
|
35
35
|
_FAILURE_KINDS = {
|
|
36
36
|
"publisher_content_error": ("publisher_content_error", "review_publisher_error"),
|
|
37
37
|
"unsupported_platform": ("unsupported_platform", "review_publisher_error"),
|
|
38
|
+
"article_not_yet_published": ("article_not_yet_published", "review_publisher_error"),
|
|
38
39
|
"browser_unresponsive": ("browser_unresponsive", "review_browser"),
|
|
39
40
|
"browser_operation_timeout": ("browser_operation_timeout", "review_browser"),
|
|
40
41
|
"publisher_access_blocked": ("access_blocked", "review_access"),
|
|
@@ -348,7 +349,8 @@ def _try_builtin_institutional(
|
|
|
348
349
|
# survives in source_failures. Neither is hidden by a later plain miss.
|
|
349
350
|
denial = next((f for f in failures if f.get("reason_code") ==
|
|
350
351
|
"institution_pdf_entitlement_missing"), None)
|
|
351
|
-
primary = next((f for code in ("source_exception", "unsupported_platform", "
|
|
352
|
+
primary = next((f for code in ("source_exception", "unsupported_platform", "article_not_yet_published",
|
|
353
|
+
"generic_institution_entry_missing",
|
|
352
354
|
"publisher_content_error", "access_blocked", *_LOGIN_FAILURE_CODES,
|
|
353
355
|
"download_timeout")
|
|
354
356
|
for f in failures if f["error_type"] == code), denial or failures[-1])
|
|
@@ -492,7 +494,8 @@ def _try_browser_batch_download(
|
|
|
492
494
|
log.info(" [Institutional] no browser backend available, skipping browser download")
|
|
493
495
|
return None
|
|
494
496
|
|
|
495
|
-
|
|
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 ""))
|
|
496
499
|
# The institution name is the user's own setting (explicit CARSI); empty means "choose by hand".
|
|
497
500
|
institution_query = (config.get("carsi_idp_name", "") if config.get("publisher_institution_federation") == "carsi"
|
|
498
501
|
else "")
|
|
@@ -556,7 +559,8 @@ def _try_browser_batch_download(
|
|
|
556
559
|
# page is unreachable, so do not wait on it a second time.
|
|
557
560
|
result.supplements = [{"status": "skipped", "reason": "challenge_timeout",
|
|
558
561
|
"url": "", "label": ""}]
|
|
559
|
-
elif result.state in ("unsupported_platform", "
|
|
562
|
+
elif result.state in ("unsupported_platform", "article_not_yet_published",
|
|
563
|
+
"publisher_access_blocked", "publisher_unreachable",
|
|
560
564
|
"login_page_closed", "user_skipped", "batch_stopped",
|
|
561
565
|
"user_marked_no_entitlement"):
|
|
562
566
|
# Nothing more to fetch there now.
|
|
@@ -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
|
|
|
@@ -146,6 +146,22 @@ def _page_evidence(response: Any) -> dict[str, Any]:
|
|
|
146
146
|
return evidence
|
|
147
147
|
|
|
148
148
|
|
|
149
|
+
def _is_verification_page(response: Any) -> bool:
|
|
150
|
+
"""A firewall's human verification page instead of the file (Figshare's AWS WAF,
|
|
151
|
+
Cloudflare): the site stopped a scripted request, the file may well exist."""
|
|
152
|
+
headers = getattr(response, "headers", None) or {}
|
|
153
|
+
return ("text/html" in str(headers.get("content-type") or "").lower()
|
|
154
|
+
and "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated")))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class _StillVerifying(Exception):
|
|
158
|
+
"""The browser, too, did not get the file past a site's verification page."""
|
|
159
|
+
|
|
160
|
+
def __init__(self, evidence: dict[str, Any]):
|
|
161
|
+
super().__init__("verification_page")
|
|
162
|
+
self.evidence = evidence
|
|
163
|
+
|
|
164
|
+
|
|
149
165
|
def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi: str, *,
|
|
150
166
|
clock=time.monotonic, sleep=time.sleep,
|
|
151
167
|
manifest_dir: Path | None = None,
|
|
@@ -186,11 +202,23 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
186
202
|
response = None
|
|
187
203
|
response = _get(request, link.url, entry, sleep)
|
|
188
204
|
_check_interrupted()
|
|
189
|
-
|
|
205
|
+
# A firewall's verification page goes to the browser as a 403 does: it
|
|
206
|
+
# opens the link as a reader would and runs the page's own check
|
|
207
|
+
# (Figshare's AWS WAF answered every scripted request, 2026-11-08).
|
|
208
|
+
challenged = download is not None and _is_verification_page(response)
|
|
209
|
+
if (response.status == 403 and download is not None) or challenged:
|
|
210
|
+
evidence = _page_evidence(response) if challenged else {}
|
|
190
211
|
if callable(getattr(response, "dispose", None)):
|
|
191
212
|
response.dispose()
|
|
192
213
|
response = None
|
|
193
|
-
|
|
214
|
+
try:
|
|
215
|
+
response = _Downloaded(*download(link.url))
|
|
216
|
+
except (BrowserUnresponsive, UserMarkedNoEntitlement):
|
|
217
|
+
raise
|
|
218
|
+
except Exception:
|
|
219
|
+
if not challenged:
|
|
220
|
+
raise
|
|
221
|
+
raise _StillVerifying(evidence)
|
|
194
222
|
entry["via"] = "browser_download"
|
|
195
223
|
_check_interrupted()
|
|
196
224
|
content_type = str(response.headers.get("content-type", "") or "")
|
|
@@ -203,10 +231,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
203
231
|
# A login wall or landing page instead of the file: which one, for the record.
|
|
204
232
|
# A firewall's human verification page is told apart (Figshare's AWS WAF,
|
|
205
233
|
# 2026-11-08): the site stopped the request, the file may well exist.
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
challenged = "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated"))
|
|
209
|
-
entry.update(status="failed", reason="verification_page" if challenged else "html_page", **evidence)
|
|
234
|
+
entry.update(status="failed", reason="verification_page" if _is_verification_page(response)
|
|
235
|
+
else "html_page", **_page_evidence(response))
|
|
210
236
|
else:
|
|
211
237
|
name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
|
|
212
238
|
link.label, content_type)
|
|
@@ -245,6 +271,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
245
271
|
temporary.unlink(missing_ok=True)
|
|
246
272
|
except SupplementTooLarge as exc:
|
|
247
273
|
entry.update(status="skipped", reason="too_large", size=exc.size)
|
|
274
|
+
except _StillVerifying as exc:
|
|
275
|
+
entry.update(status="failed", reason="verification_page", via="browser_download", **exc.evidence)
|
|
248
276
|
except (BrowserUnresponsive, UserMarkedNoEntitlement) as exc:
|
|
249
277
|
stopped_reason = ("batch_stopped" if isinstance(exc, UserStoppedBatch) else
|
|
250
278
|
"user_skipped" if isinstance(exc, UserSkippedArticle) else
|
|
@@ -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
|
|