Skip to content

The only downloader you need. 下载器的集大成者。

fix(huggingface): 填写 Access Token 后仍无法下载 Gated Repo #1019

XiaoYouChRafbc2a3ac4ee
diff --git a/GLOSSARY.md b/GLOSSARY.md
index 7682bcd2..87096fe2 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -338,6 +338,20 @@ _Avoid_: Mirror、Source、CDN;不简称「代理」(留给 Proxy)
选站方式之一:每个任务解析时让直连与全部 Proxy Site 竞速,取第一个合格响应。不跨任务记忆胜出者。
_Avoid_: 测速、最快站(不比较全部结果)
+### HuggingFace 加速
+
+**Mirror Site**:
+完整复刻 HuggingFace 接口的第三方站点,以替换域名的方式访问,如 hf-mirror.com。
+_Avoid_: Proxy Site(那是路径前缀转发)、镜像源
+
+**Gated Repo**:
+须由用户在 HuggingFace 网页上同意条款并获批后,才能下载其中文件的仓库。
+_Avoid_: 私有仓库(那是另一种权限)、受保护仓库
+
+**Access Token**:
+用户在 HuggingFace 生成、代表其身份访问 Gated Repo 与私有仓库的凭据。
+_Avoid_: 与 Pair Token 混淆;密钥、API Key
+
## Example dialogue
> **Dev:** "用户按暂停时,我们删除 Task 吗?"
diff --git a/app/client.py b/app/client.py
index ad9b6c1e..0bed6028 100644
--- a/app/client.py
+++ b/app/client.py
@@ -119,6 +119,9 @@ def buildClient(
url = proxy()
if url:
config["proxies"] = [Proxy.all(url)]
+ else:
+ # wreq 未配置代理时会自动读取环境变量中的代理,"不使用"须显式关闭
+ config["no_proxy"] = True
if resolved is not None:
config["emulation"] = resolved
diff --git a/features/huggingface_pack/android.py b/features/huggingface_pack/android.py
index e02c0597..496bd715 100644
--- a/features/huggingface_pack/android.py
+++ b/features/huggingface_pack/android.py
@@ -1,13 +1,13 @@
UI_CLASS = "com.xychr.ghostdownloader.features.huggingface_pack.HuggingFaceUi"
-def proxySiteList() -> list:
- from .config import HF_PROXY_SITES
- return list(HF_PROXY_SITES)
+def mirrorSiteList() -> list:
+ from .config import MIRROR_SITES
+ return list(MIRROR_SITES)
def tokenUrl() -> str:
from .config import TOKEN_URL
return TOKEN_URL
async def probeSites() -> dict:
- from .config import probeProxyLatencies
- return await probeProxyLatencies()
+ from .config import probeMirrorLatencies
+ return await probeMirrorLatencies()
diff --git a/features/huggingface_pack/config.py b/features/huggingface_pack/config.py
index 9d929284..bcaf300a 100644
--- a/features/huggingface_pack/config.py
+++ b/features/huggingface_pack/config.py
@@ -3,11 +3,11 @@ from __future__ import annotations
from urllib.parse import urlparse
from app.client import buildClient
-from app.config.cfg import BoolValidator, ConfigItem, ConfigValidator
+from app.config.cfg import BoolValidator, ConfigItem, ConfigValidator, OptionsValidator
from app.models.pack import PackConfig
-HF_PROXY_SITES = (
+MIRROR_SITES = (
"https://hf-mirror.com",
)
CUSTOM_SITE_KEY = "__custom__"
@@ -15,7 +15,7 @@ PROBE_TARGET = "https://huggingface.co/api/models/gpt2"
TOKEN_URL = "https://huggingface.co/settings/tokens"
-def toProxySite(site: str) -> str:
+def toMirrorSite(site: str) -> str:
value = str(site or "").strip()
if not value:
return ""
@@ -24,21 +24,17 @@ def toProxySite(site: str) -> str:
return value.rstrip("/")
-def selectedProxySite() -> str:
+def selectedMirrorSite() -> str:
if huggingFaceConfig.selectedSite.value == CUSTOM_SITE_KEY:
return huggingFaceConfig.customSite.value
return huggingFaceConfig.selectedSite.value
-def accessToken() -> str:
- return huggingFaceConfig.accessToken.value
-
-
-async def probeProxyLatencies() -> dict[str, int]:
+async def probeMirrorLatencies() -> dict[str, int]:
import asyncio
from time import perf_counter
- sites = list(HF_PROXY_SITES)
+ sites = list(MIRROR_SITES)
custom = huggingFaceConfig.customSite.value
if custom:
sites.append(custom)
@@ -60,9 +56,9 @@ async def probeProxyLatencies() -> dict[str, int]:
return dict(results)
-class HuggingFaceProxySiteValidator(ConfigValidator):
+class HuggingFaceMirrorSiteValidator(ConfigValidator):
def validate(self, value) -> bool:
- site = toProxySite(value)
+ site = toMirrorSite(value)
if not site:
return False
parsed = urlparse(site)
@@ -75,20 +71,20 @@ class HuggingFaceProxySiteValidator(ConfigValidator):
)
def correct(self, value) -> str:
- site = toProxySite(value)
+ site = toMirrorSite(value)
return site if self.validate(site) else ""
class HuggingFaceConfig(PackConfig):
isEnabled = ConfigItem("HuggingFace", "Enabled", True, BoolValidator())
- selectedSite = ConfigItem("HuggingFace", "SelectedSite", HF_PROXY_SITES[0], HuggingFaceProxySiteValidator())
- customSite = ConfigItem("HuggingFace", "CustomSite", "", HuggingFaceProxySiteValidator())
+ selectedSite = ConfigItem("HuggingFace", "SelectedSite", MIRROR_SITES[0], OptionsValidator([*MIRROR_SITES, CUSTOM_SITE_KEY]))
+ customSite = ConfigItem("HuggingFace", "CustomSite", "", HuggingFaceMirrorSiteValidator())
accessToken = ConfigItem("HuggingFace", "AccessToken", "")
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
from qfluentwidgets import FluentIcon, SwitchSettingCard
from app.view.components.setting_card_group import CollapsibleSettingCardGroup
- from .setting_cards import HuggingFaceProxySiteCard, HuggingFaceTokenCard
+ from .setting_cards import HuggingFaceMirrorSiteCard, HuggingFaceTokenCard
group = CollapsibleSettingCardGroup(self.tr("HuggingFace"), "huggingface", parent)
group.addSettingCards([
@@ -97,7 +93,7 @@ class HuggingFaceConfig(PackConfig):
self.tr("命中 HuggingFace 链接时,自动改写为所选镜像站"),
self.isEnabled, group,
),
- HuggingFaceProxySiteCard(self.submit, group),
+ HuggingFaceMirrorSiteCard(self.submit, group),
HuggingFaceTokenCard(group),
])
return [group]
diff --git a/features/huggingface_pack/i18n.py b/features/huggingface_pack/i18n.py
new file mode 100644
index 00000000..a79ee6cc
--- /dev/null
+++ b/features/huggingface_pack/i18n.py
@@ -0,0 +1,8 @@
+from app.i18n import N
+
+N("TaskErrors", "无法解析 HuggingFace 链接")
+N("TaskErrors", "无法访问仓库 {repo}({status})")
+N("TaskErrors", "仓库 {repo} 中没有 {path}")
+N("TaskErrors", "该仓库需要授权,请在设置中填写 HuggingFace Access Token")
+N("TaskErrors", "HuggingFace Access Token 无效或已过期,请在设置中更新")
+N("TaskErrors", "尚未获得该仓库的访问权限,请先在 {url} 申请;若已获批,请确认 Access Token 有读取 Gated Repo 的权限")
diff --git a/features/huggingface_pack/pack.py b/features/huggingface_pack/pack.py
index 2764198d..e8da9a16 100644
--- a/features/huggingface_pack/pack.py
+++ b/features/huggingface_pack/pack.py
@@ -1,36 +1,34 @@
from __future__ import annotations
import re
-from dataclasses import replace
from pathlib import PurePosixPath
-from urllib.parse import urlparse
+from urllib.parse import quote, unquote, urlparse
from app.client import buildClient
from app.i18n import N
from app.models.pack import FeaturePack, TaskParser
-from app.models.task import Task, TaskFile, TaskOptions
+from app.models.task import Task, TaskError, TaskOptions
from app.platform.filesystem import toSafeFilename
-from .config import accessToken, huggingFaceConfig, selectedProxySite
-from .task import HuggingFaceFile, HuggingFaceStep, HuggingFaceTask
-
-from http_pack.task import HttpTaskStep
+from .config import huggingFaceConfig, selectedMirrorSite
+from .task import (
+ API_BASE, HuggingFaceFile, HuggingFaceTask,
+ buildAuthHeaders, buildRepoUrl, probeSite, toAuthError, toSiteUrl,
+)
-HF_HOSTS = {"huggingface.co", "www.huggingface.co"}
REPO_PATTERN = re.compile(
r"^/(?P<type>(?:datasets|spaces)/)?(?P<org>[^/]+)/(?P<repo>[^/]+)"
r"(?:/(?:resolve|blob|tree)/(?P<rev>[^/]+)(?:/(?P<path>.+))?)?$"
)
-API_BASE = "https://huggingface.co"
def parseHuggingFaceUrl(url: str) -> dict | None:
parsed = urlparse(url)
host = (parsed.hostname or "").lower().removeprefix("www.")
if host not in {"huggingface.co"}:
- proxySite = selectedProxySite()
- if proxySite:
- proxyHost = (urlparse(proxySite).hostname or "").lower()
- if host != proxyHost:
+ mirrorSite = selectedMirrorSite()
+ if mirrorSite:
+ mirrorHost = (urlparse(mirrorSite).hostname or "").lower()
+ if host != mirrorHost:
return None
else:
return None
@@ -50,8 +48,8 @@ def parseHuggingFaceUrl(url: str) -> dict | None:
"org": m.group("org"),
"repo": m.group("repo"),
"repoType": repoType,
- "revision": m.group("rev") or "main",
- "filePath": m.group("path") or "",
+ "revision": unquote(m.group("rev") or "main"),
+ "filePath": unquote(m.group("path") or ""),
}
@@ -64,101 +62,64 @@ class HuggingFaceParser(TaskParser):
async def parse(self, options: TaskOptions) -> Task:
info = parseHuggingFaceUrl(options.url)
if info is None:
- raise ValueError("无法解析 HuggingFace 链接")
+ raise TaskError("无法解析 HuggingFace 链接")
repoId = f"{info['org']}/{info['repo']}"
repoType = info["repoType"]
revision = info["revision"]
- filePath = info["filePath"]
-
- headers: dict[str, str] = {}
- token = accessToken()
- if token:
- headers["authorization"] = f"Bearer {token}"
-
- from app.config.cfg import cfg
-
- if filePath:
- downloadUrl = self._fileUrl(repoId, repoType, revision, filePath)
- name = toSafeFilename(filePath.rsplit("/", 1)[-1], fallback="download")
-
- client = buildClient(headers=headers)
- try:
- response = await client.head(downloadUrl)
- fileSize = 0
- cl = response.headers.get("content-length")
- if cl:
- fileSize = int(cl)
- canUseRange = response.headers.contains_key("accept-ranges")
- finally:
- client.close()
-
- task = HuggingFaceTask(
- name=name,
- url=options.url,
- fileSize=fileSize,
- outputFolder=options.outputFolder,
- repoId=repoId,
- repoType=repoType,
- revision=revision,
- )
- task.addStep(HttpTaskStep(
- stepIndex=1,
- url=downloadUrl,
- fileSize=fileSize,
- headers=headers,
- subworkerCount=cfg.preBlockNum.value,
- canUseRangeRequests=canUseRange,
- ))
- return task
+ filePath = info["filePath"].strip("/")
+ repoUrl = buildRepoUrl(repoType, repoId)
+ token = huggingFaceConfig.accessToken.value
apiPrefix = {"dataset": "datasets", "space": "spaces"}.get(repoType, "models")
- base = selectedProxySite() or API_BASE
- apiUrl = f"{base}/api/{apiPrefix}/{repoId}/tree/{revision}"
-
- client = buildClient(headers=headers)
+ client = buildClient(headers=buildAuthHeaders(token))
try:
- entries = await self._fetchTree(client, apiUrl)
+ apiUrl = f"{API_BASE}/api/{apiPrefix}/{repoId}/revision/{quote(revision, safe='')}?blobs=true"
+ site = await probeSite(apiUrl, token)
+ response = await client.get(toSiteUrl(apiUrl, site))
+ status = response.status.as_int()
+ if authError := toAuthError(status, bool(token), repoUrl):
+ raise authError
+ if status >= 400:
+ raise TaskError("无法访问仓库 {repo}({status})", repo=repoId, status=status)
+ repo = await response.json()
+
+ # 固定到提交,仓库中途更新时续传不会拼接两个版本
+ commit = repo["sha"]
+ siblings = [
+ s for s in repo.get("siblings", [])
+ if not filePath or s["rfilename"] == filePath or s["rfilename"].startswith(f"{filePath}/")
+ ]
+ if not siblings:
+ raise TaskError("仓库 {repo} 中没有 {path}", repo=repoId, path=filePath or "/")
+
+ files = [
+ HuggingFaceFile(
+ index=i,
+ relativePath=s["rfilename"],
+ size=s.get("size", 0),
+ downloadUrl=f"{repoUrl}/resolve/{commit}/{quote(s['rfilename'])}",
+ )
+ for i, s in enumerate(siblings)
+ ]
+
+ # Gated Repo 的列表公开,下载时才鉴权,所以添加时先试一个 LFS 文件
+ if repo.get("gated"):
+ lfsFile = next((f for f, s in zip(files, siblings) if s.get("lfs")), None)
+ if lfsFile is not None:
+ response = await client.head(toSiteUrl(lfsFile.downloadUrl, site))
+ if authError := toAuthError(response.status.as_int(), bool(token), repoUrl):
+ raise authError
finally:
client.close()
- if not entries:
- raise ValueError(f"仓库 {repoId} 为空或无法访问")
-
- files: list[HuggingFaceFile] = []
- for i, entry in enumerate(entries):
- path = entry.get("path", "")
- size = entry.get("size", 0)
- lfs = entry.get("lfs")
- if lfs and isinstance(lfs, dict):
- size = lfs.get("size", size)
- files.append(HuggingFaceFile(
- index=i,
- relativePath=path,
- size=size,
- downloadUrl=self._fileUrl(repoId, repoType, revision, path),
- ))
-
if len(files) == 1:
- repoName = toSafeFilename(PurePosixPath(files[0].relativePath).name, fallback="huggingface")
+ name = toSafeFilename(PurePosixPath(files[0].relativePath).name, fallback="huggingface")
else:
- repoName = toSafeFilename(repoId.replace("/", "_"), fallback="huggingface")
-
- steps = [
- HuggingFaceStep(
- stepIndex=file.index + 1,
- url=file.downloadUrl,
- fileSize=file.size,
- headers=headers,
- subworkerCount=cfg.preBlockNum.value,
- canUseRangeRequests=file.size > 0,
- fileIndex=file.index,
- )
- for file in files
- ]
+ name = toSafeFilename(repoId.replace("/", "_"), fallback="huggingface")
return HuggingFaceTask(
- name=repoName,
+ name=name,
url=options.url,
fileSize=sum(f.size for f in files),
outputFolder=options.outputFolder,
@@ -166,37 +127,8 @@ class HuggingFaceParser(TaskParser):
repoType=repoType,
revision=revision,
files=files,
- steps=steps,
)
- async def _fetchTree(self, client, apiUrl: str) -> list[dict]:
- entries: list[dict] = []
- url = apiUrl
- while url:
- response = await client.get(url)
- if response.status.as_int() == 401:
- raise PermissionError("该仓库需要授权,请在设置中配置 HuggingFace Access Token")
- response.raise_for_status()
- page = await response.json()
- if isinstance(page, list):
- for entry in page:
- if entry.get("type") == "file":
- entries.append(entry)
- elif entry.get("type") == "directory":
- dirName = entry['path'].rsplit('/', 1)[-1]
- subUrl = f"{apiUrl}/{dirName}"
- subEntries = await self._fetchTree(client, subUrl)
- entries.extend(subEntries)
- break
- else:
- break
- return entries
-
- def _fileUrl(self, repoId: str, repoType: str, revision: str, filePath: str) -> str:
- base = selectedProxySite() or API_BASE
- typePrefix = {"dataset": "datasets/", "space": "spaces/"}.get(repoType, "")
- return f"{base}/{typePrefix}{repoId}/resolve/{revision}/{filePath}"
-
class HuggingFacePack(FeaturePack):
packId = "huggingface"
diff --git a/features/huggingface_pack/setting_cards.py b/features/huggingface_pack/setting_cards.py
index b086ffa8..0392fae5 100644
--- a/features/huggingface_pack/setting_cards.py
+++ b/features/huggingface_pack/setting_cards.py
@@ -10,21 +10,21 @@ from qfluentwidgets import (
from .config import (
CUSTOM_SITE_KEY,
- HF_PROXY_SITES,
+ MIRROR_SITES,
TOKEN_URL,
huggingFaceConfig,
- probeProxyLatencies,
+ probeMirrorLatencies,
)
-class HuggingFaceProxySiteCard(SettingCard):
+class HuggingFaceMirrorSiteCard(SettingCard):
def __init__(self, submit, parent=None):
self.submit = submit
super().__init__(
FluentIcon.GLOBE, self.tr("镜像站"),
self.tr("选择 HuggingFace 镜像站,延迟仅供参考"), parent,
)
- self._latencies: dict[str, int | None] = {s: None for s in HF_PROXY_SITES}
+ self._latencies: dict[str, int | None] = {s: None for s in MIRROR_SITES}
self._isRefreshing = False
self.comboBox = ComboBox(self)
self.customSiteEdit = LineEdit(self)
@@ -42,15 +42,15 @@ class HuggingFaceProxySiteCard(SettingCard):
self.refreshButton.setToolTip(self.tr("刷新延迟"))
self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))
- for site in HF_PROXY_SITES:
+ for site in MIRROR_SITES:
self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))
self.comboBox.addItem(self.tr("自定义"))
currentSite = huggingFaceConfig.selectedSite.value
if currentSite == CUSTOM_SITE_KEY:
- self.comboBox.setCurrentIndex(len(HF_PROXY_SITES))
- elif currentSite in HF_PROXY_SITES:
- self.comboBox.setCurrentIndex(HF_PROXY_SITES.index(currentSite))
+ self.comboBox.setCurrentIndex(len(MIRROR_SITES))
+ elif currentSite in MIRROR_SITES:
+ self.comboBox.setCurrentIndex(MIRROR_SITES.index(currentSite))
else:
self.comboBox.setCurrentIndex(0)
self.customSiteEdit.setText(huggingFaceConfig.customSite.value)
@@ -70,7 +70,7 @@ class HuggingFaceProxySiteCard(SettingCard):
self.refreshButton.clicked.connect(self.refreshLatencies)
def _refreshLatencyLabels(self) -> None:
- for i, site in enumerate(HF_PROXY_SITES):
+ for i, site in enumerate(MIRROR_SITES):
displayName = urlparse(site).netloc or site.rstrip("/")
latency = self._latencies.get(site)
if latency is None:
@@ -89,17 +89,17 @@ class HuggingFaceProxySiteCard(SettingCard):
customLabel = f"{self.tr('自定义')} ({self.tr('超时')})"
else:
customLabel = f"{self.tr('自定义')} ({customLatency} ms)"
- self.comboBox.setItemText(len(HF_PROXY_SITES), customLabel)
+ self.comboBox.setItemText(len(MIRROR_SITES), customLabel)
def _onCurrentIndexChanged(self, index: int) -> None:
from app.config.cfg import cfg
if index < 0:
return
- if index < len(HF_PROXY_SITES):
- cfg.set(huggingFaceConfig.selectedSite, HF_PROXY_SITES[index])
+ if index < len(MIRROR_SITES):
+ cfg.set(huggingFaceConfig.selectedSite, MIRROR_SITES[index])
else:
cfg.set(huggingFaceConfig.selectedSite, CUSTOM_SITE_KEY)
- self.customSiteEdit.setVisible(index >= len(HF_PROXY_SITES))
+ self.customSiteEdit.setVisible(index >= len(MIRROR_SITES))
def _onCustomSiteEditingFinished(self) -> None:
from app.config.cfg import cfg
@@ -109,11 +109,11 @@ class HuggingFaceProxySiteCard(SettingCard):
if self._isRefreshing:
return
self._isRefreshing = True
- self._latencies = {s: None for s in HF_PROXY_SITES}
+ self._latencies = {s: None for s in MIRROR_SITES}
self._refreshLatencyLabels()
self.refreshButton.setEnabled(False)
self.submit(
- probeProxyLatencies(),
+ probeMirrorLatencies(),
done=self._onLatenciesDone, failed=self._onLatenciesFailed,
owner=self,
)
diff --git a/features/huggingface_pack/task.py b/features/huggingface_pack/task.py
index 44da4d7a..5d9136ac 100644
--- a/features/huggingface_pack/task.py
+++ b/features/huggingface_pack/task.py
@@ -1,10 +1,62 @@
from __future__ import annotations
from dataclasses import dataclass
+from urllib.parse import urlsplit
-from app.models.task import Task, TaskFile, TaskStep
+from app.client import buildClient
+from app.models.task import Task, TaskError, TaskFile, TaskStep
+from .config import huggingFaceConfig, selectedMirrorSite
from http_pack.task import HttpTaskStep
+from wreq.redirect import Policy
+
+API_BASE = "https://huggingface.co"
+
+
+def buildAuthHeaders(token: str) -> dict[str, str]:
+ return {"authorization": f"Bearer {token}"} if token else {}
+
+
+def buildRepoUrl(repoType: str, repoId: str) -> str:
+ typePrefix = {"dataset": "datasets/", "space": "spaces/"}.get(repoType, "")
+ return f"{API_BASE}/{typePrefix}{repoId}"
+
+
+def toAuthError(status: int, hasToken: bool, repoUrl: str) -> TaskError | None:
+ """没有 Token 时 Mirror Site 返回 403、官方站返回 401,所以先看 Token 再看状态码。"""
+ if status not in (401, 403):
+ return None
+ if not hasToken:
+ return TaskError("该仓库需要授权,请在设置中填写 HuggingFace Access Token")
+ if status == 401:
+ return TaskError("HuggingFace Access Token 无效或已过期,请在设置中更新")
+ return TaskError(
+ "尚未获得该仓库的访问权限,请先在 {url} 申请;若已获批,请确认 Access Token 有读取 Gated Repo 的权限",
+ url=repoUrl,
+ )
+
+
+def toSiteUrl(url: str, site: str) -> str:
+ parts = urlsplit(url)
+ return f"{site}{parts.path}" + (f"?{parts.query}" if parts.query else "")
+
+
+async def probeSite(url: str, token: str) -> str:
+ """返回这次应请求的站点。Mirror Site 把请求跳回官方站时直接用官方站,否则跳转会丢掉 Token。"""
+ site = selectedMirrorSite()
+ if not site:
+ return API_BASE
+ if not token:
+ return site
+
+ client = buildClient(headers=buildAuthHeaders(token))
+ try:
+ response = await client.head(toSiteUrl(url, site), redirect=Policy.none())
+ location = bytes(response.headers.get("location") or b"").decode()
+ response.close()
+ finally:
+ client.close()
+ return API_BASE if location.startswith(f"{API_BASE}/") else site
@dataclass(kw_only=True)
@@ -18,6 +70,17 @@ class HuggingFaceStep(HttpTaskStep):
def outputPath(self) -> str:
return str(self.task.toFilePath(self.fileIndex))
+ async def run(self, reportSpeed, waitForSpeedLimit) -> None:
+ # Task.run 记录 Step 的错误,所以鉴权提示须在这里换上
+ try:
+ await super().run(reportSpeed, waitForSpeedLimit)
+ except TaskError as e:
+ repoUrl = buildRepoUrl(self.task.repoType, self.task.repoId)
+ authError = toAuthError(e.params.get("status"), "authorization" in self.headers, repoUrl)
+ if authError is None:
+ raise
+ raise authError from e
+
@classmethod
def fromFile(cls, file: TaskFile, task: Task) -> TaskStep:
from app.config.cfg import cfg
@@ -26,7 +89,6 @@ class HuggingFaceStep(HttpTaskStep):
stepIndex=file.index + 1,
url=hfFile.downloadUrl,
fileSize=file.size,
- headers=task.steps[0].headers if task.steps else {},
subworkerCount=cfg.preBlockNum.value,
canUseRangeRequests=file.size > 0,
fileIndex=file.index,
@@ -54,3 +116,14 @@ class HuggingFaceTask(Task):
@property
def countSelected(self) -> int:
return sum(1 for f in self.files if f.selected) if self.files else 0
+
+ async def run(self, reportSpeed, waitForSpeedLimit) -> None:
+ # 按当前设置刷新 Step,修改 Token 或 Mirror Site 后重试即可生效
+ steps = list(self.pendingSteps())
+ if steps:
+ token = huggingFaceConfig.accessToken.value
+ site = await probeSite(steps[0].url, token)
+ for step in steps:
+ step.url = toSiteUrl(step.url, site)
+ step.headers = buildAuthHeaders(token)
+ await super().run(reportSpeed, waitForSpeedLimit)
diff --git a/tests/huggingface_pack/__init__.py b/tests/huggingface_pack/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/huggingface_pack/test_task.py b/tests/huggingface_pack/test_task.py
new file mode 100644
index 00000000..7ef7f789
--- /dev/null
+++ b/tests/huggingface_pack/test_task.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass, field
+
+import pytest
+from aiohttp import web
+
+from app.config.cfg import cfg
+from app.config.paths import APP_DATA_DIR
+from app.models.task import TaskError, TaskOptions, TaskStatus
+from huggingface_pack.config import CUSTOM_SITE_KEY
+from huggingface_pack.pack import HuggingFaceParser
+from tests.helpers import buildRangeHandler, runStep
+
+REPO_URL = "https://huggingface.co/datasets/org/repo"
+REVISION_PATTERN = re.compile(r"^/api/datasets/org/repo/revision/(?P<rev>[^/]+)$")
+RESOLVE_PATTERN = re.compile(r"^/datasets/org/repo/resolve/(?P<commit>[^/]+)/(?P<path>.+)$")
+
+
+@dataclass
+class Hub:
+ """在本机充当 Mirror Site 的 HuggingFace 仓库。"""
+ commits: dict[str, dict[str, bytes]]
+ refs: dict[str, str]
+ isGated: bool = False
+ validTokens: set[str] = field(default_factory=set)
+
+ async def handle(self, request: web.Request) -> web.StreamResponse:
+ if m := REVISION_PATTERN.match(request.path):
+ commit = self.refs.get(m["rev"], m["rev"])
+ siblings = [
+ {"rfilename": path, "size": len(content), "lfs": {"size": len(content)}}
+ for path, content in self.commits[commit].items()
+ ]
+ return web.json_response({"sha": commit, "gated": "auto" if self.isGated else False, "siblings": siblings})
+ if m := RESOLVE_PATTERN.match(request.path):
+ authorization = request.headers.get("Authorization", "")
+ if self.isGated and authorization.removeprefix("Bearer ") not in self.validTokens:
+ # 与 hf-mirror.com 一致:没带 Token 返回 403,Token 无效返回 401
+ return web.Response(status=401 if authorization else 403)
+ return await buildRangeHandler(self.commits[m["commit"]][m["path"]])(request)
+ return web.Response(status=404)
+
+
+async def startHub(startServer, hub: Hub, *, token: str = "") -> None:
+ url = await startServer(hub.handle)
+ setConfig(site=url.removesuffix("/file"), token=token)
+
+
+def setConfig(*, site: str, token: str) -> None:
+ configFile = APP_DATA_DIR / "UserConfig.json"
+ data = json.loads(configFile.read_text(encoding="utf-8"))
+ data["HuggingFace"] = {"SelectedSite": CUSTOM_SITE_KEY, "CustomSite": site, "AccessToken": token}
+ configFile.write_text(json.dumps(data), encoding="utf-8")
+ cfg.load(configFile)
+
+
+def setToken(token: str) -> None:
+ configFile = APP_DATA_DIR / "UserConfig.json"
+ data = json.loads(configFile.read_text(encoding="utf-8"))
+ data["HuggingFace"]["AccessToken"] = token
+ configFile.write_text(json.dumps(data), encoding="utf-8")
+ cfg.load(configFile)
+
+
+async def parse(url: str, downloadFolder):
+ return await HuggingFaceParser().parse(TaskOptions(url=url, outputFolder=downloadFolder))
+
+
+async def test_run_downloads_gated_repo_with_token(config, startServer, downloadFolder):
+ files = {"a.bin": b"a" * 1000, "sub/b.bin": b"b" * 500}
+ await startHub(startServer, Hub({"c1": files}, {"main": "c1"}, isGated=True, validTokens={"t"}), token="t")
+
+ task = await parse(REPO_URL, downloadFolder)
+ await runStep(task.steps[0])
+
+ assert task.status == TaskStatus.COMPLETED
+ assert (downloadFolder / "org_repo" / "a.bin").read_bytes() == files["a.bin"]
+ assert (downloadFolder / "org_repo" / "sub" / "b.bin").read_bytes() == files["sub/b.bin"]
+
+
+async def test_parse_gated_repo_without_token_asks_for_token(config, startServer, downloadFolder):
+ await startHub(startServer, Hub({"c1": {"a.bin": b"a"}}, {"main": "c1"}, isGated=True, validTokens={"t"}))
+
+ with pytest.raises(TaskError, match="请在设置中填写 HuggingFace Access Token"):
+ await parse(REPO_URL, downloadFolder)
+
+
+async def test_run_uses_token_updated_after_parse(config, startServer, downloadFolder):
+ hub = Hub({"c1": {"a.bin": b"a" * 1000}}, {"main": "c1"}, isGated=True, validTokens={"old"})
+ await startHub(startServer, hub, token="old")
+ task = await parse(REPO_URL, downloadFolder)
+
+ hub.validTokens = {"new"}
+ setToken("new")
+ await runStep(task.steps[0])
+
+ assert (downloadFolder / "a.bin").read_bytes() == b"a" * 1000
+
+
+async def test_run_with_expired_token_asks_to_update_token(config, startServer, downloadFolder):
+ hub = Hub({"c1": {"a.bin": b"a" * 1000}}, {"main": "c1"}, isGated=True, validTokens={"old"})
+ await startHub(startServer, hub, token="old")
+ task = await parse(REPO_URL, downloadFolder)
+
+ hub.validTokens = set()
+ with pytest.raises(TaskError, match="无效或已过期"):
+ await runStep(task.steps[0])
+
+
+async def test_run_after_repo_update_downloads_added_version(config, startServer, downloadFolder):
+ hub = Hub({"c1": {"a.bin": b"1" * 1000}, "c2": {"a.bin": b"2" * 1000}}, {"main": "c1"})
+ await startHub(startServer, hub)
+ task = await parse(REPO_URL, downloadFolder)
+
+ hub.refs["main"] = "c2"
+ await runStep(task.steps[0])
+
+ assert (downloadFolder / "a.bin").read_bytes() == b"1" * 1000
+
+
+async def test_parse_folder_link_selects_folder_files(config, startServer, downloadFolder):
+ files = {"a.bin": b"a", "sub/b.bin": b"b", "sub/c.bin": b"c", "subway.bin": b"d"}
+ await startHub(startServer, Hub({"c1": files}, {"main": "c1"}))
+
+ task = await parse(f"{REPO_URL}/tree/main/sub", downloadFolder)
+
+ assert [f.relativePath for f in task.files] == ["sub/b.bin", "sub/c.bin"]
diff --git a/tests/test_proxy.py b/tests/test_proxy.py
new file mode 100644
index 00000000..07cb33c2
--- /dev/null
+++ b/tests/test_proxy.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from aiohttp import web
+
+from app.client import buildClient
+
+
+async def test_fetch_with_proxy_off_ignores_environment_proxy(config, startServer, monkeypatch):
+ proxiedPaths: list[str] = []
+
+ async def proxyHandler(request: web.Request) -> web.Response:
+ proxiedPaths.append(request.path)
+ return web.Response(status=502)
+
+ async def targetHandler(request: web.Request) -> web.Response:
+ return web.Response(text="direct")
+
+ proxyUrl = (await startServer(proxyHandler)).removesuffix("/file")
+ targetUrl = await startServer(targetHandler)
+ for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.setenv(name, proxyUrl)
+ for name in ("NO_PROXY", "no_proxy"):
+ monkeypatch.delenv(name, raising=False)
+
+ client = buildClient()
+ try:
+ response = await client.get(targetUrl)
+ assert await response.text() == "direct"
+ finally:
+ client.close()
+ assert proxiedPaths == []