File size: 2,168 Bytes
5f94a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""hf_fetch.py <repo> <local_dir> <prefix>[:<suffixes>] ...   Download only the files under each prefix of a HF dataset repo.

Why not snapshot_download: the repo has more than 100,000 files and the Hub's repo_info file list stops at 100,000 (it ends inside N021), so
snapshot_download with allow_patterns on a later folder (N025..., canonical_action_v2, pi05_v3) can "Fetch 0 files" (reported 2026-11-16, N025/stretch3).
Here each prefix is listed on its own with list_repo_tree, then the files are fetched with 32 parallel hf_hub_download; files already present with the
right size are skipped. ":<suffixes>" keeps only names ending with one of the comma-separated suffixes, e.g. canonical_action_v2:.py,.json"""
import os, sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.hf_api import RepoFile

repo, local = sys.argv[1], sys.argv[2]
tok = os.environ.get("HF_TOKEN") or None
api = HfApi(token=tok)
want = []
for arg in sys.argv[3:]:
    pre, _, suf = arg.partition(":")
    sufs = tuple(s for s in suf.split(",") if s)
    files = [x for x in api.list_repo_tree(repo, path_in_repo=pre, repo_type="dataset", recursive=True) if isinstance(x, RepoFile)]
    if sufs:
        files = [x for x in files if x.path.endswith(sufs)]
    print(f"[hf_fetch] {pre}: {len(files)} files", flush=True)
    want += files
todo = [x for x in want if not (os.path.isfile(os.path.join(local, x.path)) and os.path.getsize(os.path.join(local, x.path)) == x.size)]
print(f"[hf_fetch] {len(want)} files, {len(todo)} to download", flush=True)

def get(x):
    for attempt in range(5):
        try:
            return hf_hub_download(repo, x.path, repo_type="dataset", local_dir=local, token=tok)
        except Exception as e:  # transient 429 / timeouts
            err = e
    raise err

done = 0
with ThreadPoolExecutor(int(os.environ.get("HF_FETCH_WORKERS", "32"))) as ex:
    for f in as_completed([ex.submit(get, x) for x in todo]):
        f.result(); done += 1
        if done % 500 == 0:
            print(f"[hf_fetch] {done}/{len(todo)}", flush=True)
print("[hf_fetch] done", flush=True)