The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(arxiv): 支持 arXiv 论文下载
XiaoYouChR475b714a6985
diff --git a/GLOSSARY.md b/GLOSSARY.mdindex 87096fe2..ca928a21 100644--- a/GLOSSARY.md+++ b/GLOSSARY.md@@ -82,7 +82,7 @@ Task 有多于一个 Selectable File 时,成品是以 Name 命名的文件夹_Avoid_: 与 Task Files 混淆**Revive**:-已完成的 Task 因新选中的文件有待下载工作而回到下载状态。仅对 COMPLETED 状态的 Task 生效。+已完成的 Task 因新选中的文件或新启用的 Side File 有待下载工作而回到下载状态。仅对 COMPLETED 状态的 Task 生效。### 任务创建diff --git a/features/arxiv_pack/android.py b/features/arxiv_pack/android.pynew file mode 100644index 00000000..151da6f9--- /dev/null+++ b/features/arxiv_pack/android.py@@ -0,0 +1,22 @@+from http_pack.android import editFields as editHttpFields++UI_CLASS = "com.xychr.ghostdownloader.features.arxiv_pack.ArxivUi"+++def editFields(task) -> dict:+ fields = {**editHttpFields(task), "isBibtexEnabled": task.isBibtexEnabled}+ if task.hasSource:+ fields["isSourceEnabled"] = task.isSourceEnabled+ return fields+++def draftFields(task) -> dict:+ return {+ "hasSource": task.hasSource,+ "isSourceEnabled": task.isSourceEnabled,+ "isBibtexEnabled": task.isBibtexEnabled,+ }+++def setSideFile(task, key: str, isEnabled: bool) -> None:+ task.setOptions({key: bool(isEnabled)})diff --git a/features/arxiv_pack/cards.py b/features/arxiv_pack/cards.pynew file mode 100644index 00000000..4d81e342--- /dev/null+++ b/features/arxiv_pack/cards.py@@ -0,0 +1,87 @@+from __future__ import annotations++from PySide6.QtWidgets import QHBoxLayout+from qfluentwidgets import BodyLabel, CheckBox, FluentIcon, IconWidget++from app.format import toReadableSize+from app.view.cards.draft_cards import DraftCard+from app.view.components.option_cards import OptionCard+from app.view.components.track_bar import TrackButton+from .config import arxivConfig+from .task import ArxivTask+++class ArxivDraftCard(DraftCard):++ @property+ def task(self) -> ArxivTask:+ return self._task++ def _initWidget(self) -> None:+ super()._initWidget()+ self.sourceButton = TrackButton(FluentIcon.CODE, self)+ self.sourceButton.setToolTip(self.tr("TeX 源码"))+ self.sourceButton.setChecked(self.task.isSourceEnabled)+ self.sourceButton.setVisible(self.task.hasSource)+ self.bibtexButton = TrackButton(FluentIcon.LIBRARY, self)+ self.bibtexButton.setToolTip("BibTeX")+ self.bibtexButton.setChecked(self.task.isBibtexEnabled)++ def _initLayout(self) -> None:+ super()._initLayout()+ self.layout().addWidget(self.sourceButton)+ self.layout().addWidget(self.bibtexButton)++ def _bind(self) -> None:+ super()._bind()+ for button in (self.sourceButton, self.bibtexButton):+ button.clicked.connect(lambda _=False, b=button: b.setChecked(not b.isChecked()))+ button.toggled.connect(self._onSideFileToggled)++ def _onSideFileToggled(self) -> None:+ self.task.setOptions({+ "isSourceEnabled": self.sourceButton.isChecked(),+ "isBibtexEnabled": self.bibtexButton.isChecked(),+ })+ self.sizeLabel.setText(toReadableSize(self.task.fileSize) if self.task.fileSize > 1 else "--")+ self._refreshConflictIcon()+++class SideFileCard(OptionCard):++ def __init__(self, parent=None, *, task: ArxivTask):+ super().__init__(parent)+ self._task = task+ self._initWidget()+ self._initLayout()++ def _initWidget(self) -> None:+ self.setFixedHeight(50)+ self.iconWidget = IconWidget(FluentIcon.DOCUMENT, self)+ self.iconWidget.setFixedSize(16, 16)+ self.titleLabel = BodyLabel(self.tr("附属文件"), self)+ self.sourceCheckBox = CheckBox(self.tr("TeX 源码"), self)+ self.sourceCheckBox.setChecked(self._task.isSourceEnabled)+ self.sourceCheckBox.setVisible(self._task.hasSource)+ self.bibtexCheckBox = CheckBox("BibTeX", self)+ self.bibtexCheckBox.setChecked(self._task.isBibtexEnabled)++ def _initLayout(self) -> None:+ layout = QHBoxLayout(self)+ layout.setContentsMargins(24, 5, 24, 5)+ layout.setSpacing(15)+ layout.addWidget(self.iconWidget)+ layout.addWidget(self.titleLabel)+ layout.addStretch(1)+ layout.addWidget(self.sourceCheckBox)+ layout.addWidget(self.bibtexCheckBox)++ def options(self) -> dict:+ return {+ "isSourceEnabled": self._task.hasSource and self.sourceCheckBox.isChecked(),+ "isBibtexEnabled": self.bibtexCheckBox.isChecked(),+ }++ def reset(self) -> None:+ self.sourceCheckBox.setChecked(arxivConfig.shouldDownloadSource.value)+ self.bibtexCheckBox.setChecked(arxivConfig.shouldDownloadBibtex.value)diff --git a/features/arxiv_pack/config.py b/features/arxiv_pack/config.pynew file mode 100644index 00000000..e76d392c--- /dev/null+++ b/features/arxiv_pack/config.py@@ -0,0 +1,37 @@+from __future__ import annotations++from app.config.cfg import BoolValidator, ConfigItem+from app.models.pack import PackConfig+++class ArxivConfig(PackConfig):+ isEnabled = ConfigItem("Arxiv", "Enabled", True, BoolValidator())+ shouldDownloadSource = ConfigItem("Arxiv", "DownloadSource", False, BoolValidator())+ shouldDownloadBibtex = ConfigItem("Arxiv", "DownloadBibtex", False, BoolValidator())++ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ from qfluentwidgets import FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup++ group = CollapsibleSettingCardGroup(self.tr("arXiv 下载"), "arxiv", parent)+ group.addSettingCards([+ SwitchSettingCard(+ FluentIcon.LINK, self.tr("解析 arXiv 链接"),+ self.tr("将论文页、PDF 链接和论文编号下载为以标题命名的 PDF,关闭后按普通链接下载"),+ self.isEnabled, group,+ ),+ SwitchSettingCard(+ FluentIcon.CODE, self.tr("默认下载 TeX 源码"),+ self.tr("新任务默认勾选源码包,可在添加任务时逐个修改"),+ self.shouldDownloadSource, group,+ ),+ SwitchSettingCard(+ FluentIcon.LIBRARY, self.tr("默认下载 BibTeX"),+ self.tr("新任务默认勾选 .bib 引用文件,可在添加任务时逐个修改"),+ self.shouldDownloadBibtex, group,+ ),+ ])+ return [group]+++arxivConfig = ArxivConfig()diff --git a/features/arxiv_pack/manifest.toml b/features/arxiv_pack/manifest.tomlnew file mode 100644index 00000000..c791787d--- /dev/null+++ b/features/arxiv_pack/manifest.toml@@ -0,0 +1,6 @@+[pack]+entry = "pack.py"+class = "ArxivPack"+dependencies = ["http_pack"]+version = "1.0.0"+gdMinVersion = "4.4.6"diff --git a/features/arxiv_pack/pack.py b/features/arxiv_pack/pack.pynew file mode 100644index 00000000..e64ebc35--- /dev/null+++ b/features/arxiv_pack/pack.py@@ -0,0 +1,173 @@+from __future__ import annotations++import asyncio+import re+from dataclasses import dataclass, replace+from html import unescape+from urllib.parse import urlparse++from loguru import logger++from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.i18n import N+from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskOptions+from app.platform.filesystem import splitStemExt+from http_pack.pack import RemoteFile, probe+from http_pack.task import HttpTaskStep+from .config import arxivConfig+from .task import ArxivBibtexStep, ArxivSourceStep, ArxivTask++ARXIV_ORIGIN = "https://arxiv.org"+ARXIV_HOSTS = {"arxiv.org", "export.arxiv.org"}+MONTH = r"(?:0[1-9]|1[0-2])"+# 新式编号 1706.03762,旧式编号 hep-th/9901001;math.GT/0309136 的学科子类不属于编号,arXiv 自己也写作 math/0309136+ID = (rf"(?:(?P<new>\d\d{MONTH}\.\d{{4,5}})|(?P<archive>[a-z]+(?:-[a-z]+)*)(?:\.[A-Z]{{2}})?/(?P<serial>\d\d{MONTH}\d{{3}}))"+ rf"(?P<version>v\d+)?")+BARE_PATTERN = re.compile(rf"(?i:arxiv:)?{ID}")+ARXIV_PATH_PATTERN = re.compile(rf"/(?:abs|pdf|html)/{ID}(?:\.pdf)?(?:/.*)?")+ALPHAXIV_PATH_PATTERN = re.compile(rf"(?:.*/)?{ID}(?:\.pdf)?(?:/.*)?")+HF_PAPERS_PATH_PATTERN = re.compile(rf"/papers/{ID}/?")+TITLE_PATTERN = re.compile(r'<meta\s+name="citation_title"\s+content="(?P<title>[^"]*)"')+PDF_VERSION_PATTERN = re.compile(r"(v\d+)\.pdf$")+++@dataclass(frozen=True)+class ArxivId:+ number: str+ version: str = ""++ def __str__(self) -> str:+ return f"{self.number}{self.version}"+++def parseArxivId(text: str) -> ArxivId | None:+ text = text.strip()+ parsedUrl = urlparse(text)+ if parsedUrl.scheme.lower() not in {"http", "https"}:+ m = BARE_PATTERN.fullmatch(text)+ else:+ host = (parsedUrl.hostname or "").lower().removeprefix("www.")+ if host in ARXIV_HOSTS:+ m = ARXIV_PATH_PATTERN.fullmatch(parsedUrl.path)+ elif host == "alphaxiv.org":+ m = ALPHAXIV_PATH_PATTERN.fullmatch(parsedUrl.path)+ elif host == "huggingface.co":+ m = HF_PAPERS_PATH_PATTERN.fullmatch(parsedUrl.path)+ else:+ return None+ if m is None:+ return None+ return ArxivId(m["new"] or f"{m['archive']}/{m['serial']}", m["version"] or "")+++def buildName(arxivId: ArxivId, version: str, title: str) -> str:+ stem = arxivId.number.replace("/", "") + version+ if not title:+ return f"{stem}.pdf"+ # 冒号在 Windows 文件名里非法,"BERT: Pre-training" 写作 "BERT - Pre-training" 比写成下划线易读+ title = re.sub(r"\s*:\s*", " - ", title)+ return f"{stem} {title}.pdf"+++def buildStep(stepType: type[HttpTaskStep], stepIndex: int, url: str, options: TaskOptions,+ file: RemoteFile | None = None, **kwargs) -> HttpTaskStep:+ return stepType(+ stepIndex=stepIndex,+ url=url,+ fileSize=file.fileSize if file else 0,+ headers=dict(options.headers),+ clientProfile=options.clientProfile,+ userAgent=options.userAgent,+ subworkerCount=options.subworkerCount,+ canUseRangeRequests=file.canUseRangeRequests if file else False,+ lastModified=file.lastModified if file else "",+ **kwargs,+ )+++async def fetchTitle(options: TaskOptions) -> str:+ client = buildClient(+ emulation=toEmulation(options.clientProfile or cfg.clientProfile.value, options.sourceUserAgent),+ headers=dict(options.headers),+ userAgent=options.userAgent or None,+ timeout=30,+ )+ try:+ response = await client.get(options.url)+ response.raise_for_status()+ page = await response.text()+ finally:+ client.close()+ m = TITLE_PATTERN.search(page)+ return " ".join(unescape(m["title"]).split()) if m else ""+++class ArxivParser(TaskParser):+ # 先于 HuggingFace(85),否则 huggingface.co/papers/{编号} 会被当成模型仓库+ priority = 80++ def match(self, options: TaskOptions) -> bool:+ return arxivConfig.isEnabled.value and parseArxivId(options.url) is not None++ def matchPassive(self, options: TaskOptions) -> bool:+ return urlparse(options.url).scheme.lower() in {"http", "https"}++ async def parse(self, options: TaskOptions) -> Task:+ arxivId = parseArxivId(options.url)+ absUrl = f"{ARXIV_ORIGIN}/abs/{arxivId}"+ title, pdf, source = await asyncio.gather(+ fetchTitle(replace(options, url=absUrl)),+ probe(replace(options, url=f"{ARXIV_ORIGIN}/pdf/{arxivId}")),+ probe(replace(options, url=f"{ARXIV_ORIGIN}/src/{arxivId}")),+ return_exceptions=True,+ )+ if isinstance(pdf, BaseException):+ raise pdf+ if isinstance(title, BaseException):+ logger.opt(exception=title).warning("arXiv 标题获取失败 {}", arxivId)+ title = ""+ version = arxivId.version or (m[1] if (m := PDF_VERSION_PATTERN.search(pdf.name)) else "")+ name = buildName(arxivId, version, title) if version else pdf.name++ task = ArxivTask(name=name, url=absUrl, outputFolder=options.outputFolder)+ task.addStep(buildStep(HttpTaskStep, 1, f"{ARXIV_ORIGIN}/pdf/{arxivId}", options, pdf))+ # 只投了 PDF 的论文,src 返回的就是那份 PDF+ if isinstance(source, RemoteFile) and source.contentType != "application/pdf":+ suffix = splitStemExt(source.name)[1].lstrip(".") or "tar.gz"+ task.addStep(buildStep(ArxivSourceStep, 2, f"{ARXIV_ORIGIN}/src/{arxivId}", options, source, suffix=suffix))+ task.addStep(buildStep(ArxivBibtexStep, 3, f"{ARXIV_ORIGIN}/bibtex/{arxivId}", options))+ task.setOptions({+ "isSourceEnabled": task.hasSource and arxivConfig.shouldDownloadSource.value,+ "isBibtexEnabled": arxivConfig.shouldDownloadBibtex.value,+ })+ return task+++class ArxivPack(FeaturePack):+ packId = "arxiv"+ capturedLinks = N("ArxivPack", "arXiv 论文")+ config = arxivConfig+ parsers = [ArxivParser]++ def taskCardClass(self, task: Task) -> type | None:+ from http_pack.cards import HttpTaskCard+ return HttpTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import ArxivDraftCard+ return ArxivDraftCard++ def optionCards(self, task, parent=None):+ from http_pack.pack import HttpPack+ return HttpPack.optionCards(self, task, parent)++ def editCards(self, task, parent=None):+ from app.view.components.option_cards import UrlEditCard+ from .cards import SideFileCard+ return [+ UrlEditCard(parent, initial=task.url),+ *self.optionCards(task, parent),+ SideFileCard(parent, task=task),+ ]diff --git a/features/arxiv_pack/task.py b/features/arxiv_pack/task.pynew file mode 100644index 00000000..c277184c--- /dev/null+++ b/features/arxiv_pack/task.py@@ -0,0 +1,67 @@+from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++from app.models.task import Task, TaskStatus, TaskStep+from app.platform.filesystem import deletePath+from http_pack.task import HttpTaskStep+++@dataclass(kw_only=True)+class ArxivSourceStep(HttpTaskStep):+ suffix: str = "tar.gz"++ @property+ def outputPath(self) -> str:+ return str(self.task.toSidePath(None, self.suffix)) if self.task.isSourceEnabled else ""+++@dataclass(kw_only=True)+class ArxivBibtexStep(HttpTaskStep):++ @property+ def outputPath(self) -> str:+ return str(self.task.toSidePath(None, "bib")) if self.task.isBibtexEnabled else ""+++@dataclass(kw_only=True, eq=False)+class ArxivTask(Task):+ packId: str = "arxiv"+ canEdit = True+ isSourceEnabled: bool = False+ isBibtexEnabled: bool = False++ @property+ def hasSource(self) -> bool:+ return any(isinstance(step, ArxivSourceStep) for step in self.steps)++ def _isStepSelected(self, step: TaskStep) -> bool:+ if isinstance(step, ArxivSourceStep):+ return self.isSourceEnabled+ if isinstance(step, ArxivBibtexStep):+ return self.isBibtexEnabled+ return True++ def currentSnapshot(self) -> tuple[float, int, int]:+ steps = [step for step in self.steps if self._isStepSelected(step)]+ progress = sum(step.progress for step in steps) / len(steps)+ return progress, sum(step.speed for step in steps), sum(step.receivedBytes for step in steps)++ def setOptions(self, options: dict) -> None:+ super().setOptions(options)+ previousPaths = [(step, step.outputPath) for step in self.steps]+ self.isSourceEnabled = options.get("isSourceEnabled", self.isSourceEnabled)+ self.isBibtexEnabled = options.get("isBibtexEnabled", self.isBibtexEnabled)+ for step, previousPath in previousPaths:+ if step.status == TaskStatus.COMPLETED or bool(previousPath) == bool(step.outputPath):+ continue+ if previousPath:+ # 关掉未下完的 Side File 时不留半截文件+ step.reset()+ deletePath(Path(previousPath))+ deletePath(Path(f"{previousPath}.ghd"))+ else:+ self.completedAt = 0+ self.fileSize = sum(step.fileSize for step in self.steps if self._isStepSelected(step) and step.fileSize > 0)+ self.updateStatus()diff --git a/tests/arxiv_pack/__init__.py b/tests/arxiv_pack/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/tests/arxiv_pack/test_task.py b/tests/arxiv_pack/test_task.pynew file mode 100644index 00000000..84d9c2d7--- /dev/null+++ b/tests/arxiv_pack/test_task.py@@ -0,0 +1,139 @@+from __future__ import annotations++from pathlib import Path++import pytest+from aiohttp import web++from app.models.pack import PackServices+from app.models.task import TaskOptions, TaskStatus+from arxiv_pack.pack import ArxivPack, ArxivParser, buildName, buildStep, parseArxivId+from arxiv_pack.task import ArxivBibtexStep, ArxivSourceStep, ArxivTask+from http_pack.pack import HttpPack, RemoteFile+from http_pack.task import HttpTaskStep+from huggingface_pack.pack import HuggingFacePack+from tests.helpers import buildRangeHandler, waitUntil++NAME = "1706.03762v7 Attention Is All You Need.pdf"+PDF = b"%PDF-1.5 paper"+SOURCE = b"\x1f\x8b source"+BIBTEX = b"@misc{vaswani2023attention}"+++async def startArxiv(startServer) -> str:+ handlers = {"pdf": buildRangeHandler(PDF), "src": buildRangeHandler(SOURCE)}++ async def handle(request: web.Request) -> web.Response:+ kind = request.path.split("/")[1]+ if kind == "bibtex":+ return web.Response(body=BIBTEX, content_type="text/plain")+ return await handlers[kind](request)++ return (await startServer(handle)).removesuffix("/file")++[email protected](params=["desktop", "android"])+def engine(request, startEngine):+ return startEngine(request.param)+++def buildTask(origin: str, *, isSourceEnabled: bool = False, isBibtexEnabled: bool = False) -> ArxivTask:+ options = TaskOptions(url=f"{origin}/abs/1706.03762")+ task = ArxivTask(name=NAME, url=options.url)+ task.addStep(buildStep(HttpTaskStep, 1, f"{origin}/pdf/1706.03762", options,+ RemoteFile(name="", fileSize=len(PDF), canUseRangeRequests=True)))+ task.addStep(buildStep(ArxivSourceStep, 2, f"{origin}/src/1706.03762", options,+ RemoteFile(name="", fileSize=len(SOURCE), canUseRangeRequests=True)))+ task.addStep(buildStep(ArxivBibtexStep, 3, f"{origin}/bibtex/1706.03762", options))+ task.setOptions({"isSourceEnabled": isSourceEnabled, "isBibtexEnabled": isBibtexEnabled})+ return task+++def namesIn(folder: Path) -> list[str]:+ return sorted(p.name for p in folder.iterdir())++[email protected]("text", [+ "https://arxiv.org/abs/1706.03762",+ "https://arxiv.org/pdf/1706.03762v7",+ "https://arxiv.org/pdf/1706.03762.pdf",+ "https://arxiv.org/html/2401.00001v1/#S2",+ "https://export.arxiv.org/abs/hep-th/9901001v3",+ "https://www.alphaxiv.org/abs/2312.16682v2",+ "https://huggingface.co/papers/2401.00002",+ "arXiv:1706.03762",+ "1706.03762v7",+ "hep-th/9901001",+ "math.GT/0309136",+])+def test_match_paper_link_or_id(config, text):+ assert ArxivParser().match(TaskOptions(url=text))++[email protected]("text", [+ "https://arxiv.org/src/1706.03762",+ "https://arxiv.org/list/cs.AI/recent",+ "https://huggingface.co/org/repo",+ "https://example.com/1706.03762",+ "1234.5678",+])+def test_match_skips_other_link(config, text):+ assert not ArxivParser().match(TaskOptions(url=text))+++def test_parse_legacy_id_drops_subject_class():+ arxivId = parseArxivId("https://arxiv.org/abs/math.GT/0309136v1")++ assert buildName(arxivId, "v1", "Regular points") == "math0309136v1 Regular points.pdf"+++def test_match_passive_skips_bare_id(engine):+ services = PackServices(coroutineRunner=engine.coroutineRunner, speedMeter=engine.speedMeter)+ for pack in (ArxivPack(services), HuggingFacePack(services), HttpPack(services)):+ engine.featureService.register(pack)++ assert engine.featureService.matchPassive("https://arxiv.org/abs/1706.03762")+ assert engine.featureService.match("1706.03762")+ assert not engine.featureService.matchPassive("1706.03762")+++async def test_add_holds_enabled_side_file_beside_pdf(engine, startServer, downloadFolder):+ task = buildTask(await startArxiv(startServer), isBibtexEnabled=True)++ engine.taskService.add(task, autoStart=False)++ assert namesIn(downloadFolder) == ["1706.03762v7 Attention Is All You Need.bib", NAME]+++async def test_run_downloads_pdf_with_enabled_side_files(engine, startServer, downloadFolder):+ task = buildTask(await startArxiv(startServer), isSourceEnabled=True, isBibtexEnabled=True)++ engine.taskService.add(task)+ await waitUntil(lambda: task.status == TaskStatus.COMPLETED)++ assert (downloadFolder / NAME).read_bytes() == PDF+ assert (downloadFolder / "1706.03762v7 Attention Is All You Need.tar.gz").read_bytes() == SOURCE+ assert (downloadFolder / "1706.03762v7 Attention Is All You Need.bib").read_bytes() == BIBTEX+++async def test_edit_enable_side_file_after_completed_downloads_it(engine, startServer, downloadFolder):+ task = buildTask(await startArxiv(startServer))+ engine.taskService.add(task)+ await waitUntil(lambda: task.status == TaskStatus.COMPLETED)+ assert namesIn(downloadFolder) == [NAME]++ engine.taskService.edit(task, {"isBibtexEnabled": True})++ await waitUntil(lambda: task.status == TaskStatus.COMPLETED+ and (downloadFolder / "1706.03762v7 Attention Is All You Need.bib").read_bytes() == BIBTEX)+ assert (downloadFolder / NAME).read_bytes() == PDF+++async def test_edit_disable_side_file_releases_its_name(engine, startServer, downloadFolder):+ task = buildTask(await startArxiv(startServer), isSourceEnabled=True)+ engine.taskService.add(task, autoStart=False)++ engine.taskService.edit(task, {"isSourceEnabled": False})+ await waitUntil(lambda: task.status == TaskStatus.COMPLETED)++ assert namesIn(downloadFolder) == [NAME]