hf-transfast 0.1.0__tar.gz
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.
- hf_transfast-0.1.0/LICENSE +21 -0
- hf_transfast-0.1.0/PKG-INFO +54 -0
- hf_transfast-0.1.0/README.md +39 -0
- hf_transfast-0.1.0/pyproject.toml +37 -0
- hf_transfast-0.1.0/src/hft/__init__.py +0 -0
- hf_transfast-0.1.0/src/hft/cli.py +273 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hari
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hf-transfast
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fast Hugging Face repo downloads via aria2c
|
|
5
|
+
Keywords: huggingface,aria2,download,datasets
|
|
6
|
+
Author: hari
|
|
7
|
+
Author-email: hari <kmhari@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: huggingface-hub>=2.5.0
|
|
11
|
+
Requires-Dist: tqdm>=4.70.1
|
|
12
|
+
Requires-Python: >=3.13
|
|
13
|
+
Project-URL: Repository, https://github.com/kmhari/hf_transfast
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# hft
|
|
17
|
+
|
|
18
|
+
Fast Hugging Face dataset/model downloads by driving `aria2c` (multi-connection, resumable).
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
brew install aria2 # or: apt install aria2
|
|
23
|
+
uv tool install git+https://github.com/kmhari/hf_transfast # installs the `hft` command
|
|
24
|
+
|
|
25
|
+
Or without uv: `pipx install git+https://github.com/kmhari/hf_transfast`.
|
|
26
|
+
One-off run, no install: `uvx --from git+https://github.com/kmhari/hf_transfast hft get ...`.
|
|
27
|
+
Upgrade: `uv tool upgrade hft`. Needs Python 3.13+ (uv fetches it if missing).
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
hft get REPO_ID [--type dataset|model] [--revision REF] [--include GLOB ...] [--exclude GLOB ...]
|
|
32
|
+
[--out DIR] [-x N] [-j N] [--verify] [--dry-run]
|
|
33
|
+
|
|
34
|
+
hft get HuggingFaceFW/fineweb-edu --include 'sample/10BT/000_*' --dry-run
|
|
35
|
+
hft get openai-community/gpt2 --type model --include model.safetensors --verify
|
|
36
|
+
hft get org/data --out ./data
|
|
37
|
+
|
|
38
|
+
- `--type` default `dataset`. `--include/--exclude` are repeatable fnmatch globs (as in `snapshot_download`).
|
|
39
|
+
- Default destination is the normal HF cache (`HF_HUB_CACHE`, endpoint `HF_ENDPOINT`, token from `hf auth login`/`HF_TOKEN`),
|
|
40
|
+
so `snapshot_download(..., local_files_only=True)` finds the result. `--out DIR` writes plain files to `DIR/path`.
|
|
41
|
+
- `-x` connections per file (max 16), `-j` concurrent files. Auto-tuned from the pending files if omitted:
|
|
42
|
+
median < 20 MB: `-x 4 -j min(n,16)`; < 256 MB: `-x 8 -j min(n,8)`; else `-x 16 -j min(n,3)`.
|
|
43
|
+
- `--verify` sha256-checks LFS files (size is always checked). `--dry-run` prints counts, sizes, `-x/-j`, destination.
|
|
44
|
+
- Exit: 0 ok, 1 failure, 2 `aria2c` missing, 130 interrupted. The last stdout line is the snapshot / out path; progress goes to stderr.
|
|
45
|
+
- Always resolves the latest commit of `--revision` (no pinning). Gated/private repos need an accepted licence + token.
|
|
46
|
+
|
|
47
|
+
## Resume
|
|
48
|
+
|
|
49
|
+
Data is written to `<blob>.incomplete` (cache) or `<file>.incomplete` (`--out`) next to an aria2 `.aria2` control file.
|
|
50
|
+
Ctrl-C stops aria2c cleanly (control files saved), exits 130, and renames nothing. Re-run the same command: complete files
|
|
51
|
+
are skipped, partial ones continue where they stopped. Only after size (and `--verify` sha256) checks are files renamed
|
|
52
|
+
into place and the snapshot symlinks and `refs/<revision>` written.
|
|
53
|
+
|
|
54
|
+
The token is written to a 0600 aria2 input file under `.hft/` (removed on exit), not to the command line.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# hft
|
|
2
|
+
|
|
3
|
+
Fast Hugging Face dataset/model downloads by driving `aria2c` (multi-connection, resumable).
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
brew install aria2 # or: apt install aria2
|
|
8
|
+
uv tool install git+https://github.com/kmhari/hf_transfast # installs the `hft` command
|
|
9
|
+
|
|
10
|
+
Or without uv: `pipx install git+https://github.com/kmhari/hf_transfast`.
|
|
11
|
+
One-off run, no install: `uvx --from git+https://github.com/kmhari/hf_transfast hft get ...`.
|
|
12
|
+
Upgrade: `uv tool upgrade hft`. Needs Python 3.13+ (uv fetches it if missing).
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
hft get REPO_ID [--type dataset|model] [--revision REF] [--include GLOB ...] [--exclude GLOB ...]
|
|
17
|
+
[--out DIR] [-x N] [-j N] [--verify] [--dry-run]
|
|
18
|
+
|
|
19
|
+
hft get HuggingFaceFW/fineweb-edu --include 'sample/10BT/000_*' --dry-run
|
|
20
|
+
hft get openai-community/gpt2 --type model --include model.safetensors --verify
|
|
21
|
+
hft get org/data --out ./data
|
|
22
|
+
|
|
23
|
+
- `--type` default `dataset`. `--include/--exclude` are repeatable fnmatch globs (as in `snapshot_download`).
|
|
24
|
+
- Default destination is the normal HF cache (`HF_HUB_CACHE`, endpoint `HF_ENDPOINT`, token from `hf auth login`/`HF_TOKEN`),
|
|
25
|
+
so `snapshot_download(..., local_files_only=True)` finds the result. `--out DIR` writes plain files to `DIR/path`.
|
|
26
|
+
- `-x` connections per file (max 16), `-j` concurrent files. Auto-tuned from the pending files if omitted:
|
|
27
|
+
median < 20 MB: `-x 4 -j min(n,16)`; < 256 MB: `-x 8 -j min(n,8)`; else `-x 16 -j min(n,3)`.
|
|
28
|
+
- `--verify` sha256-checks LFS files (size is always checked). `--dry-run` prints counts, sizes, `-x/-j`, destination.
|
|
29
|
+
- Exit: 0 ok, 1 failure, 2 `aria2c` missing, 130 interrupted. The last stdout line is the snapshot / out path; progress goes to stderr.
|
|
30
|
+
- Always resolves the latest commit of `--revision` (no pinning). Gated/private repos need an accepted licence + token.
|
|
31
|
+
|
|
32
|
+
## Resume
|
|
33
|
+
|
|
34
|
+
Data is written to `<blob>.incomplete` (cache) or `<file>.incomplete` (`--out`) next to an aria2 `.aria2` control file.
|
|
35
|
+
Ctrl-C stops aria2c cleanly (control files saved), exits 130, and renames nothing. Re-run the same command: complete files
|
|
36
|
+
are skipped, partial ones continue where they stopped. Only after size (and `--verify` sha256) checks are files renamed
|
|
37
|
+
into place and the snapshot symlinks and `refs/<revision>` written.
|
|
38
|
+
|
|
39
|
+
The token is written to a 0600 aria2 input file under `.hft/` (removed on exit), not to the command line.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "hf-transfast"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Fast Hugging Face repo downloads via aria2c"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "hari", email = "kmhari@users.noreply.github.com" }
|
|
8
|
+
]
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
keywords = ["huggingface", "aria2", "download", "datasets"]
|
|
12
|
+
requires-python = ">=3.13"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"huggingface-hub>=2.5.0",
|
|
15
|
+
"tqdm>=4.70.1",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/kmhari/hf_transfast"
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
hft = "hft.cli:main"
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["uv_build>=0.11.28,<0.12.0"]
|
|
26
|
+
build-backend = "uv_build"
|
|
27
|
+
|
|
28
|
+
[tool.uv.build-backend]
|
|
29
|
+
module-name = "hft"
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = [
|
|
33
|
+
"pytest>=9.2.0",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
markers = ["network: needs internet + aria2c"]
|
|
File without changes
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""hft: download Hugging Face repos with aria2c, into the HF cache layout or a plain dir."""
|
|
2
|
+
import argparse, hashlib, json, os, secrets, shutil, signal, socket, subprocess, sys, time
|
|
3
|
+
import urllib.request
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from huggingface_hub import HfApi, constants, get_hf_file_metadata, get_token, hf_hub_url
|
|
8
|
+
from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
|
|
9
|
+
from huggingface_hub.file_download import _cache_commit_hash_for_specific_revision, repo_folder_name
|
|
10
|
+
from huggingface_hub.utils import filter_repo_objects
|
|
11
|
+
from tqdm import tqdm
|
|
12
|
+
|
|
13
|
+
MB = 1 << 20
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Entry:
|
|
18
|
+
path: str # path inside the repo
|
|
19
|
+
size: int
|
|
20
|
+
sha256: str | None # LFS only
|
|
21
|
+
etag: str # lfs sha256, else git blob oid (same as huggingface_hub)
|
|
22
|
+
url: str
|
|
23
|
+
final: Path # blob (cache mode) or out file
|
|
24
|
+
link: Path | None # snapshot symlink (cache mode)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def tmp(self) -> Path:
|
|
28
|
+
return self.final.with_name(self.final.name + ".incomplete")
|
|
29
|
+
|
|
30
|
+
def is_complete(self, manifest: dict | None = None) -> bool:
|
|
31
|
+
# manifest (out mode only): path -> etag of what we wrote; size alone can't see same-size upstream changes
|
|
32
|
+
if manifest is not None and manifest.get(self.path) != self.etag:
|
|
33
|
+
return False
|
|
34
|
+
return self.final.exists() and self.final.stat().st_size == self.size and not self.final.with_name(self.final.name + ".aria2").exists()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def tune(sizes: list[int]) -> tuple[int, int]:
|
|
38
|
+
"""Return (x connections per file, j concurrent files) from pending file sizes."""
|
|
39
|
+
n = len(sizes)
|
|
40
|
+
if n == 0:
|
|
41
|
+
return 1, 1
|
|
42
|
+
med = sorted(sizes)[n // 2]
|
|
43
|
+
if med < 20 * MB: # many small files: parallelise across files
|
|
44
|
+
return 4, min(n, 16)
|
|
45
|
+
if med < 256 * MB: # mid-size
|
|
46
|
+
return 8, min(n, 8)
|
|
47
|
+
return 16, min(n, 3) # few big files: parallelise within a file
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_entries(info, repo_id, repo_type, revision, include, exclude, out: Path | None) -> list[Entry]:
|
|
51
|
+
sibs = list(filter_repo_objects(info.siblings or [], allow_patterns=include or None,
|
|
52
|
+
ignore_patterns=exclude or None, key=lambda s: s.rfilename))
|
|
53
|
+
if out:
|
|
54
|
+
base = None
|
|
55
|
+
else:
|
|
56
|
+
base = Path(constants.HF_HUB_CACHE) / repo_folder_name(repo_id=repo_id, repo_type=repo_type)
|
|
57
|
+
entries = []
|
|
58
|
+
for s in sibs:
|
|
59
|
+
sha = s.lfs.sha256 if s.lfs else None
|
|
60
|
+
etag = sha or s.blob_id
|
|
61
|
+
url = hf_hub_url(repo_id, s.rfilename, repo_type=repo_type, revision=info.sha)
|
|
62
|
+
if out:
|
|
63
|
+
entries.append(Entry(s.rfilename, s.size, sha, etag, url, out / s.rfilename, None))
|
|
64
|
+
else:
|
|
65
|
+
entries.append(Entry(s.rfilename, s.size, sha, etag, url, base / "blobs" / etag,
|
|
66
|
+
base / "snapshots" / info.sha / s.rfilename))
|
|
67
|
+
return entries
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def free_port() -> int:
|
|
71
|
+
with socket.socket() as s:
|
|
72
|
+
s.bind(("127.0.0.1", 0))
|
|
73
|
+
return s.getsockname()[1]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def rpc(port, secret, method, *params):
|
|
77
|
+
body = json.dumps({"jsonrpc": "2.0", "id": "h", "method": f"aria2.{method}", "params": [f"token:{secret}", *params]}).encode()
|
|
78
|
+
req = urllib.request.Request(f"http://127.0.0.1:{port}/jsonrpc", body, {"Content-Type": "application/json"})
|
|
79
|
+
with urllib.request.urlopen(req, timeout=5) as r:
|
|
80
|
+
return json.load(r)["result"]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run_aria2(todo: list[Entry], workdir: Path, x: int, j: int, token: str | None, base_done: int, start: int, total: int, nfiles: int) -> int:
|
|
84
|
+
workdir.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
inp = workdir / "aria2.input"
|
|
86
|
+
with open(os.open(inp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f: # 0600: may hold the token
|
|
87
|
+
for e in todo:
|
|
88
|
+
e.tmp.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
f.write(f"{e.url}\n dir={e.tmp.parent}\n out={e.tmp.name}\n")
|
|
90
|
+
if token:
|
|
91
|
+
f.write(f" header=Authorization: Bearer {token}\n")
|
|
92
|
+
port, secret = free_port(), secrets.token_hex(16)
|
|
93
|
+
cmd = ["aria2c", f"--input-file={inp}", "--enable-rpc", f"--rpc-listen-port={port}", f"--rpc-secret={secret}",
|
|
94
|
+
f"--split={x}", f"--max-connection-per-server={min(x, 16)}", f"--max-concurrent-downloads={j}",
|
|
95
|
+
"--min-split-size=20M", "--continue=true", "--auto-file-renaming=false", "--allow-overwrite=true",
|
|
96
|
+
"--file-allocation=none", "--max-tries=8", "--retry-wait=3", "--console-log-level=warn",
|
|
97
|
+
"--summary-interval=0", "--follow-torrent=false", "--show-console-readout=false",
|
|
98
|
+
"--download-result=hide", "--max-download-result=1000000", "--enable-color=false"]
|
|
99
|
+
# own session: terminal Ctrl-C must not hit aria2c directly; we forward exactly one SIGINT
|
|
100
|
+
proc = subprocess.Popen(cmd, start_new_session=True, stdout=2)
|
|
101
|
+
bar = tqdm(total=total, initial=start, unit="B", unit_scale=True, unit_divisor=1024, file=sys.stderr, mininterval=0.5,
|
|
102
|
+
bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}] {postfix}")
|
|
103
|
+
try:
|
|
104
|
+
last, failed = 0.0, False
|
|
105
|
+
while proc.poll() is None:
|
|
106
|
+
if time.time() - last >= 1:
|
|
107
|
+
last = time.time()
|
|
108
|
+
try:
|
|
109
|
+
keys = ["completedLength", "status"]
|
|
110
|
+
live = rpc(port, secret, "tellActive", keys) + rpc(port, secret, "tellWaiting", 0, 1000000, keys)
|
|
111
|
+
stopped = rpc(port, secret, "tellStopped", 0, 1000000, keys)
|
|
112
|
+
done = base_done + sum(int(d["completedLength"]) for d in live + stopped)
|
|
113
|
+
nd = sum(d["status"] == "complete" for d in stopped)
|
|
114
|
+
bar.n = min(max(done, start), total) # start counts partial bytes already on disk
|
|
115
|
+
bar.set_postfix_str(f"{nfiles - len(todo) + nd}/{nfiles} files", refresh=False)
|
|
116
|
+
bar.refresh()
|
|
117
|
+
if not live and len(stopped) >= len(todo): # RPC mode keeps aria2c alive; stop it ourselves
|
|
118
|
+
rpc(port, secret, "shutdown")
|
|
119
|
+
proc.wait(timeout=30)
|
|
120
|
+
failed = nd < len(todo)
|
|
121
|
+
except (OSError, KeyError, ValueError): # RPC not up yet / aria2 exiting / RPC error reply
|
|
122
|
+
pass
|
|
123
|
+
time.sleep(0.2)
|
|
124
|
+
if proc.returncode == 0 and not failed:
|
|
125
|
+
bar.n = total
|
|
126
|
+
bar.set_postfix_str(f"{nfiles}/{nfiles} files", refresh=False)
|
|
127
|
+
bar.refresh()
|
|
128
|
+
return 1 if failed else proc.returncode
|
|
129
|
+
except KeyboardInterrupt:
|
|
130
|
+
proc.send_signal(signal.SIGINT) # graceful: aria2 writes .aria2 control files
|
|
131
|
+
try:
|
|
132
|
+
proc.wait(timeout=30)
|
|
133
|
+
except subprocess.TimeoutExpired:
|
|
134
|
+
proc.kill()
|
|
135
|
+
raise
|
|
136
|
+
finally:
|
|
137
|
+
bar.close()
|
|
138
|
+
inp.unlink(missing_ok=True)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def sha256_file(p: Path) -> str:
|
|
142
|
+
h = hashlib.sha256()
|
|
143
|
+
with open(p, "rb") as f:
|
|
144
|
+
while chunk := f.read(8 * MB):
|
|
145
|
+
h.update(chunk)
|
|
146
|
+
return h.hexdigest()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def free_bytes(p: Path) -> int:
|
|
150
|
+
while not p.exists():
|
|
151
|
+
p = p.parent
|
|
152
|
+
return shutil.disk_usage(p).free
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def access_error(a, e) -> int:
|
|
156
|
+
code = getattr(getattr(e, "response", None), "status_code", None)
|
|
157
|
+
if code in (401, 403) or isinstance(e, RepositoryNotFoundError):
|
|
158
|
+
print(f"error: cannot access {a.repo_id} ({code or 'not found'}). Gated or private? Accept the terms on "
|
|
159
|
+
f"{constants.ENDPOINT}/{'datasets/' if a.type == 'dataset' else ''}{a.repo_id} and run `hf auth login`.", file=sys.stderr)
|
|
160
|
+
else:
|
|
161
|
+
print(f"error: {e}", file=sys.stderr)
|
|
162
|
+
return 1
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def get(a) -> int:
|
|
166
|
+
if not shutil.which("aria2c"):
|
|
167
|
+
hint = "brew install aria2" if sys.platform == "darwin" else "apt install aria2"
|
|
168
|
+
print(f"error: aria2c not found on PATH. Install it: {hint}", file=sys.stderr)
|
|
169
|
+
return 2
|
|
170
|
+
out = Path(a.out).expanduser().resolve() if a.out else None
|
|
171
|
+
try:
|
|
172
|
+
info = HfApi().repo_info(a.repo_id, repo_type=a.type, revision=a.revision, files_metadata=True)
|
|
173
|
+
except (HfHubHTTPError, RepositoryNotFoundError) as e:
|
|
174
|
+
return access_error(a, e)
|
|
175
|
+
entries = build_entries(info, a.repo_id, a.type, a.revision, a.include, a.exclude, out)
|
|
176
|
+
if not entries:
|
|
177
|
+
print("error: no files match", file=sys.stderr)
|
|
178
|
+
return 1
|
|
179
|
+
# cache mode: files sharing an etag share one blob, download once
|
|
180
|
+
mf = out / ".hft" / "manifest.json" if out else None
|
|
181
|
+
manifest = json.loads(mf.read_text()) if mf and mf.exists() else {} if out else None
|
|
182
|
+
todo, seen = [], set()
|
|
183
|
+
for e in entries:
|
|
184
|
+
if not e.is_complete(manifest) and e.final not in seen:
|
|
185
|
+
seen.add(e.final)
|
|
186
|
+
todo.append(e)
|
|
187
|
+
total = sum(e.size for e in {e.final: e for e in entries}.values())
|
|
188
|
+
remaining = sum(e.size - min(e.size, e.tmp.stat().st_blocks * 512 if e.tmp.exists() else 0) for e in todo)
|
|
189
|
+
x, j = tune([e.size for e in todo])
|
|
190
|
+
x, j = min(a.x or x, 16), a.j or j
|
|
191
|
+
dest = out or (Path(constants.HF_HUB_CACHE) / repo_folder_name(repo_id=a.repo_id, repo_type=a.type) / "snapshots" / info.sha)
|
|
192
|
+
print(f"files: {len(entries)} total: {total / MB:.1f} MiB remaining: {remaining / MB:.1f} MiB "
|
|
193
|
+
f"pending files: {len(todo)} -x {x} -j {j}\ndestination: {dest}", file=sys.stderr)
|
|
194
|
+
if todo: # gated repos expose metadata but 403 on files: check one file before aria2c starts
|
|
195
|
+
try:
|
|
196
|
+
get_hf_file_metadata(todo[0].url, token=get_token())
|
|
197
|
+
except HfHubHTTPError as e:
|
|
198
|
+
return access_error(a, e)
|
|
199
|
+
if a.dry_run:
|
|
200
|
+
return 0
|
|
201
|
+
if remaining > free_bytes(dest):
|
|
202
|
+
print(f"error: need {remaining / MB:.0f} MiB, only {free_bytes(dest) / MB:.0f} MiB free", file=sys.stderr)
|
|
203
|
+
return 1
|
|
204
|
+
|
|
205
|
+
bad = []
|
|
206
|
+
if todo:
|
|
207
|
+
root = out if out else todo[0].final.parent.parent
|
|
208
|
+
base_done = total - sum(e.size for e in todo)
|
|
209
|
+
rc = run_aria2(todo, root / ".hft", x, j, get_token(), base_done, total - remaining, total, len({e.final for e in entries}))
|
|
210
|
+
if rc != 0:
|
|
211
|
+
print(f"error: aria2c exited with {rc}; rerun the same command to resume", file=sys.stderr)
|
|
212
|
+
return 1
|
|
213
|
+
for e in todo:
|
|
214
|
+
ok = e.tmp.exists() and e.tmp.stat().st_size == e.size
|
|
215
|
+
if ok and a.verify and e.sha256:
|
|
216
|
+
ok = sha256_file(e.tmp) == e.sha256
|
|
217
|
+
if ok:
|
|
218
|
+
os.replace(e.tmp, e.final)
|
|
219
|
+
if out:
|
|
220
|
+
manifest[e.path] = e.etag
|
|
221
|
+
else:
|
|
222
|
+
bad.append(e.path)
|
|
223
|
+
e.tmp.unlink(missing_ok=True)
|
|
224
|
+
e.tmp.with_name(e.tmp.name + ".aria2").unlink(missing_ok=True)
|
|
225
|
+
if out:
|
|
226
|
+
mf.parent.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
mf.write_text(json.dumps(manifest))
|
|
228
|
+
elif not any((root / ".hft").iterdir()):
|
|
229
|
+
(root / ".hft").rmdir()
|
|
230
|
+
for path in bad:
|
|
231
|
+
print(f"error: {path}: size/checksum mismatch, deleted", file=sys.stderr)
|
|
232
|
+
if not out:
|
|
233
|
+
repo_dir = entries[0].final.parent.parent
|
|
234
|
+
for e in entries:
|
|
235
|
+
if not e.final.exists(): # failed verify
|
|
236
|
+
continue
|
|
237
|
+
e.link.parent.mkdir(parents=True, exist_ok=True)
|
|
238
|
+
if not e.link.is_symlink() or not e.link.exists(): # same as _create_symlink: relative link
|
|
239
|
+
e.link.unlink(missing_ok=True)
|
|
240
|
+
e.link.symlink_to(os.path.relpath(e.final, e.link.parent))
|
|
241
|
+
if not bad:
|
|
242
|
+
_cache_commit_hash_for_specific_revision(str(repo_dir), a.revision, info.sha)
|
|
243
|
+
if bad:
|
|
244
|
+
return 1
|
|
245
|
+
print(dest)
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv=None) -> int:
|
|
250
|
+
p = argparse.ArgumentParser(prog="hft", description="Fast Hugging Face downloads via aria2c")
|
|
251
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
252
|
+
g = sub.add_parser("get", help="download a repo")
|
|
253
|
+
g.add_argument("repo_id")
|
|
254
|
+
g.add_argument("--type", choices=["dataset", "model"], default="dataset")
|
|
255
|
+
g.add_argument("--revision", default="main")
|
|
256
|
+
g.add_argument("--include", action="append", default=[], metavar="GLOB")
|
|
257
|
+
g.add_argument("--exclude", action="append", default=[], metavar="GLOB")
|
|
258
|
+
g.add_argument("--out", metavar="DIR")
|
|
259
|
+
g.add_argument("-x", type=int, help="connections per file (auto if omitted)")
|
|
260
|
+
g.add_argument("-j", type=int, help="concurrent files (auto if omitted)")
|
|
261
|
+
g.add_argument("--verify", action="store_true", help="sha256-check LFS files")
|
|
262
|
+
g.add_argument("--dry-run", action="store_true")
|
|
263
|
+
a = p.parse_args(argv)
|
|
264
|
+
signal.signal(signal.SIGINT, signal.default_int_handler) # background launchers may leave SIGINT ignored
|
|
265
|
+
try:
|
|
266
|
+
return get(a)
|
|
267
|
+
except KeyboardInterrupt:
|
|
268
|
+
print("\ninterrupted; rerun the same command to resume", file=sys.stderr)
|
|
269
|
+
return 130
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
if __name__ == "__main__":
|
|
273
|
+
sys.exit(main())
|